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