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