bfd/
[platform/upstream/binutils.git] / ld / emultempl / elf32.em
1 # This shell script emits a C file. -*- C -*-
2 # It does some substitutions.
3 # This file is now misnamed, because it supports both 32 bit and 64 bit
4 # ELF emulations.
5 test -z "${ELFSIZE}" && ELFSIZE=32
6 if [ -z "$MACHINE" ]; then
7   OUTPUT_ARCH=${ARCH}
8 else
9   OUTPUT_ARCH=${ARCH}:${MACHINE}
10 fi
11 cat >e${EMULATION_NAME}.c <<EOF
12 /* This file is is generated by a shell script.  DO NOT EDIT! */
13
14 /* ${ELFSIZE} bit ELF emulation code for ${EMULATION_NAME}
15    Copyright 1991, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
16    2002, 2003, 2004, 2005 Free Software Foundation, Inc.
17    Written by Steve Chamberlain <sac@cygnus.com>
18    ELF support by Ian Lance Taylor <ian@cygnus.com>
19
20 This file is part of GLD, the Gnu Linker.
21
22 This program is free software; you can redistribute it and/or modify
23 it under the terms of the GNU General Public License as published by
24 the Free Software Foundation; either version 2 of the License, or
25 (at your option) any later version.
26
27 This program is distributed in the hope that it will be useful,
28 but WITHOUT ANY WARRANTY; without even the implied warranty of
29 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
30 GNU General Public License for more details.
31
32 You should have received a copy of the GNU General Public License
33 along with this program; if not, write to the Free Software
34 Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.  */
35
36 #define TARGET_IS_${EMULATION_NAME}
37
38 #include "config.h"
39 #include "bfd.h"
40 #include "sysdep.h"
41 #include "libiberty.h"
42 #include "safe-ctype.h"
43 #include "getopt.h"
44
45 #include "bfdlink.h"
46
47 #include "ld.h"
48 #include "ldmain.h"
49 #include "ldmisc.h"
50 #include "ldexp.h"
51 #include "ldlang.h"
52 #include "ldfile.h"
53 #include "ldemul.h"
54 #include <ldgram.h>
55 #include "elf/common.h"
56
57 /* Declare functions used by various EXTRA_EM_FILEs.  */
58 static void gld${EMULATION_NAME}_before_parse (void);
59 static void gld${EMULATION_NAME}_after_open (void);
60 static void gld${EMULATION_NAME}_provide_init_fini_syms (void);
61 static void gld${EMULATION_NAME}_before_allocation (void);
62 static bfd_boolean gld${EMULATION_NAME}_place_orphan
63   (lang_input_statement_type *file, asection *s);
64 static void gld${EMULATION_NAME}_layout_sections_again (void);
65 static void gld${EMULATION_NAME}_finish (void) ATTRIBUTE_UNUSED;
66
67 EOF
68
69 if [ "x${USE_LIBPATH}" = xyes ] ; then
70   case ${target} in
71     *-*-linux-* | *-*-k*bsd*-*)
72   cat >>e${EMULATION_NAME}.c <<EOF
73 #ifdef HAVE_GLOB
74 #include <glob.h>
75 #endif
76 EOF
77     ;;
78   esac
79 fi
80
81 # Import any needed special functions and/or overrides.
82 #
83 if test -n "$EXTRA_EM_FILE" ; then
84 . ${srcdir}/emultempl/${EXTRA_EM_FILE}.em
85 fi
86
87 # Functions in this file can be overridden by setting the LDEMUL_* shell
88 # variables.  If the name of the overriding function is the same as is
89 # defined in this file, then don't output this file's version.
90 # If a different overriding name is given then output the standard function
91 # as presumably it is called from the overriding function.
92 #
93 if test x"$LDEMUL_BEFORE_PARSE" != xgld"$EMULATION_NAME"_before_parse; then
94 cat >>e${EMULATION_NAME}.c <<EOF
95
96 static void
97 gld${EMULATION_NAME}_before_parse (void)
98 {
99   ldfile_set_output_arch ("${OUTPUT_ARCH}", bfd_arch_`echo ${ARCH} | sed -e 's/:.*//'`);
100   config.dynamic_link = ${DYNAMIC_LINK-TRUE};
101   config.has_shared = `if test -n "$GENERATE_SHLIB_SCRIPT" ; then echo TRUE ; else echo FALSE ; fi`;
102 }
103
104 EOF
105 fi
106
107 if test x"$LDEMUL_RECOGNIZED_FILE" != xgld"${EMULATION_NAME}"_load_symbols; then
108 cat >>e${EMULATION_NAME}.c <<EOF
109 /* Handle as_needed DT_NEEDED.  */
110
111 static bfd_boolean
112 gld${EMULATION_NAME}_load_symbols (lang_input_statement_type *entry)
113 {
114   int class = 0;
115
116   /* Tell the ELF linker that we don't want the output file to have a
117      DT_NEEDED entry for this file, unless it is used to resolve
118      references in a regular object.  */
119   if (entry->as_needed)
120     class = DYN_AS_NEEDED;
121
122   /* Tell the ELF linker that we don't want the output file to have a
123      DT_NEEDED entry for any dynamic library in DT_NEEDED tags from
124      this file at all.  */
125   if (!entry->add_needed)
126     class |= DYN_NO_ADD_NEEDED;
127
128   if (!class
129       || (bfd_get_file_flags (entry->the_bfd) & DYNAMIC) == 0)
130     return FALSE;
131
132   bfd_elf_set_dyn_lib_class (entry->the_bfd, class);
133
134   /* Continue on with normal load_symbols processing.  */
135   return FALSE;
136 }
137 EOF
138 fi
139
140 cat >>e${EMULATION_NAME}.c <<EOF
141
142 /* These variables are required to pass information back and forth
143    between after_open and check_needed and stat_needed and vercheck.  */
144
145 static struct bfd_link_needed_list *global_needed;
146 static struct stat global_stat;
147 static bfd_boolean global_found;
148 static struct bfd_link_needed_list *global_vercheck_needed;
149 static bfd_boolean global_vercheck_failed;
150
151
152 /* On Linux, it's possible to have different versions of the same
153    shared library linked against different versions of libc.  The
154    dynamic linker somehow tags which libc version to use in
155    /etc/ld.so.cache, and, based on the libc that it sees in the
156    executable, chooses which version of the shared library to use.
157
158    We try to do a similar check here by checking whether this shared
159    library needs any other shared libraries which may conflict with
160    libraries we have already included in the link.  If it does, we
161    skip it, and try to find another shared library farther on down the
162    link path.
163
164    This is called via lang_for_each_input_file.
165    GLOBAL_VERCHECK_NEEDED is the list of objects needed by the object
166    which we are checking.  This sets GLOBAL_VERCHECK_FAILED if we find
167    a conflicting version.  */
168
169 static void
170 gld${EMULATION_NAME}_vercheck (lang_input_statement_type *s)
171 {
172   const char *soname;
173   struct bfd_link_needed_list *l;
174
175   if (global_vercheck_failed)
176     return;
177   if (s->the_bfd == NULL
178       || (bfd_get_file_flags (s->the_bfd) & DYNAMIC) == 0)
179     return;
180
181   soname = bfd_elf_get_dt_soname (s->the_bfd);
182   if (soname == NULL)
183     soname = lbasename (bfd_get_filename (s->the_bfd));
184
185   for (l = global_vercheck_needed; l != NULL; l = l->next)
186     {
187       const char *suffix;
188
189       if (strcmp (soname, l->name) == 0)
190         {
191           /* Probably can't happen, but it's an easy check.  */
192           continue;
193         }
194
195       if (strchr (l->name, '/') != NULL)
196         continue;
197
198       suffix = strstr (l->name, ".so.");
199       if (suffix == NULL)
200         continue;
201
202       suffix += sizeof ".so." - 1;
203
204       if (strncmp (soname, l->name, suffix - l->name) == 0)
205         {
206           /* Here we know that S is a dynamic object FOO.SO.VER1, and
207              the object we are considering needs a dynamic object
208              FOO.SO.VER2, and VER1 and VER2 are different.  This
209              appears to be a version mismatch, so we tell the caller
210              to try a different version of this library.  */
211           global_vercheck_failed = TRUE;
212           return;
213         }
214     }
215 }
216
217
218 /* See if an input file matches a DT_NEEDED entry by running stat on
219    the file.  */
220
221 static void
222 gld${EMULATION_NAME}_stat_needed (lang_input_statement_type *s)
223 {
224   struct stat st;
225   const char *suffix;
226   const char *soname;
227
228   if (global_found)
229     return;
230   if (s->the_bfd == NULL)
231     return;
232   if (s->as_needed
233       && (bfd_elf_get_dyn_lib_class (s->the_bfd) & DYN_AS_NEEDED) != 0)
234     return;
235
236   if (bfd_stat (s->the_bfd, &st) != 0)
237     {
238       einfo ("%P:%B: bfd_stat failed: %E\n", s->the_bfd);
239       return;
240     }
241
242   /* Some operating systems, e.g. Windows, do not provide a meaningful
243      st_ino; they always set it to zero.  (Windows does provide a
244      meaningful st_dev.)  Do not indicate a duplicate library in that
245      case.  While there is no guarantee that a system that provides
246      meaningful inode numbers will never set st_ino to zero, this is
247      merely an optimization, so we do not need to worry about false
248      negatives.  */
249   if (st.st_dev == global_stat.st_dev
250       && st.st_ino == global_stat.st_ino
251       && st.st_ino != 0)
252     {
253       global_found = TRUE;
254       return;
255     }
256
257   /* We issue a warning if it looks like we are including two
258      different versions of the same shared library.  For example,
259      there may be a problem if -lc picks up libc.so.6 but some other
260      shared library has a DT_NEEDED entry of libc.so.5.  This is a
261      heuristic test, and it will only work if the name looks like
262      NAME.so.VERSION.  FIXME: Depending on file names is error-prone.
263      If we really want to issue warnings about mixing version numbers
264      of shared libraries, we need to find a better way.  */
265
266   if (strchr (global_needed->name, '/') != NULL)
267     return;
268   suffix = strstr (global_needed->name, ".so.");
269   if (suffix == NULL)
270     return;
271   suffix += sizeof ".so." - 1;
272
273   soname = bfd_elf_get_dt_soname (s->the_bfd);
274   if (soname == NULL)
275     soname = lbasename (s->filename);
276
277   if (strncmp (soname, global_needed->name, suffix - global_needed->name) == 0)
278     einfo ("%P: warning: %s, needed by %B, may conflict with %s\n",
279            global_needed->name, global_needed->by, soname);
280 }
281
282 struct dt_needed
283 {
284   bfd *by;
285   const char *name;
286 };
287
288 /* This function is called for each possible name for a dynamic object
289    named by a DT_NEEDED entry.  The FORCE parameter indicates whether
290    to skip the check for a conflicting version.  */
291
292 static bfd_boolean
293 gld${EMULATION_NAME}_try_needed (struct dt_needed *needed,
294                                  int force)
295 {
296   bfd *abfd;
297   const char *name = needed->name;
298   const char *soname;
299   int class;
300
301   abfd = bfd_openr (name, bfd_get_target (output_bfd));
302   if (abfd == NULL)
303     return FALSE;
304   if (! bfd_check_format (abfd, bfd_object))
305     {
306       bfd_close (abfd);
307       return FALSE;
308     }
309   if ((bfd_get_file_flags (abfd) & DYNAMIC) == 0)
310     {
311       bfd_close (abfd);
312       return FALSE;
313     }
314
315   /* For DT_NEEDED, they have to match.  */
316   if (abfd->xvec != output_bfd->xvec)
317     {
318       bfd_close (abfd);
319       return FALSE;
320     }
321
322   /* Check whether this object would include any conflicting library
323      versions.  If FORCE is set, then we skip this check; we use this
324      the second time around, if we couldn't find any compatible
325      instance of the shared library.  */
326
327   if (! force)
328     {
329       struct bfd_link_needed_list *needed;
330
331       if (! bfd_elf_get_bfd_needed_list (abfd, &needed))
332         einfo ("%F%P:%B: bfd_elf_get_bfd_needed_list failed: %E\n", abfd);
333
334       if (needed != NULL)
335         {
336           global_vercheck_needed = needed;
337           global_vercheck_failed = FALSE;
338           lang_for_each_input_file (gld${EMULATION_NAME}_vercheck);
339           if (global_vercheck_failed)
340             {
341               bfd_close (abfd);
342               /* Return FALSE to force the caller to move on to try
343                  another file on the search path.  */
344               return FALSE;
345             }
346
347           /* But wait!  It gets much worse.  On Linux, if a shared
348              library does not use libc at all, we are supposed to skip
349              it the first time around in case we encounter a shared
350              library later on with the same name which does use the
351              version of libc that we want.  This is much too horrible
352              to use on any system other than Linux.  */
353
354 EOF
355 case ${target} in
356   *-*-linux-* | *-*-k*bsd*-*)
357     cat >>e${EMULATION_NAME}.c <<EOF
358           {
359             struct bfd_link_needed_list *l;
360
361             for (l = needed; l != NULL; l = l->next)
362               if (strncmp (l->name, "libc.so", 7) == 0)
363                 break;
364             if (l == NULL)
365               {
366                 bfd_close (abfd);
367                 return FALSE;
368               }
369           }
370
371 EOF
372     ;;
373 esac
374 cat >>e${EMULATION_NAME}.c <<EOF
375         }
376     }
377
378   /* We've found a dynamic object matching the DT_NEEDED entry.  */
379
380   /* We have already checked that there is no other input file of the
381      same name.  We must now check again that we are not including the
382      same file twice.  We need to do this because on many systems
383      libc.so is a symlink to, e.g., libc.so.1.  The SONAME entry will
384      reference libc.so.1.  If we have already included libc.so, we
385      don't want to include libc.so.1 if they are the same file, and we
386      can only check that using stat.  */
387
388   if (bfd_stat (abfd, &global_stat) != 0)
389     einfo ("%F%P:%B: bfd_stat failed: %E\n", abfd);
390
391   /* First strip off everything before the last '/'.  */
392   soname = lbasename (abfd->filename);
393
394   if (trace_file_tries)
395     info_msg (_("found %s at %s\n"), soname, name);
396
397   global_found = FALSE;
398   lang_for_each_input_file (gld${EMULATION_NAME}_stat_needed);
399   if (global_found)
400     {
401       /* Return TRUE to indicate that we found the file, even though
402          we aren't going to do anything with it.  */
403       return TRUE;
404     }
405
406   /* Specify the soname to use.  */
407   bfd_elf_set_dt_needed_name (abfd, soname);
408
409   /* Tell the ELF linker that we don't want the output file to have a
410      DT_NEEDED entry for this file, unless it is used to resolve
411      references in a regular object.  */
412   class = DYN_DT_NEEDED;
413
414   /* Tell the ELF linker that we don't want the output file to have a
415      DT_NEEDED entry for this file at all if the entry is from a file
416      with DYN_NO_ADD_NEEDED.  */
417   if (needed->by != NULL
418       && (bfd_elf_get_dyn_lib_class (needed->by) & DYN_NO_ADD_NEEDED) != 0)
419     class |= DYN_NO_NEEDED | DYN_NO_ADD_NEEDED;
420
421   bfd_elf_set_dyn_lib_class (abfd, class);
422
423   /* Add this file into the symbol table.  */
424   if (! bfd_link_add_symbols (abfd, &link_info))
425     einfo ("%F%B: could not read symbols: %E\n", abfd);
426
427   return TRUE;
428 }
429
430
431 /* Search for a needed file in a path.  */
432
433 static bfd_boolean
434 gld${EMULATION_NAME}_search_needed (const char *path,
435                                     struct dt_needed *n, int force)
436 {
437   const char *s;
438   const char *name = n->name;
439   size_t len;
440   struct dt_needed needed;
441
442   if (name[0] == '/')
443     return gld${EMULATION_NAME}_try_needed (n, force);
444
445   if (path == NULL || *path == '\0')
446     return FALSE;
447
448   needed.by = n->by;
449   needed.name = n->name;
450
451   len = strlen (name);
452   while (1)
453     {
454       char *filename, *sset;
455
456       s = strchr (path, ':');
457       if (s == NULL)
458         s = path + strlen (path);
459
460       filename = (char *) xmalloc (s - path + len + 2);
461       if (s == path)
462         sset = filename;
463       else
464         {
465           memcpy (filename, path, s - path);
466           filename[s - path] = '/';
467           sset = filename + (s - path) + 1;
468         }
469       strcpy (sset, name);
470
471       needed.name = filename;
472       if (gld${EMULATION_NAME}_try_needed (&needed, force))
473         return TRUE;
474
475       free (filename);
476
477       if (*s == '\0')
478         break;
479       path = s + 1;
480     }
481
482   return FALSE;
483 }
484
485 EOF
486 if [ "x${USE_LIBPATH}" = xyes ] ; then
487   cat >>e${EMULATION_NAME}.c <<EOF
488
489 /* Add the sysroot to every entry in a colon-separated path.  */
490
491 static char *
492 gld${EMULATION_NAME}_add_sysroot (const char *path)
493 {
494   int len, colons, i;
495   char *ret, *p;
496
497   len = strlen (path);
498   colons = 0;
499   i = 0;
500   while (path[i])
501     if (path[i++] == ':')
502       colons++;
503
504   if (path[i])
505     colons++;
506
507   len = len + (colons + 1) * strlen (ld_sysroot);
508   ret = xmalloc (len + 1);
509   strcpy (ret, ld_sysroot);
510   p = ret + strlen (ret);
511   i = 0;
512   while (path[i])
513     if (path[i] == ':')
514       {
515         *p++ = path[i++];
516         strcpy (p, ld_sysroot);
517         p = p + strlen (p);
518       }
519     else
520       *p++ = path[i++];
521
522   *p = 0;
523   return ret;
524 }
525
526 EOF
527   case ${target} in
528     *-*-linux-* | *-*-k*bsd*-*)
529       cat >>e${EMULATION_NAME}.c <<EOF
530 /* For a native linker, check the file /etc/ld.so.conf for directories
531    in which we may find shared libraries.  /etc/ld.so.conf is really
532    only meaningful on Linux.  */
533
534 struct gld${EMULATION_NAME}_ld_so_conf
535 {
536   char *path;
537   size_t len, alloc;
538 };
539
540 static void
541 gld${EMULATION_NAME}_parse_ld_so_conf
542      (struct gld${EMULATION_NAME}_ld_so_conf *info, const char *filename);
543
544 static void
545 gld${EMULATION_NAME}_parse_ld_so_conf_include
546      (struct gld${EMULATION_NAME}_ld_so_conf *info, const char *filename,
547       const char *pattern)
548 {
549   char *newp = NULL;
550 #ifdef HAVE_GLOB
551   glob_t gl;
552 #endif
553
554   if (pattern[0] != '/')
555     {
556       char *p = strrchr (filename, '/');
557       size_t patlen = strlen (pattern) + 1;
558
559       newp = xmalloc (p - filename + 1 + patlen);
560       memcpy (newp, filename, p - filename + 1);
561       memcpy (newp + (p - filename + 1), pattern, patlen);
562       pattern = newp;
563     }
564
565 #ifdef HAVE_GLOB
566   if (glob (pattern, 0, NULL, &gl) == 0)
567     {
568       size_t i;
569
570       for (i = 0; i < gl.gl_pathc; ++i)
571         gld${EMULATION_NAME}_parse_ld_so_conf (info, gl.gl_pathv[i]);
572       globfree (&gl);
573     }
574 #else
575   /* If we do not have glob, treat the pattern as a literal filename.  */
576   gld${EMULATION_NAME}_parse_ld_so_conf (info, pattern);
577 #endif
578
579   if (newp)
580     free (newp);
581 }
582
583 static void
584 gld${EMULATION_NAME}_parse_ld_so_conf
585      (struct gld${EMULATION_NAME}_ld_so_conf *info, const char *filename)
586 {
587   FILE *f = fopen (filename, FOPEN_RT);
588   char *line;
589   size_t linelen;
590
591   if (f == NULL)
592     return;
593
594   linelen = 256;
595   line = xmalloc (linelen);
596   do
597     {
598       char *p = line, *q;
599
600       /* Normally this would use getline(3), but we need to be portable.  */
601       while ((q = fgets (p, linelen - (p - line), f)) != NULL
602              && strlen (q) == linelen - (p - line) - 1
603              && line[linelen - 2] != '\n')
604         {
605           line = xrealloc (line, 2 * linelen);
606           p = line + linelen - 1;
607           linelen += linelen;
608         }
609
610       if (q == NULL && p == line)
611         break;
612
613       p = strchr (line, '\n');
614       if (p)
615         *p = '\0';
616
617       /* Because the file format does not know any form of quoting we
618          can search forward for the next '#' character and if found
619          make it terminating the line.  */
620       p = strchr (line, '#');
621       if (p)
622         *p = '\0';
623
624       /* Remove leading whitespace.  NUL is no whitespace character.  */
625       p = line;
626       while (*p == ' ' || *p == '\f' || *p == '\r' || *p == '\t' || *p == '\v')
627         ++p;
628
629       /* If the line is blank it is ignored.  */
630       if (p[0] == '\0')
631         continue;
632
633       if (!strncmp (p, "include", 7) && (p[7] == ' ' || p[7] == '\t'))
634         {
635           char *dir, c;
636           p += 8;
637           do
638             {
639               while (*p == ' ' || *p == '\t')
640                 ++p;
641
642               if (*p == '\0')
643                 break;
644
645               dir = p;
646
647               while (*p != ' ' && *p != '\t' && *p)
648                 ++p;
649
650               c = *p;
651               *p++ = '\0';
652               if (dir[0] != '\0')
653                 gld${EMULATION_NAME}_parse_ld_so_conf_include (info, filename,
654                                                                dir);
655             }
656           while (c != '\0');
657         }
658       else
659         {
660           char *dir = p;
661           while (*p && *p != '=' && *p != ' ' && *p != '\t' && *p != '\f'
662                  && *p != '\r' && *p != '\v')
663             ++p;
664
665           while (p != dir && p[-1] == '/')
666             --p;
667           if (info->path == NULL)
668             {
669               info->alloc = p - dir + 1 + 256;
670               info->path = xmalloc (info->alloc);
671               info->len = 0;
672             }
673           else
674             {
675               if (info->len + 1 + (p - dir) >= info->alloc)
676                 {
677                   info->alloc += p - dir + 256;
678                   info->path = xrealloc (info->path, info->alloc);
679                 }
680               info->path[info->len++] = ':';
681             }
682           memcpy (info->path + info->len, dir, p - dir);
683           info->len += p - dir;
684           info->path[info->len] = '\0';
685         }
686     }
687   while (! feof (f));
688   free (line);
689   fclose (f);
690 }
691
692 static bfd_boolean
693 gld${EMULATION_NAME}_check_ld_so_conf (const char *name, int force)
694 {
695   static bfd_boolean initialized;
696   static char *ld_so_conf;
697   struct dt_needed needed;
698
699   if (! initialized)
700     {
701       char *tmppath;
702       struct gld${EMULATION_NAME}_ld_so_conf info;
703
704       tmppath = concat (ld_sysroot, "/etc/ld.so.conf", NULL);
705       info.path = NULL;
706       info.len = info.alloc = 0;
707       gld${EMULATION_NAME}_parse_ld_so_conf (&info, tmppath);
708       free (tmppath);
709       if (info.path)
710         {
711           char *d = gld${EMULATION_NAME}_add_sysroot (info.path);
712           free (info.path);
713           ld_so_conf = d;
714         }
715       initialized = TRUE;
716     }
717
718   if (ld_so_conf == NULL)
719     return FALSE;
720
721
722   needed.by = NULL;
723   needed.name = name;
724   return gld${EMULATION_NAME}_search_needed (ld_so_conf, &needed, force);
725 }
726
727 EOF
728     # Linux
729     ;;
730   esac
731 fi
732 cat >>e${EMULATION_NAME}.c <<EOF
733
734 /* See if an input file matches a DT_NEEDED entry by name.  */
735
736 static void
737 gld${EMULATION_NAME}_check_needed (lang_input_statement_type *s)
738 {
739   if (global_found)
740     return;
741
742   /* If this input file was an as-needed entry, and wasn't found to be
743      needed at the stage it was linked, then don't say we have loaded it.  */
744   if (s->as_needed
745       && (s->the_bfd == NULL
746           || (bfd_elf_get_dyn_lib_class (s->the_bfd) & DYN_AS_NEEDED) != 0))
747     return;
748
749   if (s->filename != NULL)
750     {
751       const char *f;
752
753       if (strcmp (s->filename, global_needed->name) == 0)
754         {
755           global_found = TRUE;
756           return;
757         }
758
759       if (s->search_dirs_flag)
760         {
761           f = strrchr (s->filename, '/');
762           if (f != NULL
763               && strcmp (f + 1, global_needed->name) == 0)
764             {
765               global_found = TRUE;
766               return;
767             }
768         }
769     }
770
771   if (s->the_bfd != NULL)
772     {
773       const char *soname;
774
775       soname = bfd_elf_get_dt_soname (s->the_bfd);
776       if (soname != NULL
777           && strcmp (soname, global_needed->name) == 0)
778         {
779           global_found = TRUE;
780           return;
781         }
782     }
783 }
784
785 EOF
786
787 if test x"$LDEMUL_AFTER_OPEN" != xgld"$EMULATION_NAME"_after_open; then
788 cat >>e${EMULATION_NAME}.c <<EOF
789
790 /* This is called after all the input files have been opened.  */
791
792 static void
793 gld${EMULATION_NAME}_after_open (void)
794 {
795   struct bfd_link_needed_list *needed, *l;
796
797   /* We only need to worry about this when doing a final link.  */
798   if (link_info.relocatable || !link_info.executable)
799     return;
800
801   /* Get the list of files which appear in DT_NEEDED entries in
802      dynamic objects included in the link (often there will be none).
803      For each such file, we want to track down the corresponding
804      library, and include the symbol table in the link.  This is what
805      the runtime dynamic linker will do.  Tracking the files down here
806      permits one dynamic object to include another without requiring
807      special action by the person doing the link.  Note that the
808      needed list can actually grow while we are stepping through this
809      loop.  */
810   needed = bfd_elf_get_needed_list (output_bfd, &link_info);
811   for (l = needed; l != NULL; l = l->next)
812     {
813       struct bfd_link_needed_list *ll;
814       struct dt_needed n, nn;
815       int force;
816
817       /* If the lib that needs this one was --as-needed and wasn't
818          found to be needed, then this lib isn't needed either.  */
819       if (l->by != NULL
820           && (bfd_elf_get_dyn_lib_class (l->by) & DYN_AS_NEEDED) != 0)
821         continue;
822
823       /* If we've already seen this file, skip it.  */
824       for (ll = needed; ll != l; ll = ll->next)
825         if ((ll->by == NULL
826              || (bfd_elf_get_dyn_lib_class (ll->by) & DYN_AS_NEEDED) == 0)
827             && strcmp (ll->name, l->name) == 0)
828           break;
829       if (ll != l)
830         continue;
831
832       /* See if this file was included in the link explicitly.  */
833       global_needed = l;
834       global_found = FALSE;
835       lang_for_each_input_file (gld${EMULATION_NAME}_check_needed);
836       if (global_found)
837         continue;
838
839       n.by = l->by;
840       n.name = l->name;
841       nn.by = l->by;
842       if (trace_file_tries)
843         info_msg (_("%s needed by %B\n"), l->name, l->by);
844
845       /* We need to find this file and include the symbol table.  We
846          want to search for the file in the same way that the dynamic
847          linker will search.  That means that we want to use
848          rpath_link, rpath, then the environment variable
849          LD_LIBRARY_PATH (native only), then the DT_RPATH/DT_RUNPATH
850          entries (native only), then the linker script LIB_SEARCH_DIRS.
851          We do not search using the -L arguments.
852
853          We search twice.  The first time, we skip objects which may
854          introduce version mismatches.  The second time, we force
855          their use.  See gld${EMULATION_NAME}_vercheck comment.  */
856       for (force = 0; force < 2; force++)
857         {
858           size_t len;
859           search_dirs_type *search;
860 EOF
861 if [ "x${NATIVE}" = xyes ] ; then
862 cat >>e${EMULATION_NAME}.c <<EOF
863           const char *lib_path;
864 EOF
865 fi
866 if [ "x${USE_LIBPATH}" = xyes ] ; then
867 cat >>e${EMULATION_NAME}.c <<EOF
868           struct bfd_link_needed_list *rp;
869           int found;
870 EOF
871 fi
872 cat >>e${EMULATION_NAME}.c <<EOF
873
874           if (gld${EMULATION_NAME}_search_needed (command_line.rpath_link,
875                                                   &n, force))
876             break;
877 EOF
878 if [ "x${USE_LIBPATH}" = xyes ] ; then
879 cat >>e${EMULATION_NAME}.c <<EOF
880           if (gld${EMULATION_NAME}_search_needed (command_line.rpath,
881                                                   &n, force))
882             break;
883 EOF
884 fi
885 if [ "x${NATIVE}" = xyes ] ; then
886 cat >>e${EMULATION_NAME}.c <<EOF
887           if (command_line.rpath_link == NULL
888               && command_line.rpath == NULL)
889             {
890               lib_path = (const char *) getenv ("LD_RUN_PATH");
891               if (gld${EMULATION_NAME}_search_needed (lib_path, &n,
892                                                       force))
893                 break;
894             }
895           lib_path = (const char *) getenv ("LD_LIBRARY_PATH");
896           if (gld${EMULATION_NAME}_search_needed (lib_path, &n, force))
897             break;
898 EOF
899 fi
900 if [ "x${USE_LIBPATH}" = xyes ] ; then
901 cat >>e${EMULATION_NAME}.c <<EOF
902           found = 0;
903           rp = bfd_elf_get_runpath_list (output_bfd, &link_info);
904           for (; !found && rp != NULL; rp = rp->next)
905             {
906               char *tmpname = gld${EMULATION_NAME}_add_sysroot (rp->name);
907               found = (rp->by == l->by
908                        && gld${EMULATION_NAME}_search_needed (tmpname,
909                                                               &n,
910                                                               force));
911               free (tmpname);
912             }
913           if (found)
914             break;
915
916 EOF
917 fi
918 cat >>e${EMULATION_NAME}.c <<EOF
919           len = strlen (l->name);
920           for (search = search_head; search != NULL; search = search->next)
921             {
922               char *filename;
923
924               if (search->cmdline)
925                 continue;
926               filename = (char *) xmalloc (strlen (search->name) + len + 2);
927               sprintf (filename, "%s/%s", search->name, l->name);
928               nn.name = filename;
929               if (gld${EMULATION_NAME}_try_needed (&nn, force))
930                 break;
931               free (filename);
932             }
933           if (search != NULL)
934             break;
935 EOF
936 if [ "x${USE_LIBPATH}" = xyes ] ; then
937   case ${target} in
938     *-*-linux-* | *-*-k*bsd*-*)
939       cat >>e${EMULATION_NAME}.c <<EOF
940           if (gld${EMULATION_NAME}_check_ld_so_conf (l->name, force))
941             break;
942 EOF
943     # Linux
944     ;;
945   esac
946 fi
947 cat >>e${EMULATION_NAME}.c <<EOF
948         }
949
950       if (force < 2)
951         continue;
952
953       einfo ("%P: warning: %s, needed by %B, not found (try using -rpath or -rpath-link)\n",
954              l->name, l->by);
955     }
956 }
957
958 EOF
959 fi
960
961 cat >>e${EMULATION_NAME}.c <<EOF
962
963 /* Look through an expression for an assignment statement.  */
964
965 static void
966 gld${EMULATION_NAME}_find_exp_assignment (etree_type *exp)
967 {
968   bfd_boolean provide = FALSE;
969
970   switch (exp->type.node_class)
971     {
972     case etree_provide:
973       provide = TRUE;
974       /* Fall thru */
975     case etree_assign:
976       /* We call record_link_assignment even if the symbol is defined.
977          This is because if it is defined by a dynamic object, we
978          actually want to use the value defined by the linker script,
979          not the value from the dynamic object (because we are setting
980          symbols like etext).  If the symbol is defined by a regular
981          object, then, as it happens, calling record_link_assignment
982          will do no harm.  */
983       if (strcmp (exp->assign.dst, ".") != 0)
984         {
985           if (!bfd_elf_record_link_assignment (&link_info, exp->assign.dst,
986                                                provide))
987             einfo ("%P%F: failed to record assignment to %s: %E\n",
988                    exp->assign.dst);
989         }
990       gld${EMULATION_NAME}_find_exp_assignment (exp->assign.src);
991       break;
992
993     case etree_binary:
994       gld${EMULATION_NAME}_find_exp_assignment (exp->binary.lhs);
995       gld${EMULATION_NAME}_find_exp_assignment (exp->binary.rhs);
996       break;
997
998     case etree_trinary:
999       gld${EMULATION_NAME}_find_exp_assignment (exp->trinary.cond);
1000       gld${EMULATION_NAME}_find_exp_assignment (exp->trinary.lhs);
1001       gld${EMULATION_NAME}_find_exp_assignment (exp->trinary.rhs);
1002       break;
1003
1004     case etree_unary:
1005       gld${EMULATION_NAME}_find_exp_assignment (exp->unary.child);
1006       break;
1007
1008     default:
1009       break;
1010     }
1011 }
1012
1013
1014 /* This is called by the before_allocation routine via
1015    lang_for_each_statement.  It locates any assignment statements, and
1016    tells the ELF backend about them, in case they are assignments to
1017    symbols which are referred to by dynamic objects.  */
1018
1019 static void
1020 gld${EMULATION_NAME}_find_statement_assignment (lang_statement_union_type *s)
1021 {
1022   if (s->header.type == lang_assignment_statement_enum)
1023     gld${EMULATION_NAME}_find_exp_assignment (s->assignment_statement.exp);
1024 }
1025
1026 EOF
1027
1028 if test x"$LDEMUL_BEFORE_ALLOCATION" != xgld"$EMULATION_NAME"_before_allocation; then
1029   if test x"${ELF_INTERPRETER_NAME+set}" = xset; then
1030     ELF_INTERPRETER_SET_DEFAULT="
1031   if (sinterp != NULL)
1032     {
1033       sinterp->contents = (unsigned char *) ${ELF_INTERPRETER_NAME};
1034       sinterp->size = strlen ((char *) sinterp->contents) + 1;
1035     }
1036
1037 "
1038   else
1039     ELF_INTERPRETER_SET_DEFAULT=
1040   fi
1041 cat >>e${EMULATION_NAME}.c <<EOF
1042
1043 static void
1044 gld${EMULATION_NAME}_provide_bound_symbols (const char *sec,
1045                                             const char *start,
1046                                             const char *end)
1047 {
1048   asection *s = bfd_get_section_by_name (output_bfd, sec);
1049   _bfd_elf_provide_section_bound_symbols (&link_info, s, start, end);
1050 }
1051
1052 /* If not building a shared library, provide
1053
1054    __preinit_array_start
1055    __preinit_array_end
1056    __init_array_start
1057    __init_array_end
1058    __fini_array_start
1059    __fini_array_end
1060
1061    They are set here rather than via PROVIDE in the linker
1062    script, because using PROVIDE inside an output section
1063    statement results in unnecessary output sections.  Using
1064    PROVIDE outside an output section statement runs the risk of
1065    section alignment affecting where the section starts.  */
1066
1067 static void
1068 gld${EMULATION_NAME}_provide_init_fini_syms (void)
1069 {
1070   if (!link_info.relocatable && link_info.executable)
1071     {
1072       gld${EMULATION_NAME}_provide_bound_symbols (".preinit_array",
1073                                                   "__preinit_array_start",
1074                                                   "__preinit_array_end");
1075       gld${EMULATION_NAME}_provide_bound_symbols (".init_array",
1076                                                   "__init_array_start",
1077                                                   "__init_array_end");
1078       gld${EMULATION_NAME}_provide_bound_symbols (".fini_array",
1079                                                   "__fini_array_start",
1080                                                   "__fini_array_end");
1081     }
1082 }
1083
1084 /* This is called after the sections have been attached to output
1085    sections, but before any sizes or addresses have been set.  */
1086
1087 static void
1088 gld${EMULATION_NAME}_before_allocation (void)
1089 {
1090   const char *rpath;
1091   asection *sinterp;
1092
1093   if (link_info.hash->type == bfd_link_elf_hash_table)
1094     _bfd_elf_tls_setup (output_bfd, &link_info);
1095
1096   /* If we are going to make any variable assignments, we need to let
1097      the ELF backend know about them in case the variables are
1098      referred to by dynamic objects.  */
1099   lang_for_each_statement (gld${EMULATION_NAME}_find_statement_assignment);
1100
1101   ldemul_do_assignments ();
1102
1103   /* Let the ELF backend work out the sizes of any sections required
1104      by dynamic linking.  */
1105   rpath = command_line.rpath;
1106   if (rpath == NULL)
1107     rpath = (const char *) getenv ("LD_RUN_PATH");
1108   if (! (bfd_elf_size_dynamic_sections
1109          (output_bfd, command_line.soname, rpath,
1110           command_line.filter_shlib,
1111           (const char * const *) command_line.auxiliary_filters,
1112           &link_info, &sinterp, lang_elf_version_info)))
1113     einfo ("%P%F: failed to set dynamic section sizes: %E\n");
1114
1115 ${ELF_INTERPRETER_SET_DEFAULT}
1116   /* Let the user override the dynamic linker we are using.  */
1117   if (command_line.interpreter != NULL
1118       && sinterp != NULL)
1119     {
1120       sinterp->contents = (bfd_byte *) command_line.interpreter;
1121       sinterp->size = strlen (command_line.interpreter) + 1;
1122     }
1123
1124   /* Look for any sections named .gnu.warning.  As a GNU extensions,
1125      we treat such sections as containing warning messages.  We print
1126      out the warning message, and then zero out the section size so
1127      that it does not get copied into the output file.  */
1128
1129   {
1130     LANG_FOR_EACH_INPUT_STATEMENT (is)
1131       {
1132         asection *s;
1133         bfd_size_type sz;
1134         bfd_size_type prefix_len;
1135         char *msg;
1136         bfd_boolean ret;
1137         const char * gnu_warning_prefix = _("warning: ");
1138
1139         if (is->just_syms_flag)
1140           continue;
1141
1142         s = bfd_get_section_by_name (is->the_bfd, ".gnu.warning");
1143         if (s == NULL)
1144           continue;
1145
1146         sz = s->size;
1147         prefix_len = strlen (gnu_warning_prefix);
1148         msg = xmalloc ((size_t) (prefix_len + sz + 1));
1149         strcpy (msg, gnu_warning_prefix);
1150         if (! bfd_get_section_contents (is->the_bfd, s, msg + prefix_len,
1151                                         (file_ptr) 0, sz))
1152           einfo ("%F%B: Can't read contents of section .gnu.warning: %E\n",
1153                  is->the_bfd);
1154         msg[prefix_len + sz] = '\0';
1155         ret = link_info.callbacks->warning (&link_info, msg,
1156                                             (const char *) NULL,
1157                                             is->the_bfd, (asection *) NULL,
1158                                             (bfd_vma) 0);
1159         ASSERT (ret);
1160         free (msg);
1161
1162         /* Clobber the section size, so that we don't waste copying the
1163            warning into the output file.  */
1164         s->size = 0;
1165
1166         /* Also set SEC_EXCLUDE, so that symbols defined in the warning
1167            section don't get copied to the output.  */
1168         s->flags |= SEC_EXCLUDE;
1169       }
1170   }
1171
1172   if (!link_info.relocatable)
1173     strip_excluded_output_sections ();
1174
1175   if (!bfd_elf_size_dynsym_hash_dynstr (output_bfd, &link_info))
1176     einfo ("%P%F: failed to set dynamic section sizes: %E\n");
1177 }
1178
1179 EOF
1180 fi
1181
1182 if test x"$LDEMUL_OPEN_DYNAMIC_ARCHIVE" != xgld"$EMULATION_NAME"_open_dynamic_archive; then
1183 cat >>e${EMULATION_NAME}.c <<EOF
1184
1185 /* Try to open a dynamic archive.  This is where we know that ELF
1186    dynamic libraries have an extension of .so (or .sl on oddball systems
1187    like hpux).  */
1188
1189 static bfd_boolean
1190 gld${EMULATION_NAME}_open_dynamic_archive
1191   (const char *arch, search_dirs_type *search, lang_input_statement_type *entry)
1192 {
1193   const char *filename;
1194   char *string;
1195
1196   if (! entry->is_archive)
1197     return FALSE;
1198
1199   filename = entry->filename;
1200
1201   /* This allocates a few bytes too many when EXTRA_SHLIB_EXTENSION
1202      is defined, but it does not seem worth the headache to optimize
1203      away those two bytes of space.  */
1204   string = (char *) xmalloc (strlen (search->name)
1205                              + strlen (filename)
1206                              + strlen (arch)
1207 #ifdef EXTRA_SHLIB_EXTENSION
1208                              + strlen (EXTRA_SHLIB_EXTENSION)
1209 #endif
1210                              + sizeof "/lib.so");
1211
1212   sprintf (string, "%s/lib%s%s.so", search->name, filename, arch);
1213
1214 #ifdef EXTRA_SHLIB_EXTENSION
1215   /* Try the .so extension first.  If that fails build a new filename
1216      using EXTRA_SHLIB_EXTENSION.  */
1217   if (! ldfile_try_open_bfd (string, entry))
1218     sprintf (string, "%s/lib%s%s%s", search->name,
1219              filename, arch, EXTRA_SHLIB_EXTENSION);
1220 #endif
1221
1222   if (! ldfile_try_open_bfd (string, entry))
1223     {
1224       free (string);
1225       return FALSE;
1226     }
1227
1228   entry->filename = string;
1229
1230   /* We have found a dynamic object to include in the link.  The ELF
1231      backend linker will create a DT_NEEDED entry in the .dynamic
1232      section naming this file.  If this file includes a DT_SONAME
1233      entry, it will be used.  Otherwise, the ELF linker will just use
1234      the name of the file.  For an archive found by searching, like
1235      this one, the DT_NEEDED entry should consist of just the name of
1236      the file, without the path information used to find it.  Note
1237      that we only need to do this if we have a dynamic object; an
1238      archive will never be referenced by a DT_NEEDED entry.
1239
1240      FIXME: This approach--using bfd_elf_set_dt_needed_name--is not
1241      very pretty.  I haven't been able to think of anything that is
1242      pretty, though.  */
1243   if (bfd_check_format (entry->the_bfd, bfd_object)
1244       && (entry->the_bfd->flags & DYNAMIC) != 0)
1245     {
1246       ASSERT (entry->is_archive && entry->search_dirs_flag);
1247
1248       /* Rather than duplicating the logic above.  Just use the
1249          filename we recorded earlier.  */
1250
1251       filename = lbasename (entry->filename);
1252       bfd_elf_set_dt_needed_name (entry->the_bfd, filename);
1253     }
1254
1255   return TRUE;
1256 }
1257
1258 EOF
1259 fi
1260
1261 if test x"$LDEMUL_PLACE_ORPHAN" != xgld"$EMULATION_NAME"_place_orphan; then
1262 cat >>e${EMULATION_NAME}.c <<EOF
1263
1264 /* A variant of lang_output_section_find used by place_orphan.  */
1265
1266 static lang_output_section_statement_type *
1267 output_rel_find (asection *sec, int isdyn)
1268 {
1269   lang_output_section_statement_type *lookup;
1270   lang_output_section_statement_type *last = NULL;
1271   lang_output_section_statement_type *last_alloc = NULL;
1272   lang_output_section_statement_type *last_rel = NULL;
1273   lang_output_section_statement_type *last_rel_alloc = NULL;
1274   int rela = sec->name[4] == 'a';
1275
1276   for (lookup = &lang_output_section_statement.head->output_section_statement;
1277        lookup != NULL;
1278        lookup = lookup->next)
1279     {
1280       if (lookup->constraint != -1
1281           && strncmp (".rel", lookup->name, 4) == 0)
1282         {
1283           int lookrela = lookup->name[4] == 'a';
1284
1285           /* .rel.dyn must come before all other reloc sections, to suit
1286              GNU ld.so.  */
1287           if (isdyn)
1288             break;
1289
1290           /* Don't place after .rel.plt as doing so results in wrong
1291              dynamic tags.  */
1292           if (strcmp (".plt", lookup->name + 4 + lookrela) == 0)
1293             break;
1294
1295           if (rela == lookrela || last_rel == NULL)
1296             last_rel = lookup;
1297           if ((rela == lookrela || last_rel_alloc == NULL)
1298               && lookup->bfd_section != NULL
1299               && (lookup->bfd_section->flags & SEC_ALLOC) != 0)
1300             last_rel_alloc = lookup;
1301         }
1302
1303       last = lookup;
1304       if (lookup->bfd_section != NULL
1305           && (lookup->bfd_section->flags & SEC_ALLOC) != 0)
1306         last_alloc = lookup;
1307     }
1308
1309   if (last_rel_alloc)
1310     return last_rel_alloc;
1311
1312   if (last_rel)
1313     return last_rel;
1314
1315   if (last_alloc)
1316     return last_alloc;
1317
1318   return last;
1319 }
1320
1321 /* Place an orphan section.  We use this to put random SHF_ALLOC
1322    sections in the right segment.  */
1323
1324 static bfd_boolean
1325 gld${EMULATION_NAME}_place_orphan (lang_input_statement_type *file, asection *s)
1326 {
1327   static struct orphan_save hold[] =
1328     {
1329       { ".text",
1330         SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_CODE,
1331         0, 0, 0, 0 },
1332       { ".rodata",
1333         SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
1334         0, 0, 0, 0 },
1335       { ".data",
1336         SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA,
1337         0, 0, 0, 0 },
1338       { ".bss",
1339         SEC_ALLOC,
1340         0, 0, 0, 0 },
1341       { 0,
1342         SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
1343         0, 0, 0, 0 },
1344       { ".interp",
1345         SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
1346         0, 0, 0, 0 },
1347       { ".sdata",
1348         SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA | SEC_SMALL_DATA,
1349         0, 0, 0, 0 }
1350     };
1351   enum orphan_save_index
1352     {
1353       orphan_text = 0,
1354       orphan_rodata,
1355       orphan_data,
1356       orphan_bss,
1357       orphan_rel,
1358       orphan_interp,
1359       orphan_sdata
1360     };
1361   static int orphan_init_done = 0;
1362   struct orphan_save *place;
1363   const char *secname;
1364   lang_output_section_statement_type *after;
1365   lang_output_section_statement_type *os;
1366   int isdyn = 0;
1367
1368   secname = bfd_get_section_name (s->owner, s);
1369
1370   if (! link_info.relocatable
1371       && link_info.combreloc
1372       && (s->flags & SEC_ALLOC)
1373       && strncmp (secname, ".rel", 4) == 0)
1374     {
1375       if (secname[4] == 'a')
1376         secname = ".rela.dyn";
1377       else
1378         secname = ".rel.dyn";
1379       isdyn = 1;
1380     }
1381
1382   if (isdyn || (!config.unique_orphan_sections && !unique_section_p (s)))
1383     {
1384       /* Look through the script to see where to place this section.  */
1385       os = lang_output_section_find (secname);
1386
1387       if (os != NULL
1388           && (os->bfd_section == NULL
1389               || os->bfd_section->flags == 0
1390               || ((s->flags ^ os->bfd_section->flags)
1391                   & (SEC_LOAD | SEC_ALLOC)) == 0))
1392         {
1393           /* We already have an output section statement with this
1394              name, and its bfd section, if any, has compatible flags.
1395              If the section already exists but does not have any flags
1396              set, then it has been created by the linker, probably as a
1397              result of a --section-start command line switch.  */
1398           lang_add_section (&os->children, s, os, file);
1399           return TRUE;
1400         }
1401     }
1402
1403   if (!orphan_init_done)
1404     {
1405       struct orphan_save *ho;
1406       for (ho = hold; ho < hold + sizeof (hold) / sizeof (hold[0]); ++ho)
1407         if (ho->name != NULL)
1408           {
1409             ho->os = lang_output_section_find (ho->name);
1410             if (ho->os != NULL && ho->os->flags == 0)
1411               ho->os->flags = ho->flags;
1412           }
1413       orphan_init_done = 1;
1414     }
1415
1416   /* If this is a final link, then always put .gnu.warning.SYMBOL
1417      sections into the .text section to get them out of the way.  */
1418   if (link_info.executable
1419       && ! link_info.relocatable
1420       && strncmp (secname, ".gnu.warning.", sizeof ".gnu.warning." - 1) == 0
1421       && hold[orphan_text].os != NULL)
1422     {
1423       lang_add_section (&hold[orphan_text].os->children, s,
1424                         hold[orphan_text].os, file);
1425       return TRUE;
1426     }
1427
1428   /* Decide which segment the section should go in based on the
1429      section name and section flags.  We put loadable .note sections
1430      right after the .interp section, so that the PT_NOTE segment is
1431      stored right after the program headers where the OS can read it
1432      in the first page.  */
1433
1434   place = NULL;
1435   if ((s->flags & SEC_ALLOC) == 0)
1436     ;
1437   else if ((s->flags & SEC_LOAD) != 0
1438            && strncmp (secname, ".note", 5) == 0)
1439     place = &hold[orphan_interp];
1440   else if ((s->flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
1441     place = &hold[orphan_bss];
1442   else if ((s->flags & SEC_SMALL_DATA) != 0)
1443     place = &hold[orphan_sdata];
1444   else if ((s->flags & SEC_READONLY) == 0)
1445     place = &hold[orphan_data];
1446   else if (strncmp (secname, ".rel", 4) == 0
1447            && (s->flags & SEC_LOAD) != 0)
1448     place = &hold[orphan_rel];
1449   else if ((s->flags & SEC_CODE) == 0)
1450     place = &hold[orphan_rodata];
1451   else
1452     place = &hold[orphan_text];
1453
1454   after = NULL;
1455   if (place != NULL)
1456     {
1457       if (place->os == NULL)
1458         {
1459           if (place->name != NULL)
1460             place->os = lang_output_section_find (place->name);
1461           else
1462             place->os = output_rel_find (s, isdyn);
1463         }
1464       after = place->os;
1465       if (after == NULL)
1466         after = lang_output_section_find_by_flags (s, &place->os);
1467       if (after == NULL)
1468         /* *ABS* is always the first output section statement.  */
1469         after = &lang_output_section_statement.head->output_section_statement;
1470     }
1471
1472   /* Choose a unique name for the section.  This will be needed if the
1473      same section name appears in the input file with different
1474      loadable or allocatable characteristics.  */
1475   if (bfd_get_section_by_name (output_bfd, secname) != NULL)
1476     {
1477       static int count = 1;
1478       secname = bfd_get_unique_section_name (output_bfd, secname, &count);
1479       if (secname == NULL)
1480         einfo ("%F%P: place_orphan failed: %E\n");
1481     }
1482
1483   lang_insert_orphan (file, s, secname, after, place, NULL, NULL);
1484
1485   return TRUE;
1486 }
1487 EOF
1488 fi
1489
1490 if test x"$LDEMUL_FINISH" != xgld"$EMULATION_NAME"_finish; then
1491 cat >>e${EMULATION_NAME}.c <<EOF
1492
1493 static void
1494 gld${EMULATION_NAME}_layout_sections_again (void)
1495 {
1496   lang_reset_memory_regions ();
1497
1498   /* Resize the sections.  */
1499   lang_size_sections (NULL, TRUE);
1500
1501   /* Redo special stuff.  */
1502   ldemul_after_allocation ();
1503
1504   /* Do the assignments again.  */
1505   lang_do_assignments ();
1506 }
1507
1508 static void
1509 gld${EMULATION_NAME}_finish (void)
1510 {
1511   if (bfd_elf_discard_info (output_bfd, &link_info))
1512     gld${EMULATION_NAME}_layout_sections_again ();
1513
1514   _bfd_elf_fix_excluded_sec_syms (output_bfd, &link_info);
1515 }
1516 EOF
1517 fi
1518
1519 if test x"$LDEMUL_GET_SCRIPT" != xgld"$EMULATION_NAME"_get_script; then
1520 cat >>e${EMULATION_NAME}.c <<EOF
1521
1522 static char *
1523 gld${EMULATION_NAME}_get_script (int *isfile)
1524 EOF
1525
1526 if test -n "$COMPILE_IN"
1527 then
1528 # Scripts compiled in.
1529
1530 # sed commands to quote an ld script as a C string.
1531 sc="-f stringify.sed"
1532
1533 cat >>e${EMULATION_NAME}.c <<EOF
1534 {
1535   *isfile = 0;
1536
1537   if (link_info.relocatable && config.build_constructors)
1538     return
1539 EOF
1540 sed $sc ldscripts/${EMULATION_NAME}.xu                  >> e${EMULATION_NAME}.c
1541 echo '  ; else if (link_info.relocatable) return'       >> e${EMULATION_NAME}.c
1542 sed $sc ldscripts/${EMULATION_NAME}.xr                  >> e${EMULATION_NAME}.c
1543 echo '  ; else if (!config.text_read_only) return'      >> e${EMULATION_NAME}.c
1544 sed $sc ldscripts/${EMULATION_NAME}.xbn                 >> e${EMULATION_NAME}.c
1545 if cmp -s ldscripts/${EMULATION_NAME}.x ldscripts/${EMULATION_NAME}.xn; then : ; else
1546 echo '  ; else if (!config.magic_demand_paged) return'  >> e${EMULATION_NAME}.c
1547 sed $sc ldscripts/${EMULATION_NAME}.xn                  >> e${EMULATION_NAME}.c
1548 fi
1549 if test -n "$GENERATE_PIE_SCRIPT" ; then
1550 if test -n "$GENERATE_COMBRELOC_SCRIPT" ; then
1551 echo '  ; else if (link_info.pie && link_info.combreloc' >> e${EMULATION_NAME}.c
1552 echo '             && link_info.relro' >> e${EMULATION_NAME}.c
1553 echo '             && (link_info.flags & DT_BIND_NOW)) return' >> e${EMULATION_NAME}.c
1554 sed $sc ldscripts/${EMULATION_NAME}.xdw                 >> e${EMULATION_NAME}.c
1555 echo '  ; else if (link_info.pie && link_info.combreloc) return' >> e${EMULATION_NAME}.c
1556 sed $sc ldscripts/${EMULATION_NAME}.xdc                 >> e${EMULATION_NAME}.c
1557 fi
1558 echo '  ; else if (link_info.pie) return'               >> e${EMULATION_NAME}.c
1559 sed $sc ldscripts/${EMULATION_NAME}.xd                  >> e${EMULATION_NAME}.c
1560 fi
1561 if test -n "$GENERATE_SHLIB_SCRIPT" ; then
1562 if test -n "$GENERATE_COMBRELOC_SCRIPT" ; then
1563 echo '  ; else if (link_info.shared && link_info.combreloc' >> e${EMULATION_NAME}.c
1564 echo '             && link_info.relro' >> e${EMULATION_NAME}.c
1565 echo '             && (link_info.flags & DT_BIND_NOW)) return' >> e${EMULATION_NAME}.c
1566 sed $sc ldscripts/${EMULATION_NAME}.xsw                 >> e${EMULATION_NAME}.c
1567 echo '  ; else if (link_info.shared && link_info.combreloc) return' >> e${EMULATION_NAME}.c
1568 sed $sc ldscripts/${EMULATION_NAME}.xsc                 >> e${EMULATION_NAME}.c
1569 fi
1570 echo '  ; else if (link_info.shared) return'            >> e${EMULATION_NAME}.c
1571 sed $sc ldscripts/${EMULATION_NAME}.xs                  >> e${EMULATION_NAME}.c
1572 fi
1573 if test -n "$GENERATE_COMBRELOC_SCRIPT" ; then
1574 echo '  ; else if (link_info.combreloc && link_info.relro' >> e${EMULATION_NAME}.c
1575 echo '             && (link_info.flags & DT_BIND_NOW)) return' >> e${EMULATION_NAME}.c
1576 sed $sc ldscripts/${EMULATION_NAME}.xw                  >> e${EMULATION_NAME}.c
1577 echo '  ; else if (link_info.combreloc) return'         >> e${EMULATION_NAME}.c
1578 sed $sc ldscripts/${EMULATION_NAME}.xc                  >> e${EMULATION_NAME}.c
1579 fi
1580 echo '  ; else return'                                  >> e${EMULATION_NAME}.c
1581 sed $sc ldscripts/${EMULATION_NAME}.x                   >> e${EMULATION_NAME}.c
1582 echo '; }'                                              >> e${EMULATION_NAME}.c
1583
1584 else
1585 # Scripts read from the filesystem.
1586
1587 cat >>e${EMULATION_NAME}.c <<EOF
1588 {
1589   *isfile = 1;
1590
1591   if (link_info.relocatable && config.build_constructors)
1592     return "ldscripts/${EMULATION_NAME}.xu";
1593   else if (link_info.relocatable)
1594     return "ldscripts/${EMULATION_NAME}.xr";
1595   else if (!config.text_read_only)
1596     return "ldscripts/${EMULATION_NAME}.xbn";
1597 EOF
1598 if cmp -s ldscripts/${EMULATION_NAME}.x ldscripts/${EMULATION_NAME}.xn; then :
1599 else
1600 cat >>e${EMULATION_NAME}.c <<EOF
1601   else if (!config.magic_demand_paged)
1602     return "ldscripts/${EMULATION_NAME}.xn";
1603 EOF
1604 fi
1605 if test -n "$GENERATE_PIE_SCRIPT" ; then
1606 if test -n "$GENERATE_COMBRELOC_SCRIPT" ; then
1607 cat >>e${EMULATION_NAME}.c <<EOF
1608   else if (link_info.pie && link_info.combreloc
1609            && link_info.relro && (link_info.flags & DT_BIND_NOW))
1610     return "ldscripts/${EMULATION_NAME}.xdw";
1611   else if (link_info.pie && link_info.combreloc)
1612     return "ldscripts/${EMULATION_NAME}.xdc";
1613 EOF
1614 fi
1615 cat >>e${EMULATION_NAME}.c <<EOF
1616   else if (link_info.pie)
1617     return "ldscripts/${EMULATION_NAME}.xd";
1618 EOF
1619 fi
1620 if test -n "$GENERATE_SHLIB_SCRIPT" ; then
1621 if test -n "$GENERATE_COMBRELOC_SCRIPT" ; then
1622 cat >>e${EMULATION_NAME}.c <<EOF
1623   else if (link_info.shared && link_info.combreloc
1624            && link_info.relro && (link_info.flags & DT_BIND_NOW))
1625     return "ldscripts/${EMULATION_NAME}.xsw";
1626   else if (link_info.shared && link_info.combreloc)
1627     return "ldscripts/${EMULATION_NAME}.xsc";
1628 EOF
1629 fi
1630 cat >>e${EMULATION_NAME}.c <<EOF
1631   else if (link_info.shared)
1632     return "ldscripts/${EMULATION_NAME}.xs";
1633 EOF
1634 fi
1635 if test -n "$GENERATE_COMBRELOC_SCRIPT" ; then
1636 cat >>e${EMULATION_NAME}.c <<EOF
1637   else if (link_info.combreloc && link_info.relro
1638            && (link_info.flags & DT_BIND_NOW))
1639     return "ldscripts/${EMULATION_NAME}.xw";
1640   else if (link_info.combreloc)
1641     return "ldscripts/${EMULATION_NAME}.xc";
1642 EOF
1643 fi
1644 cat >>e${EMULATION_NAME}.c <<EOF
1645   else
1646     return "ldscripts/${EMULATION_NAME}.x";
1647 }
1648
1649 EOF
1650 fi
1651 fi
1652
1653 if test -n "$PARSE_AND_LIST_ARGS_CASES" -o x"$GENERATE_SHLIB_SCRIPT" = xyes; then
1654
1655 if test -n "$PARSE_AND_LIST_PROLOGUE" ; then
1656 cat >>e${EMULATION_NAME}.c <<EOF
1657  $PARSE_AND_LIST_PROLOGUE
1658 EOF
1659 fi
1660
1661 cat >>e${EMULATION_NAME}.c <<EOF
1662
1663 #define OPTION_DISABLE_NEW_DTAGS        (400)
1664 #define OPTION_ENABLE_NEW_DTAGS         (OPTION_DISABLE_NEW_DTAGS + 1)
1665 #define OPTION_GROUP                    (OPTION_ENABLE_NEW_DTAGS + 1)
1666 #define OPTION_EH_FRAME_HDR             (OPTION_GROUP + 1)
1667 #define OPTION_EXCLUDE_LIBS             (OPTION_EH_FRAME_HDR + 1)
1668   
1669 static void
1670 gld${EMULATION_NAME}_add_options
1671   (int ns, char **shortopts, int nl, struct option **longopts,
1672    int nrl ATTRIBUTE_UNUSED, struct option **really_longopts ATTRIBUTE_UNUSED)
1673 {
1674   static const char xtra_short[] = "${PARSE_AND_LIST_SHORTOPTS}z:";
1675   static const struct option xtra_long[] = {
1676 EOF
1677
1678 if test x"$GENERATE_SHLIB_SCRIPT" = xyes; then
1679 cat >>e${EMULATION_NAME}.c <<EOF
1680     {"disable-new-dtags", no_argument, NULL, OPTION_DISABLE_NEW_DTAGS},
1681     {"enable-new-dtags", no_argument, NULL, OPTION_ENABLE_NEW_DTAGS},
1682     {"eh-frame-hdr", no_argument, NULL, OPTION_EH_FRAME_HDR},
1683     {"exclude-libs", required_argument, NULL, OPTION_EXCLUDE_LIBS},
1684     {"Bgroup", no_argument, NULL, OPTION_GROUP},
1685 EOF
1686 fi
1687
1688 if test -n "$PARSE_AND_LIST_LONGOPTS" ; then
1689 cat >>e${EMULATION_NAME}.c <<EOF
1690     $PARSE_AND_LIST_LONGOPTS
1691 EOF
1692 fi
1693
1694 cat >>e${EMULATION_NAME}.c <<EOF
1695     {NULL, no_argument, NULL, 0}
1696   };
1697
1698   *shortopts = (char *) xrealloc (*shortopts, ns + sizeof (xtra_short));
1699   memcpy (*shortopts + ns, &xtra_short, sizeof (xtra_short));
1700   *longopts = (struct option *)
1701     xrealloc (*longopts, nl * sizeof (struct option) + sizeof (xtra_long));
1702   memcpy (*longopts + nl, &xtra_long, sizeof (xtra_long));
1703 }
1704
1705 static bfd_boolean
1706 gld${EMULATION_NAME}_handle_option (int optc)
1707 {
1708   switch (optc)
1709     {
1710     default:
1711       return FALSE;
1712
1713 EOF
1714
1715 if test x"$GENERATE_SHLIB_SCRIPT" = xyes; then
1716 cat >>e${EMULATION_NAME}.c <<EOF
1717     case OPTION_DISABLE_NEW_DTAGS:
1718       link_info.new_dtags = FALSE;
1719       break;
1720
1721     case OPTION_ENABLE_NEW_DTAGS:
1722       link_info.new_dtags = TRUE;
1723       break;
1724
1725     case OPTION_EH_FRAME_HDR:
1726       link_info.eh_frame_hdr = TRUE;
1727       break;
1728
1729     case OPTION_GROUP:
1730       link_info.flags_1 |= (bfd_vma) DF_1_GROUP;
1731       /* Groups must be self-contained.  */
1732       link_info.unresolved_syms_in_objects = RM_GENERATE_ERROR;
1733       link_info.unresolved_syms_in_shared_libs = RM_GENERATE_ERROR;
1734       break;
1735
1736     case OPTION_EXCLUDE_LIBS:
1737       add_excluded_libs (optarg);
1738       break;
1739
1740     case 'z':
1741       if (strcmp (optarg, "initfirst") == 0)
1742         link_info.flags_1 |= (bfd_vma) DF_1_INITFIRST;
1743       else if (strcmp (optarg, "interpose") == 0)
1744         link_info.flags_1 |= (bfd_vma) DF_1_INTERPOSE;
1745       else if (strcmp (optarg, "loadfltr") == 0)
1746         link_info.flags_1 |= (bfd_vma) DF_1_LOADFLTR;
1747       else if (strcmp (optarg, "nodefaultlib") == 0)
1748         link_info.flags_1 |= (bfd_vma) DF_1_NODEFLIB;
1749       else if (strcmp (optarg, "nodelete") == 0)
1750         link_info.flags_1 |= (bfd_vma) DF_1_NODELETE;
1751       else if (strcmp (optarg, "nodlopen") == 0)
1752         link_info.flags_1 |= (bfd_vma) DF_1_NOOPEN;
1753       else if (strcmp (optarg, "nodump") == 0)
1754         link_info.flags_1 |= (bfd_vma) DF_1_NODUMP;
1755       else if (strcmp (optarg, "now") == 0)
1756         {
1757           link_info.flags |= (bfd_vma) DF_BIND_NOW;
1758           link_info.flags_1 |= (bfd_vma) DF_1_NOW;
1759         }
1760       else if (strcmp (optarg, "origin") == 0)
1761         {
1762           link_info.flags |= (bfd_vma) DF_ORIGIN;
1763           link_info.flags_1 |= (bfd_vma) DF_1_ORIGIN;
1764         }
1765       else if (strcmp (optarg, "defs") == 0)
1766         link_info.unresolved_syms_in_objects = RM_GENERATE_ERROR;
1767       else if (strcmp (optarg, "muldefs") == 0)
1768         link_info.allow_multiple_definition = TRUE;
1769       else if (strcmp (optarg, "combreloc") == 0)
1770         link_info.combreloc = TRUE;
1771       else if (strcmp (optarg, "nocombreloc") == 0)
1772         link_info.combreloc = FALSE;
1773       else if (strcmp (optarg, "nocopyreloc") == 0)
1774         link_info.nocopyreloc = TRUE;
1775       else if (strcmp (optarg, "execstack") == 0)
1776         {
1777           link_info.execstack = TRUE;
1778           link_info.noexecstack = FALSE;
1779         }
1780       else if (strcmp (optarg, "noexecstack") == 0)
1781         {
1782           link_info.noexecstack = TRUE;
1783           link_info.execstack = FALSE;
1784         }
1785       else if (strcmp (optarg, "relro") == 0)
1786         link_info.relro = TRUE;
1787       else if (strcmp (optarg, "norelro") == 0)
1788         link_info.relro = FALSE;
1789       /* What about the other Solaris -z options? FIXME.  */
1790       break;
1791 EOF
1792 fi
1793
1794 if test -n "$PARSE_AND_LIST_ARGS_CASES" ; then
1795 cat >>e${EMULATION_NAME}.c <<EOF
1796  $PARSE_AND_LIST_ARGS_CASES
1797 EOF
1798 fi
1799
1800 cat >>e${EMULATION_NAME}.c <<EOF
1801     }
1802
1803   return TRUE;
1804 }
1805
1806 EOF
1807
1808 if test x"$LDEMUL_LIST_OPTIONS" != xgld"$EMULATION_NAME"_list_options; then
1809 cat >>e${EMULATION_NAME}.c <<EOF
1810
1811 static void
1812 gld${EMULATION_NAME}_list_options (FILE * file)
1813 {
1814 EOF
1815
1816 if test x"$GENERATE_SHLIB_SCRIPT" = xyes; then
1817 cat >>e${EMULATION_NAME}.c <<EOF
1818   fprintf (file, _("  -Bgroup\t\tSelects group name lookup rules for DSO\n"));
1819   fprintf (file, _("  --disable-new-dtags\tDisable new dynamic tags\n"));
1820   fprintf (file, _("  --enable-new-dtags\tEnable new dynamic tags\n"));
1821   fprintf (file, _("  --eh-frame-hdr\tCreate .eh_frame_hdr section\n"));
1822   fprintf (file, _("  -z combreloc\t\tMerge dynamic relocs into one section and sort\n"));
1823   fprintf (file, _("  -z defs\t\tReport unresolved symbols in object files.\n"));
1824   fprintf (file, _("  -z execstack\t\tMark executable as requiring executable stack\n"));
1825   fprintf (file, _("  -z initfirst\t\tMark DSO to be initialized first at runtime\n"));
1826   fprintf (file, _("  -z interpose\t\tMark object to interpose all DSOs but executable\n"));
1827   fprintf (file, _("  -z loadfltr\t\tMark object requiring immediate process\n"));
1828   fprintf (file, _("  -z muldefs\t\tAllow multiple definitions\n"));
1829   fprintf (file, _("  -z nocombreloc\tDon't merge dynamic relocs into one section\n"));
1830   fprintf (file, _("  -z nocopyreloc\tDon't create copy relocs\n"));
1831   fprintf (file, _("  -z nodefaultlib\tMark object not to use default search paths\n"));
1832   fprintf (file, _("  -z nodelete\t\tMark DSO non-deletable at runtime\n"));
1833   fprintf (file, _("  -z nodlopen\t\tMark DSO not available to dlopen\n"));
1834   fprintf (file, _("  -z nodump\t\tMark DSO not available to dldump\n"));
1835   fprintf (file, _("  -z noexecstack\tMark executable as not requiring executable stack\n"));
1836   fprintf (file, _("  -z norelro\t\tDon't create RELRO program header\n"));
1837   fprintf (file, _("  -z now\t\tMark object non-lazy runtime binding\n"));
1838   fprintf (file, _("  -z origin\t\tMark object requiring immediate \$ORIGIN processing\n\t\t\t  at runtime\n"));
1839   fprintf (file, _("  -z relro\t\tCreate RELRO program header\n"));
1840   fprintf (file, _("  -z KEYWORD\t\tIgnored for Solaris compatibility\n"));
1841 EOF
1842 fi
1843
1844 if test -n "$PARSE_AND_LIST_OPTIONS" ; then
1845 cat >>e${EMULATION_NAME}.c <<EOF
1846  $PARSE_AND_LIST_OPTIONS
1847 EOF
1848 fi
1849
1850 cat >>e${EMULATION_NAME}.c <<EOF
1851 }
1852 EOF
1853
1854 if test -n "$PARSE_AND_LIST_EPILOGUE" ; then
1855 cat >>e${EMULATION_NAME}.c <<EOF
1856  $PARSE_AND_LIST_EPILOGUE
1857 EOF
1858 fi
1859 fi
1860 else
1861 cat >>e${EMULATION_NAME}.c <<EOF
1862 #define gld${EMULATION_NAME}_add_options NULL
1863 #define gld${EMULATION_NAME}_handle_option NULL
1864 EOF
1865 if test x"$LDEMUL_LIST_OPTIONS" != xgld"$EMULATION_NAME"_list_options; then
1866 cat >>e${EMULATION_NAME}.c <<EOF
1867 #define gld${EMULATION_NAME}_list_options NULL
1868 EOF
1869 fi
1870 fi
1871
1872 cat >>e${EMULATION_NAME}.c <<EOF
1873
1874 struct ld_emulation_xfer_struct ld_${EMULATION_NAME}_emulation =
1875 {
1876   ${LDEMUL_BEFORE_PARSE-gld${EMULATION_NAME}_before_parse},
1877   ${LDEMUL_SYSLIB-syslib_default},
1878   ${LDEMUL_HLL-hll_default},
1879   ${LDEMUL_AFTER_PARSE-after_parse_default},
1880   ${LDEMUL_AFTER_OPEN-gld${EMULATION_NAME}_after_open},
1881   ${LDEMUL_AFTER_ALLOCATION-after_allocation_default},
1882   ${LDEMUL_SET_OUTPUT_ARCH-set_output_arch_default},
1883   ${LDEMUL_CHOOSE_TARGET-ldemul_default_target},
1884   ${LDEMUL_BEFORE_ALLOCATION-gld${EMULATION_NAME}_before_allocation},
1885   ${LDEMUL_DO_ASSIGNMENTS-gld${EMULATION_NAME}_provide_init_fini_syms},
1886   ${LDEMUL_GET_SCRIPT-gld${EMULATION_NAME}_get_script},
1887   "${EMULATION_NAME}",
1888   "${OUTPUT_FORMAT}",
1889   ${LDEMUL_FINISH-gld${EMULATION_NAME}_finish},
1890   ${LDEMUL_CREATE_OUTPUT_SECTION_STATEMENTS-NULL},
1891   ${LDEMUL_OPEN_DYNAMIC_ARCHIVE-gld${EMULATION_NAME}_open_dynamic_archive},
1892   ${LDEMUL_PLACE_ORPHAN-gld${EMULATION_NAME}_place_orphan},
1893   ${LDEMUL_SET_SYMBOLS-NULL},
1894   ${LDEMUL_PARSE_ARGS-NULL},
1895   gld${EMULATION_NAME}_add_options,
1896   gld${EMULATION_NAME}_handle_option,
1897   ${LDEMUL_UNRECOGNIZED_FILE-NULL},
1898   ${LDEMUL_LIST_OPTIONS-gld${EMULATION_NAME}_list_options},
1899   ${LDEMUL_RECOGNIZED_FILE-gld${EMULATION_NAME}_load_symbols},
1900   ${LDEMUL_FIND_POTENTIAL_LIBRARIES-NULL},
1901   ${LDEMUL_NEW_VERS_PATTERN-NULL}
1902 };
1903 EOF