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