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