Add AIX 64 shared library support and emulation layer for binutils
[external/binutils.git] / ld / emultempl / aix.em
1 # This shell script emits a C file. -*- C -*-
2 # It does some substitutions.
3 if [ -z "$MACHINE" ]; then
4   OUTPUT_ARCH=${ARCH}
5 else
6   OUTPUT_ARCH=${ARCH}:${MACHINE}
7 fi
8 cat >e${EMULATION_NAME}.c <<EOF
9 /* This file is is generated by a shell script.  DO NOT EDIT! */
10
11 /* AIX emulation code for ${EMULATION_NAME}
12    Copyright 1991, 1993, 1995, 1996, 1997, 1998, 2000, 2001
13    Free Software Foundation, Inc.
14    Written by Steve Chamberlain <sac@cygnus.com>
15    AIX support by Ian Lance Taylor <ian@cygnus.com>
16    AIX 64 bit support by Tom Rix <trix@redhat.com>
17
18 This file is part of GLD, the Gnu Linker.
19
20 This program is free software; you can redistribute it and/or modify
21 it under the terms of the GNU General Public License as published by
22 the Free Software Foundation; either version 2 of the License, or
23 (at your option) any later version.
24
25 This program is distributed in the hope that it will be useful,
26 but WITHOUT ANY WARRANTY; without even the implied warranty of
27 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
28 GNU General Public License for more details.
29
30 You should have received a copy of the GNU General Public License
31 along with this program; if not, write to the Free Software
32 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
33
34 #define TARGET_IS_${EMULATION_NAME}
35
36 #include "bfd.h"
37 #include "sysdep.h"
38 #include "libiberty.h"
39 #include "safe-ctype.h"
40 #include "getopt.h"
41 #include "obstack.h"
42 #include "bfdlink.h"
43
44 #include "ld.h"
45 #include "ldmain.h"
46 #include "ldmisc.h"
47 #include "ldexp.h"
48 #include "ldlang.h"
49 #include "ldfile.h"
50 #include "ldemul.h"
51 #include "ldctor.h"
52 #include "ldgram.h"
53
54 #include "coff/internal.h"
55 #include "coff/xcoff.h"
56
57 static void gld${EMULATION_NAME}_before_parse PARAMS ((void));
58 static int gld${EMULATION_NAME}_parse_args PARAMS ((int, char **));
59 static void gld${EMULATION_NAME}_after_open PARAMS ((void));
60 static char *choose_target PARAMS ((int, char **));
61 static void gld${EMULATION_NAME}_before_allocation PARAMS ((void));
62 static void gld${EMULATION_NAME}_read_file PARAMS ((const char *, boolean));
63 static void gld${EMULATION_NAME}_free PARAMS ((PTR));
64 static void gld${EMULATION_NAME}_find_relocs 
65 PARAMS ((lang_statement_union_type *));
66 static void gld${EMULATION_NAME}_find_exp_assignment PARAMS ((etree_type *));
67 static char *gld${EMULATION_NAME}_get_script PARAMS ((int *isfile));
68 static boolean gld${EMULATION_NAME}_unrecognized_file
69   PARAMS ((lang_input_statement_type *));
70 static void gld${EMULATION_NAME}_create_output_section_statements 
71   PARAMS((void));
72 static int is_syscall PARAMS ((char *, unsigned int *));
73 static int change_symbol_mode PARAMS ((char *));
74
75 /* The file alignment required for each section.  */
76 static unsigned long file_align;
77
78 /* The maximum size the stack is permitted to grow.  This is stored in
79    the a.out header.  */
80 static unsigned long maxstack;
81
82 /* The maximum data size.  This is stored in the a.out header.  */
83 static unsigned long maxdata;
84
85 /* Whether to perform garbage collection.  */
86 static int gc = 1;
87
88 /* The module type to use.  */
89 static unsigned short modtype = ('1' << 8) | 'L';
90
91 /* Whether the .text section must be read-only (i.e., no relocs
92    permitted).  */
93 static int textro;
94
95 /* Whether to implement Unix like linker semantics.  */
96 static int unix_ld;
97
98 /* Structure used to hold import file list.  */
99
100 struct filelist
101 {
102   struct filelist *next;
103   const char *name;
104 };
105
106 /* List of import files.  */
107 static struct filelist *import_files;
108
109 /* List of export symbols read from the export files.  */
110
111 struct export_symbol_list
112 {
113   struct export_symbol_list *next;
114   const char *name;
115 };
116
117 static struct export_symbol_list *export_symbols;
118
119 /* Maintains the 32 or 64 bit mode state of import file */
120 static unsigned int symbol_mode = 0x04;
121
122 /* Which symbol modes are valid */
123 static unsigned int symbol_mode_mask = 0x0d;
124
125 /* Whether this is a 64 bit link */
126 static int is_64bit = 0;
127
128 /* Which syscalls from import file are valid */
129 static unsigned int syscall_mask = 0x77;
130
131 /* fake file for -binitfini support */
132 static lang_input_statement_type *initfini_file;
133
134 /* Whether to do run time linking */
135 static boolean rtld;
136
137 /* This routine is called before anything else is done.  */
138
139 static void
140 gld${EMULATION_NAME}_before_parse ()
141 {
142 #ifndef TARGET_                 /* I.e., if not generic.  */
143   const bfd_arch_info_type *arch = bfd_scan_arch ("${OUTPUT_ARCH}");
144   if (arch)
145     {
146       ldfile_output_architecture = arch->arch;
147       ldfile_output_machine = arch->mach;
148       ldfile_output_machine_name = arch->printable_name;
149     }
150   else
151     ldfile_output_architecture = bfd_arch_${ARCH};
152 #endif /* not TARGET_ */
153   config.has_shared = true;
154
155   /* The link_info.[init|fini]_functions are initialized in ld/lexsup.c.
156      Override them here so we can use the link_info.init_function as a
157      state flag that lets the backend know that -binitfini has been done.  */ 
158
159   link_info.init_function = NULL;
160   link_info.fini_function = NULL;
161 }
162
163 /* Handle AIX specific options.  */
164
165 static int
166 gld${EMULATION_NAME}_parse_args (argc, argv)
167      int argc;
168      char **argv;
169 {
170   int prevoptind = optind;
171   int prevopterr = opterr;
172   int indx;
173   int longind;
174   int optc;
175   bfd_signed_vma val;
176   char *end;
177
178   enum 
179   {
180     OPTION_IGNORE = 300,
181     OPTION_AUTOIMP,
182     OPTION_ERNOTOK,
183     OPTION_EROK,
184     OPTION_EXPORT,
185     OPTION_IMPORT,
186     OPTION_INITFINI,
187     OPTION_LOADMAP,
188     OPTION_MAXDATA,
189     OPTION_MAXSTACK,
190     OPTION_MODTYPE,
191     OPTION_NOAUTOIMP,
192     OPTION_NOSTRCMPCT,
193     OPTION_PD,
194     OPTION_PT,
195     OPTION_STRCMPCT,
196     OPTION_UNIX,
197     OPTION_32,
198     OPTION_64,
199   };
200
201   /* -binitfini has special handling in the linker backend.  The native linker
202      uses the arguemnts to generate a table of init and fini functions for
203      the executable.  The important use for this option is to support aix 4.2+
204      c++ constructors and destructors.  This is tied into gcc via collect2.c.
205      
206      The function table is accessed by the runtime linker/loader by checking if
207      the first symbol in the loader symbol table is __rtinit.  The gnu linker
208      generates this symbol and makes it the first loader symbol.  */
209
210   static const struct option longopts[] = {
211     {"basis", no_argument, NULL, OPTION_IGNORE},
212     {"bautoimp", no_argument, NULL, OPTION_AUTOIMP},
213     {"bcomprld", no_argument, NULL, OPTION_IGNORE},
214     {"bcrld", no_argument, NULL, OPTION_IGNORE},
215     {"bcror31", no_argument, NULL, OPTION_IGNORE},
216     {"bD", required_argument, NULL, OPTION_MAXDATA},
217     {"bE", required_argument, NULL, OPTION_EXPORT},
218     {"bernotok", no_argument, NULL, OPTION_ERNOTOK},
219     {"berok", no_argument, NULL, OPTION_EROK},
220     {"berrmsg", no_argument, NULL, OPTION_IGNORE},
221     {"bexport", required_argument, NULL, OPTION_EXPORT},
222     {"bf", no_argument, NULL, OPTION_ERNOTOK},
223     {"bgc", no_argument, &gc, 1},
224     {"bh", required_argument, NULL, OPTION_IGNORE},
225     {"bhalt", required_argument, NULL, OPTION_IGNORE},
226     {"bI", required_argument, NULL, OPTION_IMPORT},
227     {"bimport", required_argument, NULL, OPTION_IMPORT},
228     {"binitfini", required_argument, NULL, OPTION_INITFINI},
229     {"bl", required_argument, NULL, OPTION_LOADMAP},
230     {"bloadmap", required_argument, NULL, OPTION_LOADMAP},
231     {"bmaxdata", required_argument, NULL, OPTION_MAXDATA},
232     {"bmaxstack", required_argument, NULL, OPTION_MAXSTACK},
233     {"bM", required_argument, NULL, OPTION_MODTYPE},
234     {"bmodtype", required_argument, NULL, OPTION_MODTYPE},
235     {"bnoautoimp", no_argument, NULL, OPTION_NOAUTOIMP},
236     {"bnodelcsect", no_argument, NULL, OPTION_IGNORE},
237     {"bnoentry", no_argument, NULL, OPTION_IGNORE},
238     {"bnogc", no_argument, &gc, 0},
239     {"bnso", no_argument, NULL, OPTION_NOAUTOIMP},
240     {"bnostrcmpct", no_argument, NULL, OPTION_NOSTRCMPCT},
241     {"bnotextro", no_argument, &textro, 0},
242     {"bnro", no_argument, &textro, 0},
243     {"bpD", required_argument, NULL, OPTION_PD},
244     {"bpT", required_argument, NULL, OPTION_PT},
245     {"bro", no_argument, &textro, 1},
246     {"brtl", no_argument, &rtld, 1},
247     {"bS", required_argument, NULL, OPTION_MAXSTACK},
248     {"bso", no_argument, NULL, OPTION_AUTOIMP},
249     {"bstrcmpct", no_argument, NULL, OPTION_STRCMPCT},
250     {"btextro", no_argument, &textro, 1},
251     {"b32", no_argument, NULL, OPTION_32},
252     {"b64", no_argument, NULL, OPTION_64},
253     {"static", no_argument, NULL, OPTION_NOAUTOIMP},
254     {"unix", no_argument, NULL, OPTION_UNIX},
255     {NULL, no_argument, NULL, 0}
256   };
257
258   /* Options supported by the AIX linker which we do not support: -f,
259      -S, -v, -Z, -bbindcmds, -bbinder, -bbindopts, -bcalls, -bcaps,
260      -bcror15, -bdebugopt, -bdbg, -bdelcsect, -bex?, -bfilelist, -bfl,
261      -bgcbypass, -bglink, -binsert, -bi, -bloadmap, -bl, -bmap, -bnl,
262      -bnobind, -bnocomprld, -bnocrld, -bnoerrmsg, -bnoglink,
263      -bnoloadmap, -bnl, -bnoobjreorder, -bnoquiet, -bnoreorder,
264      -bnotypchk, -bnox, -bquiet, -bR, -brename, -breorder, -btypchk,
265      -bx, -bX, -bxref.  */
266
267   /* If the current option starts with -b, change the first : to an =.
268      The AIX linker uses : to separate the option from the argument;
269      changing it to = lets us treat it as a getopt option.  */
270   indx = optind;
271   if (indx == 0)
272     indx = 1;
273
274   if (indx < argc && strncmp (argv[indx], "-b", 2) == 0)
275     {
276       char *s;
277
278       for (s = argv[indx]; *s != '\0'; s++)
279         {
280           if (*s == ':')
281             {
282               *s = '=';
283               break;
284             }
285         }
286     }
287
288
289   /* We add s and u so to the short options list so that -s and -u on
290      the command line do not match -static and -unix.  */
291
292   opterr = 0;
293   optc = getopt_long_only (argc, argv, "-D:H:KT:zsu", longopts, &longind);
294   opterr = prevopterr;
295
296   switch (optc)
297     {
298     case 's':
299     case 'u':
300     default:
301       optind = prevoptind;
302       return 0;
303
304     case 0:
305       /* Long option which just sets a flag.  */
306       break;
307
308     case 'D':
309       val = strtoll (optarg, &end, 0);
310       if (*end != '\0')
311         einfo ("%P: warning: ignoring invalid -D number %s\n", optarg);
312       else if (val != -1)
313         lang_section_start (".data", exp_intop (val));
314       break;
315
316     case 'H':
317       val = strtoul (optarg, &end, 0);
318       if (*end != '\0' || (val & (val - 1)) != 0)
319         einfo ("%P: warning: ignoring invalid -H number %s\n", optarg);
320       else
321         file_align = val;
322       break;
323
324     case 'K':
325     case 'z':
326       /* FIXME: This should use the page size for the target system.  */
327       file_align = 4096;
328       break;
329
330     case 'T':
331       /* On AIX this is the same as GNU ld -Ttext.  When we see -T
332          number, we assume the AIX option is intended.  Otherwise, we
333          assume the usual GNU ld -T option is intended.  We can't just
334          ignore the AIX option, because gcc passes it to the linker.  */
335       val = strtoull (optarg, &end, 0);
336       if (*end != '\0')
337         {
338           optind = prevoptind;
339           return 0;
340         }
341       lang_section_start (".text", exp_intop (val));
342       break;
343
344     case OPTION_IGNORE:
345       break;
346
347     case OPTION_INITFINI:
348       {
349         /*
350          * The aix linker init fini has the format :
351          *
352          * -binitfini:[ Initial][:Termination][:Priority]
353          *
354          * it allows the Termination and Priority to be optional.
355          *
356          * Since we support only one init/fini pair, we ignore the Priority.
357          *
358          * Define the special symbol __rtinit.
359          *
360          * strtok does not correctly handle the case of -binitfini::fini: so
361          * do it by hand
362          */
363         char *t, *i, *f;
364
365         i = t = optarg;
366         while (*t && ':' != *t)
367           t++;
368         if (*t)
369           *t++ = 0;
370
371         if (0 != strlen (i))
372           link_info.init_function = i;
373
374         f = t;
375         while (*t && ':' != *t)
376           t++;
377         *t = 0;
378
379         if (0 != strlen (f))
380           link_info.fini_function = f;
381       }
382       break;
383       
384     case OPTION_AUTOIMP:
385       link_info.static_link = false;
386       break;
387
388     case OPTION_ERNOTOK:
389       force_make_executable = false;
390       break;
391
392     case OPTION_EROK:
393       force_make_executable = true;
394       break;
395
396     case OPTION_EXPORT:
397       gld${EMULATION_NAME}_read_file (optarg, false);
398       break;
399
400     case OPTION_IMPORT:
401       {
402         struct filelist *n;
403         struct filelist **flpp;
404
405         n = (struct filelist *) xmalloc (sizeof (struct filelist));
406         n->next = NULL;
407         n->name = optarg;
408         flpp = &import_files;
409         while (*flpp != NULL)
410           flpp = &(*flpp)->next;
411         *flpp = n;
412       }
413       break;
414
415     case OPTION_LOADMAP:
416       config.map_filename = optarg;
417       break;
418
419     case OPTION_MAXDATA:
420       val = strtoull (optarg, &end, 0);
421       if (*end != '\0')
422         einfo ("%P: warning: ignoring invalid -bmaxdata number %s\n", optarg);
423       else
424         maxdata = val;
425       break;
426
427     case OPTION_MAXSTACK:
428       val = strtoull (optarg, &end, 0);
429       if (*end != '\0')
430         einfo ("%P: warning: ignoring invalid -bmaxstack number %s\n", 
431                optarg);
432       else
433         maxstack = val;
434       break;
435
436     case OPTION_MODTYPE:
437       if (*optarg == 'S')
438         {
439           link_info.shared = true;
440           ++optarg;
441         }
442       if (*optarg == '\0' || optarg[1] == '\0')
443         einfo ("%P: warning: ignoring invalid module type %s\n", optarg);
444       else
445         modtype = (*optarg << 8) | optarg[1];
446       break;
447
448     case OPTION_NOAUTOIMP:
449       link_info.static_link = true;
450       break;
451
452     case OPTION_NOSTRCMPCT:
453       link_info.traditional_format = true;
454       break;
455
456     case OPTION_PD:
457       /* This sets the page that the .data section is supposed to
458          start on.  The offset within the page should still be the
459          offset within the file, so we need to build an appropriate
460          expression.  */
461       val = strtoull (optarg, &end, 0);
462       if (*end != '\0')
463         einfo ("%P: warning: ignoring invalid -pD number %s\n", optarg);
464       else
465         {
466           etree_type *t;
467
468           t = exp_binop ('+',
469                          exp_intop (val),
470                          exp_binop ('&',
471                                     exp_nameop (NAME, "."),
472                                     exp_intop (0xfff)));
473           t = exp_binop ('&',
474                          exp_binop ('+', t, exp_intop (31)),
475                          exp_intop (~(bfd_vma) 31));
476           lang_section_start (".data", t);
477         }
478       break;
479
480     case OPTION_PT:
481       /* This set the page that the .text section is supposed to start
482          on.  The offset within the page should still be the offset
483          within the file.  */
484       val = strtoull (optarg, &end, 0);
485       if (*end != '\0')
486         einfo ("%P: warning: ignoring invalid -pT number %s\n", optarg);
487       else
488         {
489           etree_type *t;
490
491           t = exp_binop ('+',
492                          exp_intop (val),
493                          exp_nameop (SIZEOF_HEADERS, NULL));
494           t = exp_binop ('&',
495                          exp_binop ('+', t, exp_intop (31)),
496                          exp_intop (~(bfd_vma) 31));
497           lang_section_start (".text", t);
498         }
499       break;
500
501     case OPTION_STRCMPCT:
502       link_info.traditional_format = false;
503       break;
504
505     case OPTION_UNIX:
506       unix_ld = true;
507       break;
508
509     case OPTION_32:
510       is_64bit = 0;
511       syscall_mask = 0x77;
512       symbol_mode_mask = 0x0d;
513       break;
514
515     case OPTION_64:
516       is_64bit = 1;
517       syscall_mask = 0xcc;
518       symbol_mode_mask = 0x0e;
519       break;
520
521     }
522
523   return 1;
524 }
525
526 /* This is called when an input file can not be recognized as a BFD
527    object or an archive.  If the file starts with #!, we must treat it
528    as an import file.  This is for AIX compatibility.  */
529
530 static boolean
531 gld${EMULATION_NAME}_unrecognized_file (entry)
532      lang_input_statement_type *entry;
533 {
534   FILE *e;
535   boolean ret;
536
537   e = fopen (entry->filename, FOPEN_RT);
538   if (e == NULL)
539     return false;
540
541   ret = false;
542
543   if (getc (e) == '#' && getc (e) == '!')
544     {
545       struct filelist *n;
546       struct filelist **flpp;
547
548       n = (struct filelist *) xmalloc (sizeof (struct filelist));
549       n->next = NULL;
550       n->name = entry->filename;
551       flpp = &import_files;
552       while (*flpp != NULL)
553         flpp = &(*flpp)->next;
554       *flpp = n;
555
556       ret = true;
557       entry->loaded = true;
558     }
559
560   fclose (e);
561
562   return ret;
563 }
564
565 /* This is called after the input files have been opened.  */
566
567 static void
568 gld${EMULATION_NAME}_after_open ()
569 {
570   boolean r;
571   struct set_info *p;
572
573   /* Call ldctor_build_sets, after pretending that this is a
574      relocateable link.  We do this because AIX requires relocation
575      entries for all references to symbols, even in a final
576      executable.  Of course, we only want to do this if we are
577      producing an XCOFF output file.  */
578   r = link_info.relocateable;
579   if (strstr (bfd_get_target (output_bfd), "xcoff") != NULL)
580     link_info.relocateable = true;
581   ldctor_build_sets ();
582   link_info.relocateable = r;
583
584   /* For each set, record the size, so that the XCOFF backend can
585      output the correct csect length.  */
586   for (p = sets; p != (struct set_info *) NULL; p = p->next)
587     {
588       bfd_size_type size;
589
590       /* If the symbol is defined, we may have been invoked from
591          collect, and the sets may already have been built, so we do
592          not do anything.  */
593       if (p->h->type == bfd_link_hash_defined
594           || p->h->type == bfd_link_hash_defweak)
595         continue;
596
597       if (p->reloc != BFD_RELOC_CTOR)
598         {
599           /* Handle this if we need to.  */
600           abort ();
601         }
602
603       size = (p->count + 2) * 4;
604       if (!bfd_xcoff_link_record_set (output_bfd, &link_info, p->h, size))
605         einfo ("%F%P: bfd_xcoff_link_record_set failed: %E\n");
606     }
607 }
608
609 /* This is called after the sections have been attached to output
610    sections, but before any sizes or addresses have been set.  */
611
612 static void
613 gld${EMULATION_NAME}_before_allocation ()
614 {
615   struct filelist *fl;
616   struct export_symbol_list *el;
617   char *libpath;
618   asection *special_sections[XCOFF_NUMBER_OF_SPECIAL_SECTIONS];
619   int i;
620
621   /* Handle the import and export files, if any.  */
622   for (fl = import_files; fl != NULL; fl = fl->next)
623     gld${EMULATION_NAME}_read_file (fl->name, true);
624   for (el = export_symbols; el != NULL; el = el->next)
625     {
626       struct bfd_link_hash_entry *h;
627
628       h = bfd_link_hash_lookup (link_info.hash, el->name, false, false, false);
629       if (h == NULL)
630         einfo ("%P%F: bfd_link_hash_lookup of export symbol failed: %E\n");
631       if (!bfd_xcoff_export_symbol (output_bfd, &link_info, h))
632         einfo ("%P%F: bfd_xcoff_export_symbol failed: %E\n");
633     }
634
635   /* Track down all relocations called for by the linker script (these
636      are typically constructor/destructor entries created by
637      CONSTRUCTORS) and let the backend know it will need to create
638      .loader relocs for them.  */
639   lang_for_each_statement (gld${EMULATION_NAME}_find_relocs);
640
641   /* We need to build LIBPATH from the -L arguments.  If any -rpath
642      arguments were used, though, we use -rpath instead, as a GNU
643      extension.  */
644   if (command_line.rpath != NULL)
645     libpath = command_line.rpath;
646   else if (search_head == NULL)
647     libpath = (char *) "";
648   else
649     {
650       size_t len;
651       search_dirs_type *search;
652
653       len = strlen (search_head->name);
654       libpath = xmalloc (len + 1);
655       strcpy (libpath, search_head->name);
656       for (search = search_head->next; search != NULL; search = search->next)
657         {
658           size_t nlen;
659
660           nlen = strlen (search->name);
661           libpath = xrealloc (libpath, len + nlen + 2);
662           libpath[len] = ':';
663           strcpy (libpath + len + 1, search->name);
664           len += nlen + 1;
665         }
666     }
667
668   /* Let the XCOFF backend set up the .loader section.  */
669   if (!bfd_xcoff_size_dynamic_sections 
670       (output_bfd, &link_info, libpath, entry_symbol, file_align,
671        maxstack, maxdata, gc && !unix_ld ? true : false,
672        modtype, textro ? true : false, unix_ld, special_sections, rtld))
673     einfo ("%P%F: failed to set dynamic section sizes: %E\n");
674
675   /* Look through the special sections, and put them in the right
676      place in the link ordering.  This is especially magic.  */
677   for (i = 0; i < XCOFF_NUMBER_OF_SPECIAL_SECTIONS; i++)
678     {
679       asection *sec;
680       lang_output_section_statement_type *os;
681       lang_statement_union_type **pls;
682       lang_input_section_type *is;
683       const char *oname;
684       boolean start;
685
686       sec = special_sections[i];
687       if (sec == NULL)
688         continue;
689
690       /* Remove this section from the list of the output section.
691          This assumes we know what the script looks like.  */
692       is = NULL;
693       os = lang_output_section_find (sec->output_section->name);
694       if (os == NULL) 
695         einfo ("%P%F: can't find output section %s\n",
696                sec->output_section->name);
697
698       for (pls = &os->children.head; *pls != NULL; pls = &(*pls)->header.next)
699         {
700           if ((*pls)->header.type == lang_input_section_enum 
701               && (*pls)->input_section.section == sec)
702             {
703               is = (lang_input_section_type *) * pls;
704               *pls = (*pls)->header.next;
705               break;
706             }
707
708           if ((*pls)->header.type == lang_wild_statement_enum)
709             {
710               lang_statement_union_type **pwls;
711
712               for (pwls = &(*pls)->wild_statement.children.head;
713                    *pwls != NULL; pwls = &(*pwls)->header.next)
714                 {
715
716                   if ((*pwls)->header.type == lang_input_section_enum 
717                       && (*pwls)->input_section.section == sec)
718                     {
719                       is = (lang_input_section_type *) * pwls;
720                       *pwls = (*pwls)->header.next;
721                       break;
722                     }
723                 }
724
725               if (is != NULL)
726                 break;
727             }
728         }
729
730       if (is == NULL)
731         {
732           einfo ("%P%F: can't find %s in output section\n",
733                  bfd_get_section_name (sec->owner, sec));
734         }
735
736       /* Now figure out where the section should go.  */
737       switch (i)
738         {
739
740         default:                /* to avoid warnings */
741         case XCOFF_SPECIAL_SECTION_TEXT:
742           /* _text */
743           oname = ".text";
744           start = true;
745           break;
746
747         case XCOFF_SPECIAL_SECTION_ETEXT:
748           /* _etext */
749           oname = ".text";
750           start = false;
751           break;
752
753         case XCOFF_SPECIAL_SECTION_DATA:
754           /* _data */
755           oname = ".data";
756           start = true;
757           break;
758
759         case XCOFF_SPECIAL_SECTION_EDATA:
760           /* _edata */
761           oname = ".data";
762           start = false;
763           break;
764
765         case XCOFF_SPECIAL_SECTION_END:
766         case XCOFF_SPECIAL_SECTION_END2:
767           /* _end and end */
768           oname = ".bss";
769           start = false;
770           break;
771         }
772
773       os = lang_output_section_find (oname);
774
775       if (start)
776         {
777           is->header.next = os->children.head;
778           os->children.head = (lang_statement_union_type *) is;
779         }
780       else
781         {
782           is->header.next = NULL;
783           lang_statement_append (&os->children,
784                                  (lang_statement_union_type *) is,
785                                  &is->header.next);
786         }
787     }
788 }
789
790 static char *
791 choose_target (argc, argv)
792      int argc;
793      char **argv;
794 {
795   int i, j, jmax;
796   static char *from_outside;
797   static char *from_inside;
798   static char *argv_to_target[][2] = { 
799     {NULL,   "${OUTPUT_FORMAT}"},
800     {"-b32", "${OUTPUT_FORMAT_32BIT}"},
801     {"-b64", "${OUTPUT_FORMAT_64BIT}"},
802   };
803
804   jmax = 3;
805
806   from_outside = getenv (TARGET_ENVIRON);
807   if (from_outside != (char *) NULL)
808     return from_outside;
809
810   /* Set to default. */
811   from_inside = argv_to_target[0][1];
812   for (i = 1; i < argc; i++)
813     {
814       for (j = 1; j < jmax; j++) 
815         {
816           if (0 == strcmp (argv[i], argv_to_target[j][0]))
817             from_inside = argv_to_target[j][1];
818         }
819     }
820
821   return from_inside;
822 }
823
824 /* Returns 
825    1 : state changed
826    0 : no change */
827 static int 
828 change_symbol_mode (input)
829      char *input;
830 {
831   char *symbol_mode_string[] = {
832     "# 32",                     /* 0x01 */
833     "# 64",                     /* 0x02 */
834     "# no32",                   /* 0x04 */
835     "# no64",                   /* 0x08 */
836     NULL,
837   };
838
839   unsigned int bit;
840   char *string;
841
842   for (bit = 0;; bit++)
843     {
844       string = symbol_mode_string[bit];
845       if (string == NULL)
846         return 0;
847
848       if (0 == strcmp (input, string))
849         {
850           symbol_mode = (1 << bit);
851           return 1;
852         }
853     }
854   /* should not be here */
855   return 0;
856 }
857
858 /* Returns 
859    1 : yes
860    0 : ignore
861    -1 : error, try something else */
862 static int 
863 is_syscall (input, flag)
864      char *input;
865      unsigned int *flag;
866 {
867   unsigned int bit;
868   char *string;
869   
870   struct sc {
871     char *syscall_string;
872     unsigned int flag;
873   } s [] = {
874     { "svc"         /* 0x01 */, XCOFF_SYSCALL32 },
875     { "svc32"       /* 0x02 */, XCOFF_SYSCALL32 },
876     { "svc3264"     /* 0x04 */, XCOFF_SYSCALL32 | XCOFF_SYSCALL64 },
877     { "svc64"       /* 0x08 */, XCOFF_SYSCALL64 },
878     { "syscall"     /* 0x10 */, XCOFF_SYSCALL32 },
879     { "syscall32"   /* 0x20 */, XCOFF_SYSCALL32 },
880     { "syscall3264" /* 0x40 */, XCOFF_SYSCALL32 | XCOFF_SYSCALL64 },
881     { "syscall64"   /* 0x80 */, XCOFF_SYSCALL64 },
882     { NULL, 0 },
883   };
884
885   *flag = 0;
886
887   for (bit = 0;; bit++) 
888     {
889       string = s[bit].syscall_string;
890       if (string == NULL) 
891         return -1;
892
893       if (0 == strcmp (input, string)) 
894         {
895           if (1 << bit & syscall_mask) 
896             {
897               *flag = s[bit].flag;
898               return 1;
899             } 
900           else 
901             {
902               return 0;
903             }
904         }
905     }
906   /* should not be here */
907   return -1;
908 }
909
910 /* Read an import or export file.  For an import file, this is called
911    by the before_allocation emulation routine.  For an export file,
912    this is called by the parse_args emulation routine.  */
913
914 static void
915 gld${EMULATION_NAME}_read_file (filename, import)
916      const char *filename;
917      boolean import;
918 {
919   struct obstack *o;
920   FILE *f;
921   int lineno;
922   int c;
923   boolean keep;
924   const char *imppath;
925   const char *impfile;
926   const char *impmember;
927
928   o = (struct obstack *) xmalloc (sizeof (struct obstack));
929   obstack_specify_allocation (o, 0, 0, xmalloc, gld${EMULATION_NAME}_free);
930
931   f = fopen (filename, FOPEN_RT);
932   if (f == NULL)
933     {
934       bfd_set_error (bfd_error_system_call);
935       einfo ("%F%s: %E\n", filename);
936     }
937
938   keep = false;
939
940   imppath = NULL;
941   impfile = NULL;
942   impmember = NULL;
943
944   lineno = 0;
945
946   /* Default to 32 and 64 bit mode
947      symbols at top of /lib/syscalls.exp do not have a mode modifier and they
948      are not repeated, assume 64 bit routines also want to use them.
949      See the routine change_symbol_mode for more information.  */
950
951   symbol_mode = 0x04;
952
953   while ((c = getc (f)) != EOF)
954     {
955       char *s;
956       char *symname;
957       unsigned int syscall_flag = 0;
958       bfd_vma address;
959       struct bfd_link_hash_entry *h;
960
961       if (c != '\n')
962         {
963           obstack_1grow (o, c);
964           continue;
965         }
966
967       obstack_1grow (o, '\0');
968       ++lineno;
969
970       s = (char *) obstack_base (o);
971       while (ISSPACE (*s))
972         ++s;
973       if (*s == '\0'
974           || *s == '*'
975           || change_symbol_mode (s)
976           || (*s == '#' && s[1] == ' ')
977           || (!import && *s == '#' && s[1] == '!'))
978         {
979           obstack_free (o, obstack_base (o));
980           continue;
981         }
982
983       if (*s == '#' && s[1] == '!')
984         {
985           s += 2;
986           while (ISSPACE (*s))
987             ++s;
988           if (*s == '\0')
989             {
990               imppath = NULL;
991               impfile = NULL;
992               impmember = NULL;
993               obstack_free (o, obstack_base (o));
994             }
995           else if (*s == '(')
996             einfo ("%F%s%d: #! ([member]) is not supported in import files\n",
997                    filename, lineno);
998           else
999             {
1000               char cs;
1001               char *file;
1002
1003               (void) obstack_finish (o);
1004               keep = true;
1005               imppath = s;
1006               file = NULL;
1007               while (!ISSPACE (*s) && *s != '(' && *s != '\0')
1008                 {
1009                   if (*s == '/')
1010                     file = s + 1;
1011                   ++s;
1012                 }
1013               if (file != NULL)
1014                 {
1015                   file[-1] = '\0';
1016                   impfile = file;
1017                   if (imppath == file - 1)
1018                     imppath = "/";
1019                 }
1020               else
1021                 {
1022                   impfile = imppath;
1023                   imppath = "";
1024                 }
1025               cs = *s;
1026               *s = '\0';
1027               while (ISSPACE (cs))
1028                 {
1029                   ++s;
1030                   cs = *s;
1031                 }
1032               if (cs != '(')
1033                 {
1034                   impmember = "";
1035                   if (cs != '\0')
1036                     einfo ("%s:%d: warning: syntax error in import file\n",
1037                            filename, lineno);
1038                 }
1039               else
1040                 {
1041                   ++s;
1042                   impmember = s;
1043                   while (*s != ')' && *s != '\0')
1044                     ++s;
1045                   if (*s == ')')
1046                     *s = '\0';
1047                   else
1048                     einfo ("%s:%d: warning: syntax error in import file\n",
1049                            filename, lineno);
1050                 }
1051             }
1052
1053           continue;
1054         }
1055
1056       if (symbol_mode & symbol_mode_mask)
1057         {
1058           /* This is a symbol to be imported or exported.  */
1059           symname = s;
1060           syscall_flag = 0;
1061           address = (bfd_vma) -1;
1062
1063           while (!ISSPACE (*s) && *s != '\0')
1064             ++s;
1065           if (*s != '\0')
1066             {
1067               char *se;
1068
1069               *s++ = '\0';
1070
1071               while (ISSPACE (*s))
1072                 ++s;
1073
1074               se = s;
1075               while (!ISSPACE (*se) && *se != '\0')
1076                 ++se;
1077               if (*se != '\0')
1078                 {
1079                   *se++ = '\0';
1080                   while (ISSPACE (*se))
1081                     ++se;
1082                   if (*se != '\0')
1083                     einfo ("%s%d: warning: syntax error in import/export file\n",
1084                            filename, lineno);
1085                 }
1086
1087               if (s != se)
1088                 {
1089                   int status;
1090                   char *end;
1091
1092                   status = is_syscall (s, &syscall_flag);
1093               
1094                   if (0 > status) 
1095                     {
1096                       /* not a system call, check for address */
1097                       address = strtoul (s, &end, 0);
1098                       if (*end != '\0')
1099                         {
1100                           einfo ("%s:%d: warning: syntax error in import/export file\n",
1101                                  filename, lineno);
1102                           
1103                         }
1104                     }
1105                 }
1106             }
1107
1108           if (!import)
1109             {
1110               struct export_symbol_list *n;
1111
1112               ldlang_add_undef (symname);
1113               n = ((struct export_symbol_list *)
1114                    xmalloc (sizeof (struct export_symbol_list)));
1115               n->next = export_symbols;
1116               n->name = xstrdup (symname);
1117               export_symbols = n;
1118             }
1119           else
1120             {
1121               h = bfd_link_hash_lookup (link_info.hash, symname, false, false,
1122                                         true);
1123               if (h == NULL || h->type == bfd_link_hash_new)
1124                 {
1125                   /* We can just ignore attempts to import an unreferenced
1126                      symbol.  */
1127                 }
1128               else
1129                 {
1130                   if (!bfd_xcoff_import_symbol (output_bfd, &link_info, h,
1131                                                 address, imppath, impfile,
1132                                                 impmember, syscall_flag))
1133                     einfo ("%X%s:%d: failed to import symbol %s: %E\n",
1134                            filename, lineno, symname);
1135                 }
1136             }
1137         }
1138       obstack_free (o, obstack_base (o));
1139     }
1140
1141   if (obstack_object_size (o) > 0)
1142     {
1143       einfo ("%s:%d: warning: ignoring unterminated last line\n",
1144              filename, lineno);
1145       obstack_free (o, obstack_base (o));
1146     }
1147
1148   if (!keep)
1149     {
1150       obstack_free (o, NULL);
1151       free (o);
1152     }
1153 }
1154
1155 /* This routine saves us from worrying about declaring free.  */
1156
1157 static void
1158 gld${EMULATION_NAME}_free (p)
1159      PTR p;
1160 {
1161   free (p);
1162 }
1163
1164 /* This is called by the before_allocation routine via
1165    lang_for_each_statement.  It looks for relocations and assignments
1166    to symbols.  */
1167
1168 static void
1169 gld${EMULATION_NAME}_find_relocs (s)
1170      lang_statement_union_type *s;
1171 {
1172   if (s->header.type == lang_reloc_statement_enum)
1173     {
1174       lang_reloc_statement_type *rs;
1175
1176       rs = &s->reloc_statement;
1177       if (rs->name == NULL)
1178         einfo ("%F%P: only relocations against symbols are permitted\n");
1179       if (!bfd_xcoff_link_count_reloc (output_bfd, &link_info, rs->name))
1180         einfo ("%F%P: bfd_xcoff_link_count_reloc failed: %E\n");
1181     }
1182
1183   if (s->header.type == lang_assignment_statement_enum)
1184     gld${EMULATION_NAME}_find_exp_assignment (s->assignment_statement.exp);
1185 }
1186
1187 /* Look through an expression for an assignment statement.  */
1188
1189 static void
1190 gld${EMULATION_NAME}_find_exp_assignment (exp)
1191      etree_type *exp;
1192 {
1193   struct bfd_link_hash_entry *h;
1194
1195   switch (exp->type.node_class)
1196     {
1197     case etree_provide:
1198       h = bfd_link_hash_lookup (link_info.hash, exp->assign.dst,
1199                                 false, false, false);
1200       if (h == NULL)
1201         break;
1202       /* Fall through.  */
1203     case etree_assign:
1204       if (strcmp (exp->assign.dst, ".") != 0)
1205         {
1206           if (!bfd_xcoff_record_link_assignment (output_bfd, &link_info,
1207                                                  exp->assign.dst))
1208             einfo ("%P%F: failed to record assignment to %s: %E\n",
1209                    exp->assign.dst);
1210         }
1211       gld${EMULATION_NAME}_find_exp_assignment (exp->assign.src);
1212       break;
1213
1214     case etree_binary:
1215       gld${EMULATION_NAME}_find_exp_assignment (exp->binary.lhs);
1216       gld${EMULATION_NAME}_find_exp_assignment (exp->binary.rhs);
1217       break;
1218
1219     case etree_trinary:
1220       gld${EMULATION_NAME}_find_exp_assignment (exp->trinary.cond);
1221       gld${EMULATION_NAME}_find_exp_assignment (exp->trinary.lhs);
1222       gld${EMULATION_NAME}_find_exp_assignment (exp->trinary.rhs);
1223       break;
1224
1225     case etree_unary:
1226       gld${EMULATION_NAME}_find_exp_assignment (exp->unary.child);
1227       break;
1228
1229     default:
1230       break;
1231     }
1232 }
1233
1234 static char *
1235 gld${EMULATION_NAME}_get_script (isfile)
1236      int *isfile;
1237 EOF
1238
1239 if test -n "$COMPILE_IN"
1240 then
1241 # Scripts compiled in.
1242
1243 # sed commands to quote an ld script as a C string.
1244 sc="-f ${srcdir}/emultempl/ostring.sed"
1245
1246 cat >>e${EMULATION_NAME}.c <<EOF
1247 {
1248   *isfile = 0;
1249
1250   if (link_info.relocateable == true && config.build_constructors == true)
1251     return
1252 EOF
1253 sed $sc ldscripts/${EMULATION_NAME}.xu                     >> e${EMULATION_NAME}.c
1254 echo '  ; else if (link_info.relocateable == true) return' >> e${EMULATION_NAME}.c
1255 sed $sc ldscripts/${EMULATION_NAME}.xr                     >> e${EMULATION_NAME}.c
1256 echo '  ; else if (!config.text_read_only) return'         >> e${EMULATION_NAME}.c
1257 sed $sc ldscripts/${EMULATION_NAME}.xbn                    >> e${EMULATION_NAME}.c
1258 echo '  ; else if (!config.magic_demand_paged) return'     >> e${EMULATION_NAME}.c
1259 sed $sc ldscripts/${EMULATION_NAME}.xn                     >> e${EMULATION_NAME}.c
1260 echo '  ; else return'                                     >> e${EMULATION_NAME}.c
1261 sed $sc ldscripts/${EMULATION_NAME}.x                      >> e${EMULATION_NAME}.c
1262 echo '; }'                                                 >> e${EMULATION_NAME}.c
1263
1264 else
1265 # Scripts read from the filesystem.
1266
1267 cat >>e${EMULATION_NAME}.c <<EOF
1268 {
1269   *isfile = 1;
1270
1271   if (link_info.relocateable == true && config.build_constructors == true)
1272     return "ldscripts/${EMULATION_NAME}.xu";
1273   else if (link_info.relocateable == true)
1274     return "ldscripts/${EMULATION_NAME}.xr";
1275   else if (!config.text_read_only)
1276     return "ldscripts/${EMULATION_NAME}.xbn";
1277   else if (!config.magic_demand_paged)
1278     return "ldscripts/${EMULATION_NAME}.xn";
1279   else
1280     return "ldscripts/${EMULATION_NAME}.x";
1281 }
1282 EOF
1283
1284 fi
1285
1286 cat >>e${EMULATION_NAME}.c <<EOF
1287
1288 static void 
1289 gld${EMULATION_NAME}_create_output_section_statements()
1290 {
1291   /* __rtinit */
1292   if ((bfd_get_flavour (output_bfd) == bfd_target_xcoff_flavour) 
1293       && (link_info.init_function != NULL  
1294           || link_info.fini_function != NULL
1295           || rtld == true))
1296     {
1297       initfini_file = lang_add_input_file ("initfini",
1298                                            lang_input_file_is_file_enum,
1299                                            NULL);
1300       
1301       initfini_file->the_bfd = bfd_create ("initfini", output_bfd);
1302       if (initfini_file->the_bfd == NULL
1303           || ! bfd_set_arch_mach (initfini_file->the_bfd,
1304                                   bfd_get_arch (output_bfd),
1305                                   bfd_get_mach (output_bfd)))
1306         {
1307           einfo ("%X%P: can not create BFD %E\n");
1308           return;
1309         }
1310       
1311       /* Call backend to fill in the rest */
1312       if (false == bfd_xcoff_link_generate_rtinit (initfini_file->the_bfd, 
1313                                                    link_info.init_function, 
1314                                                    link_info.fini_function,
1315                                                    rtld))
1316         {
1317           einfo ("%X%P: can not create BFD %E\n");
1318           return;
1319         }
1320
1321       /* __rtld defined in /lib/librtl.a */
1322       if (true == rtld) 
1323         lang_add_input_file ("rtl", lang_input_file_is_l_enum, NULL);
1324     }
1325 }
1326
1327 struct ld_emulation_xfer_struct ld_${EMULATION_NAME}_emulation = {
1328   gld${EMULATION_NAME}_before_parse,
1329   syslib_default,
1330   hll_default,
1331   after_parse_default,
1332   gld${EMULATION_NAME}_after_open,
1333   after_allocation_default,
1334   set_output_arch_default,
1335   choose_target,
1336   gld${EMULATION_NAME}_before_allocation,
1337   gld${EMULATION_NAME}_get_script,
1338   "${EMULATION_NAME}",
1339   "${OUTPUT_FORMAT}",
1340   0,                            /* finish */
1341   gld${EMULATION_NAME}_create_output_section_statements,
1342   0,                            /* open_dynamic_archive */
1343   0,                            /* place_orphan */
1344   0,                            /* set_symbols */
1345   gld${EMULATION_NAME}_parse_args,
1346   gld${EMULATION_NAME}_unrecognized_file,
1347   NULL,                         /* list_options */
1348   NULL,                         /* recognized_file */
1349   NULL,                         /* find potential_libraries */
1350 };
1351 EOF