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