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