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