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