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