Add support for generating and inserting build IDs into COFF binaries.
[external/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 fragment <<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 (C) 1991-2014 Free Software Foundation, Inc.
16    Written by Steve Chamberlain <sac@cygnus.com>
17    ELF support by Ian Lance Taylor <ian@cygnus.com>
18
19    This file is part of the GNU Binutils.
20
21    This program is free software; you can redistribute it and/or modify
22    it under the terms of the GNU General Public License as published by
23    the Free Software Foundation; either version 3 of the License, or
24    (at your option) any later version.
25
26    This program is distributed in the hope that it will be useful,
27    but WITHOUT ANY WARRANTY; without even the implied warranty of
28    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
29    GNU General Public License for more details.
30
31    You should have received a copy of the GNU General Public License
32    along with this program; if not, write to the Free Software
33    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
34    MA 02110-1301, USA.  */
35
36 #define TARGET_IS_${EMULATION_NAME}
37
38 #include "sysdep.h"
39 #include "bfd.h"
40 #include "libiberty.h"
41 #include "filenames.h"
42 #include "getopt.h"
43 #include <fcntl.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 "ldbuildid.h"
55 #include <ldgram.h>
56 #include "elf/common.h"
57 #include "elf-bfd.h"
58 #include "filenames.h"
59
60 /* Declare functions used by various EXTRA_EM_FILEs.  */
61 static void gld${EMULATION_NAME}_before_parse (void);
62 static void gld${EMULATION_NAME}_after_open (void);
63 static void gld${EMULATION_NAME}_before_allocation (void);
64 static void gld${EMULATION_NAME}_after_allocation (void);
65 static lang_output_section_statement_type *gld${EMULATION_NAME}_place_orphan
66   (asection *, const char *, int);
67 EOF
68
69 if [ "x${USE_LIBPATH}" = xyes ] ; then
70   case ${target} in
71     *-*-linux-* | *-*-k*bsd*-* | *-*-gnu*)
72   fragment <<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 source_em ${srcdir}/emultempl/elf-generic.em
84 if test -n "$EXTRA_EM_FILE" ; then
85   source_em ${srcdir}/emultempl/${EXTRA_EM_FILE}.em
86 fi
87
88 # Functions in this file can be overridden by setting the LDEMUL_* shell
89 # variables.  If the name of the overriding function is the same as is
90 # defined in this file, then don't output this file's version.
91 # If a different overriding name is given then output the standard function
92 # as presumably it is called from the overriding function.
93 #
94 if test x"$LDEMUL_BEFORE_PARSE" != xgld"$EMULATION_NAME"_before_parse; then
95 fragment <<EOF
96
97 static void
98 gld${EMULATION_NAME}_before_parse (void)
99 {
100   ldfile_set_output_arch ("${OUTPUT_ARCH}", bfd_arch_`echo ${ARCH} | sed -e 's/:.*//'`);
101   input_flags.dynamic = ${DYNAMIC_LINK-TRUE};
102   config.has_shared = `if test -n "$GENERATE_SHLIB_SCRIPT" ; then echo TRUE ; else echo FALSE ; fi`;
103   config.separate_code = `if test "x${SEPARATE_CODE}" = xyes ; then echo TRUE ; else echo FALSE ; fi`;
104 }
105
106 EOF
107 fi
108
109 if test x"$LDEMUL_RECOGNIZED_FILE" != xgld"${EMULATION_NAME}"_load_symbols; then
110 fragment <<EOF
111 /* Handle the generation of DT_NEEDED tags.  */
112
113 static bfd_boolean
114 gld${EMULATION_NAME}_load_symbols (lang_input_statement_type *entry)
115 {
116   int link_class = 0;
117
118   /* Tell the ELF linker that we don't want the output file to have a
119      DT_NEEDED entry for this file, unless it is used to resolve
120      references in a regular object.  */
121   if (entry->flags.add_DT_NEEDED_for_regular)
122     link_class = DYN_AS_NEEDED;
123
124   /* Tell the ELF linker that we don't want the output file to have a
125      DT_NEEDED entry for any dynamic library in DT_NEEDED tags from
126      this file at all.  */
127   if (!entry->flags.add_DT_NEEDED_for_dynamic)
128     link_class |= DYN_NO_ADD_NEEDED;
129
130   if (entry->flags.just_syms
131       && (bfd_get_file_flags (entry->the_bfd) & DYNAMIC) != 0)
132     einfo (_("%P%F: --just-symbols may not be used on DSO: %B\n"),
133            entry->the_bfd);
134
135   if (link_class == 0
136       || (bfd_get_file_flags (entry->the_bfd) & DYNAMIC) == 0)
137     return FALSE;
138
139   bfd_elf_set_dyn_lib_class (entry->the_bfd,
140                              (enum dynamic_lib_link_class) link_class);
141
142   /* Continue on with normal load_symbols processing.  */
143   return FALSE;
144 }
145 EOF
146 fi
147
148 fragment <<EOF
149
150 /* These variables are required to pass information back and forth
151    between after_open and check_needed and stat_needed and vercheck.  */
152
153 static struct bfd_link_needed_list *global_needed;
154 static struct stat global_stat;
155 static lang_input_statement_type *global_found;
156 static struct bfd_link_needed_list *global_vercheck_needed;
157 static bfd_boolean global_vercheck_failed;
158
159 /* These variables are used to implement target options */
160
161 static char *audit; /* colon (typically) separated list of libs */
162 static char *depaudit; /* colon (typically) separated list of libs */
163
164 /* Style of .note.gnu.build-id section.  */
165 static const char *emit_note_gnu_build_id;
166
167 /* On Linux, it's possible to have different versions of the same
168    shared library linked against different versions of libc.  The
169    dynamic linker somehow tags which libc version to use in
170    /etc/ld.so.cache, and, based on the libc that it sees in the
171    executable, chooses which version of the shared library to use.
172
173    We try to do a similar check here by checking whether this shared
174    library needs any other shared libraries which may conflict with
175    libraries we have already included in the link.  If it does, we
176    skip it, and try to find another shared library farther on down the
177    link path.
178
179    This is called via lang_for_each_input_file.
180    GLOBAL_VERCHECK_NEEDED is the list of objects needed by the object
181    which we are checking.  This sets GLOBAL_VERCHECK_FAILED if we find
182    a conflicting version.  */
183
184 static void
185 gld${EMULATION_NAME}_vercheck (lang_input_statement_type *s)
186 {
187   const char *soname;
188   struct bfd_link_needed_list *l;
189
190   if (global_vercheck_failed)
191     return;
192   if (s->the_bfd == NULL
193       || (bfd_get_file_flags (s->the_bfd) & DYNAMIC) == 0)
194     return;
195
196   soname = bfd_elf_get_dt_soname (s->the_bfd);
197   if (soname == NULL)
198     soname = lbasename (bfd_get_filename (s->the_bfd));
199
200   for (l = global_vercheck_needed; l != NULL; l = l->next)
201     {
202       const char *suffix;
203
204       if (filename_cmp (soname, l->name) == 0)
205         {
206           /* Probably can't happen, but it's an easy check.  */
207           continue;
208         }
209
210       if (strchr (l->name, '/') != NULL)
211         continue;
212
213       suffix = strstr (l->name, ".so.");
214       if (suffix == NULL)
215         continue;
216
217       suffix += sizeof ".so." - 1;
218
219       if (filename_ncmp (soname, l->name, suffix - l->name) == 0)
220         {
221           /* Here we know that S is a dynamic object FOO.SO.VER1, and
222              the object we are considering needs a dynamic object
223              FOO.SO.VER2, and VER1 and VER2 are different.  This
224              appears to be a version mismatch, so we tell the caller
225              to try a different version of this library.  */
226           global_vercheck_failed = TRUE;
227           return;
228         }
229     }
230 }
231
232
233 /* See if an input file matches a DT_NEEDED entry by running stat on
234    the file.  */
235
236 static void
237 gld${EMULATION_NAME}_stat_needed (lang_input_statement_type *s)
238 {
239   struct stat st;
240   const char *suffix;
241   const char *soname;
242
243   if (global_found != NULL)
244     return;
245   if (s->the_bfd == NULL)
246     return;
247
248   /* If this input file was an as-needed entry, and wasn't found to be
249      needed at the stage it was linked, then don't say we have loaded it.  */
250   if ((bfd_elf_get_dyn_lib_class (s->the_bfd) & DYN_AS_NEEDED) != 0)
251     return;
252
253   if (bfd_stat (s->the_bfd, &st) != 0)
254     {
255       einfo ("%P:%B: bfd_stat failed: %E\n", s->the_bfd);
256       return;
257     }
258
259   /* Some operating systems, e.g. Windows, do not provide a meaningful
260      st_ino; they always set it to zero.  (Windows does provide a
261      meaningful st_dev.)  Do not indicate a duplicate library in that
262      case.  While there is no guarantee that a system that provides
263      meaningful inode numbers will never set st_ino to zero, this is
264      merely an optimization, so we do not need to worry about false
265      negatives.  */
266   if (st.st_dev == global_stat.st_dev
267       && st.st_ino == global_stat.st_ino
268       && st.st_ino != 0)
269     {
270       global_found = s;
271       return;
272     }
273
274   /* We issue a warning if it looks like we are including two
275      different versions of the same shared library.  For example,
276      there may be a problem if -lc picks up libc.so.6 but some other
277      shared library has a DT_NEEDED entry of libc.so.5.  This is a
278      heuristic test, and it will only work if the name looks like
279      NAME.so.VERSION.  FIXME: Depending on file names is error-prone.
280      If we really want to issue warnings about mixing version numbers
281      of shared libraries, we need to find a better way.  */
282
283   if (strchr (global_needed->name, '/') != NULL)
284     return;
285   suffix = strstr (global_needed->name, ".so.");
286   if (suffix == NULL)
287     return;
288   suffix += sizeof ".so." - 1;
289
290   soname = bfd_elf_get_dt_soname (s->the_bfd);
291   if (soname == NULL)
292     soname = lbasename (s->filename);
293
294   if (filename_ncmp (soname, global_needed->name, suffix - global_needed->name) == 0)
295     einfo ("%P: warning: %s, needed by %B, may conflict with %s\n",
296            global_needed->name, global_needed->by, soname);
297 }
298
299 struct dt_needed
300 {
301   bfd *by;
302   const char *name;
303 };
304
305 /* This function is called for each possible name for a dynamic object
306    named by a DT_NEEDED entry.  The FORCE parameter indicates whether
307    to skip the check for a conflicting version.  */
308
309 static bfd_boolean
310 gld${EMULATION_NAME}_try_needed (struct dt_needed *needed,
311                                  int force)
312 {
313   bfd *abfd;
314   const char *name = needed->name;
315   const char *soname;
316   int link_class;
317
318   abfd = bfd_openr (name, bfd_get_target (link_info.output_bfd));
319   if (abfd == NULL)
320     return FALSE;
321
322   /* Linker needs to decompress sections.  */
323   abfd->flags |= BFD_DECOMPRESS;
324
325   if (! bfd_check_format (abfd, bfd_object))
326     {
327       bfd_close (abfd);
328       return FALSE;
329     }
330   if ((bfd_get_file_flags (abfd) & DYNAMIC) == 0)
331     {
332       bfd_close (abfd);
333       return FALSE;
334     }
335
336   /* For DT_NEEDED, they have to match.  */
337   if (abfd->xvec != link_info.output_bfd->xvec)
338     {
339       bfd_close (abfd);
340       return FALSE;
341     }
342
343   /* Check whether this object would include any conflicting library
344      versions.  If FORCE is set, then we skip this check; we use this
345      the second time around, if we couldn't find any compatible
346      instance of the shared library.  */
347
348   if (! force)
349     {
350       struct bfd_link_needed_list *needs;
351
352       if (! bfd_elf_get_bfd_needed_list (abfd, &needs))
353         einfo ("%F%P:%B: bfd_elf_get_bfd_needed_list failed: %E\n", abfd);
354
355       if (needs != NULL)
356         {
357           global_vercheck_needed = needs;
358           global_vercheck_failed = FALSE;
359           lang_for_each_input_file (gld${EMULATION_NAME}_vercheck);
360           if (global_vercheck_failed)
361             {
362               bfd_close (abfd);
363               /* Return FALSE to force the caller to move on to try
364                  another file on the search path.  */
365               return FALSE;
366             }
367
368           /* But wait!  It gets much worse.  On Linux, if a shared
369              library does not use libc at all, we are supposed to skip
370              it the first time around in case we encounter a shared
371              library later on with the same name which does use the
372              version of libc that we want.  This is much too horrible
373              to use on any system other than Linux.  */
374
375 EOF
376 case ${target} in
377   *-*-linux-* | *-*-k*bsd*-* | *-*-gnu*)
378     fragment <<EOF
379           {
380             struct bfd_link_needed_list *l;
381
382             for (l = needs; l != NULL; l = l->next)
383               if (CONST_STRNEQ (l->name, "libc.so"))
384                 break;
385             if (l == NULL)
386               {
387                 bfd_close (abfd);
388                 return FALSE;
389               }
390           }
391
392 EOF
393     ;;
394 esac
395 fragment <<EOF
396         }
397     }
398
399   /* We've found a dynamic object matching the DT_NEEDED entry.  */
400
401   /* We have already checked that there is no other input file of the
402      same name.  We must now check again that we are not including the
403      same file twice.  We need to do this because on many systems
404      libc.so is a symlink to, e.g., libc.so.1.  The SONAME entry will
405      reference libc.so.1.  If we have already included libc.so, we
406      don't want to include libc.so.1 if they are the same file, and we
407      can only check that using stat.  */
408
409   if (bfd_stat (abfd, &global_stat) != 0)
410     einfo ("%F%P:%B: bfd_stat failed: %E\n", abfd);
411
412   /* First strip off everything before the last '/'.  */
413   soname = lbasename (abfd->filename);
414
415   if (verbose)
416     info_msg (_("found %s at %s\n"), soname, name);
417
418   global_found = NULL;
419   lang_for_each_input_file (gld${EMULATION_NAME}_stat_needed);
420   if (global_found != NULL)
421     {
422       /* Return TRUE to indicate that we found the file, even though
423          we aren't going to do anything with it.  */
424       return TRUE;
425     }
426
427   /* Specify the soname to use.  */
428   bfd_elf_set_dt_needed_name (abfd, soname);
429
430   /* Tell the ELF linker that we don't want the output file to have a
431      DT_NEEDED entry for this file, unless it is used to resolve
432      references in a regular object.  */
433   link_class = DYN_DT_NEEDED;
434
435   /* Tell the ELF linker that we don't want the output file to have a
436      DT_NEEDED entry for this file at all if the entry is from a file
437      with DYN_NO_ADD_NEEDED.  */
438   if (needed->by != NULL
439       && (bfd_elf_get_dyn_lib_class (needed->by) & DYN_NO_ADD_NEEDED) != 0)
440     link_class |= DYN_NO_NEEDED | DYN_NO_ADD_NEEDED;
441
442   bfd_elf_set_dyn_lib_class (abfd, (enum dynamic_lib_link_class) link_class);
443
444   /* Add this file into the symbol table.  */
445   if (! bfd_link_add_symbols (abfd, &link_info))
446     einfo ("%F%B: error adding symbols: %E\n", abfd);
447
448   return TRUE;
449 }
450
451
452 /* Search for a needed file in a path.  */
453
454 static bfd_boolean
455 gld${EMULATION_NAME}_search_needed (const char *path,
456                                     struct dt_needed *n, int force)
457 {
458   const char *s;
459   const char *name = n->name;
460   size_t len;
461   struct dt_needed needed;
462
463   if (name[0] == '/')
464     return gld${EMULATION_NAME}_try_needed (n, force);
465
466   if (path == NULL || *path == '\0')
467     return FALSE;
468
469   needed.by = n->by;
470   needed.name = n->name;
471
472   len = strlen (name);
473   while (1)
474     {
475       char *filename, *sset;
476
477       s = strchr (path, config.rpath_separator);
478       if (s == NULL)
479         s = path + strlen (path);
480
481 #if HAVE_DOS_BASED_FILE_SYSTEM
482       /* Assume a match on the second char is part of drive specifier.  */
483       else if (config.rpath_separator == ':'
484                && s == path + 1
485                && ISALPHA (*path))
486         {
487           s = strchr (s + 1, config.rpath_separator);
488           if (s == NULL)
489             s = path + strlen (path);
490         }
491 #endif
492       filename = (char *) xmalloc (s - path + len + 2);
493       if (s == path)
494         sset = filename;
495       else
496         {
497           memcpy (filename, path, s - path);
498           filename[s - path] = '/';
499           sset = filename + (s - path) + 1;
500         }
501       strcpy (sset, name);
502
503       needed.name = filename;
504       if (gld${EMULATION_NAME}_try_needed (&needed, force))
505         return TRUE;
506
507       free (filename);
508
509       if (*s == '\0')
510         break;
511       path = s + 1;
512     }
513
514   return FALSE;
515 }
516
517 EOF
518 if [ "x${USE_LIBPATH}" = xyes ] ; then
519   fragment <<EOF
520
521 /* Add the sysroot to every entry in a path separated by
522    config.rpath_separator.  */
523
524 static char *
525 gld${EMULATION_NAME}_add_sysroot (const char *path)
526 {
527   int len, colons, i;
528   char *ret, *p;
529
530   len = strlen (path);
531   colons = 0;
532   i = 0;
533   while (path[i])
534     if (path[i++] == config.rpath_separator)
535       colons++;
536
537   if (path[i])
538     colons++;
539
540   len = len + (colons + 1) * strlen (ld_sysroot);
541   ret = xmalloc (len + 1);
542   strcpy (ret, ld_sysroot);
543   p = ret + strlen (ret);
544   i = 0;
545   while (path[i])
546     if (path[i] == config.rpath_separator)
547       {
548         *p++ = path[i++];
549         strcpy (p, ld_sysroot);
550         p = p + strlen (p);
551       }
552     else
553       *p++ = path[i++];
554
555   *p = 0;
556   return ret;
557 }
558
559 EOF
560   case ${target} in
561     *-*-freebsd* | *-*-dragonfly*)
562       fragment <<EOF
563 /* Read the system search path the FreeBSD way rather than the Linux way.  */
564 #ifdef HAVE_ELF_HINTS_H
565 #include <elf-hints.h>
566 #else
567 #include "elf-hints-local.h"
568 #endif
569
570 static bfd_boolean
571 gld${EMULATION_NAME}_check_ld_elf_hints (const struct bfd_link_needed_list *l,
572                                          int force)
573 {
574   static bfd_boolean initialized;
575   static char *ld_elf_hints;
576   struct dt_needed needed;
577
578   if (!initialized)
579     {
580       FILE *f;
581       char *tmppath;
582
583       tmppath = concat (ld_sysroot, _PATH_ELF_HINTS, (const char *) NULL);
584       f = fopen (tmppath, FOPEN_RB);
585       free (tmppath);
586       if (f != NULL)
587         {
588           struct elfhints_hdr hdr;
589
590           if (fread (&hdr, 1, sizeof (hdr), f) == sizeof (hdr)
591               && hdr.magic == ELFHINTS_MAGIC
592               && hdr.version == 1)
593             {
594               if (fseek (f, hdr.strtab + hdr.dirlist, SEEK_SET) != -1)
595                 {
596                   char *b;
597
598                   b = xmalloc (hdr.dirlistlen + 1);
599                   if (fread (b, 1, hdr.dirlistlen + 1, f) ==
600                       hdr.dirlistlen + 1)
601                     ld_elf_hints = gld${EMULATION_NAME}_add_sysroot (b);
602
603                   free (b);
604                 }
605             }
606           fclose (f);
607         }
608
609       initialized = TRUE;
610     }
611
612   if (ld_elf_hints == NULL)
613     return FALSE;
614
615   needed.by = l->by;
616   needed.name = l->name;
617   return gld${EMULATION_NAME}_search_needed (ld_elf_hints, &needed, force);
618 }
619 EOF
620     # FreeBSD
621     ;;
622
623     *-*-linux-* | *-*-k*bsd*-* | *-*-gnu*)
624       fragment <<EOF
625 /* For a native linker, check the file /etc/ld.so.conf for directories
626    in which we may find shared libraries.  /etc/ld.so.conf is really
627    only meaningful on Linux.  */
628
629 struct gld${EMULATION_NAME}_ld_so_conf
630 {
631   char *path;
632   size_t len, alloc;
633 };
634
635 static bfd_boolean
636 gld${EMULATION_NAME}_parse_ld_so_conf
637      (struct gld${EMULATION_NAME}_ld_so_conf *info, const char *filename);
638
639 static void
640 gld${EMULATION_NAME}_parse_ld_so_conf_include
641      (struct gld${EMULATION_NAME}_ld_so_conf *info, const char *filename,
642       const char *pattern)
643 {
644   char *newp = NULL;
645 #ifdef HAVE_GLOB
646   glob_t gl;
647 #endif
648
649   if (pattern[0] != '/')
650     {
651       char *p = strrchr (filename, '/');
652       size_t patlen = strlen (pattern) + 1;
653
654       newp = xmalloc (p - filename + 1 + patlen);
655       memcpy (newp, filename, p - filename + 1);
656       memcpy (newp + (p - filename + 1), pattern, patlen);
657       pattern = newp;
658     }
659
660 #ifdef HAVE_GLOB
661   if (glob (pattern, 0, NULL, &gl) == 0)
662     {
663       size_t i;
664
665       for (i = 0; i < gl.gl_pathc; ++i)
666         gld${EMULATION_NAME}_parse_ld_so_conf (info, gl.gl_pathv[i]);
667       globfree (&gl);
668     }
669 #else
670   /* If we do not have glob, treat the pattern as a literal filename.  */
671   gld${EMULATION_NAME}_parse_ld_so_conf (info, pattern);
672 #endif
673
674   if (newp)
675     free (newp);
676 }
677
678 static bfd_boolean
679 gld${EMULATION_NAME}_parse_ld_so_conf
680      (struct gld${EMULATION_NAME}_ld_so_conf *info, const char *filename)
681 {
682   FILE *f = fopen (filename, FOPEN_RT);
683   char *line;
684   size_t linelen;
685
686   if (f == NULL)
687     return FALSE;
688
689   linelen = 256;
690   line = xmalloc (linelen);
691   do
692     {
693       char *p = line, *q;
694
695       /* Normally this would use getline(3), but we need to be portable.  */
696       while ((q = fgets (p, linelen - (p - line), f)) != NULL
697              && strlen (q) == linelen - (p - line) - 1
698              && line[linelen - 2] != '\n')
699         {
700           line = xrealloc (line, 2 * linelen);
701           p = line + linelen - 1;
702           linelen += linelen;
703         }
704
705       if (q == NULL && p == line)
706         break;
707
708       p = strchr (line, '\n');
709       if (p)
710         *p = '\0';
711
712       /* Because the file format does not know any form of quoting we
713          can search forward for the next '#' character and if found
714          make it terminating the line.  */
715       p = strchr (line, '#');
716       if (p)
717         *p = '\0';
718
719       /* Remove leading whitespace.  NUL is no whitespace character.  */
720       p = line;
721       while (*p == ' ' || *p == '\f' || *p == '\r' || *p == '\t' || *p == '\v')
722         ++p;
723
724       /* If the line is blank it is ignored.  */
725       if (p[0] == '\0')
726         continue;
727
728       if (CONST_STRNEQ (p, "include") && (p[7] == ' ' || p[7] == '\t'))
729         {
730           char *dir, c;
731           p += 8;
732           do
733             {
734               while (*p == ' ' || *p == '\t')
735                 ++p;
736
737               if (*p == '\0')
738                 break;
739
740               dir = p;
741
742               while (*p != ' ' && *p != '\t' && *p)
743                 ++p;
744
745               c = *p;
746               *p++ = '\0';
747               if (dir[0] != '\0')
748                 gld${EMULATION_NAME}_parse_ld_so_conf_include (info, filename,
749                                                                dir);
750             }
751           while (c != '\0');
752         }
753       else
754         {
755           char *dir = p;
756           while (*p && *p != '=' && *p != ' ' && *p != '\t' && *p != '\f'
757                  && *p != '\r' && *p != '\v')
758             ++p;
759
760           while (p != dir && p[-1] == '/')
761             --p;
762           if (info->path == NULL)
763             {
764               info->alloc = p - dir + 1 + 256;
765               info->path = xmalloc (info->alloc);
766               info->len = 0;
767             }
768           else
769             {
770               if (info->len + 1 + (p - dir) >= info->alloc)
771                 {
772                   info->alloc += p - dir + 256;
773                   info->path = xrealloc (info->path, info->alloc);
774                 }
775               info->path[info->len++] = config.rpath_separator;
776             }
777           memcpy (info->path + info->len, dir, p - dir);
778           info->len += p - dir;
779           info->path[info->len] = '\0';
780         }
781     }
782   while (! feof (f));
783   free (line);
784   fclose (f);
785   return TRUE;
786 }
787
788 static bfd_boolean
789 gld${EMULATION_NAME}_check_ld_so_conf (const struct bfd_link_needed_list *l,
790                                        int force)
791 {
792   static bfd_boolean initialized;
793   static char *ld_so_conf;
794   struct dt_needed needed;
795
796   if (! initialized)
797     {
798       char *tmppath;
799       struct gld${EMULATION_NAME}_ld_so_conf info;
800
801       info.path = NULL;
802       info.len = info.alloc = 0;
803       tmppath = concat (ld_sysroot, "${prefix}/etc/ld.so.conf",
804                         (const char *) NULL);
805       if (!gld${EMULATION_NAME}_parse_ld_so_conf (&info, tmppath))
806         {
807           free (tmppath);
808           tmppath = concat (ld_sysroot, "/etc/ld.so.conf",
809                             (const char *) NULL);
810           gld${EMULATION_NAME}_parse_ld_so_conf (&info, tmppath);
811         }
812       free (tmppath);
813
814       if (info.path)
815         {
816           char *d = gld${EMULATION_NAME}_add_sysroot (info.path);
817           free (info.path);
818           ld_so_conf = d;
819         }
820       initialized = TRUE;
821     }
822
823   if (ld_so_conf == NULL)
824     return FALSE;
825
826
827   needed.by = l->by;
828   needed.name = l->name;
829   return gld${EMULATION_NAME}_search_needed (ld_so_conf, &needed, force);
830 }
831
832 EOF
833     # Linux
834     ;;
835   esac
836 fi
837 fragment <<EOF
838
839 /* See if an input file matches a DT_NEEDED entry by name.  */
840
841 static void
842 gld${EMULATION_NAME}_check_needed (lang_input_statement_type *s)
843 {
844   const char *soname;
845
846   /* Stop looking if we've found a loaded lib.  */
847   if (global_found != NULL
848       && (bfd_elf_get_dyn_lib_class (global_found->the_bfd)
849           & DYN_AS_NEEDED) == 0)
850     return;
851
852   if (s->filename == NULL || s->the_bfd == NULL)
853     return;
854
855   /* Don't look for a second non-loaded as-needed lib.  */
856   if (global_found != NULL
857       && (bfd_elf_get_dyn_lib_class (s->the_bfd) & DYN_AS_NEEDED) != 0)
858     return;
859
860   if (filename_cmp (s->filename, global_needed->name) == 0)
861     {
862       global_found = s;
863       return;
864     }
865
866   if (s->flags.search_dirs)
867     {
868       const char *f = strrchr (s->filename, '/');
869       if (f != NULL
870           && filename_cmp (f + 1, global_needed->name) == 0)
871         {
872           global_found = s;
873           return;
874         }
875     }
876
877   soname = bfd_elf_get_dt_soname (s->the_bfd);
878   if (soname != NULL
879       && filename_cmp (soname, global_needed->name) == 0)
880     {
881       global_found = s;
882       return;
883     }
884 }
885
886 EOF
887
888 if test x"$LDEMUL_AFTER_OPEN" != xgld"$EMULATION_NAME"_after_open; then
889 fragment <<EOF
890
891 static bfd_size_type
892 id_note_section_size (bfd *abfd ATTRIBUTE_UNUSED)
893 {
894   const char *style = emit_note_gnu_build_id;
895   bfd_size_type size;
896   bfd_size_type build_id_size;
897
898   size = offsetof (Elf_External_Note, name[sizeof "GNU"]);
899   size = (size + 3) & -(bfd_size_type) 4;
900
901   build_id_size = compute_build_id_size (style);
902   if (build_id_size)
903     size += build_id_size;
904   else
905     size = 0;
906
907   return size;
908 }
909
910 static bfd_boolean
911 write_build_id (bfd *abfd)
912 {
913   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
914   struct elf_obj_tdata *t = elf_tdata (abfd);
915   const char *style;
916   asection *asec;
917   Elf_Internal_Shdr *i_shdr;
918   unsigned char *contents, *id_bits;
919   bfd_size_type size;
920   file_ptr position;
921   Elf_External_Note *e_note;
922
923   style = t->o->build_id.style;
924   asec = t->o->build_id.sec;
925   if (bfd_is_abs_section (asec->output_section))
926     {
927       einfo (_("%P: warning: .note.gnu.build-id section discarded,"
928                " --build-id ignored.\n"));
929       return TRUE;
930     }
931   i_shdr = &elf_section_data (asec->output_section)->this_hdr;
932
933   if (i_shdr->contents == NULL)
934     {
935       if (asec->contents == NULL)
936         asec->contents = (unsigned char *) xmalloc (asec->size);
937       contents = asec->contents;
938     }
939   else
940     contents = i_shdr->contents + asec->output_offset;
941
942   e_note = (Elf_External_Note *) contents;
943   size = offsetof (Elf_External_Note, name[sizeof "GNU"]);
944   size = (size + 3) & -(bfd_size_type) 4;
945   id_bits = contents + size;
946   size = asec->size - size;
947
948   bfd_h_put_32 (abfd, sizeof "GNU", &e_note->namesz);
949   bfd_h_put_32 (abfd, size, &e_note->descsz);
950   bfd_h_put_32 (abfd, NT_GNU_BUILD_ID, &e_note->type);
951   memcpy (e_note->name, "GNU", sizeof "GNU");
952
953   generate_build_id (abfd, style, bed->s->checksum_contents, id_bits, size);
954
955   position = i_shdr->sh_offset + asec->output_offset;
956   size = asec->size;
957   return (bfd_seek (abfd, position, SEEK_SET) == 0
958           && bfd_bwrite (contents, size, abfd) == size);
959 }
960
961 /* Make .note.gnu.build-id section, and set up elf_tdata->build_id.  */
962
963 static bfd_boolean
964 setup_build_id (bfd *ibfd)
965 {
966   asection *s;
967   bfd_size_type size;
968   flagword flags;
969
970   size = id_note_section_size (ibfd);
971   if (size == 0)
972     {
973       einfo ("%P: warning: unrecognized --build-id style ignored.\n");
974       return FALSE;
975     }
976
977   flags = (SEC_ALLOC | SEC_LOAD | SEC_IN_MEMORY
978            | SEC_LINKER_CREATED | SEC_READONLY | SEC_DATA);
979   s = bfd_make_section_with_flags (ibfd, ".note.gnu.build-id", flags);
980   if (s != NULL && bfd_set_section_alignment (ibfd, s, 2))
981     {
982       struct elf_obj_tdata *t = elf_tdata (link_info.output_bfd);
983       t->o->build_id.after_write_object_contents = &write_build_id;
984       t->o->build_id.style = emit_note_gnu_build_id;
985       t->o->build_id.sec = s;
986       elf_section_type (s) = SHT_NOTE;
987       s->size = size;
988       return TRUE;
989     }
990
991   einfo ("%P: warning: Cannot create .note.gnu.build-id section,"
992          " --build-id ignored.\n");
993   return FALSE;
994 }
995
996 /* This is called after all the input files have been opened.  */
997
998 static void
999 gld${EMULATION_NAME}_after_open (void)
1000 {
1001   struct bfd_link_needed_list *needed, *l;
1002   struct elf_link_hash_table *htab;
1003
1004   after_open_default ();
1005
1006   htab = elf_hash_table (&link_info);
1007   if (!is_elf_hash_table (htab))
1008     return;
1009
1010   if (emit_note_gnu_build_id != NULL)
1011     {
1012       bfd *abfd;
1013
1014       /* Find an ELF input.  */
1015       for (abfd = link_info.input_bfds;
1016            abfd != (bfd *) NULL; abfd = abfd->link_next)
1017         if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
1018           break;
1019
1020       /* PR 10555: If there are no ELF input files do not try to
1021          create a .note.gnu-build-id section.  */
1022       if (abfd == NULL
1023           || !setup_build_id (abfd))
1024         {
1025           free ((char *) emit_note_gnu_build_id);
1026           emit_note_gnu_build_id = NULL;
1027         }
1028     }
1029
1030   if (link_info.relocatable)
1031     {
1032       if (link_info.execstack == ! link_info.noexecstack)
1033         /* PR ld/16744: If "-z [no]execstack" has been specified on the
1034            command line and we are perfoming a relocatable link then no
1035            PT_GNU_STACK segment will be created and so the
1036            linkinfo.[no]execstack values set in _handle_option() will have no
1037            effect.  Instead we create a .note.GNU-stack section in much the
1038            same way as the assembler does with its --[no]execstack option.  */
1039         (void) bfd_make_section_with_flags (link_info.input_bfds,
1040                                             ".note.GNU-stack",
1041                                             SEC_READONLY | (link_info.execstack ? SEC_CODE : 0));
1042
1043       return;
1044     }
1045
1046   if (link_info.eh_frame_hdr
1047       && !link_info.traditional_format)
1048     {
1049       bfd *abfd, *elfbfd = NULL;
1050       bfd_boolean warn_eh_frame = FALSE;
1051       asection *s;
1052
1053       for (abfd = link_info.input_bfds; abfd; abfd = abfd->link_next)
1054         {
1055           if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
1056             elfbfd = abfd;
1057           if (!warn_eh_frame)
1058             {
1059               s = bfd_get_section_by_name (abfd, ".eh_frame");
1060               while (s != NULL
1061                      && (s->size <= 8
1062                          || bfd_is_abs_section (s->output_section)))
1063                 s = bfd_get_next_section_by_name (s);
1064               warn_eh_frame = s != NULL;
1065             }
1066           if (elfbfd && warn_eh_frame)
1067             break;
1068         }
1069       if (elfbfd)
1070         {
1071           const struct elf_backend_data *bed;
1072
1073           bed = get_elf_backend_data (elfbfd);
1074           s = bfd_make_section_with_flags (elfbfd, ".eh_frame_hdr",
1075                                            bed->dynamic_sec_flags
1076                                            | SEC_READONLY);
1077           if (s != NULL
1078               && bfd_set_section_alignment (elfbfd, s, 2))
1079             {
1080               htab->eh_info.hdr_sec = s;
1081               warn_eh_frame = FALSE;
1082             }
1083         }
1084       if (warn_eh_frame)
1085         einfo ("%P: warning: Cannot create .eh_frame_hdr section,"
1086                " --eh-frame-hdr ignored.\n");
1087     }
1088
1089   /* Get the list of files which appear in DT_NEEDED entries in
1090      dynamic objects included in the link (often there will be none).
1091      For each such file, we want to track down the corresponding
1092      library, and include the symbol table in the link.  This is what
1093      the runtime dynamic linker will do.  Tracking the files down here
1094      permits one dynamic object to include another without requiring
1095      special action by the person doing the link.  Note that the
1096      needed list can actually grow while we are stepping through this
1097      loop.  */
1098   needed = bfd_elf_get_needed_list (link_info.output_bfd, &link_info);
1099   for (l = needed; l != NULL; l = l->next)
1100     {
1101       struct bfd_link_needed_list *ll;
1102       struct dt_needed n, nn;
1103       int force;
1104
1105       /* If the lib that needs this one was --as-needed and wasn't
1106          found to be needed, then this lib isn't needed either.  */
1107       if (l->by != NULL
1108           && (bfd_elf_get_dyn_lib_class (l->by) & DYN_AS_NEEDED) != 0)
1109         continue;
1110
1111       /* Skip the lib if --no-copy-dt-needed-entries and
1112          --allow-shlib-undefined is in effect.  */
1113       if (l->by != NULL
1114           && link_info.unresolved_syms_in_shared_libs == RM_IGNORE
1115           && (bfd_elf_get_dyn_lib_class (l->by) & DYN_NO_ADD_NEEDED) != 0)
1116         continue;
1117
1118       /* If we've already seen this file, skip it.  */
1119       for (ll = needed; ll != l; ll = ll->next)
1120         if ((ll->by == NULL
1121              || (bfd_elf_get_dyn_lib_class (ll->by) & DYN_AS_NEEDED) == 0)
1122             && strcmp (ll->name, l->name) == 0)
1123           break;
1124       if (ll != l)
1125         continue;
1126
1127       /* See if this file was included in the link explicitly.  */
1128       global_needed = l;
1129       global_found = NULL;
1130       lang_for_each_input_file (gld${EMULATION_NAME}_check_needed);
1131       if (global_found != NULL
1132           && (bfd_elf_get_dyn_lib_class (global_found->the_bfd)
1133               & DYN_AS_NEEDED) == 0)
1134         continue;
1135
1136       n.by = l->by;
1137       n.name = l->name;
1138       nn.by = l->by;
1139       if (verbose)
1140         info_msg (_("%s needed by %B\n"), l->name, l->by);
1141
1142       /* As-needed libs specified on the command line (or linker script)
1143          take priority over libs found in search dirs.  */
1144       if (global_found != NULL)
1145         {
1146           nn.name = global_found->filename;
1147           if (gld${EMULATION_NAME}_try_needed (&nn, TRUE))
1148             continue;
1149         }
1150
1151       /* We need to find this file and include the symbol table.  We
1152          want to search for the file in the same way that the dynamic
1153          linker will search.  That means that we want to use
1154          rpath_link, rpath, then the environment variable
1155          LD_LIBRARY_PATH (native only), then the DT_RPATH/DT_RUNPATH
1156          entries (native only), then the linker script LIB_SEARCH_DIRS.
1157          We do not search using the -L arguments.
1158
1159          We search twice.  The first time, we skip objects which may
1160          introduce version mismatches.  The second time, we force
1161          their use.  See gld${EMULATION_NAME}_vercheck comment.  */
1162       for (force = 0; force < 2; force++)
1163         {
1164           size_t len;
1165           search_dirs_type *search;
1166 EOF
1167 if [ "x${NATIVE}" = xyes ] ; then
1168 fragment <<EOF
1169           const char *lib_path;
1170 EOF
1171 fi
1172 if [ "x${USE_LIBPATH}" = xyes ] ; then
1173 fragment <<EOF
1174           struct bfd_link_needed_list *rp;
1175           int found;
1176 EOF
1177 fi
1178 fragment <<EOF
1179
1180           if (gld${EMULATION_NAME}_search_needed (command_line.rpath_link,
1181                                                   &n, force))
1182             break;
1183 EOF
1184 if [ "x${USE_LIBPATH}" = xyes ] ; then
1185 fragment <<EOF
1186           if (gld${EMULATION_NAME}_search_needed (command_line.rpath,
1187                                                   &n, force))
1188             break;
1189 EOF
1190 fi
1191 if [ "x${NATIVE}" = xyes ] ; then
1192 fragment <<EOF
1193           if (command_line.rpath_link == NULL
1194               && command_line.rpath == NULL)
1195             {
1196               lib_path = (const char *) getenv ("LD_RUN_PATH");
1197               if (gld${EMULATION_NAME}_search_needed (lib_path, &n,
1198                                                       force))
1199                 break;
1200             }
1201           lib_path = (const char *) getenv ("LD_LIBRARY_PATH");
1202           if (gld${EMULATION_NAME}_search_needed (lib_path, &n, force))
1203             break;
1204 EOF
1205 fi
1206 if [ "x${USE_LIBPATH}" = xyes ] ; then
1207 fragment <<EOF
1208           found = 0;
1209           rp = bfd_elf_get_runpath_list (link_info.output_bfd, &link_info);
1210           for (; !found && rp != NULL; rp = rp->next)
1211             {
1212               char *tmpname = gld${EMULATION_NAME}_add_sysroot (rp->name);
1213               found = (rp->by == l->by
1214                        && gld${EMULATION_NAME}_search_needed (tmpname,
1215                                                               &n,
1216                                                               force));
1217               free (tmpname);
1218             }
1219           if (found)
1220             break;
1221
1222 EOF
1223 fi
1224 if [ "x${USE_LIBPATH}" = xyes ] ; then
1225   case ${target} in
1226     *-*-freebsd* | *-*-dragonfly*)
1227       fragment <<EOF
1228           if (gld${EMULATION_NAME}_check_ld_elf_hints (l, force))
1229             break;
1230 EOF
1231     # FreeBSD
1232     ;;
1233
1234     *-*-linux-* | *-*-k*bsd*-* | *-*-gnu*)
1235       fragment <<EOF
1236           if (gld${EMULATION_NAME}_check_ld_so_conf (l, force))
1237             break;
1238
1239 EOF
1240     # Linux
1241     ;;
1242   esac
1243 fi
1244 fragment <<EOF
1245           len = strlen (l->name);
1246           for (search = search_head; search != NULL; search = search->next)
1247             {
1248               char *filename;
1249
1250               if (search->cmdline)
1251                 continue;
1252               filename = (char *) xmalloc (strlen (search->name) + len + 2);
1253               sprintf (filename, "%s/%s", search->name, l->name);
1254               nn.name = filename;
1255               if (gld${EMULATION_NAME}_try_needed (&nn, force))
1256                 break;
1257               free (filename);
1258             }
1259           if (search != NULL)
1260             break;
1261 EOF
1262 fragment <<EOF
1263         }
1264
1265       if (force < 2)
1266         continue;
1267
1268       einfo ("%P: warning: %s, needed by %B, not found (try using -rpath or -rpath-link)\n",
1269              l->name, l->by);
1270     }
1271 }
1272
1273 EOF
1274 fi
1275
1276 fragment <<EOF
1277
1278 /* Look through an expression for an assignment statement.  */
1279
1280 static void
1281 gld${EMULATION_NAME}_find_exp_assignment (etree_type *exp)
1282 {
1283   bfd_boolean provide = FALSE;
1284
1285   switch (exp->type.node_class)
1286     {
1287     case etree_provide:
1288     case etree_provided:
1289       provide = TRUE;
1290       /* Fall thru */
1291     case etree_assign:
1292       /* We call record_link_assignment even if the symbol is defined.
1293          This is because if it is defined by a dynamic object, we
1294          actually want to use the value defined by the linker script,
1295          not the value from the dynamic object (because we are setting
1296          symbols like etext).  If the symbol is defined by a regular
1297          object, then, as it happens, calling record_link_assignment
1298          will do no harm.  */
1299       if (strcmp (exp->assign.dst, ".") != 0)
1300         {
1301           if (!bfd_elf_record_link_assignment (link_info.output_bfd,
1302                                                &link_info,
1303                                                exp->assign.dst, provide,
1304                                                exp->assign.hidden))
1305             einfo ("%P%F: failed to record assignment to %s: %E\n",
1306                    exp->assign.dst);
1307         }
1308       gld${EMULATION_NAME}_find_exp_assignment (exp->assign.src);
1309       break;
1310
1311     case etree_binary:
1312       gld${EMULATION_NAME}_find_exp_assignment (exp->binary.lhs);
1313       gld${EMULATION_NAME}_find_exp_assignment (exp->binary.rhs);
1314       break;
1315
1316     case etree_trinary:
1317       gld${EMULATION_NAME}_find_exp_assignment (exp->trinary.cond);
1318       gld${EMULATION_NAME}_find_exp_assignment (exp->trinary.lhs);
1319       gld${EMULATION_NAME}_find_exp_assignment (exp->trinary.rhs);
1320       break;
1321
1322     case etree_unary:
1323       gld${EMULATION_NAME}_find_exp_assignment (exp->unary.child);
1324       break;
1325
1326     default:
1327       break;
1328     }
1329 }
1330
1331
1332 /* This is called by the before_allocation routine via
1333    lang_for_each_statement.  It locates any assignment statements, and
1334    tells the ELF backend about them, in case they are assignments to
1335    symbols which are referred to by dynamic objects.  */
1336
1337 static void
1338 gld${EMULATION_NAME}_find_statement_assignment (lang_statement_union_type *s)
1339 {
1340   if (s->header.type == lang_assignment_statement_enum)
1341     gld${EMULATION_NAME}_find_exp_assignment (s->assignment_statement.exp);
1342 }
1343
1344 EOF
1345
1346 if test x"$LDEMUL_BEFORE_ALLOCATION" != xgld"$EMULATION_NAME"_before_allocation; then
1347   if test x"${ELF_INTERPRETER_NAME+set}" = xset; then
1348     ELF_INTERPRETER_SET_DEFAULT="
1349   if (sinterp != NULL)
1350     {
1351       sinterp->contents = (unsigned char *) ${ELF_INTERPRETER_NAME};
1352       sinterp->size = strlen ((char *) sinterp->contents) + 1;
1353     }
1354
1355 "
1356   else
1357     ELF_INTERPRETER_SET_DEFAULT=
1358   fi
1359 fragment <<EOF
1360
1361 /* used by before_allocation and handle_option. */
1362 static void
1363 gld${EMULATION_NAME}_append_to_separated_string (char **to, char *op_arg)
1364 {
1365   if (*to == NULL)
1366     *to = xstrdup (op_arg);
1367   else
1368     {
1369       size_t to_len = strlen (*to);
1370       size_t op_arg_len = strlen (op_arg);
1371       char *buf;
1372       char *cp = *to;
1373
1374       /* First see whether OPTARG is already in the path.  */
1375       do
1376         {
1377           if (strncmp (op_arg, cp, op_arg_len) == 0
1378               && (cp[op_arg_len] == 0
1379                   || cp[op_arg_len] == config.rpath_separator))
1380             /* We found it.  */
1381             break;
1382
1383           /* Not yet found.  */
1384           cp = strchr (cp, config.rpath_separator);
1385           if (cp != NULL)
1386             ++cp;
1387         }
1388       while (cp != NULL);
1389
1390       if (cp == NULL)
1391         {
1392           buf = xmalloc (to_len + op_arg_len + 2);
1393           sprintf (buf, "%s%c%s", *to,
1394                    config.rpath_separator, op_arg);
1395           free (*to);
1396           *to = buf;
1397         }
1398     }
1399 }
1400
1401 /* This is called after the sections have been attached to output
1402    sections, but before any sizes or addresses have been set.  */
1403
1404 static void
1405 gld${EMULATION_NAME}_before_allocation (void)
1406 {
1407   const char *rpath;
1408   asection *sinterp;
1409   bfd *abfd;
1410   struct elf_link_hash_entry *ehdr_start = NULL;
1411   struct bfd_link_hash_entry ehdr_start_save = ehdr_start_save;
1412
1413   if (is_elf_hash_table (link_info.hash))
1414     {
1415       _bfd_elf_tls_setup (link_info.output_bfd, &link_info);
1416
1417       /* Make __ehdr_start hidden if it has been referenced, to
1418          prevent the symbol from being dynamic.  */
1419       if (!link_info.relocatable)
1420        {
1421          struct elf_link_hash_entry *h
1422            = elf_link_hash_lookup (elf_hash_table (&link_info), "__ehdr_start",
1423                                    FALSE, FALSE, TRUE);
1424
1425          /* Only adjust the export class if the symbol was referenced
1426             and not defined, otherwise leave it alone.  */
1427          if (h != NULL
1428              && (h->root.type == bfd_link_hash_new
1429                  || h->root.type == bfd_link_hash_undefined
1430                  || h->root.type == bfd_link_hash_undefweak
1431                  || h->root.type == bfd_link_hash_common))
1432            {
1433              _bfd_elf_link_hash_hide_symbol (&link_info, h, TRUE);
1434              if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
1435                h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
1436              /* Don't leave the symbol undefined.  Undefined hidden
1437                 symbols typically won't have dynamic relocations, but
1438                 we most likely will need dynamic relocations for
1439                 __ehdr_start if we are building a PIE or shared
1440                 library.  */
1441              ehdr_start = h;
1442              ehdr_start_save = h->root;
1443              h->root.type = bfd_link_hash_defined;
1444              h->root.u.def.section = bfd_abs_section_ptr;
1445              h->root.u.def.value = 0;
1446            }
1447        }
1448
1449       /* If we are going to make any variable assignments, we need to
1450          let the ELF backend know about them in case the variables are
1451          referred to by dynamic objects.  */
1452       lang_for_each_statement (gld${EMULATION_NAME}_find_statement_assignment);
1453     }
1454
1455   /* Let the ELF backend work out the sizes of any sections required
1456      by dynamic linking.  */
1457   rpath = command_line.rpath;
1458   if (rpath == NULL)
1459     rpath = (const char *) getenv ("LD_RUN_PATH");
1460
1461   for (abfd = link_info.input_bfds; abfd; abfd = abfd->link_next)
1462     if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
1463       {
1464         const char *audit_libs = elf_dt_audit (abfd);
1465
1466         /* If the input bfd contains an audit entry, we need to add it as
1467            a dep audit entry.  */
1468         if (audit_libs && *audit_libs != '\0')
1469           {
1470             char *cp = xstrdup (audit_libs);
1471             do
1472               {
1473                 int more = 0;
1474                 char *cp2 = strchr (cp, config.rpath_separator);
1475
1476                 if (cp2)
1477                   {
1478                     *cp2 = '\0';
1479                     more = 1;
1480                   }
1481
1482                 if (cp != NULL && *cp != '\0')
1483                   gld${EMULATION_NAME}_append_to_separated_string (&depaudit, cp);
1484
1485                 cp = more ? ++cp2 : NULL;
1486               }
1487             while (cp != NULL);
1488           }
1489       }
1490
1491   if (! (bfd_elf_size_dynamic_sections
1492          (link_info.output_bfd, command_line.soname, rpath,
1493           command_line.filter_shlib, audit, depaudit,
1494           (const char * const *) command_line.auxiliary_filters,
1495           &link_info, &sinterp)))
1496     einfo ("%P%F: failed to set dynamic section sizes: %E\n");
1497
1498 ${ELF_INTERPRETER_SET_DEFAULT}
1499   /* Let the user override the dynamic linker we are using.  */
1500   if (command_line.interpreter != NULL
1501       && sinterp != NULL)
1502     {
1503       sinterp->contents = (bfd_byte *) command_line.interpreter;
1504       sinterp->size = strlen (command_line.interpreter) + 1;
1505     }
1506
1507   /* Look for any sections named .gnu.warning.  As a GNU extensions,
1508      we treat such sections as containing warning messages.  We print
1509      out the warning message, and then zero out the section size so
1510      that it does not get copied into the output file.  */
1511
1512   {
1513     LANG_FOR_EACH_INPUT_STATEMENT (is)
1514       {
1515         asection *s;
1516         bfd_size_type sz;
1517         char *msg;
1518         bfd_boolean ret;
1519
1520         if (is->flags.just_syms)
1521           continue;
1522
1523         s = bfd_get_section_by_name (is->the_bfd, ".gnu.warning");
1524         if (s == NULL)
1525           continue;
1526
1527         sz = s->size;
1528         msg = (char *) xmalloc ((size_t) (sz + 1));
1529         if (! bfd_get_section_contents (is->the_bfd, s, msg,
1530                                         (file_ptr) 0, sz))
1531           einfo ("%F%B: Can't read contents of section .gnu.warning: %E\n",
1532                  is->the_bfd);
1533         msg[sz] = '\0';
1534         ret = link_info.callbacks->warning (&link_info, msg,
1535                                             (const char *) NULL,
1536                                             is->the_bfd, (asection *) NULL,
1537                                             (bfd_vma) 0);
1538         ASSERT (ret);
1539         free (msg);
1540
1541         /* Clobber the section size, so that we don't waste space
1542            copying the warning into the output file.  If we've already
1543            sized the output section, adjust its size.  The adjustment
1544            is on rawsize because targets that size sections early will
1545            have called lang_reset_memory_regions after sizing.  */
1546         if (s->output_section != NULL
1547             && s->output_section->rawsize >= s->size)
1548           s->output_section->rawsize -= s->size;
1549
1550         s->size = 0;
1551
1552         /* Also set SEC_EXCLUDE, so that local symbols defined in the
1553            warning section don't get copied to the output.  */
1554         s->flags |= SEC_EXCLUDE | SEC_KEEP;
1555       }
1556   }
1557
1558   before_allocation_default ();
1559
1560   if (!bfd_elf_size_dynsym_hash_dynstr (link_info.output_bfd, &link_info))
1561     einfo ("%P%F: failed to set dynamic section sizes: %E\n");
1562
1563   if (ehdr_start != NULL)
1564     {
1565       /* If we twiddled __ehdr_start to defined earlier, put it back
1566          as it was.  */
1567       ehdr_start->root.type = ehdr_start_save.type;
1568       ehdr_start->root.u = ehdr_start_save.u;
1569     }
1570 }
1571
1572 EOF
1573 fi
1574
1575 if test x"$LDEMUL_OPEN_DYNAMIC_ARCHIVE" != xgld"$EMULATION_NAME"_open_dynamic_archive; then
1576 fragment <<EOF
1577
1578 /* Try to open a dynamic archive.  This is where we know that ELF
1579    dynamic libraries have an extension of .so (or .sl on oddball systems
1580    like hpux).  */
1581
1582 static bfd_boolean
1583 gld${EMULATION_NAME}_open_dynamic_archive
1584   (const char *arch, search_dirs_type *search, lang_input_statement_type *entry)
1585 {
1586   const char *filename;
1587   char *string;
1588   size_t len;
1589   bfd_boolean opened = FALSE;
1590
1591   if (! entry->flags.maybe_archive)
1592     return FALSE;
1593
1594   filename = entry->filename;
1595   len = strlen (search->name) + strlen (filename);
1596   if (entry->flags.full_name_provided)
1597     {
1598       len += sizeof "/";
1599       string = (char *) xmalloc (len);
1600       sprintf (string, "%s/%s", search->name, filename);
1601     }
1602   else
1603     {
1604       size_t xlen = 0;
1605
1606       len += strlen (arch) + sizeof "/lib.so";
1607 #ifdef EXTRA_SHLIB_EXTENSION
1608       xlen = (strlen (EXTRA_SHLIB_EXTENSION) > 3
1609               ? strlen (EXTRA_SHLIB_EXTENSION) - 3
1610               : 0);
1611 #endif
1612       string = (char *) xmalloc (len + xlen);
1613       sprintf (string, "%s/lib%s%s.so", search->name, filename, arch);
1614 #ifdef EXTRA_SHLIB_EXTENSION
1615       /* Try the .so extension first.  If that fails build a new filename
1616          using EXTRA_SHLIB_EXTENSION.  */
1617       opened = ldfile_try_open_bfd (string, entry);
1618       if (!opened)
1619         strcpy (string + len - 4, EXTRA_SHLIB_EXTENSION);
1620 #endif
1621     }
1622
1623   if (!opened && !ldfile_try_open_bfd (string, entry))
1624     {
1625       free (string);
1626       return FALSE;
1627     }
1628
1629   entry->filename = string;
1630
1631   /* We have found a dynamic object to include in the link.  The ELF
1632      backend linker will create a DT_NEEDED entry in the .dynamic
1633      section naming this file.  If this file includes a DT_SONAME
1634      entry, it will be used.  Otherwise, the ELF linker will just use
1635      the name of the file.  For an archive found by searching, like
1636      this one, the DT_NEEDED entry should consist of just the name of
1637      the file, without the path information used to find it.  Note
1638      that we only need to do this if we have a dynamic object; an
1639      archive will never be referenced by a DT_NEEDED entry.
1640
1641      FIXME: This approach--using bfd_elf_set_dt_needed_name--is not
1642      very pretty.  I haven't been able to think of anything that is
1643      pretty, though.  */
1644   if (bfd_check_format (entry->the_bfd, bfd_object)
1645       && (entry->the_bfd->flags & DYNAMIC) != 0)
1646     {
1647       ASSERT (entry->flags.maybe_archive && entry->flags.search_dirs);
1648
1649       /* Rather than duplicating the logic above.  Just use the
1650          filename we recorded earlier.  */
1651
1652       if (!entry->flags.full_name_provided)
1653         filename = lbasename (entry->filename);
1654       bfd_elf_set_dt_needed_name (entry->the_bfd, filename);
1655     }
1656
1657   return TRUE;
1658 }
1659
1660 EOF
1661 fi
1662
1663 if test x"$LDEMUL_PLACE_ORPHAN" != xgld"$EMULATION_NAME"_place_orphan; then
1664 fragment <<EOF
1665
1666 /* A variant of lang_output_section_find used by place_orphan.  */
1667
1668 static lang_output_section_statement_type *
1669 output_rel_find (asection *sec, int isdyn)
1670 {
1671   lang_output_section_statement_type *lookup;
1672   lang_output_section_statement_type *last = NULL;
1673   lang_output_section_statement_type *last_alloc = NULL;
1674   lang_output_section_statement_type *last_ro_alloc = NULL;
1675   lang_output_section_statement_type *last_rel = NULL;
1676   lang_output_section_statement_type *last_rel_alloc = NULL;
1677   int rela = sec->name[4] == 'a';
1678
1679   for (lookup = &lang_output_section_statement.head->output_section_statement;
1680        lookup != NULL;
1681        lookup = lookup->next)
1682     {
1683       if (lookup->constraint >= 0
1684           && CONST_STRNEQ (lookup->name, ".rel"))
1685         {
1686           int lookrela = lookup->name[4] == 'a';
1687
1688           /* .rel.dyn must come before all other reloc sections, to suit
1689              GNU ld.so.  */
1690           if (isdyn)
1691             break;
1692
1693           /* Don't place after .rel.plt as doing so results in wrong
1694              dynamic tags.  */
1695           if (strcmp (".plt", lookup->name + 4 + lookrela) == 0)
1696             break;
1697
1698           if (rela == lookrela || last_rel == NULL)
1699             last_rel = lookup;
1700           if ((rela == lookrela || last_rel_alloc == NULL)
1701               && lookup->bfd_section != NULL
1702               && (lookup->bfd_section->flags & SEC_ALLOC) != 0)
1703             last_rel_alloc = lookup;
1704         }
1705
1706       last = lookup;
1707       if (lookup->bfd_section != NULL
1708           && (lookup->bfd_section->flags & SEC_ALLOC) != 0)
1709         {
1710           last_alloc = lookup;
1711           if ((lookup->bfd_section->flags & SEC_READONLY) != 0)
1712             last_ro_alloc = lookup;
1713         }
1714     }
1715
1716   if (last_rel_alloc)
1717     return last_rel_alloc;
1718
1719   if (last_rel)
1720     return last_rel;
1721
1722   if (last_ro_alloc)
1723     return last_ro_alloc;
1724
1725   if (last_alloc)
1726     return last_alloc;
1727
1728   return last;
1729 }
1730
1731 /* Place an orphan section.  We use this to put random SHF_ALLOC
1732    sections in the right segment.  */
1733
1734 static lang_output_section_statement_type *
1735 gld${EMULATION_NAME}_place_orphan (asection *s,
1736                                    const char *secname,
1737                                    int constraint)
1738 {
1739   static struct orphan_save hold[] =
1740     {
1741       { ".text",
1742         SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_CODE,
1743         0, 0, 0, 0 },
1744       { ".rodata",
1745         SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
1746         0, 0, 0, 0 },
1747       { ".tdata",
1748         SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA | SEC_THREAD_LOCAL,
1749         0, 0, 0, 0 },
1750       { ".data",
1751         SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA,
1752         0, 0, 0, 0 },
1753       { ".bss",
1754         SEC_ALLOC,
1755         0, 0, 0, 0 },
1756       { 0,
1757         SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
1758         0, 0, 0, 0 },
1759       { ".interp",
1760         SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
1761         0, 0, 0, 0 },
1762       { ".sdata",
1763         SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA | SEC_SMALL_DATA,
1764         0, 0, 0, 0 },
1765       { ".comment",
1766         SEC_HAS_CONTENTS,
1767         0, 0, 0, 0 },
1768     };
1769   enum orphan_save_index
1770     {
1771       orphan_text = 0,
1772       orphan_rodata,
1773       orphan_tdata,
1774       orphan_data,
1775       orphan_bss,
1776       orphan_rel,
1777       orphan_interp,
1778       orphan_sdata,
1779       orphan_nonalloc
1780     };
1781   static int orphan_init_done = 0;
1782   struct orphan_save *place;
1783   lang_output_section_statement_type *after;
1784   lang_output_section_statement_type *os;
1785   lang_output_section_statement_type *match_by_name = NULL;
1786   int isdyn = 0;
1787   int iself = s->owner->xvec->flavour == bfd_target_elf_flavour;
1788   unsigned int sh_type = iself ? elf_section_type (s) : SHT_NULL;
1789
1790   if (! link_info.relocatable
1791       && link_info.combreloc
1792       && (s->flags & SEC_ALLOC))
1793     {
1794       if (iself)
1795         switch (sh_type)
1796           {
1797           case SHT_RELA:
1798             secname = ".rela.dyn";
1799             isdyn = 1;
1800             break;
1801           case SHT_REL:
1802             secname = ".rel.dyn";
1803             isdyn = 1;
1804             break;
1805           default:
1806             break;
1807           }
1808       else if (CONST_STRNEQ (secname, ".rel"))
1809         {
1810           secname = secname[4] == 'a' ? ".rela.dyn" : ".rel.dyn";
1811           isdyn = 1;
1812         }
1813     }
1814
1815   /* Look through the script to see where to place this section.  */
1816   if (constraint == 0)
1817     for (os = lang_output_section_find (secname);
1818          os != NULL;
1819          os = next_matching_output_section_statement (os, 0))
1820       {
1821         /* If we don't match an existing output section, tell
1822            lang_insert_orphan to create a new output section.  */
1823         constraint = SPECIAL;
1824
1825         if (os->bfd_section != NULL
1826             && (os->bfd_section->flags == 0
1827                 || (_bfd_elf_match_sections_by_type (link_info.output_bfd,
1828                                                      os->bfd_section,
1829                                                      s->owner, s)
1830                     && ((s->flags ^ os->bfd_section->flags)
1831                         & (SEC_LOAD | SEC_ALLOC)) == 0)))
1832           {
1833             /* We already have an output section statement with this
1834                name, and its bfd section has compatible flags.
1835                If the section already exists but does not have any flags
1836                set, then it has been created by the linker, probably as a
1837                result of a --section-start command line switch.  */
1838             lang_add_section (&os->children, s, NULL, os);
1839             return os;
1840           }
1841
1842         /* Save unused output sections in case we can match them
1843            against orphans later.  */
1844         if (os->bfd_section == NULL)
1845           match_by_name = os;
1846       }
1847
1848   /* If we didn't match an active output section, see if we matched an
1849      unused one and use that.  */
1850   if (match_by_name)
1851     {
1852       lang_add_section (&match_by_name->children, s, NULL, match_by_name);
1853       return match_by_name;
1854     }
1855
1856   if (!orphan_init_done)
1857     {
1858       struct orphan_save *ho;
1859
1860       for (ho = hold; ho < hold + sizeof (hold) / sizeof (hold[0]); ++ho)
1861         if (ho->name != NULL)
1862           {
1863             ho->os = lang_output_section_find (ho->name);
1864             if (ho->os != NULL && ho->os->flags == 0)
1865               ho->os->flags = ho->flags;
1866           }
1867       orphan_init_done = 1;
1868     }
1869
1870   /* If this is a final link, then always put .gnu.warning.SYMBOL
1871      sections into the .text section to get them out of the way.  */
1872   if (link_info.executable
1873       && ! link_info.relocatable
1874       && CONST_STRNEQ (s->name, ".gnu.warning.")
1875       && hold[orphan_text].os != NULL)
1876     {
1877       os = hold[orphan_text].os;
1878       lang_add_section (&os->children, s, NULL, os);
1879       return os;
1880     }
1881
1882   /* Decide which segment the section should go in based on the
1883      section name and section flags.  We put loadable .note sections
1884      right after the .interp section, so that the PT_NOTE segment is
1885      stored right after the program headers where the OS can read it
1886      in the first page.  */
1887
1888   place = NULL;
1889   if ((s->flags & (SEC_ALLOC | SEC_DEBUGGING)) == 0)
1890     place = &hold[orphan_nonalloc];
1891   else if ((s->flags & SEC_ALLOC) == 0)
1892     ;
1893   else if ((s->flags & SEC_LOAD) != 0
1894            && ((iself && sh_type == SHT_NOTE)
1895                || (!iself && CONST_STRNEQ (secname, ".note"))))
1896     place = &hold[orphan_interp];
1897   else if ((s->flags & (SEC_LOAD | SEC_HAS_CONTENTS | SEC_THREAD_LOCAL)) == 0)
1898     place = &hold[orphan_bss];
1899   else if ((s->flags & SEC_SMALL_DATA) != 0)
1900     place = &hold[orphan_sdata];
1901   else if ((s->flags & SEC_THREAD_LOCAL) != 0)
1902     place = &hold[orphan_tdata];
1903   else if ((s->flags & SEC_READONLY) == 0)
1904     place = &hold[orphan_data];
1905   else if (((iself && (sh_type == SHT_RELA || sh_type == SHT_REL))
1906             || (!iself && CONST_STRNEQ (secname, ".rel")))
1907            && (s->flags & SEC_LOAD) != 0)
1908     place = &hold[orphan_rel];
1909   else if ((s->flags & SEC_CODE) == 0)
1910     place = &hold[orphan_rodata];
1911   else
1912     place = &hold[orphan_text];
1913
1914   after = NULL;
1915   if (place != NULL)
1916     {
1917       if (place->os == NULL)
1918         {
1919           if (place->name != NULL)
1920             place->os = lang_output_section_find (place->name);
1921           else
1922             place->os = output_rel_find (s, isdyn);
1923         }
1924       after = place->os;
1925       if (after == NULL)
1926         after = lang_output_section_find_by_flags
1927           (s, &place->os, _bfd_elf_match_sections_by_type);
1928       if (after == NULL)
1929         /* *ABS* is always the first output section statement.  */
1930         after = &lang_output_section_statement.head->output_section_statement;
1931     }
1932
1933   return lang_insert_orphan (s, secname, constraint, after, place, NULL, NULL);
1934 }
1935 EOF
1936 fi
1937
1938 if test x"$LDEMUL_AFTER_ALLOCATION" != xgld"$EMULATION_NAME"_after_allocation; then
1939 fragment <<EOF
1940
1941 static void
1942 gld${EMULATION_NAME}_after_allocation (void)
1943 {
1944   bfd_boolean need_layout = bfd_elf_discard_info (link_info.output_bfd,
1945                                                   &link_info);
1946   gld${EMULATION_NAME}_map_segments (need_layout);
1947 }
1948 EOF
1949 fi
1950
1951 if test x"$LDEMUL_GET_SCRIPT" != xgld"$EMULATION_NAME"_get_script; then
1952 fragment <<EOF
1953
1954 static char *
1955 gld${EMULATION_NAME}_get_script (int *isfile)
1956 EOF
1957
1958 if test x"$COMPILE_IN" = xyes
1959 then
1960 # Scripts compiled in.
1961
1962 # sed commands to quote an ld script as a C string.
1963 sc="-f stringify.sed"
1964
1965 fragment <<EOF
1966 {
1967   *isfile = 0;
1968
1969   if (link_info.relocatable && config.build_constructors)
1970     return
1971 EOF
1972 sed $sc ldscripts/${EMULATION_NAME}.xu                  >> e${EMULATION_NAME}.c
1973 echo '  ; else if (link_info.relocatable) return'       >> e${EMULATION_NAME}.c
1974 sed $sc ldscripts/${EMULATION_NAME}.xr                  >> e${EMULATION_NAME}.c
1975 echo '  ; else if (!config.text_read_only) return'      >> e${EMULATION_NAME}.c
1976 sed $sc ldscripts/${EMULATION_NAME}.xbn                 >> e${EMULATION_NAME}.c
1977 if cmp -s ldscripts/${EMULATION_NAME}.x ldscripts/${EMULATION_NAME}.xn; then : ; else
1978 echo '  ; else if (!config.magic_demand_paged) return'  >> e${EMULATION_NAME}.c
1979 sed $sc ldscripts/${EMULATION_NAME}.xn                  >> e${EMULATION_NAME}.c
1980 fi
1981 if test -n "$GENERATE_PIE_SCRIPT" ; then
1982 if test -n "$GENERATE_COMBRELOC_SCRIPT" ; then
1983 echo '  ; else if (link_info.pie && link_info.combreloc' >> e${EMULATION_NAME}.c
1984 echo '             && link_info.relro' >> e${EMULATION_NAME}.c
1985 echo '             && (link_info.flags & DF_BIND_NOW)) return' >> e${EMULATION_NAME}.c
1986 sed $sc ldscripts/${EMULATION_NAME}.xdw                 >> e${EMULATION_NAME}.c
1987 echo '  ; else if (link_info.pie && link_info.combreloc) return' >> e${EMULATION_NAME}.c
1988 sed $sc ldscripts/${EMULATION_NAME}.xdc                 >> e${EMULATION_NAME}.c
1989 fi
1990 echo '  ; else if (link_info.pie) return'               >> e${EMULATION_NAME}.c
1991 sed $sc ldscripts/${EMULATION_NAME}.xd                  >> e${EMULATION_NAME}.c
1992 fi
1993 if test -n "$GENERATE_SHLIB_SCRIPT" ; then
1994 if test -n "$GENERATE_COMBRELOC_SCRIPT" ; then
1995 echo '  ; else if (link_info.shared && link_info.combreloc' >> e${EMULATION_NAME}.c
1996 echo '             && link_info.relro' >> e${EMULATION_NAME}.c
1997 echo '             && (link_info.flags & DF_BIND_NOW)) return' >> e${EMULATION_NAME}.c
1998 sed $sc ldscripts/${EMULATION_NAME}.xsw                 >> e${EMULATION_NAME}.c
1999 echo '  ; else if (link_info.shared && link_info.combreloc) return' >> e${EMULATION_NAME}.c
2000 sed $sc ldscripts/${EMULATION_NAME}.xsc                 >> e${EMULATION_NAME}.c
2001 fi
2002 echo '  ; else if (link_info.shared) return'            >> e${EMULATION_NAME}.c
2003 sed $sc ldscripts/${EMULATION_NAME}.xs                  >> e${EMULATION_NAME}.c
2004 fi
2005 if test -n "$GENERATE_COMBRELOC_SCRIPT" ; then
2006 echo '  ; else if (link_info.combreloc && link_info.relro' >> e${EMULATION_NAME}.c
2007 echo '             && (link_info.flags & DF_BIND_NOW)) return' >> e${EMULATION_NAME}.c
2008 sed $sc ldscripts/${EMULATION_NAME}.xw                  >> e${EMULATION_NAME}.c
2009 echo '  ; else if (link_info.combreloc) return'         >> e${EMULATION_NAME}.c
2010 sed $sc ldscripts/${EMULATION_NAME}.xc                  >> e${EMULATION_NAME}.c
2011 fi
2012 echo '  ; else return'                                  >> e${EMULATION_NAME}.c
2013 sed $sc ldscripts/${EMULATION_NAME}.x                   >> e${EMULATION_NAME}.c
2014 echo '; }'                                              >> e${EMULATION_NAME}.c
2015
2016 else
2017 # Scripts read from the filesystem.
2018
2019 fragment <<EOF
2020 {
2021   *isfile = 1;
2022
2023   if (link_info.relocatable && config.build_constructors)
2024     return "ldscripts/${EMULATION_NAME}.xu";
2025   else if (link_info.relocatable)
2026     return "ldscripts/${EMULATION_NAME}.xr";
2027   else if (!config.text_read_only)
2028     return "ldscripts/${EMULATION_NAME}.xbn";
2029 EOF
2030 if cmp -s ldscripts/${EMULATION_NAME}.x ldscripts/${EMULATION_NAME}.xn; then :
2031 else
2032 fragment <<EOF
2033   else if (!config.magic_demand_paged)
2034     return "ldscripts/${EMULATION_NAME}.xn";
2035 EOF
2036 fi
2037 if test -n "$GENERATE_PIE_SCRIPT" ; then
2038 if test -n "$GENERATE_COMBRELOC_SCRIPT" ; then
2039 fragment <<EOF
2040   else if (link_info.pie && link_info.combreloc
2041            && link_info.relro && (link_info.flags & DF_BIND_NOW))
2042     return "ldscripts/${EMULATION_NAME}.xdw";
2043   else if (link_info.pie && link_info.combreloc)
2044     return "ldscripts/${EMULATION_NAME}.xdc";
2045 EOF
2046 fi
2047 fragment <<EOF
2048   else if (link_info.pie)
2049     return "ldscripts/${EMULATION_NAME}.xd";
2050 EOF
2051 fi
2052 if test -n "$GENERATE_SHLIB_SCRIPT" ; then
2053 if test -n "$GENERATE_COMBRELOC_SCRIPT" ; then
2054 fragment <<EOF
2055   else if (link_info.shared && link_info.combreloc
2056            && link_info.relro && (link_info.flags & DF_BIND_NOW))
2057     return "ldscripts/${EMULATION_NAME}.xsw";
2058   else if (link_info.shared && link_info.combreloc)
2059     return "ldscripts/${EMULATION_NAME}.xsc";
2060 EOF
2061 fi
2062 fragment <<EOF
2063   else if (link_info.shared)
2064     return "ldscripts/${EMULATION_NAME}.xs";
2065 EOF
2066 fi
2067 if test -n "$GENERATE_COMBRELOC_SCRIPT" ; then
2068 fragment <<EOF
2069   else if (link_info.combreloc && link_info.relro
2070            && (link_info.flags & DF_BIND_NOW))
2071     return "ldscripts/${EMULATION_NAME}.xw";
2072   else if (link_info.combreloc)
2073     return "ldscripts/${EMULATION_NAME}.xc";
2074 EOF
2075 fi
2076 fragment <<EOF
2077   else
2078     return "ldscripts/${EMULATION_NAME}.x";
2079 }
2080
2081 EOF
2082 fi
2083 fi
2084
2085 if test -n "$PARSE_AND_LIST_PROLOGUE" ; then
2086 fragment <<EOF
2087  $PARSE_AND_LIST_PROLOGUE
2088 EOF
2089 fi
2090
2091 fragment <<EOF
2092
2093 #define OPTION_DISABLE_NEW_DTAGS        (400)
2094 #define OPTION_ENABLE_NEW_DTAGS         (OPTION_DISABLE_NEW_DTAGS + 1)
2095 #define OPTION_GROUP                    (OPTION_ENABLE_NEW_DTAGS + 1)
2096 #define OPTION_EH_FRAME_HDR             (OPTION_GROUP + 1)
2097 #define OPTION_EXCLUDE_LIBS             (OPTION_EH_FRAME_HDR + 1)
2098 #define OPTION_HASH_STYLE               (OPTION_EXCLUDE_LIBS + 1)
2099 #define OPTION_BUILD_ID                 (OPTION_HASH_STYLE + 1)
2100 #define OPTION_AUDIT                    (OPTION_BUILD_ID + 1)
2101
2102 static void
2103 gld${EMULATION_NAME}_add_options
2104   (int ns, char **shortopts, int nl, struct option **longopts,
2105    int nrl ATTRIBUTE_UNUSED, struct option **really_longopts ATTRIBUTE_UNUSED)
2106 {
2107 EOF
2108 if test x"$GENERATE_SHLIB_SCRIPT" = xyes; then
2109 fragment <<EOF
2110   static const char xtra_short[] = "${PARSE_AND_LIST_SHORTOPTS}z:P:";
2111 EOF
2112 else
2113 fragment <<EOF
2114   static const char xtra_short[] = "${PARSE_AND_LIST_SHORTOPTS}z:";
2115 EOF
2116 fi
2117 fragment <<EOF
2118   static const struct option xtra_long[] = {
2119 EOF
2120 if test x"$GENERATE_SHLIB_SCRIPT" = xyes; then
2121 fragment <<EOF
2122     {"audit", required_argument, NULL, OPTION_AUDIT},
2123     {"Bgroup", no_argument, NULL, OPTION_GROUP},
2124 EOF
2125 fi
2126 fragment <<EOF
2127     {"build-id", optional_argument, NULL, OPTION_BUILD_ID},
2128 EOF
2129 if test x"$GENERATE_SHLIB_SCRIPT" = xyes; then
2130 fragment <<EOF
2131     {"depaudit", required_argument, NULL, 'P'},
2132     {"disable-new-dtags", no_argument, NULL, OPTION_DISABLE_NEW_DTAGS},
2133     {"enable-new-dtags", no_argument, NULL, OPTION_ENABLE_NEW_DTAGS},
2134     {"eh-frame-hdr", no_argument, NULL, OPTION_EH_FRAME_HDR},
2135     {"exclude-libs", required_argument, NULL, OPTION_EXCLUDE_LIBS},
2136     {"hash-style", required_argument, NULL, OPTION_HASH_STYLE},
2137 EOF
2138 fi
2139 if test -n "$PARSE_AND_LIST_LONGOPTS" ; then
2140 fragment <<EOF
2141     $PARSE_AND_LIST_LONGOPTS
2142 EOF
2143 fi
2144 fragment <<EOF
2145     {NULL, no_argument, NULL, 0}
2146   };
2147
2148   *shortopts = (char *) xrealloc (*shortopts, ns + sizeof (xtra_short));
2149   memcpy (*shortopts + ns, &xtra_short, sizeof (xtra_short));
2150   *longopts = (struct option *)
2151     xrealloc (*longopts, nl * sizeof (struct option) + sizeof (xtra_long));
2152   memcpy (*longopts + nl, &xtra_long, sizeof (xtra_long));
2153 }
2154
2155 #define DEFAULT_BUILD_ID_STYLE  "sha1"
2156
2157 static bfd_boolean
2158 gld${EMULATION_NAME}_handle_option (int optc)
2159 {
2160   switch (optc)
2161     {
2162     default:
2163       return FALSE;
2164
2165     case OPTION_BUILD_ID:
2166       if (emit_note_gnu_build_id != NULL)
2167         {
2168           free ((char *) emit_note_gnu_build_id);
2169           emit_note_gnu_build_id = NULL;
2170         }
2171       if (optarg == NULL)
2172         optarg = DEFAULT_BUILD_ID_STYLE;
2173       if (strcmp (optarg, "none"))
2174         emit_note_gnu_build_id = xstrdup (optarg);
2175       break;
2176
2177 EOF
2178
2179 if test x"$GENERATE_SHLIB_SCRIPT" = xyes; then
2180 fragment <<EOF
2181     case OPTION_AUDIT:
2182         gld${EMULATION_NAME}_append_to_separated_string (&audit, optarg);
2183         break;
2184
2185     case 'P':
2186         gld${EMULATION_NAME}_append_to_separated_string (&depaudit, optarg);
2187         break;
2188
2189     case OPTION_DISABLE_NEW_DTAGS:
2190       link_info.new_dtags = FALSE;
2191       break;
2192
2193     case OPTION_ENABLE_NEW_DTAGS:
2194       link_info.new_dtags = TRUE;
2195       break;
2196
2197     case OPTION_EH_FRAME_HDR:
2198       link_info.eh_frame_hdr = TRUE;
2199       break;
2200
2201     case OPTION_GROUP:
2202       link_info.flags_1 |= (bfd_vma) DF_1_GROUP;
2203       /* Groups must be self-contained.  */
2204       link_info.unresolved_syms_in_objects = RM_GENERATE_ERROR;
2205       link_info.unresolved_syms_in_shared_libs = RM_GENERATE_ERROR;
2206       break;
2207
2208     case OPTION_EXCLUDE_LIBS:
2209       add_excluded_libs (optarg);
2210       break;
2211
2212     case OPTION_HASH_STYLE:
2213       link_info.emit_hash = FALSE;
2214       link_info.emit_gnu_hash = FALSE;
2215       if (strcmp (optarg, "sysv") == 0)
2216         link_info.emit_hash = TRUE;
2217       else if (strcmp (optarg, "gnu") == 0)
2218         link_info.emit_gnu_hash = TRUE;
2219       else if (strcmp (optarg, "both") == 0)
2220         {
2221           link_info.emit_hash = TRUE;
2222           link_info.emit_gnu_hash = TRUE;
2223         }
2224       else
2225         einfo (_("%P%F: invalid hash style \`%s'\n"), optarg);
2226       break;
2227
2228 EOF
2229 fi
2230 fragment <<EOF
2231     case 'z':
2232       if (strcmp (optarg, "defs") == 0)
2233         link_info.unresolved_syms_in_objects = RM_GENERATE_ERROR;
2234       else if (strcmp (optarg, "muldefs") == 0)
2235         link_info.allow_multiple_definition = TRUE;
2236       else if (CONST_STRNEQ (optarg, "max-page-size="))
2237         {
2238           char *end;
2239
2240           config.maxpagesize = strtoul (optarg + 14, &end, 0);
2241           if (*end || (config.maxpagesize & (config.maxpagesize - 1)) != 0)
2242             einfo (_("%P%F: invalid maxium page size \`%s'\n"),
2243                    optarg + 14);
2244         }
2245       else if (CONST_STRNEQ (optarg, "common-page-size="))
2246         {
2247           char *end;
2248           config.commonpagesize = strtoul (optarg + 17, &end, 0);
2249           if (*end
2250               || (config.commonpagesize & (config.commonpagesize - 1)) != 0)
2251             einfo (_("%P%F: invalid common page size \`%s'\n"),
2252                    optarg + 17);
2253         }
2254       else if (CONST_STRNEQ (optarg, "stack-size="))
2255         {
2256           char *end;
2257           link_info.stacksize = strtoul (optarg + 11, &end, 0);
2258           if (*end || link_info.stacksize < 0)
2259             einfo (_("%P%F: invalid stack size \`%s'\n"), optarg + 11);
2260           if (!link_info.stacksize)
2261             /* Use -1 for explicit no-stack, because zero means
2262                'default'.   */
2263             link_info.stacksize = -1;
2264         }
2265       else if (strcmp (optarg, "execstack") == 0)
2266         {
2267           link_info.execstack = TRUE;
2268           link_info.noexecstack = FALSE;
2269         }
2270       else if (strcmp (optarg, "noexecstack") == 0)
2271         {
2272           link_info.noexecstack = TRUE;
2273           link_info.execstack = FALSE;
2274         }
2275 EOF
2276 if test x"$GENERATE_SHLIB_SCRIPT" = xyes; then
2277 fragment <<EOF
2278       else if (strcmp (optarg, "global") == 0)
2279         link_info.flags_1 |= (bfd_vma) DF_1_GLOBAL;
2280       else if (strcmp (optarg, "initfirst") == 0)
2281         link_info.flags_1 |= (bfd_vma) DF_1_INITFIRST;
2282       else if (strcmp (optarg, "interpose") == 0)
2283         link_info.flags_1 |= (bfd_vma) DF_1_INTERPOSE;
2284       else if (strcmp (optarg, "loadfltr") == 0)
2285         link_info.flags_1 |= (bfd_vma) DF_1_LOADFLTR;
2286       else if (strcmp (optarg, "nodefaultlib") == 0)
2287         link_info.flags_1 |= (bfd_vma) DF_1_NODEFLIB;
2288       else if (strcmp (optarg, "nodelete") == 0)
2289         link_info.flags_1 |= (bfd_vma) DF_1_NODELETE;
2290       else if (strcmp (optarg, "nodlopen") == 0)
2291         link_info.flags_1 |= (bfd_vma) DF_1_NOOPEN;
2292       else if (strcmp (optarg, "nodump") == 0)
2293         link_info.flags_1 |= (bfd_vma) DF_1_NODUMP;
2294       else if (strcmp (optarg, "now") == 0)
2295         {
2296           link_info.flags |= (bfd_vma) DF_BIND_NOW;
2297           link_info.flags_1 |= (bfd_vma) DF_1_NOW;
2298         }
2299       else if (strcmp (optarg, "lazy") == 0)
2300         {
2301           link_info.flags &= ~(bfd_vma) DF_BIND_NOW;
2302           link_info.flags_1 &= ~(bfd_vma) DF_1_NOW;
2303         }
2304       else if (strcmp (optarg, "origin") == 0)
2305         {
2306           link_info.flags |= (bfd_vma) DF_ORIGIN;
2307           link_info.flags_1 |= (bfd_vma) DF_1_ORIGIN;
2308         }
2309       else if (strcmp (optarg, "combreloc") == 0)
2310         link_info.combreloc = TRUE;
2311       else if (strcmp (optarg, "nocombreloc") == 0)
2312         link_info.combreloc = FALSE;
2313       else if (strcmp (optarg, "nocopyreloc") == 0)
2314         link_info.nocopyreloc = TRUE;
2315       else if (strcmp (optarg, "relro") == 0)
2316         link_info.relro = TRUE;
2317       else if (strcmp (optarg, "norelro") == 0)
2318         link_info.relro = FALSE;
2319       else if (strcmp (optarg, "text") == 0)
2320         link_info.error_textrel = TRUE;
2321       else if (strcmp (optarg, "notext") == 0)
2322         link_info.error_textrel = FALSE;
2323       else if (strcmp (optarg, "textoff") == 0)
2324         link_info.error_textrel = FALSE;
2325 EOF
2326 fi
2327
2328 fragment <<EOF
2329       else
2330         einfo (_("%P: warning: -z %s ignored.\n"), optarg);
2331       break;
2332 EOF
2333
2334 if test -n "$PARSE_AND_LIST_ARGS_CASES" ; then
2335 fragment <<EOF
2336  $PARSE_AND_LIST_ARGS_CASES
2337 EOF
2338 fi
2339
2340 fragment <<EOF
2341     }
2342
2343   return TRUE;
2344 }
2345
2346 EOF
2347
2348 if test x"$LDEMUL_LIST_OPTIONS" != xgld"$EMULATION_NAME"_list_options; then
2349 fragment <<EOF
2350
2351 static void
2352 gld${EMULATION_NAME}_list_options (FILE * file)
2353 {
2354 EOF
2355 if test x"$GENERATE_SHLIB_SCRIPT" = xyes; then
2356 fragment <<EOF
2357   fprintf (file, _("\
2358   --audit=AUDITLIB            Specify a library to use for auditing\n"));
2359   fprintf (file, _("\
2360   -Bgroup                     Selects group name lookup rules for DSO\n"));
2361 EOF
2362 fi
2363 fragment <<EOF
2364   fprintf (file, _("\
2365   --build-id[=STYLE]          Generate build ID note\n"));
2366 EOF
2367 if test x"$GENERATE_SHLIB_SCRIPT" = xyes; then
2368 fragment <<EOF
2369   fprintf (file, _("\
2370   -P AUDITLIB, --depaudit=AUDITLIB\n" "\
2371                               Specify a library to use for auditing dependencies\n"));
2372   fprintf (file, _("\
2373   --disable-new-dtags         Disable new dynamic tags\n"));
2374   fprintf (file, _("\
2375   --enable-new-dtags          Enable new dynamic tags\n"));
2376   fprintf (file, _("\
2377   --eh-frame-hdr              Create .eh_frame_hdr section\n"));
2378   fprintf (file, _("\
2379   --exclude-libs=LIBS         Make all symbols in LIBS hidden\n"));
2380   fprintf (file, _("\
2381   --hash-style=STYLE          Set hash style to sysv, gnu or both\n"));
2382   fprintf (file, _("\
2383   -z combreloc                Merge dynamic relocs into one section and sort\n"));
2384 EOF
2385 fi
2386
2387 fragment <<EOF
2388   fprintf (file, _("\
2389   -z common-page-size=SIZE    Set common page size to SIZE\n"));
2390   fprintf (file, _("\
2391   -z defs                     Report unresolved symbols in object files.\n"));
2392   fprintf (file, _("\
2393   -z execstack                Mark executable as requiring executable stack\n"));
2394 EOF
2395
2396 if test x"$GENERATE_SHLIB_SCRIPT" = xyes; then
2397 fragment <<EOF
2398   fprintf (file, _("\
2399   -z global                   Make symbols in DSO available for subsequently\n\
2400                                loaded objects\n"));
2401   fprintf (file, _("\
2402   -z initfirst                Mark DSO to be initialized first at runtime\n"));
2403   fprintf (file, _("\
2404   -z interpose                Mark object to interpose all DSOs but executable\n"));
2405   fprintf (file, _("\
2406   -z lazy                     Mark object lazy runtime binding (default)\n"));
2407   fprintf (file, _("\
2408   -z loadfltr                 Mark object requiring immediate process\n"));
2409 EOF
2410 fi
2411
2412 fragment <<EOF
2413   fprintf (file, _("\
2414   -z max-page-size=SIZE       Set maximum page size to SIZE\n"));
2415   fprintf (file, _("\
2416   -z muldefs                  Allow multiple definitions\n"));
2417 EOF
2418
2419 if test x"$GENERATE_SHLIB_SCRIPT" = xyes; then
2420 fragment <<EOF
2421   fprintf (file, _("\
2422   -z nocombreloc              Don't merge dynamic relocs into one section\n"));
2423   fprintf (file, _("\
2424   -z nocopyreloc              Don't create copy relocs\n"));
2425   fprintf (file, _("\
2426   -z nodefaultlib             Mark object not to use default search paths\n"));
2427   fprintf (file, _("\
2428   -z nodelete                 Mark DSO non-deletable at runtime\n"));
2429   fprintf (file, _("\
2430   -z nodlopen                 Mark DSO not available to dlopen\n"));
2431   fprintf (file, _("\
2432   -z nodump                   Mark DSO not available to dldump\n"));
2433 EOF
2434 fi
2435 fragment <<EOF
2436   fprintf (file, _("\
2437   -z noexecstack              Mark executable as not requiring executable stack\n"));
2438 EOF
2439 if test x"$GENERATE_SHLIB_SCRIPT" = xyes; then
2440 fragment <<EOF
2441   fprintf (file, _("\
2442   -z norelro                  Don't create RELRO program header\n"));
2443   fprintf (file, _("\
2444   -z now                      Mark object non-lazy runtime binding\n"));
2445   fprintf (file, _("\
2446   -z origin                   Mark object requiring immediate \$ORIGIN\n\
2447                                 processing at runtime\n"));
2448   fprintf (file, _("\
2449   -z relro                    Create RELRO program header\n"));
2450   fprintf (file, _("\
2451   -z stacksize=SIZE           Set size of stack segment\n"));
2452 EOF
2453 fi
2454
2455 if test -n "$PARSE_AND_LIST_OPTIONS" ; then
2456 fragment <<EOF
2457  $PARSE_AND_LIST_OPTIONS
2458 EOF
2459 fi
2460
2461 fragment <<EOF
2462 }
2463 EOF
2464
2465 if test -n "$PARSE_AND_LIST_EPILOGUE" ; then
2466 fragment <<EOF
2467  $PARSE_AND_LIST_EPILOGUE
2468 EOF
2469 fi
2470 fi
2471
2472 fragment <<EOF
2473
2474 struct ld_emulation_xfer_struct ld_${EMULATION_NAME}_emulation =
2475 {
2476   ${LDEMUL_BEFORE_PARSE-gld${EMULATION_NAME}_before_parse},
2477   ${LDEMUL_SYSLIB-syslib_default},
2478   ${LDEMUL_HLL-hll_default},
2479   ${LDEMUL_AFTER_PARSE-after_parse_default},
2480   ${LDEMUL_AFTER_OPEN-gld${EMULATION_NAME}_after_open},
2481   ${LDEMUL_AFTER_ALLOCATION-gld${EMULATION_NAME}_after_allocation},
2482   ${LDEMUL_SET_OUTPUT_ARCH-set_output_arch_default},
2483   ${LDEMUL_CHOOSE_TARGET-ldemul_default_target},
2484   ${LDEMUL_BEFORE_ALLOCATION-gld${EMULATION_NAME}_before_allocation},
2485   ${LDEMUL_GET_SCRIPT-gld${EMULATION_NAME}_get_script},
2486   "${EMULATION_NAME}",
2487   "${OUTPUT_FORMAT}",
2488   ${LDEMUL_FINISH-finish_default},
2489   ${LDEMUL_CREATE_OUTPUT_SECTION_STATEMENTS-NULL},
2490   ${LDEMUL_OPEN_DYNAMIC_ARCHIVE-gld${EMULATION_NAME}_open_dynamic_archive},
2491   ${LDEMUL_PLACE_ORPHAN-gld${EMULATION_NAME}_place_orphan},
2492   ${LDEMUL_SET_SYMBOLS-NULL},
2493   ${LDEMUL_PARSE_ARGS-NULL},
2494   gld${EMULATION_NAME}_add_options,
2495   gld${EMULATION_NAME}_handle_option,
2496   ${LDEMUL_UNRECOGNIZED_FILE-NULL},
2497   ${LDEMUL_LIST_OPTIONS-gld${EMULATION_NAME}_list_options},
2498   ${LDEMUL_RECOGNIZED_FILE-gld${EMULATION_NAME}_load_symbols},
2499   ${LDEMUL_FIND_POTENTIAL_LIBRARIES-NULL},
2500   ${LDEMUL_NEW_VERS_PATTERN-NULL}
2501 };
2502 EOF