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