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