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