1/* ELF linking support for BFD.
2   Copyright 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3   2005, 2006, 2007 Free Software Foundation, Inc.
4
5   This file is part of BFD, the Binary File Descriptor library.
6
7   This program is free software; you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation; either version 2 of the License, or
10   (at your option) any later version.
11
12   This program is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program; if not, write to the Free Software
19   Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.  */
20
21#include "sysdep.h"
22#include "bfd.h"
23#include "bfdlink.h"
24#include "libbfd.h"
25#define ARCH_SIZE 0
26#include "elf-bfd.h"
27#include "safe-ctype.h"
28#include "libiberty.h"
29#include "objalloc.h"
30
31/* Define a symbol in a dynamic linkage section.  */
32
33struct elf_link_hash_entry *
34_bfd_elf_define_linkage_sym (bfd *abfd,
35			     struct bfd_link_info *info,
36			     asection *sec,
37			     const char *name)
38{
39  struct elf_link_hash_entry *h;
40  struct bfd_link_hash_entry *bh;
41  const struct elf_backend_data *bed;
42
43  h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
44  if (h != NULL)
45    {
46      /* Zap symbol defined in an as-needed lib that wasn't linked.
47	 This is a symptom of a larger problem:  Absolute symbols
48	 defined in shared libraries can't be overridden, because we
49	 lose the link to the bfd which is via the symbol section.  */
50      h->root.type = bfd_link_hash_new;
51    }
52
53  bh = &h->root;
54  if (!_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL,
55					 sec, 0, NULL, FALSE,
56					 get_elf_backend_data (abfd)->collect,
57					 &bh))
58    return NULL;
59  h = (struct elf_link_hash_entry *) bh;
60  h->def_regular = 1;
61  h->type = STT_OBJECT;
62  h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
63
64  bed = get_elf_backend_data (abfd);
65  (*bed->elf_backend_hide_symbol) (info, h, TRUE);
66  return h;
67}
68
69bfd_boolean
70_bfd_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
71{
72  flagword flags;
73  asection *s;
74  struct elf_link_hash_entry *h;
75  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
76  int ptralign;
77
78  /* This function may be called more than once.  */
79  s = bfd_get_section_by_name (abfd, ".got");
80  if (s != NULL && (s->flags & SEC_LINKER_CREATED) != 0)
81    return TRUE;
82
83  switch (bed->s->arch_size)
84    {
85    case 32:
86      ptralign = 2;
87      break;
88
89    case 64:
90      ptralign = 3;
91      break;
92
93    default:
94      bfd_set_error (bfd_error_bad_value);
95      return FALSE;
96    }
97
98  flags = bed->dynamic_sec_flags;
99
100  s = bfd_make_section_with_flags (abfd, ".got", flags);
101  if (s == NULL
102      || !bfd_set_section_alignment (abfd, s, ptralign))
103    return FALSE;
104
105  if (bed->want_got_plt)
106    {
107      s = bfd_make_section_with_flags (abfd, ".got.plt", flags);
108      if (s == NULL
109	  || !bfd_set_section_alignment (abfd, s, ptralign))
110	return FALSE;
111    }
112
113  if (bed->want_got_sym)
114    {
115      /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
116	 (or .got.plt) section.  We don't do this in the linker script
117	 because we don't want to define the symbol if we are not creating
118	 a global offset table.  */
119      h = _bfd_elf_define_linkage_sym (abfd, info, s, "_GLOBAL_OFFSET_TABLE_");
120      elf_hash_table (info)->hgot = h;
121      if (h == NULL)
122	return FALSE;
123    }
124
125  /* The first bit of the global offset table is the header.  */
126  s->size += bed->got_header_size;
127
128  return TRUE;
129}
130
131/* Create a strtab to hold the dynamic symbol names.  */
132static bfd_boolean
133_bfd_elf_link_create_dynstrtab (bfd *abfd, struct bfd_link_info *info)
134{
135  struct elf_link_hash_table *hash_table;
136
137  hash_table = elf_hash_table (info);
138  if (hash_table->dynobj == NULL)
139    hash_table->dynobj = abfd;
140
141  if (hash_table->dynstr == NULL)
142    {
143      hash_table->dynstr = _bfd_elf_strtab_init ();
144      if (hash_table->dynstr == NULL)
145	return FALSE;
146    }
147  return TRUE;
148}
149
150/* Create some sections which will be filled in with dynamic linking
151   information.  ABFD is an input file which requires dynamic sections
152   to be created.  The dynamic sections take up virtual memory space
153   when the final executable is run, so we need to create them before
154   addresses are assigned to the output sections.  We work out the
155   actual contents and size of these sections later.  */
156
157bfd_boolean
158_bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
159{
160  flagword flags;
161  register asection *s;
162  const struct elf_backend_data *bed;
163
164  if (! is_elf_hash_table (info->hash))
165    return FALSE;
166
167  if (elf_hash_table (info)->dynamic_sections_created)
168    return TRUE;
169
170  if (!_bfd_elf_link_create_dynstrtab (abfd, info))
171    return FALSE;
172
173  abfd = elf_hash_table (info)->dynobj;
174  bed = get_elf_backend_data (abfd);
175
176  flags = bed->dynamic_sec_flags;
177
178  /* A dynamically linked executable has a .interp section, but a
179     shared library does not.  */
180  if (info->executable)
181    {
182      s = bfd_make_section_with_flags (abfd, ".interp",
183				       flags | SEC_READONLY);
184      if (s == NULL)
185	return FALSE;
186    }
187
188  /* Create sections to hold version informations.  These are removed
189     if they are not needed.  */
190  s = bfd_make_section_with_flags (abfd, ".gnu.version_d",
191				   flags | SEC_READONLY);
192  if (s == NULL
193      || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
194    return FALSE;
195
196  s = bfd_make_section_with_flags (abfd, ".gnu.version",
197				   flags | SEC_READONLY);
198  if (s == NULL
199      || ! bfd_set_section_alignment (abfd, s, 1))
200    return FALSE;
201
202  s = bfd_make_section_with_flags (abfd, ".gnu.version_r",
203				   flags | SEC_READONLY);
204  if (s == NULL
205      || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
206    return FALSE;
207
208  s = bfd_make_section_with_flags (abfd, ".dynsym",
209				   flags | SEC_READONLY);
210  if (s == NULL
211      || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
212    return FALSE;
213
214  s = bfd_make_section_with_flags (abfd, ".dynstr",
215				   flags | SEC_READONLY);
216  if (s == NULL)
217    return FALSE;
218
219  s = bfd_make_section_with_flags (abfd, ".dynamic", flags);
220  if (s == NULL
221      || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
222    return FALSE;
223
224  /* The special symbol _DYNAMIC is always set to the start of the
225     .dynamic section.  We could set _DYNAMIC in a linker script, but we
226     only want to define it if we are, in fact, creating a .dynamic
227     section.  We don't want to define it if there is no .dynamic
228     section, since on some ELF platforms the start up code examines it
229     to decide how to initialize the process.  */
230  if (!_bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC"))
231    return FALSE;
232
233  if (info->emit_hash)
234    {
235      s = bfd_make_section_with_flags (abfd, ".hash", flags | SEC_READONLY);
236      if (s == NULL
237	  || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
238	return FALSE;
239      elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
240    }
241
242  if (info->emit_gnu_hash)
243    {
244      s = bfd_make_section_with_flags (abfd, ".gnu.hash",
245				       flags | SEC_READONLY);
246      if (s == NULL
247	  || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
248	return FALSE;
249      /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
250	 4 32-bit words followed by variable count of 64-bit words, then
251	 variable count of 32-bit words.  */
252      if (bed->s->arch_size == 64)
253	elf_section_data (s)->this_hdr.sh_entsize = 0;
254      else
255	elf_section_data (s)->this_hdr.sh_entsize = 4;
256    }
257
258  /* Let the backend create the rest of the sections.  This lets the
259     backend set the right flags.  The backend will normally create
260     the .got and .plt sections.  */
261  if (! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
262    return FALSE;
263
264  elf_hash_table (info)->dynamic_sections_created = TRUE;
265
266  return TRUE;
267}
268
269/* Create dynamic sections when linking against a dynamic object.  */
270
271bfd_boolean
272_bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
273{
274  flagword flags, pltflags;
275  struct elf_link_hash_entry *h;
276  asection *s;
277  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
278
279  /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
280     .rel[a].bss sections.  */
281  flags = bed->dynamic_sec_flags;
282
283  pltflags = flags;
284  if (bed->plt_not_loaded)
285    /* We do not clear SEC_ALLOC here because we still want the OS to
286       allocate space for the section; it's just that there's nothing
287       to read in from the object file.  */
288    pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
289  else
290    pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
291  if (bed->plt_readonly)
292    pltflags |= SEC_READONLY;
293
294  s = bfd_make_section_with_flags (abfd, ".plt", pltflags);
295  if (s == NULL
296      || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
297    return FALSE;
298
299  /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
300     .plt section.  */
301  if (bed->want_plt_sym)
302    {
303      h = _bfd_elf_define_linkage_sym (abfd, info, s,
304				       "_PROCEDURE_LINKAGE_TABLE_");
305      elf_hash_table (info)->hplt = h;
306      if (h == NULL)
307	return FALSE;
308    }
309
310  s = bfd_make_section_with_flags (abfd,
311				   (bed->default_use_rela_p
312				    ? ".rela.plt" : ".rel.plt"),
313				   flags | SEC_READONLY);
314  if (s == NULL
315      || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
316    return FALSE;
317
318  if (! _bfd_elf_create_got_section (abfd, info))
319    return FALSE;
320
321  if (bed->want_dynbss)
322    {
323      /* The .dynbss section is a place to put symbols which are defined
324	 by dynamic objects, are referenced by regular objects, and are
325	 not functions.  We must allocate space for them in the process
326	 image and use a R_*_COPY reloc to tell the dynamic linker to
327	 initialize them at run time.  The linker script puts the .dynbss
328	 section into the .bss section of the final image.  */
329      s = bfd_make_section_with_flags (abfd, ".dynbss",
330				       (SEC_ALLOC
331					| SEC_LINKER_CREATED));
332      if (s == NULL)
333	return FALSE;
334
335      /* The .rel[a].bss section holds copy relocs.  This section is not
336	 normally needed.  We need to create it here, though, so that the
337	 linker will map it to an output section.  We can't just create it
338	 only if we need it, because we will not know whether we need it
339	 until we have seen all the input files, and the first time the
340	 main linker code calls BFD after examining all the input files
341	 (size_dynamic_sections) the input sections have already been
342	 mapped to the output sections.  If the section turns out not to
343	 be needed, we can discard it later.  We will never need this
344	 section when generating a shared object, since they do not use
345	 copy relocs.  */
346      if (! info->shared)
347	{
348	  s = bfd_make_section_with_flags (abfd,
349					   (bed->default_use_rela_p
350					    ? ".rela.bss" : ".rel.bss"),
351					   flags | SEC_READONLY);
352	  if (s == NULL
353	      || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
354	    return FALSE;
355	}
356    }
357
358  return TRUE;
359}
360
361/* Record a new dynamic symbol.  We record the dynamic symbols as we
362   read the input files, since we need to have a list of all of them
363   before we can determine the final sizes of the output sections.
364   Note that we may actually call this function even though we are not
365   going to output any dynamic symbols; in some cases we know that a
366   symbol should be in the dynamic symbol table, but only if there is
367   one.  */
368
369bfd_boolean
370bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
371				    struct elf_link_hash_entry *h)
372{
373  if (h->dynindx == -1)
374    {
375      struct elf_strtab_hash *dynstr;
376      char *p;
377      const char *name;
378      bfd_size_type indx;
379
380      /* XXX: The ABI draft says the linker must turn hidden and
381	 internal symbols into STB_LOCAL symbols when producing the
382	 DSO. However, if ld.so honors st_other in the dynamic table,
383	 this would not be necessary.  */
384      switch (ELF_ST_VISIBILITY (h->other))
385	{
386	case STV_INTERNAL:
387	case STV_HIDDEN:
388	  if (h->root.type != bfd_link_hash_undefined
389	      && h->root.type != bfd_link_hash_undefweak)
390	    {
391	      h->forced_local = 1;
392	      if (!elf_hash_table (info)->is_relocatable_executable)
393		return TRUE;
394	    }
395
396	default:
397	  break;
398	}
399
400      h->dynindx = elf_hash_table (info)->dynsymcount;
401      ++elf_hash_table (info)->dynsymcount;
402
403      dynstr = elf_hash_table (info)->dynstr;
404      if (dynstr == NULL)
405	{
406	  /* Create a strtab to hold the dynamic symbol names.  */
407	  elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
408	  if (dynstr == NULL)
409	    return FALSE;
410	}
411
412      /* We don't put any version information in the dynamic string
413	 table.  */
414      name = h->root.root.string;
415      p = strchr (name, ELF_VER_CHR);
416      if (p != NULL)
417	/* We know that the p points into writable memory.  In fact,
418	   there are only a few symbols that have read-only names, being
419	   those like _GLOBAL_OFFSET_TABLE_ that are created specially
420	   by the backends.  Most symbols will have names pointing into
421	   an ELF string table read from a file, or to objalloc memory.  */
422	*p = 0;
423
424      indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
425
426      if (p != NULL)
427	*p = ELF_VER_CHR;
428
429      if (indx == (bfd_size_type) -1)
430	return FALSE;
431      h->dynstr_index = indx;
432    }
433
434  return TRUE;
435}
436
437/* Mark a symbol dynamic.  */
438
439void
440bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
441				  struct elf_link_hash_entry *h,
442				  Elf_Internal_Sym *sym)
443{
444  struct bfd_elf_dynamic_list *d = info->dynamic_list;
445
446  /* It may be called more than once on the same H.  */
447  if(h->dynamic || info->relocatable)
448    return;
449
450  if ((info->dynamic_data
451       && (h->type == STT_OBJECT
452	   || (sym != NULL
453	       && ELF_ST_TYPE (sym->st_info) == STT_OBJECT)))
454      || (d != NULL
455	  && h->root.type == bfd_link_hash_new
456	  && (*d->match) (&d->head, NULL, h->root.root.string)))
457    h->dynamic = 1;
458}
459
460/* Record an assignment to a symbol made by a linker script.  We need
461   this in case some dynamic object refers to this symbol.  */
462
463bfd_boolean
464bfd_elf_record_link_assignment (bfd *output_bfd,
465				struct bfd_link_info *info,
466				const char *name,
467				bfd_boolean provide,
468				bfd_boolean hidden)
469{
470  struct elf_link_hash_entry *h;
471  struct elf_link_hash_table *htab;
472
473  if (!is_elf_hash_table (info->hash))
474    return TRUE;
475
476  htab = elf_hash_table (info);
477  h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
478  if (h == NULL)
479    return provide;
480
481  /* Since we're defining the symbol, don't let it seem to have not
482     been defined.  record_dynamic_symbol and size_dynamic_sections
483     may depend on this.  */
484  if (h->root.type == bfd_link_hash_undefweak
485      || h->root.type == bfd_link_hash_undefined)
486    {
487      h->root.type = bfd_link_hash_new;
488      if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
489	bfd_link_repair_undef_list (&htab->root);
490    }
491  else if (h->root.type == bfd_link_hash_new)
492    {
493      bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
494      h->non_elf = 0;
495    }
496  else if (h->root.type == bfd_link_hash_indirect)
497    {
498      const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
499      struct elf_link_hash_entry *hv = h;
500      do
501	hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
502      while (hv->root.type == bfd_link_hash_indirect
503	     || hv->root.type == bfd_link_hash_warning);
504      h->root.type = bfd_link_hash_undefined;
505      hv->root.type = bfd_link_hash_indirect;
506      hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
507      (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
508    }
509  else if (h->root.type == bfd_link_hash_warning)
510    {
511      abort ();
512    }
513
514  /* If this symbol is being provided by the linker script, and it is
515     currently defined by a dynamic object, but not by a regular
516     object, then mark it as undefined so that the generic linker will
517     force the correct value.  */
518  if (provide
519      && h->def_dynamic
520      && !h->def_regular)
521    h->root.type = bfd_link_hash_undefined;
522
523  /* If this symbol is not being provided by the linker script, and it is
524     currently defined by a dynamic object, but not by a regular object,
525     then clear out any version information because the symbol will not be
526     associated with the dynamic object any more.  */
527  if (!provide
528      && h->def_dynamic
529      && !h->def_regular)
530    h->verinfo.verdef = NULL;
531
532  h->def_regular = 1;
533
534  if (provide && hidden)
535    {
536      const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
537
538      h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
539      (*bed->elf_backend_hide_symbol) (info, h, TRUE);
540    }
541
542  /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
543     and executables.  */
544  if (!info->relocatable
545      && h->dynindx != -1
546      && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
547	  || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
548    h->forced_local = 1;
549
550  if ((h->def_dynamic
551       || h->ref_dynamic
552       || info->shared
553       || (info->executable && elf_hash_table (info)->is_relocatable_executable))
554      && h->dynindx == -1)
555    {
556      if (! bfd_elf_link_record_dynamic_symbol (info, h))
557	return FALSE;
558
559      /* If this is a weak defined symbol, and we know a corresponding
560	 real symbol from the same dynamic object, make sure the real
561	 symbol is also made into a dynamic symbol.  */
562      if (h->u.weakdef != NULL
563	  && h->u.weakdef->dynindx == -1)
564	{
565	  if (! bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
566	    return FALSE;
567	}
568    }
569
570  return TRUE;
571}
572
573/* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
574   success, and 2 on a failure caused by attempting to record a symbol
575   in a discarded section, eg. a discarded link-once section symbol.  */
576
577int
578bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
579					  bfd *input_bfd,
580					  long input_indx)
581{
582  bfd_size_type amt;
583  struct elf_link_local_dynamic_entry *entry;
584  struct elf_link_hash_table *eht;
585  struct elf_strtab_hash *dynstr;
586  unsigned long dynstr_index;
587  char *name;
588  Elf_External_Sym_Shndx eshndx;
589  char esym[sizeof (Elf64_External_Sym)];
590
591  if (! is_elf_hash_table (info->hash))
592    return 0;
593
594  /* See if the entry exists already.  */
595  for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
596    if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
597      return 1;
598
599  amt = sizeof (*entry);
600  entry = bfd_alloc (input_bfd, amt);
601  if (entry == NULL)
602    return 0;
603
604  /* Go find the symbol, so that we can find it's name.  */
605  if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
606			     1, input_indx, &entry->isym, esym, &eshndx))
607    {
608      bfd_release (input_bfd, entry);
609      return 0;
610    }
611
612  if (entry->isym.st_shndx != SHN_UNDEF
613      && (entry->isym.st_shndx < SHN_LORESERVE
614	  || entry->isym.st_shndx > SHN_HIRESERVE))
615    {
616      asection *s;
617
618      s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
619      if (s == NULL || bfd_is_abs_section (s->output_section))
620	{
621	  /* We can still bfd_release here as nothing has done another
622	     bfd_alloc.  We can't do this later in this function.  */
623	  bfd_release (input_bfd, entry);
624	  return 2;
625	}
626    }
627
628  name = (bfd_elf_string_from_elf_section
629	  (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
630	   entry->isym.st_name));
631
632  dynstr = elf_hash_table (info)->dynstr;
633  if (dynstr == NULL)
634    {
635      /* Create a strtab to hold the dynamic symbol names.  */
636      elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
637      if (dynstr == NULL)
638	return 0;
639    }
640
641  dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
642  if (dynstr_index == (unsigned long) -1)
643    return 0;
644  entry->isym.st_name = dynstr_index;
645
646  eht = elf_hash_table (info);
647
648  entry->next = eht->dynlocal;
649  eht->dynlocal = entry;
650  entry->input_bfd = input_bfd;
651  entry->input_indx = input_indx;
652  eht->dynsymcount++;
653
654  /* Whatever binding the symbol had before, it's now local.  */
655  entry->isym.st_info
656    = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
657
658  /* The dynindx will be set at the end of size_dynamic_sections.  */
659
660  return 1;
661}
662
663/* Return the dynindex of a local dynamic symbol.  */
664
665long
666_bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
667				    bfd *input_bfd,
668				    long input_indx)
669{
670  struct elf_link_local_dynamic_entry *e;
671
672  for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
673    if (e->input_bfd == input_bfd && e->input_indx == input_indx)
674      return e->dynindx;
675  return -1;
676}
677
678/* This function is used to renumber the dynamic symbols, if some of
679   them are removed because they are marked as local.  This is called
680   via elf_link_hash_traverse.  */
681
682static bfd_boolean
683elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
684				      void *data)
685{
686  size_t *count = data;
687
688  if (h->root.type == bfd_link_hash_warning)
689    h = (struct elf_link_hash_entry *) h->root.u.i.link;
690
691  if (h->forced_local)
692    return TRUE;
693
694  if (h->dynindx != -1)
695    h->dynindx = ++(*count);
696
697  return TRUE;
698}
699
700
701/* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
702   STB_LOCAL binding.  */
703
704static bfd_boolean
705elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
706					    void *data)
707{
708  size_t *count = data;
709
710  if (h->root.type == bfd_link_hash_warning)
711    h = (struct elf_link_hash_entry *) h->root.u.i.link;
712
713  if (!h->forced_local)
714    return TRUE;
715
716  if (h->dynindx != -1)
717    h->dynindx = ++(*count);
718
719  return TRUE;
720}
721
722/* Return true if the dynamic symbol for a given section should be
723   omitted when creating a shared library.  */
724bfd_boolean
725_bfd_elf_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED,
726				   struct bfd_link_info *info,
727				   asection *p)
728{
729  struct elf_link_hash_table *htab;
730
731  switch (elf_section_data (p)->this_hdr.sh_type)
732    {
733    case SHT_PROGBITS:
734    case SHT_NOBITS:
735      /* If sh_type is yet undecided, assume it could be
736	 SHT_PROGBITS/SHT_NOBITS.  */
737    case SHT_NULL:
738      htab = elf_hash_table (info);
739      if (p == htab->tls_sec)
740	return FALSE;
741
742      if (htab->text_index_section != NULL)
743	return p != htab->text_index_section && p != htab->data_index_section;
744
745      if (strcmp (p->name, ".got") == 0
746	  || strcmp (p->name, ".got.plt") == 0
747	  || strcmp (p->name, ".plt") == 0)
748	{
749	  asection *ip;
750
751	  if (htab->dynobj != NULL
752	      && (ip = bfd_get_section_by_name (htab->dynobj, p->name)) != NULL
753	      && (ip->flags & SEC_LINKER_CREATED)
754	      && ip->output_section == p)
755	    return TRUE;
756	}
757      return FALSE;
758
759      /* There shouldn't be section relative relocations
760	 against any other section.  */
761    default:
762      return TRUE;
763    }
764}
765
766/* Assign dynsym indices.  In a shared library we generate a section
767   symbol for each output section, which come first.  Next come symbols
768   which have been forced to local binding.  Then all of the back-end
769   allocated local dynamic syms, followed by the rest of the global
770   symbols.  */
771
772static unsigned long
773_bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
774				struct bfd_link_info *info,
775				unsigned long *section_sym_count)
776{
777  unsigned long dynsymcount = 0;
778
779  if (info->shared || elf_hash_table (info)->is_relocatable_executable)
780    {
781      const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
782      asection *p;
783      for (p = output_bfd->sections; p ; p = p->next)
784	if ((p->flags & SEC_EXCLUDE) == 0
785	    && (p->flags & SEC_ALLOC) != 0
786	    && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
787	  elf_section_data (p)->dynindx = ++dynsymcount;
788	else
789	  elf_section_data (p)->dynindx = 0;
790    }
791  *section_sym_count = dynsymcount;
792
793  elf_link_hash_traverse (elf_hash_table (info),
794			  elf_link_renumber_local_hash_table_dynsyms,
795			  &dynsymcount);
796
797  if (elf_hash_table (info)->dynlocal)
798    {
799      struct elf_link_local_dynamic_entry *p;
800      for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
801	p->dynindx = ++dynsymcount;
802    }
803
804  elf_link_hash_traverse (elf_hash_table (info),
805			  elf_link_renumber_hash_table_dynsyms,
806			  &dynsymcount);
807
808  /* There is an unused NULL entry at the head of the table which
809     we must account for in our count.  Unless there weren't any
810     symbols, which means we'll have no table at all.  */
811  if (dynsymcount != 0)
812    ++dynsymcount;
813
814  elf_hash_table (info)->dynsymcount = dynsymcount;
815  return dynsymcount;
816}
817
818/* This function is called when we want to define a new symbol.  It
819   handles the various cases which arise when we find a definition in
820   a dynamic object, or when there is already a definition in a
821   dynamic object.  The new symbol is described by NAME, SYM, PSEC,
822   and PVALUE.  We set SYM_HASH to the hash table entry.  We set
823   OVERRIDE if the old symbol is overriding a new definition.  We set
824   TYPE_CHANGE_OK if it is OK for the type to change.  We set
825   SIZE_CHANGE_OK if it is OK for the size to change.  By OK to
826   change, we mean that we shouldn't warn if the type or size does
827   change.  We set POLD_ALIGNMENT if an old common symbol in a dynamic
828   object is overridden by a regular object.  */
829
830bfd_boolean
831_bfd_elf_merge_symbol (bfd *abfd,
832		       struct bfd_link_info *info,
833		       const char *name,
834		       Elf_Internal_Sym *sym,
835		       asection **psec,
836		       bfd_vma *pvalue,
837		       unsigned int *pold_alignment,
838		       struct elf_link_hash_entry **sym_hash,
839		       bfd_boolean *skip,
840		       bfd_boolean *override,
841		       bfd_boolean *type_change_ok,
842		       bfd_boolean *size_change_ok)
843{
844  asection *sec, *oldsec;
845  struct elf_link_hash_entry *h;
846  struct elf_link_hash_entry *flip;
847  int bind;
848  bfd *oldbfd;
849  bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
850  bfd_boolean newweak, oldweak;
851  const struct elf_backend_data *bed;
852
853  *skip = FALSE;
854  *override = FALSE;
855
856  sec = *psec;
857  bind = ELF_ST_BIND (sym->st_info);
858
859  /* Silently discard TLS symbols from --just-syms.  There's no way to
860     combine a static TLS block with a new TLS block for this executable.  */
861  if (ELF_ST_TYPE (sym->st_info) == STT_TLS
862      && sec->sec_info_type == ELF_INFO_TYPE_JUST_SYMS)
863    {
864      *skip = TRUE;
865      return TRUE;
866    }
867
868  if (! bfd_is_und_section (sec))
869    h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
870  else
871    h = ((struct elf_link_hash_entry *)
872	 bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
873  if (h == NULL)
874    return FALSE;
875  *sym_hash = h;
876
877  bed = get_elf_backend_data (abfd);
878
879  /* This code is for coping with dynamic objects, and is only useful
880     if we are doing an ELF link.  */
881  if (!(*bed->relocs_compatible) (abfd->xvec, info->hash->creator))
882    return TRUE;
883
884  /* For merging, we only care about real symbols.  */
885
886  while (h->root.type == bfd_link_hash_indirect
887	 || h->root.type == bfd_link_hash_warning)
888    h = (struct elf_link_hash_entry *) h->root.u.i.link;
889
890  /* We have to check it for every instance since the first few may be
891     refereences and not all compilers emit symbol type for undefined
892     symbols.  */
893  bfd_elf_link_mark_dynamic_symbol (info, h, sym);
894
895  /* If we just created the symbol, mark it as being an ELF symbol.
896     Other than that, there is nothing to do--there is no merge issue
897     with a newly defined symbol--so we just return.  */
898
899  if (h->root.type == bfd_link_hash_new)
900    {
901      h->non_elf = 0;
902      return TRUE;
903    }
904
905  /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
906     existing symbol.  */
907
908  switch (h->root.type)
909    {
910    default:
911      oldbfd = NULL;
912      oldsec = NULL;
913      break;
914
915    case bfd_link_hash_undefined:
916    case bfd_link_hash_undefweak:
917      oldbfd = h->root.u.undef.abfd;
918      oldsec = NULL;
919      break;
920
921    case bfd_link_hash_defined:
922    case bfd_link_hash_defweak:
923      oldbfd = h->root.u.def.section->owner;
924      oldsec = h->root.u.def.section;
925      break;
926
927    case bfd_link_hash_common:
928      oldbfd = h->root.u.c.p->section->owner;
929      oldsec = h->root.u.c.p->section;
930      break;
931    }
932
933  /* In cases involving weak versioned symbols, we may wind up trying
934     to merge a symbol with itself.  Catch that here, to avoid the
935     confusion that results if we try to override a symbol with
936     itself.  The additional tests catch cases like
937     _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
938     dynamic object, which we do want to handle here.  */
939  if (abfd == oldbfd
940      && ((abfd->flags & DYNAMIC) == 0
941	  || !h->def_regular))
942    return TRUE;
943
944  /* NEWDYN and OLDDYN indicate whether the new or old symbol,
945     respectively, is from a dynamic object.  */
946
947  newdyn = (abfd->flags & DYNAMIC) != 0;
948
949  olddyn = FALSE;
950  if (oldbfd != NULL)
951    olddyn = (oldbfd->flags & DYNAMIC) != 0;
952  else if (oldsec != NULL)
953    {
954      /* This handles the special SHN_MIPS_{TEXT,DATA} section
955	 indices used by MIPS ELF.  */
956      olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
957    }
958
959  /* NEWDEF and OLDDEF indicate whether the new or old symbol,
960     respectively, appear to be a definition rather than reference.  */
961
962  newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
963
964  olddef = (h->root.type != bfd_link_hash_undefined
965	    && h->root.type != bfd_link_hash_undefweak
966	    && h->root.type != bfd_link_hash_common);
967
968  /* When we try to create a default indirect symbol from the dynamic
969     definition with the default version, we skip it if its type and
970     the type of existing regular definition mismatch.  We only do it
971     if the existing regular definition won't be dynamic.  */
972  if (pold_alignment == NULL
973      && !info->shared
974      && !info->export_dynamic
975      && !h->ref_dynamic
976      && newdyn
977      && newdef
978      && !olddyn
979      && (olddef || h->root.type == bfd_link_hash_common)
980      && ELF_ST_TYPE (sym->st_info) != h->type
981      && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
982      && h->type != STT_NOTYPE
983      && !(bed->is_function_type (ELF_ST_TYPE (sym->st_info))
984	   && bed->is_function_type (h->type)))
985    {
986      *skip = TRUE;
987      return TRUE;
988    }
989
990  /* Check TLS symbol.  We don't check undefined symbol introduced by
991     "ld -u".  */
992  if ((ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS)
993      && ELF_ST_TYPE (sym->st_info) != h->type
994      && oldbfd != NULL)
995    {
996      bfd *ntbfd, *tbfd;
997      bfd_boolean ntdef, tdef;
998      asection *ntsec, *tsec;
999
1000      if (h->type == STT_TLS)
1001	{
1002	  ntbfd = abfd;
1003	  ntsec = sec;
1004	  ntdef = newdef;
1005	  tbfd = oldbfd;
1006	  tsec = oldsec;
1007	  tdef = olddef;
1008	}
1009      else
1010	{
1011	  ntbfd = oldbfd;
1012	  ntsec = oldsec;
1013	  ntdef = olddef;
1014	  tbfd = abfd;
1015	  tsec = sec;
1016	  tdef = newdef;
1017	}
1018
1019      if (tdef && ntdef)
1020	(*_bfd_error_handler)
1021	  (_("%s: TLS definition in %B section %A mismatches non-TLS definition in %B section %A"),
1022	   tbfd, tsec, ntbfd, ntsec, h->root.root.string);
1023      else if (!tdef && !ntdef)
1024	(*_bfd_error_handler)
1025	  (_("%s: TLS reference in %B mismatches non-TLS reference in %B"),
1026	   tbfd, ntbfd, h->root.root.string);
1027      else if (tdef)
1028	(*_bfd_error_handler)
1029	  (_("%s: TLS definition in %B section %A mismatches non-TLS reference in %B"),
1030	   tbfd, tsec, ntbfd, h->root.root.string);
1031      else
1032	(*_bfd_error_handler)
1033	  (_("%s: TLS reference in %B mismatches non-TLS definition in %B section %A"),
1034	   tbfd, ntbfd, ntsec, h->root.root.string);
1035
1036      bfd_set_error (bfd_error_bad_value);
1037      return FALSE;
1038    }
1039
1040  /* We need to remember if a symbol has a definition in a dynamic
1041     object or is weak in all dynamic objects. Internal and hidden
1042     visibility will make it unavailable to dynamic objects.  */
1043  if (newdyn && !h->dynamic_def)
1044    {
1045      if (!bfd_is_und_section (sec))
1046	h->dynamic_def = 1;
1047      else
1048	{
1049	  /* Check if this symbol is weak in all dynamic objects. If it
1050	     is the first time we see it in a dynamic object, we mark
1051	     if it is weak. Otherwise, we clear it.  */
1052	  if (!h->ref_dynamic)
1053	    {
1054	      if (bind == STB_WEAK)
1055		h->dynamic_weak = 1;
1056	    }
1057	  else if (bind != STB_WEAK)
1058	    h->dynamic_weak = 0;
1059	}
1060    }
1061
1062  /* If the old symbol has non-default visibility, we ignore the new
1063     definition from a dynamic object.  */
1064  if (newdyn
1065      && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1066      && !bfd_is_und_section (sec))
1067    {
1068      *skip = TRUE;
1069      /* Make sure this symbol is dynamic.  */
1070      h->ref_dynamic = 1;
1071      /* A protected symbol has external availability. Make sure it is
1072	 recorded as dynamic.
1073
1074	 FIXME: Should we check type and size for protected symbol?  */
1075      if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1076	return bfd_elf_link_record_dynamic_symbol (info, h);
1077      else
1078	return TRUE;
1079    }
1080  else if (!newdyn
1081	   && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1082	   && h->def_dynamic)
1083    {
1084      /* If the new symbol with non-default visibility comes from a
1085	 relocatable file and the old definition comes from a dynamic
1086	 object, we remove the old definition.  */
1087      if ((*sym_hash)->root.type == bfd_link_hash_indirect)
1088	{
1089	  /* Handle the case where the old dynamic definition is
1090	     default versioned.  We need to copy the symbol info from
1091	     the symbol with default version to the normal one if it
1092	     was referenced before.  */
1093	  if (h->ref_regular)
1094	    {
1095	      const struct elf_backend_data *bed
1096		= get_elf_backend_data (abfd);
1097	      struct elf_link_hash_entry *vh = *sym_hash;
1098	      vh->root.type = h->root.type;
1099	      h->root.type = bfd_link_hash_indirect;
1100	      (*bed->elf_backend_copy_indirect_symbol) (info, vh, h);
1101	      /* Protected symbols will override the dynamic definition
1102		 with default version.  */
1103	      if (ELF_ST_VISIBILITY (sym->st_other) == STV_PROTECTED)
1104		{
1105		  h->root.u.i.link = (struct bfd_link_hash_entry *) vh;
1106		  vh->dynamic_def = 1;
1107		  vh->ref_dynamic = 1;
1108		}
1109	      else
1110		{
1111		  h->root.type = vh->root.type;
1112		  vh->ref_dynamic = 0;
1113		  /* We have to hide it here since it was made dynamic
1114		     global with extra bits when the symbol info was
1115		     copied from the old dynamic definition.  */
1116		  (*bed->elf_backend_hide_symbol) (info, vh, TRUE);
1117		}
1118	      h = vh;
1119	    }
1120	  else
1121	    h = *sym_hash;
1122	}
1123
1124      if ((h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1125	  && bfd_is_und_section (sec))
1126	{
1127	  /* If the new symbol is undefined and the old symbol was
1128	     also undefined before, we need to make sure
1129	     _bfd_generic_link_add_one_symbol doesn't mess
1130	     up the linker hash table undefs list.  Since the old
1131	     definition came from a dynamic object, it is still on the
1132	     undefs list.  */
1133	  h->root.type = bfd_link_hash_undefined;
1134	  h->root.u.undef.abfd = abfd;
1135	}
1136      else
1137	{
1138	  h->root.type = bfd_link_hash_new;
1139	  h->root.u.undef.abfd = NULL;
1140	}
1141
1142      if (h->def_dynamic)
1143	{
1144	  h->def_dynamic = 0;
1145	  h->ref_dynamic = 1;
1146	  h->dynamic_def = 1;
1147	}
1148      /* FIXME: Should we check type and size for protected symbol?  */
1149      h->size = 0;
1150      h->type = 0;
1151      return TRUE;
1152    }
1153
1154  /* Differentiate strong and weak symbols.  */
1155  newweak = bind == STB_WEAK;
1156  oldweak = (h->root.type == bfd_link_hash_defweak
1157	     || h->root.type == bfd_link_hash_undefweak);
1158
1159  /* If a new weak symbol definition comes from a regular file and the
1160     old symbol comes from a dynamic library, we treat the new one as
1161     strong.  Similarly, an old weak symbol definition from a regular
1162     file is treated as strong when the new symbol comes from a dynamic
1163     library.  Further, an old weak symbol from a dynamic library is
1164     treated as strong if the new symbol is from a dynamic library.
1165     This reflects the way glibc's ld.so works.
1166
1167     Do this before setting *type_change_ok or *size_change_ok so that
1168     we warn properly when dynamic library symbols are overridden.  */
1169
1170  if (newdef && !newdyn && olddyn)
1171    newweak = FALSE;
1172  if (olddef && newdyn)
1173    oldweak = FALSE;
1174
1175  /* Allow changes between different types of funciton symbol.  */
1176  if (bed->is_function_type (ELF_ST_TYPE (sym->st_info))
1177      && bed->is_function_type (h->type))
1178    *type_change_ok = TRUE;
1179
1180  /* It's OK to change the type if either the existing symbol or the
1181     new symbol is weak.  A type change is also OK if the old symbol
1182     is undefined and the new symbol is defined.  */
1183
1184  if (oldweak
1185      || newweak
1186      || (newdef
1187	  && h->root.type == bfd_link_hash_undefined))
1188    *type_change_ok = TRUE;
1189
1190  /* It's OK to change the size if either the existing symbol or the
1191     new symbol is weak, or if the old symbol is undefined.  */
1192
1193  if (*type_change_ok
1194      || h->root.type == bfd_link_hash_undefined)
1195    *size_change_ok = TRUE;
1196
1197  /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1198     symbol, respectively, appears to be a common symbol in a dynamic
1199     object.  If a symbol appears in an uninitialized section, and is
1200     not weak, and is not a function, then it may be a common symbol
1201     which was resolved when the dynamic object was created.  We want
1202     to treat such symbols specially, because they raise special
1203     considerations when setting the symbol size: if the symbol
1204     appears as a common symbol in a regular object, and the size in
1205     the regular object is larger, we must make sure that we use the
1206     larger size.  This problematic case can always be avoided in C,
1207     but it must be handled correctly when using Fortran shared
1208     libraries.
1209
1210     Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1211     likewise for OLDDYNCOMMON and OLDDEF.
1212
1213     Note that this test is just a heuristic, and that it is quite
1214     possible to have an uninitialized symbol in a shared object which
1215     is really a definition, rather than a common symbol.  This could
1216     lead to some minor confusion when the symbol really is a common
1217     symbol in some regular object.  However, I think it will be
1218     harmless.  */
1219
1220  if (newdyn
1221      && newdef
1222      && !newweak
1223      && (sec->flags & SEC_ALLOC) != 0
1224      && (sec->flags & SEC_LOAD) == 0
1225      && sym->st_size > 0
1226      && !bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
1227    newdyncommon = TRUE;
1228  else
1229    newdyncommon = FALSE;
1230
1231  if (olddyn
1232      && olddef
1233      && h->root.type == bfd_link_hash_defined
1234      && h->def_dynamic
1235      && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1236      && (h->root.u.def.section->flags & SEC_LOAD) == 0
1237      && h->size > 0
1238      && !bed->is_function_type (h->type))
1239    olddyncommon = TRUE;
1240  else
1241    olddyncommon = FALSE;
1242
1243  /* We now know everything about the old and new symbols.  We ask the
1244     backend to check if we can merge them.  */
1245  if (bed->merge_symbol
1246      && !bed->merge_symbol (info, sym_hash, h, sym, psec, pvalue,
1247			     pold_alignment, skip, override,
1248			     type_change_ok, size_change_ok,
1249			     &newdyn, &newdef, &newdyncommon, &newweak,
1250			     abfd, &sec,
1251			     &olddyn, &olddef, &olddyncommon, &oldweak,
1252			     oldbfd, &oldsec))
1253    return FALSE;
1254
1255  /* If both the old and the new symbols look like common symbols in a
1256     dynamic object, set the size of the symbol to the larger of the
1257     two.  */
1258
1259  if (olddyncommon
1260      && newdyncommon
1261      && sym->st_size != h->size)
1262    {
1263      /* Since we think we have two common symbols, issue a multiple
1264	 common warning if desired.  Note that we only warn if the
1265	 size is different.  If the size is the same, we simply let
1266	 the old symbol override the new one as normally happens with
1267	 symbols defined in dynamic objects.  */
1268
1269      if (! ((*info->callbacks->multiple_common)
1270	     (info, h->root.root.string, oldbfd, bfd_link_hash_common,
1271	      h->size, abfd, bfd_link_hash_common, sym->st_size)))
1272	return FALSE;
1273
1274      if (sym->st_size > h->size)
1275	h->size = sym->st_size;
1276
1277      *size_change_ok = TRUE;
1278    }
1279
1280  /* If we are looking at a dynamic object, and we have found a
1281     definition, we need to see if the symbol was already defined by
1282     some other object.  If so, we want to use the existing
1283     definition, and we do not want to report a multiple symbol
1284     definition error; we do this by clobbering *PSEC to be
1285     bfd_und_section_ptr.
1286
1287     We treat a common symbol as a definition if the symbol in the
1288     shared library is a function, since common symbols always
1289     represent variables; this can cause confusion in principle, but
1290     any such confusion would seem to indicate an erroneous program or
1291     shared library.  We also permit a common symbol in a regular
1292     object to override a weak symbol in a shared object.  */
1293
1294  if (newdyn
1295      && newdef
1296      && (olddef
1297	  || (h->root.type == bfd_link_hash_common
1298	      && (newweak
1299		  || bed->is_function_type (ELF_ST_TYPE (sym->st_info))))))
1300    {
1301      *override = TRUE;
1302      newdef = FALSE;
1303      newdyncommon = FALSE;
1304
1305      *psec = sec = bfd_und_section_ptr;
1306      *size_change_ok = TRUE;
1307
1308      /* If we get here when the old symbol is a common symbol, then
1309	 we are explicitly letting it override a weak symbol or
1310	 function in a dynamic object, and we don't want to warn about
1311	 a type change.  If the old symbol is a defined symbol, a type
1312	 change warning may still be appropriate.  */
1313
1314      if (h->root.type == bfd_link_hash_common)
1315	*type_change_ok = TRUE;
1316    }
1317
1318  /* Handle the special case of an old common symbol merging with a
1319     new symbol which looks like a common symbol in a shared object.
1320     We change *PSEC and *PVALUE to make the new symbol look like a
1321     common symbol, and let _bfd_generic_link_add_one_symbol do the
1322     right thing.  */
1323
1324  if (newdyncommon
1325      && h->root.type == bfd_link_hash_common)
1326    {
1327      *override = TRUE;
1328      newdef = FALSE;
1329      newdyncommon = FALSE;
1330      *pvalue = sym->st_size;
1331      *psec = sec = bed->common_section (oldsec);
1332      *size_change_ok = TRUE;
1333    }
1334
1335  /* Skip weak definitions of symbols that are already defined.  */
1336  if (newdef && olddef && newweak)
1337    *skip = TRUE;
1338
1339  /* If the old symbol is from a dynamic object, and the new symbol is
1340     a definition which is not from a dynamic object, then the new
1341     symbol overrides the old symbol.  Symbols from regular files
1342     always take precedence over symbols from dynamic objects, even if
1343     they are defined after the dynamic object in the link.
1344
1345     As above, we again permit a common symbol in a regular object to
1346     override a definition in a shared object if the shared object
1347     symbol is a function or is weak.  */
1348
1349  flip = NULL;
1350  if (!newdyn
1351      && (newdef
1352	  || (bfd_is_com_section (sec)
1353	      && (oldweak
1354		  || bed->is_function_type (h->type))))
1355      && olddyn
1356      && olddef
1357      && h->def_dynamic)
1358    {
1359      /* Change the hash table entry to undefined, and let
1360	 _bfd_generic_link_add_one_symbol do the right thing with the
1361	 new definition.  */
1362
1363      h->root.type = bfd_link_hash_undefined;
1364      h->root.u.undef.abfd = h->root.u.def.section->owner;
1365      *size_change_ok = TRUE;
1366
1367      olddef = FALSE;
1368      olddyncommon = FALSE;
1369
1370      /* We again permit a type change when a common symbol may be
1371	 overriding a function.  */
1372
1373      if (bfd_is_com_section (sec))
1374	*type_change_ok = TRUE;
1375
1376      if ((*sym_hash)->root.type == bfd_link_hash_indirect)
1377	flip = *sym_hash;
1378      else
1379	/* This union may have been set to be non-NULL when this symbol
1380	   was seen in a dynamic object.  We must force the union to be
1381	   NULL, so that it is correct for a regular symbol.  */
1382	h->verinfo.vertree = NULL;
1383    }
1384
1385  /* Handle the special case of a new common symbol merging with an
1386     old symbol that looks like it might be a common symbol defined in
1387     a shared object.  Note that we have already handled the case in
1388     which a new common symbol should simply override the definition
1389     in the shared library.  */
1390
1391  if (! newdyn
1392      && bfd_is_com_section (sec)
1393      && olddyncommon)
1394    {
1395      /* It would be best if we could set the hash table entry to a
1396	 common symbol, but we don't know what to use for the section
1397	 or the alignment.  */
1398      if (! ((*info->callbacks->multiple_common)
1399	     (info, h->root.root.string, oldbfd, bfd_link_hash_common,
1400	      h->size, abfd, bfd_link_hash_common, sym->st_size)))
1401	return FALSE;
1402
1403      /* If the presumed common symbol in the dynamic object is
1404	 larger, pretend that the new symbol has its size.  */
1405
1406      if (h->size > *pvalue)
1407	*pvalue = h->size;
1408
1409      /* We need to remember the alignment required by the symbol
1410	 in the dynamic object.  */
1411      BFD_ASSERT (pold_alignment);
1412      *pold_alignment = h->root.u.def.section->alignment_power;
1413
1414      olddef = FALSE;
1415      olddyncommon = FALSE;
1416
1417      h->root.type = bfd_link_hash_undefined;
1418      h->root.u.undef.abfd = h->root.u.def.section->owner;
1419
1420      *size_change_ok = TRUE;
1421      *type_change_ok = TRUE;
1422
1423      if ((*sym_hash)->root.type == bfd_link_hash_indirect)
1424	flip = *sym_hash;
1425      else
1426	h->verinfo.vertree = NULL;
1427    }
1428
1429  if (flip != NULL)
1430    {
1431      /* Handle the case where we had a versioned symbol in a dynamic
1432	 library and now find a definition in a normal object.  In this
1433	 case, we make the versioned symbol point to the normal one.  */
1434      const struct elf_backend_data *bed = get_elf_backend_data (abfd);
1435      flip->root.type = h->root.type;
1436      flip->root.u.undef.abfd = h->root.u.undef.abfd;
1437      h->root.type = bfd_link_hash_indirect;
1438      h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1439      (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1440      if (h->def_dynamic)
1441	{
1442	  h->def_dynamic = 0;
1443	  flip->ref_dynamic = 1;
1444	}
1445    }
1446
1447  return TRUE;
1448}
1449
1450/* This function is called to create an indirect symbol from the
1451   default for the symbol with the default version if needed. The
1452   symbol is described by H, NAME, SYM, PSEC, VALUE, and OVERRIDE.  We
1453   set DYNSYM if the new indirect symbol is dynamic.  */
1454
1455bfd_boolean
1456_bfd_elf_add_default_symbol (bfd *abfd,
1457			     struct bfd_link_info *info,
1458			     struct elf_link_hash_entry *h,
1459			     const char *name,
1460			     Elf_Internal_Sym *sym,
1461			     asection **psec,
1462			     bfd_vma *value,
1463			     bfd_boolean *dynsym,
1464			     bfd_boolean override)
1465{
1466  bfd_boolean type_change_ok;
1467  bfd_boolean size_change_ok;
1468  bfd_boolean skip;
1469  char *shortname;
1470  struct elf_link_hash_entry *hi;
1471  struct bfd_link_hash_entry *bh;
1472  const struct elf_backend_data *bed;
1473  bfd_boolean collect;
1474  bfd_boolean dynamic;
1475  char *p;
1476  size_t len, shortlen;
1477  asection *sec;
1478
1479  /* If this symbol has a version, and it is the default version, we
1480     create an indirect symbol from the default name to the fully
1481     decorated name.  This will cause external references which do not
1482     specify a version to be bound to this version of the symbol.  */
1483  p = strchr (name, ELF_VER_CHR);
1484  if (p == NULL || p[1] != ELF_VER_CHR)
1485    return TRUE;
1486
1487  if (override)
1488    {
1489      /* We are overridden by an old definition. We need to check if we
1490	 need to create the indirect symbol from the default name.  */
1491      hi = elf_link_hash_lookup (elf_hash_table (info), name, TRUE,
1492				 FALSE, FALSE);
1493      BFD_ASSERT (hi != NULL);
1494      if (hi == h)
1495	return TRUE;
1496      while (hi->root.type == bfd_link_hash_indirect
1497	     || hi->root.type == bfd_link_hash_warning)
1498	{
1499	  hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1500	  if (hi == h)
1501	    return TRUE;
1502	}
1503    }
1504
1505  bed = get_elf_backend_data (abfd);
1506  collect = bed->collect;
1507  dynamic = (abfd->flags & DYNAMIC) != 0;
1508
1509  shortlen = p - name;
1510  shortname = bfd_hash_allocate (&info->hash->table, shortlen + 1);
1511  if (shortname == NULL)
1512    return FALSE;
1513  memcpy (shortname, name, shortlen);
1514  shortname[shortlen] = '\0';
1515
1516  /* We are going to create a new symbol.  Merge it with any existing
1517     symbol with this name.  For the purposes of the merge, act as
1518     though we were defining the symbol we just defined, although we
1519     actually going to define an indirect symbol.  */
1520  type_change_ok = FALSE;
1521  size_change_ok = FALSE;
1522  sec = *psec;
1523  if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &sec, value,
1524			      NULL, &hi, &skip, &override,
1525			      &type_change_ok, &size_change_ok))
1526    return FALSE;
1527
1528  if (skip)
1529    goto nondefault;
1530
1531  if (! override)
1532    {
1533      bh = &hi->root;
1534      if (! (_bfd_generic_link_add_one_symbol
1535	     (info, abfd, shortname, BSF_INDIRECT, bfd_ind_section_ptr,
1536	      0, name, FALSE, collect, &bh)))
1537	return FALSE;
1538      hi = (struct elf_link_hash_entry *) bh;
1539    }
1540  else
1541    {
1542      /* In this case the symbol named SHORTNAME is overriding the
1543	 indirect symbol we want to add.  We were planning on making
1544	 SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1545	 is the name without a version.  NAME is the fully versioned
1546	 name, and it is the default version.
1547
1548	 Overriding means that we already saw a definition for the
1549	 symbol SHORTNAME in a regular object, and it is overriding
1550	 the symbol defined in the dynamic object.
1551
1552	 When this happens, we actually want to change NAME, the
1553	 symbol we just added, to refer to SHORTNAME.  This will cause
1554	 references to NAME in the shared object to become references
1555	 to SHORTNAME in the regular object.  This is what we expect
1556	 when we override a function in a shared object: that the
1557	 references in the shared object will be mapped to the
1558	 definition in the regular object.  */
1559
1560      while (hi->root.type == bfd_link_hash_indirect
1561	     || hi->root.type == bfd_link_hash_warning)
1562	hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1563
1564      h->root.type = bfd_link_hash_indirect;
1565      h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1566      if (h->def_dynamic)
1567	{
1568	  h->def_dynamic = 0;
1569	  hi->ref_dynamic = 1;
1570	  if (hi->ref_regular
1571	      || hi->def_regular)
1572	    {
1573	      if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1574		return FALSE;
1575	    }
1576	}
1577
1578      /* Now set HI to H, so that the following code will set the
1579	 other fields correctly.  */
1580      hi = h;
1581    }
1582
1583  /* Check if HI is a warning symbol.  */
1584  if (hi->root.type == bfd_link_hash_warning)
1585    hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1586
1587  /* If there is a duplicate definition somewhere, then HI may not
1588     point to an indirect symbol.  We will have reported an error to
1589     the user in that case.  */
1590
1591  if (hi->root.type == bfd_link_hash_indirect)
1592    {
1593      struct elf_link_hash_entry *ht;
1594
1595      ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1596      (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
1597
1598      /* See if the new flags lead us to realize that the symbol must
1599	 be dynamic.  */
1600      if (! *dynsym)
1601	{
1602	  if (! dynamic)
1603	    {
1604	      if (info->shared
1605		  || hi->ref_dynamic)
1606		*dynsym = TRUE;
1607	    }
1608	  else
1609	    {
1610	      if (hi->ref_regular)
1611		*dynsym = TRUE;
1612	    }
1613	}
1614    }
1615
1616  /* We also need to define an indirection from the nondefault version
1617     of the symbol.  */
1618
1619nondefault:
1620  len = strlen (name);
1621  shortname = bfd_hash_allocate (&info->hash->table, len);
1622  if (shortname == NULL)
1623    return FALSE;
1624  memcpy (shortname, name, shortlen);
1625  memcpy (shortname + shortlen, p + 1, len - shortlen);
1626
1627  /* Once again, merge with any existing symbol.  */
1628  type_change_ok = FALSE;
1629  size_change_ok = FALSE;
1630  sec = *psec;
1631  if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &sec, value,
1632			      NULL, &hi, &skip, &override,
1633			      &type_change_ok, &size_change_ok))
1634    return FALSE;
1635
1636  if (skip)
1637    return TRUE;
1638
1639  if (override)
1640    {
1641      /* Here SHORTNAME is a versioned name, so we don't expect to see
1642	 the type of override we do in the case above unless it is
1643	 overridden by a versioned definition.  */
1644      if (hi->root.type != bfd_link_hash_defined
1645	  && hi->root.type != bfd_link_hash_defweak)
1646	(*_bfd_error_handler)
1647	  (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
1648	   abfd, shortname);
1649    }
1650  else
1651    {
1652      bh = &hi->root;
1653      if (! (_bfd_generic_link_add_one_symbol
1654	     (info, abfd, shortname, BSF_INDIRECT,
1655	      bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
1656	return FALSE;
1657      hi = (struct elf_link_hash_entry *) bh;
1658
1659      /* If there is a duplicate definition somewhere, then HI may not
1660	 point to an indirect symbol.  We will have reported an error
1661	 to the user in that case.  */
1662
1663      if (hi->root.type == bfd_link_hash_indirect)
1664	{
1665	  (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
1666
1667	  /* See if the new flags lead us to realize that the symbol
1668	     must be dynamic.  */
1669	  if (! *dynsym)
1670	    {
1671	      if (! dynamic)
1672		{
1673		  if (info->shared
1674		      || hi->ref_dynamic)
1675		    *dynsym = TRUE;
1676		}
1677	      else
1678		{
1679		  if (hi->ref_regular)
1680		    *dynsym = TRUE;
1681		}
1682	    }
1683	}
1684    }
1685
1686  return TRUE;
1687}
1688
1689/* This routine is used to export all defined symbols into the dynamic
1690   symbol table.  It is called via elf_link_hash_traverse.  */
1691
1692bfd_boolean
1693_bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
1694{
1695  struct elf_info_failed *eif = data;
1696
1697  /* Ignore this if we won't export it.  */
1698  if (!eif->info->export_dynamic && !h->dynamic)
1699    return TRUE;
1700
1701  /* Ignore indirect symbols.  These are added by the versioning code.  */
1702  if (h->root.type == bfd_link_hash_indirect)
1703    return TRUE;
1704
1705  if (h->root.type == bfd_link_hash_warning)
1706    h = (struct elf_link_hash_entry *) h->root.u.i.link;
1707
1708  if (h->dynindx == -1
1709      && (h->def_regular
1710	  || h->ref_regular))
1711    {
1712      struct bfd_elf_version_tree *t;
1713      struct bfd_elf_version_expr *d;
1714
1715      for (t = eif->verdefs; t != NULL; t = t->next)
1716	{
1717	  if (t->globals.list != NULL)
1718	    {
1719	      d = (*t->match) (&t->globals, NULL, h->root.root.string);
1720	      if (d != NULL)
1721		goto doit;
1722	    }
1723
1724	  if (t->locals.list != NULL)
1725	    {
1726	      d = (*t->match) (&t->locals, NULL, h->root.root.string);
1727	      if (d != NULL)
1728		return TRUE;
1729	    }
1730	}
1731
1732      if (!eif->verdefs)
1733	{
1734	doit:
1735	  if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
1736	    {
1737	      eif->failed = TRUE;
1738	      return FALSE;
1739	    }
1740	}
1741    }
1742
1743  return TRUE;
1744}
1745
1746/* Look through the symbols which are defined in other shared
1747   libraries and referenced here.  Update the list of version
1748   dependencies.  This will be put into the .gnu.version_r section.
1749   This function is called via elf_link_hash_traverse.  */
1750
1751bfd_boolean
1752_bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
1753					 void *data)
1754{
1755  struct elf_find_verdep_info *rinfo = data;
1756  Elf_Internal_Verneed *t;
1757  Elf_Internal_Vernaux *a;
1758  bfd_size_type amt;
1759
1760  if (h->root.type == bfd_link_hash_warning)
1761    h = (struct elf_link_hash_entry *) h->root.u.i.link;
1762
1763  /* We only care about symbols defined in shared objects with version
1764     information.  */
1765  if (!h->def_dynamic
1766      || h->def_regular
1767      || h->dynindx == -1
1768      || h->verinfo.verdef == NULL)
1769    return TRUE;
1770
1771  /* See if we already know about this version.  */
1772  for (t = elf_tdata (rinfo->output_bfd)->verref; t != NULL; t = t->vn_nextref)
1773    {
1774      if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
1775	continue;
1776
1777      for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
1778	if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
1779	  return TRUE;
1780
1781      break;
1782    }
1783
1784  /* This is a new version.  Add it to tree we are building.  */
1785
1786  if (t == NULL)
1787    {
1788      amt = sizeof *t;
1789      t = bfd_zalloc (rinfo->output_bfd, amt);
1790      if (t == NULL)
1791	{
1792	  rinfo->failed = TRUE;
1793	  return FALSE;
1794	}
1795
1796      t->vn_bfd = h->verinfo.verdef->vd_bfd;
1797      t->vn_nextref = elf_tdata (rinfo->output_bfd)->verref;
1798      elf_tdata (rinfo->output_bfd)->verref = t;
1799    }
1800
1801  amt = sizeof *a;
1802  a = bfd_zalloc (rinfo->output_bfd, amt);
1803
1804  /* Note that we are copying a string pointer here, and testing it
1805     above.  If bfd_elf_string_from_elf_section is ever changed to
1806     discard the string data when low in memory, this will have to be
1807     fixed.  */
1808  a->vna_nodename = h->verinfo.verdef->vd_nodename;
1809
1810  a->vna_flags = h->verinfo.verdef->vd_flags;
1811  a->vna_nextptr = t->vn_auxptr;
1812
1813  h->verinfo.verdef->vd_exp_refno = rinfo->vers;
1814  ++rinfo->vers;
1815
1816  a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
1817
1818  t->vn_auxptr = a;
1819
1820  return TRUE;
1821}
1822
1823/* Figure out appropriate versions for all the symbols.  We may not
1824   have the version number script until we have read all of the input
1825   files, so until that point we don't know which symbols should be
1826   local.  This function is called via elf_link_hash_traverse.  */
1827
1828bfd_boolean
1829_bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
1830{
1831  struct elf_assign_sym_version_info *sinfo;
1832  struct bfd_link_info *info;
1833  const struct elf_backend_data *bed;
1834  struct elf_info_failed eif;
1835  char *p;
1836  bfd_size_type amt;
1837
1838  sinfo = data;
1839  info = sinfo->info;
1840
1841  if (h->root.type == bfd_link_hash_warning)
1842    h = (struct elf_link_hash_entry *) h->root.u.i.link;
1843
1844  /* Fix the symbol flags.  */
1845  eif.failed = FALSE;
1846  eif.info = info;
1847  if (! _bfd_elf_fix_symbol_flags (h, &eif))
1848    {
1849      if (eif.failed)
1850	sinfo->failed = TRUE;
1851      return FALSE;
1852    }
1853
1854  /* We only need version numbers for symbols defined in regular
1855     objects.  */
1856  if (!h->def_regular)
1857    return TRUE;
1858
1859  bed = get_elf_backend_data (sinfo->output_bfd);
1860  p = strchr (h->root.root.string, ELF_VER_CHR);
1861  if (p != NULL && h->verinfo.vertree == NULL)
1862    {
1863      struct bfd_elf_version_tree *t;
1864      bfd_boolean hidden;
1865
1866      hidden = TRUE;
1867
1868      /* There are two consecutive ELF_VER_CHR characters if this is
1869	 not a hidden symbol.  */
1870      ++p;
1871      if (*p == ELF_VER_CHR)
1872	{
1873	  hidden = FALSE;
1874	  ++p;
1875	}
1876
1877      /* If there is no version string, we can just return out.  */
1878      if (*p == '\0')
1879	{
1880	  if (hidden)
1881	    h->hidden = 1;
1882	  return TRUE;
1883	}
1884
1885      /* Look for the version.  If we find it, it is no longer weak.  */
1886      for (t = sinfo->verdefs; t != NULL; t = t->next)
1887	{
1888	  if (strcmp (t->name, p) == 0)
1889	    {
1890	      size_t len;
1891	      char *alc;
1892	      struct bfd_elf_version_expr *d;
1893
1894	      len = p - h->root.root.string;
1895	      alc = bfd_malloc (len);
1896	      if (alc == NULL)
1897		return FALSE;
1898	      memcpy (alc, h->root.root.string, len - 1);
1899	      alc[len - 1] = '\0';
1900	      if (alc[len - 2] == ELF_VER_CHR)
1901		alc[len - 2] = '\0';
1902
1903	      h->verinfo.vertree = t;
1904	      t->used = TRUE;
1905	      d = NULL;
1906
1907	      if (t->globals.list != NULL)
1908		d = (*t->match) (&t->globals, NULL, alc);
1909
1910	      /* See if there is anything to force this symbol to
1911		 local scope.  */
1912	      if (d == NULL && t->locals.list != NULL)
1913		{
1914		  d = (*t->match) (&t->locals, NULL, alc);
1915		  if (d != NULL
1916		      && h->dynindx != -1
1917		      && ! info->export_dynamic)
1918		    (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1919		}
1920
1921	      free (alc);
1922	      break;
1923	    }
1924	}
1925
1926      /* If we are building an application, we need to create a
1927	 version node for this version.  */
1928      if (t == NULL && info->executable)
1929	{
1930	  struct bfd_elf_version_tree **pp;
1931	  int version_index;
1932
1933	  /* If we aren't going to export this symbol, we don't need
1934	     to worry about it.  */
1935	  if (h->dynindx == -1)
1936	    return TRUE;
1937
1938	  amt = sizeof *t;
1939	  t = bfd_zalloc (sinfo->output_bfd, amt);
1940	  if (t == NULL)
1941	    {
1942	      sinfo->failed = TRUE;
1943	      return FALSE;
1944	    }
1945
1946	  t->name = p;
1947	  t->name_indx = (unsigned int) -1;
1948	  t->used = TRUE;
1949
1950	  version_index = 1;
1951	  /* Don't count anonymous version tag.  */
1952	  if (sinfo->verdefs != NULL && sinfo->verdefs->vernum == 0)
1953	    version_index = 0;
1954	  for (pp = &sinfo->verdefs; *pp != NULL; pp = &(*pp)->next)
1955	    ++version_index;
1956	  t->vernum = version_index;
1957
1958	  *pp = t;
1959
1960	  h->verinfo.vertree = t;
1961	}
1962      else if (t == NULL)
1963	{
1964	  /* We could not find the version for a symbol when
1965	     generating a shared archive.  Return an error.  */
1966	  (*_bfd_error_handler)
1967	    (_("%B: version node not found for symbol %s"),
1968	     sinfo->output_bfd, h->root.root.string);
1969	  bfd_set_error (bfd_error_bad_value);
1970	  sinfo->failed = TRUE;
1971	  return FALSE;
1972	}
1973
1974      if (hidden)
1975	h->hidden = 1;
1976    }
1977
1978  /* If we don't have a version for this symbol, see if we can find
1979     something.  */
1980  if (h->verinfo.vertree == NULL && sinfo->verdefs != NULL)
1981    {
1982      struct bfd_elf_version_tree *t;
1983      struct bfd_elf_version_tree *local_ver;
1984      struct bfd_elf_version_expr *d;
1985
1986      /* See if can find what version this symbol is in.  If the
1987	 symbol is supposed to be local, then don't actually register
1988	 it.  */
1989      local_ver = NULL;
1990      for (t = sinfo->verdefs; t != NULL; t = t->next)
1991	{
1992	  if (t->globals.list != NULL)
1993	    {
1994	      bfd_boolean matched;
1995
1996	      matched = FALSE;
1997	      d = NULL;
1998	      while ((d = (*t->match) (&t->globals, d,
1999				       h->root.root.string)) != NULL)
2000		if (d->symver)
2001		  matched = TRUE;
2002		else
2003		  {
2004		    /* There is a version without definition.  Make
2005		       the symbol the default definition for this
2006		       version.  */
2007		    h->verinfo.vertree = t;
2008		    local_ver = NULL;
2009		    d->script = 1;
2010		    break;
2011		  }
2012	      if (d != NULL)
2013		break;
2014	      else if (matched)
2015		/* There is no undefined version for this symbol. Hide the
2016		   default one.  */
2017		(*bed->elf_backend_hide_symbol) (info, h, TRUE);
2018	    }
2019
2020	  if (t->locals.list != NULL)
2021	    {
2022	      d = NULL;
2023	      while ((d = (*t->match) (&t->locals, d,
2024				       h->root.root.string)) != NULL)
2025		{
2026		  local_ver = t;
2027		  /* If the match is "*", keep looking for a more
2028		     explicit, perhaps even global, match.
2029		     XXX: Shouldn't this be !d->wildcard instead?  */
2030		  if (d->pattern[0] != '*' || d->pattern[1] != '\0')
2031		    break;
2032		}
2033
2034	      if (d != NULL)
2035		break;
2036	    }
2037	}
2038
2039      if (local_ver != NULL)
2040	{
2041	  h->verinfo.vertree = local_ver;
2042	  if (h->dynindx != -1
2043	      && ! info->export_dynamic)
2044	    {
2045	      (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2046	    }
2047	}
2048    }
2049
2050  return TRUE;
2051}
2052
2053/* Read and swap the relocs from the section indicated by SHDR.  This
2054   may be either a REL or a RELA section.  The relocations are
2055   translated into RELA relocations and stored in INTERNAL_RELOCS,
2056   which should have already been allocated to contain enough space.
2057   The EXTERNAL_RELOCS are a buffer where the external form of the
2058   relocations should be stored.
2059
2060   Returns FALSE if something goes wrong.  */
2061
2062static bfd_boolean
2063elf_link_read_relocs_from_section (bfd *abfd,
2064				   asection *sec,
2065				   Elf_Internal_Shdr *shdr,
2066				   void *external_relocs,
2067				   Elf_Internal_Rela *internal_relocs)
2068{
2069  const struct elf_backend_data *bed;
2070  void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2071  const bfd_byte *erela;
2072  const bfd_byte *erelaend;
2073  Elf_Internal_Rela *irela;
2074  Elf_Internal_Shdr *symtab_hdr;
2075  size_t nsyms;
2076
2077  /* Position ourselves at the start of the section.  */
2078  if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2079    return FALSE;
2080
2081  /* Read the relocations.  */
2082  if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2083    return FALSE;
2084
2085  symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2086  nsyms = symtab_hdr->sh_size / symtab_hdr->sh_entsize;
2087
2088  bed = get_elf_backend_data (abfd);
2089
2090  /* Convert the external relocations to the internal format.  */
2091  if (shdr->sh_entsize == bed->s->sizeof_rel)
2092    swap_in = bed->s->swap_reloc_in;
2093  else if (shdr->sh_entsize == bed->s->sizeof_rela)
2094    swap_in = bed->s->swap_reloca_in;
2095  else
2096    {
2097      bfd_set_error (bfd_error_wrong_format);
2098      return FALSE;
2099    }
2100
2101  erela = external_relocs;
2102  erelaend = erela + shdr->sh_size;
2103  irela = internal_relocs;
2104  while (erela < erelaend)
2105    {
2106      bfd_vma r_symndx;
2107
2108      (*swap_in) (abfd, erela, irela);
2109      r_symndx = ELF32_R_SYM (irela->r_info);
2110      if (bed->s->arch_size == 64)
2111	r_symndx >>= 24;
2112      if ((size_t) r_symndx >= nsyms)
2113	{
2114	  (*_bfd_error_handler)
2115	    (_("%B: bad reloc symbol index (0x%lx >= 0x%lx)"
2116	       " for offset 0x%lx in section `%A'"),
2117	     abfd, sec,
2118	     (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2119	  bfd_set_error (bfd_error_bad_value);
2120	  return FALSE;
2121	}
2122      irela += bed->s->int_rels_per_ext_rel;
2123      erela += shdr->sh_entsize;
2124    }
2125
2126  return TRUE;
2127}
2128
2129/* Read and swap the relocs for a section O.  They may have been
2130   cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2131   not NULL, they are used as buffers to read into.  They are known to
2132   be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2133   the return value is allocated using either malloc or bfd_alloc,
2134   according to the KEEP_MEMORY argument.  If O has two relocation
2135   sections (both REL and RELA relocations), then the REL_HDR
2136   relocations will appear first in INTERNAL_RELOCS, followed by the
2137   REL_HDR2 relocations.  */
2138
2139Elf_Internal_Rela *
2140_bfd_elf_link_read_relocs (bfd *abfd,
2141			   asection *o,
2142			   void *external_relocs,
2143			   Elf_Internal_Rela *internal_relocs,
2144			   bfd_boolean keep_memory)
2145{
2146  Elf_Internal_Shdr *rel_hdr;
2147  void *alloc1 = NULL;
2148  Elf_Internal_Rela *alloc2 = NULL;
2149  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2150
2151  if (elf_section_data (o)->relocs != NULL)
2152    return elf_section_data (o)->relocs;
2153
2154  if (o->reloc_count == 0)
2155    return NULL;
2156
2157  rel_hdr = &elf_section_data (o)->rel_hdr;
2158
2159  if (internal_relocs == NULL)
2160    {
2161      bfd_size_type size;
2162
2163      size = o->reloc_count;
2164      size *= bed->s->int_rels_per_ext_rel * sizeof (Elf_Internal_Rela);
2165      if (keep_memory)
2166	internal_relocs = bfd_alloc (abfd, size);
2167      else
2168	internal_relocs = alloc2 = bfd_malloc (size);
2169      if (internal_relocs == NULL)
2170	goto error_return;
2171    }
2172
2173  if (external_relocs == NULL)
2174    {
2175      bfd_size_type size = rel_hdr->sh_size;
2176
2177      if (elf_section_data (o)->rel_hdr2)
2178	size += elf_section_data (o)->rel_hdr2->sh_size;
2179      alloc1 = bfd_malloc (size);
2180      if (alloc1 == NULL)
2181	goto error_return;
2182      external_relocs = alloc1;
2183    }
2184
2185  if (!elf_link_read_relocs_from_section (abfd, o, rel_hdr,
2186					  external_relocs,
2187					  internal_relocs))
2188    goto error_return;
2189  if (elf_section_data (o)->rel_hdr2
2190      && (!elf_link_read_relocs_from_section
2191	  (abfd, o,
2192	   elf_section_data (o)->rel_hdr2,
2193	   ((bfd_byte *) external_relocs) + rel_hdr->sh_size,
2194	   internal_relocs + (NUM_SHDR_ENTRIES (rel_hdr)
2195			      * bed->s->int_rels_per_ext_rel))))
2196    goto error_return;
2197
2198  /* Cache the results for next time, if we can.  */
2199  if (keep_memory)
2200    elf_section_data (o)->relocs = internal_relocs;
2201
2202  if (alloc1 != NULL)
2203    free (alloc1);
2204
2205  /* Don't free alloc2, since if it was allocated we are passing it
2206     back (under the name of internal_relocs).  */
2207
2208  return internal_relocs;
2209
2210 error_return:
2211  if (alloc1 != NULL)
2212    free (alloc1);
2213  if (alloc2 != NULL)
2214    free (alloc2);
2215  return NULL;
2216}
2217
2218/* Compute the size of, and allocate space for, REL_HDR which is the
2219   section header for a section containing relocations for O.  */
2220
2221bfd_boolean
2222_bfd_elf_link_size_reloc_section (bfd *abfd,
2223				  Elf_Internal_Shdr *rel_hdr,
2224				  asection *o)
2225{
2226  bfd_size_type reloc_count;
2227  bfd_size_type num_rel_hashes;
2228
2229  /* Figure out how many relocations there will be.  */
2230  if (rel_hdr == &elf_section_data (o)->rel_hdr)
2231    reloc_count = elf_section_data (o)->rel_count;
2232  else
2233    reloc_count = elf_section_data (o)->rel_count2;
2234
2235  num_rel_hashes = o->reloc_count;
2236  if (num_rel_hashes < reloc_count)
2237    num_rel_hashes = reloc_count;
2238
2239  /* That allows us to calculate the size of the section.  */
2240  rel_hdr->sh_size = rel_hdr->sh_entsize * reloc_count;
2241
2242  /* The contents field must last into write_object_contents, so we
2243     allocate it with bfd_alloc rather than malloc.  Also since we
2244     cannot be sure that the contents will actually be filled in,
2245     we zero the allocated space.  */
2246  rel_hdr->contents = bfd_zalloc (abfd, rel_hdr->sh_size);
2247  if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2248    return FALSE;
2249
2250  /* We only allocate one set of hash entries, so we only do it the
2251     first time we are called.  */
2252  if (elf_section_data (o)->rel_hashes == NULL
2253      && num_rel_hashes)
2254    {
2255      struct elf_link_hash_entry **p;
2256
2257      p = bfd_zmalloc (num_rel_hashes * sizeof (struct elf_link_hash_entry *));
2258      if (p == NULL)
2259	return FALSE;
2260
2261      elf_section_data (o)->rel_hashes = p;
2262    }
2263
2264  return TRUE;
2265}
2266
2267/* Copy the relocations indicated by the INTERNAL_RELOCS (which
2268   originated from the section given by INPUT_REL_HDR) to the
2269   OUTPUT_BFD.  */
2270
2271bfd_boolean
2272_bfd_elf_link_output_relocs (bfd *output_bfd,
2273			     asection *input_section,
2274			     Elf_Internal_Shdr *input_rel_hdr,
2275			     Elf_Internal_Rela *internal_relocs,
2276			     struct elf_link_hash_entry **rel_hash
2277			       ATTRIBUTE_UNUSED)
2278{
2279  Elf_Internal_Rela *irela;
2280  Elf_Internal_Rela *irelaend;
2281  bfd_byte *erel;
2282  Elf_Internal_Shdr *output_rel_hdr;
2283  asection *output_section;
2284  unsigned int *rel_countp = NULL;
2285  const struct elf_backend_data *bed;
2286  void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2287
2288  output_section = input_section->output_section;
2289  output_rel_hdr = NULL;
2290
2291  if (elf_section_data (output_section)->rel_hdr.sh_entsize
2292      == input_rel_hdr->sh_entsize)
2293    {
2294      output_rel_hdr = &elf_section_data (output_section)->rel_hdr;
2295      rel_countp = &elf_section_data (output_section)->rel_count;
2296    }
2297  else if (elf_section_data (output_section)->rel_hdr2
2298	   && (elf_section_data (output_section)->rel_hdr2->sh_entsize
2299	       == input_rel_hdr->sh_entsize))
2300    {
2301      output_rel_hdr = elf_section_data (output_section)->rel_hdr2;
2302      rel_countp = &elf_section_data (output_section)->rel_count2;
2303    }
2304  else
2305    {
2306      (*_bfd_error_handler)
2307	(_("%B: relocation size mismatch in %B section %A"),
2308	 output_bfd, input_section->owner, input_section);
2309      bfd_set_error (bfd_error_wrong_object_format);
2310      return FALSE;
2311    }
2312
2313  bed = get_elf_backend_data (output_bfd);
2314  if (input_rel_hdr->sh_entsize == bed->s->sizeof_rel)
2315    swap_out = bed->s->swap_reloc_out;
2316  else if (input_rel_hdr->sh_entsize == bed->s->sizeof_rela)
2317    swap_out = bed->s->swap_reloca_out;
2318  else
2319    abort ();
2320
2321  erel = output_rel_hdr->contents;
2322  erel += *rel_countp * input_rel_hdr->sh_entsize;
2323  irela = internal_relocs;
2324  irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2325		      * bed->s->int_rels_per_ext_rel);
2326  while (irela < irelaend)
2327    {
2328      (*swap_out) (output_bfd, irela, erel);
2329      irela += bed->s->int_rels_per_ext_rel;
2330      erel += input_rel_hdr->sh_entsize;
2331    }
2332
2333  /* Bump the counter, so that we know where to add the next set of
2334     relocations.  */
2335  *rel_countp += NUM_SHDR_ENTRIES (input_rel_hdr);
2336
2337  return TRUE;
2338}
2339
2340/* Make weak undefined symbols in PIE dynamic.  */
2341
2342bfd_boolean
2343_bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2344				 struct elf_link_hash_entry *h)
2345{
2346  if (info->pie
2347      && h->dynindx == -1
2348      && h->root.type == bfd_link_hash_undefweak)
2349    return bfd_elf_link_record_dynamic_symbol (info, h);
2350
2351  return TRUE;
2352}
2353
2354/* Fix up the flags for a symbol.  This handles various cases which
2355   can only be fixed after all the input files are seen.  This is
2356   currently called by both adjust_dynamic_symbol and
2357   assign_sym_version, which is unnecessary but perhaps more robust in
2358   the face of future changes.  */
2359
2360bfd_boolean
2361_bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2362			   struct elf_info_failed *eif)
2363{
2364  const struct elf_backend_data *bed = NULL;
2365
2366  /* If this symbol was mentioned in a non-ELF file, try to set
2367     DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2368     permit a non-ELF file to correctly refer to a symbol defined in
2369     an ELF dynamic object.  */
2370  if (h->non_elf)
2371    {
2372      while (h->root.type == bfd_link_hash_indirect)
2373	h = (struct elf_link_hash_entry *) h->root.u.i.link;
2374
2375      if (h->root.type != bfd_link_hash_defined
2376	  && h->root.type != bfd_link_hash_defweak)
2377	{
2378	  h->ref_regular = 1;
2379	  h->ref_regular_nonweak = 1;
2380	}
2381      else
2382	{
2383	  if (h->root.u.def.section->owner != NULL
2384	      && (bfd_get_flavour (h->root.u.def.section->owner)
2385		  == bfd_target_elf_flavour))
2386	    {
2387	      h->ref_regular = 1;
2388	      h->ref_regular_nonweak = 1;
2389	    }
2390	  else
2391	    h->def_regular = 1;
2392	}
2393
2394      if (h->dynindx == -1
2395	  && (h->def_dynamic
2396	      || h->ref_dynamic))
2397	{
2398	  if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2399	    {
2400	      eif->failed = TRUE;
2401	      return FALSE;
2402	    }
2403	}
2404    }
2405  else
2406    {
2407      /* Unfortunately, NON_ELF is only correct if the symbol
2408	 was first seen in a non-ELF file.  Fortunately, if the symbol
2409	 was first seen in an ELF file, we're probably OK unless the
2410	 symbol was defined in a non-ELF file.  Catch that case here.
2411	 FIXME: We're still in trouble if the symbol was first seen in
2412	 a dynamic object, and then later in a non-ELF regular object.  */
2413      if ((h->root.type == bfd_link_hash_defined
2414	   || h->root.type == bfd_link_hash_defweak)
2415	  && !h->def_regular
2416	  && (h->root.u.def.section->owner != NULL
2417	      ? (bfd_get_flavour (h->root.u.def.section->owner)
2418		 != bfd_target_elf_flavour)
2419	      : (bfd_is_abs_section (h->root.u.def.section)
2420		 && !h->def_dynamic)))
2421	h->def_regular = 1;
2422    }
2423
2424  /* Backend specific symbol fixup.  */
2425  if (elf_hash_table (eif->info)->dynobj)
2426    {
2427      bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2428      if (bed->elf_backend_fixup_symbol
2429	  && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2430	return FALSE;
2431    }
2432
2433  /* If this is a final link, and the symbol was defined as a common
2434     symbol in a regular object file, and there was no definition in
2435     any dynamic object, then the linker will have allocated space for
2436     the symbol in a common section but the DEF_REGULAR
2437     flag will not have been set.  */
2438  if (h->root.type == bfd_link_hash_defined
2439      && !h->def_regular
2440      && h->ref_regular
2441      && !h->def_dynamic
2442      && (h->root.u.def.section->owner->flags & DYNAMIC) == 0)
2443    h->def_regular = 1;
2444
2445  /* If -Bsymbolic was used (which means to bind references to global
2446     symbols to the definition within the shared object), and this
2447     symbol was defined in a regular object, then it actually doesn't
2448     need a PLT entry.  Likewise, if the symbol has non-default
2449     visibility.  If the symbol has hidden or internal visibility, we
2450     will force it local.  */
2451  if (h->needs_plt
2452      && eif->info->shared
2453      && is_elf_hash_table (eif->info->hash)
2454      && (SYMBOLIC_BIND (eif->info, h)
2455	  || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2456      && h->def_regular)
2457    {
2458      bfd_boolean force_local;
2459
2460      force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2461		     || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2462      (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2463    }
2464
2465  /* If a weak undefined symbol has non-default visibility, we also
2466     hide it from the dynamic linker.  */
2467  if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2468      && h->root.type == bfd_link_hash_undefweak)
2469    {
2470      const struct elf_backend_data *bed;
2471      bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2472      (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2473    }
2474
2475  /* If this is a weak defined symbol in a dynamic object, and we know
2476     the real definition in the dynamic object, copy interesting flags
2477     over to the real definition.  */
2478  if (h->u.weakdef != NULL)
2479    {
2480      struct elf_link_hash_entry *weakdef;
2481
2482      weakdef = h->u.weakdef;
2483      if (h->root.type == bfd_link_hash_indirect)
2484	h = (struct elf_link_hash_entry *) h->root.u.i.link;
2485
2486      BFD_ASSERT (h->root.type == bfd_link_hash_defined
2487		  || h->root.type == bfd_link_hash_defweak);
2488      BFD_ASSERT (weakdef->root.type == bfd_link_hash_defined
2489		  || weakdef->root.type == bfd_link_hash_defweak);
2490      BFD_ASSERT (weakdef->def_dynamic);
2491
2492      /* If the real definition is defined by a regular object file,
2493	 don't do anything special.  See the longer description in
2494	 _bfd_elf_adjust_dynamic_symbol, below.  */
2495      if (weakdef->def_regular)
2496	h->u.weakdef = NULL;
2497      else
2498	(*bed->elf_backend_copy_indirect_symbol) (eif->info, weakdef,
2499						  h);
2500    }
2501
2502  return TRUE;
2503}
2504
2505/* Make the backend pick a good value for a dynamic symbol.  This is
2506   called via elf_link_hash_traverse, and also calls itself
2507   recursively.  */
2508
2509bfd_boolean
2510_bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2511{
2512  struct elf_info_failed *eif = data;
2513  bfd *dynobj;
2514  const struct elf_backend_data *bed;
2515
2516  if (! is_elf_hash_table (eif->info->hash))
2517    return FALSE;
2518
2519  if (h->root.type == bfd_link_hash_warning)
2520    {
2521      h->got = elf_hash_table (eif->info)->init_got_offset;
2522      h->plt = elf_hash_table (eif->info)->init_plt_offset;
2523
2524      /* When warning symbols are created, they **replace** the "real"
2525	 entry in the hash table, thus we never get to see the real
2526	 symbol in a hash traversal.  So look at it now.  */
2527      h = (struct elf_link_hash_entry *) h->root.u.i.link;
2528    }
2529
2530  /* Ignore indirect symbols.  These are added by the versioning code.  */
2531  if (h->root.type == bfd_link_hash_indirect)
2532    return TRUE;
2533
2534  /* Fix the symbol flags.  */
2535  if (! _bfd_elf_fix_symbol_flags (h, eif))
2536    return FALSE;
2537
2538  /* If this symbol does not require a PLT entry, and it is not
2539     defined by a dynamic object, or is not referenced by a regular
2540     object, ignore it.  We do have to handle a weak defined symbol,
2541     even if no regular object refers to it, if we decided to add it
2542     to the dynamic symbol table.  FIXME: Do we normally need to worry
2543     about symbols which are defined by one dynamic object and
2544     referenced by another one?  */
2545  if (!h->needs_plt
2546      && (h->def_regular
2547	  || !h->def_dynamic
2548	  || (!h->ref_regular
2549	      && (h->u.weakdef == NULL || h->u.weakdef->dynindx == -1))))
2550    {
2551      h->plt = elf_hash_table (eif->info)->init_plt_offset;
2552      return TRUE;
2553    }
2554
2555  /* If we've already adjusted this symbol, don't do it again.  This
2556     can happen via a recursive call.  */
2557  if (h->dynamic_adjusted)
2558    return TRUE;
2559
2560  /* Don't look at this symbol again.  Note that we must set this
2561     after checking the above conditions, because we may look at a
2562     symbol once, decide not to do anything, and then get called
2563     recursively later after REF_REGULAR is set below.  */
2564  h->dynamic_adjusted = 1;
2565
2566  /* If this is a weak definition, and we know a real definition, and
2567     the real symbol is not itself defined by a regular object file,
2568     then get a good value for the real definition.  We handle the
2569     real symbol first, for the convenience of the backend routine.
2570
2571     Note that there is a confusing case here.  If the real definition
2572     is defined by a regular object file, we don't get the real symbol
2573     from the dynamic object, but we do get the weak symbol.  If the
2574     processor backend uses a COPY reloc, then if some routine in the
2575     dynamic object changes the real symbol, we will not see that
2576     change in the corresponding weak symbol.  This is the way other
2577     ELF linkers work as well, and seems to be a result of the shared
2578     library model.
2579
2580     I will clarify this issue.  Most SVR4 shared libraries define the
2581     variable _timezone and define timezone as a weak synonym.  The
2582     tzset call changes _timezone.  If you write
2583       extern int timezone;
2584       int _timezone = 5;
2585       int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2586     you might expect that, since timezone is a synonym for _timezone,
2587     the same number will print both times.  However, if the processor
2588     backend uses a COPY reloc, then actually timezone will be copied
2589     into your process image, and, since you define _timezone
2590     yourself, _timezone will not.  Thus timezone and _timezone will
2591     wind up at different memory locations.  The tzset call will set
2592     _timezone, leaving timezone unchanged.  */
2593
2594  if (h->u.weakdef != NULL)
2595    {
2596      /* If we get to this point, we know there is an implicit
2597	 reference by a regular object file via the weak symbol H.
2598	 FIXME: Is this really true?  What if the traversal finds
2599	 H->U.WEAKDEF before it finds H?  */
2600      h->u.weakdef->ref_regular = 1;
2601
2602      if (! _bfd_elf_adjust_dynamic_symbol (h->u.weakdef, eif))
2603	return FALSE;
2604    }
2605
2606  /* If a symbol has no type and no size and does not require a PLT
2607     entry, then we are probably about to do the wrong thing here: we
2608     are probably going to create a COPY reloc for an empty object.
2609     This case can arise when a shared object is built with assembly
2610     code, and the assembly code fails to set the symbol type.  */
2611  if (h->size == 0
2612      && h->type == STT_NOTYPE
2613      && !h->needs_plt)
2614    (*_bfd_error_handler)
2615      (_("warning: type and size of dynamic symbol `%s' are not defined"),
2616       h->root.root.string);
2617
2618  dynobj = elf_hash_table (eif->info)->dynobj;
2619  bed = get_elf_backend_data (dynobj);
2620  if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2621    {
2622      eif->failed = TRUE;
2623      return FALSE;
2624    }
2625
2626  return TRUE;
2627}
2628
2629/* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2630   DYNBSS.  */
2631
2632bfd_boolean
2633_bfd_elf_adjust_dynamic_copy (struct elf_link_hash_entry *h,
2634			      asection *dynbss)
2635{
2636  unsigned int power_of_two;
2637  bfd_vma mask;
2638  asection *sec = h->root.u.def.section;
2639
2640  /* The section aligment of definition is the maximum alignment
2641     requirement of symbols defined in the section.  Since we don't
2642     know the symbol alignment requirement, we start with the
2643     maximum alignment and check low bits of the symbol address
2644     for the minimum alignment.  */
2645  power_of_two = bfd_get_section_alignment (sec->owner, sec);
2646  mask = ((bfd_vma) 1 << power_of_two) - 1;
2647  while ((h->root.u.def.value & mask) != 0)
2648    {
2649       mask >>= 1;
2650       --power_of_two;
2651    }
2652
2653  if (power_of_two > bfd_get_section_alignment (dynbss->owner,
2654						dynbss))
2655    {
2656      /* Adjust the section alignment if needed.  */
2657      if (! bfd_set_section_alignment (dynbss->owner, dynbss,
2658				       power_of_two))
2659	return FALSE;
2660    }
2661
2662  /* We make sure that the symbol will be aligned properly.  */
2663  dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
2664
2665  /* Define the symbol as being at this point in DYNBSS.  */
2666  h->root.u.def.section = dynbss;
2667  h->root.u.def.value = dynbss->size;
2668
2669  /* Increment the size of DYNBSS to make room for the symbol.  */
2670  dynbss->size += h->size;
2671
2672  return TRUE;
2673}
2674
2675/* Adjust all external symbols pointing into SEC_MERGE sections
2676   to reflect the object merging within the sections.  */
2677
2678bfd_boolean
2679_bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
2680{
2681  asection *sec;
2682
2683  if (h->root.type == bfd_link_hash_warning)
2684    h = (struct elf_link_hash_entry *) h->root.u.i.link;
2685
2686  if ((h->root.type == bfd_link_hash_defined
2687       || h->root.type == bfd_link_hash_defweak)
2688      && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
2689      && sec->sec_info_type == ELF_INFO_TYPE_MERGE)
2690    {
2691      bfd *output_bfd = data;
2692
2693      h->root.u.def.value =
2694	_bfd_merged_section_offset (output_bfd,
2695				    &h->root.u.def.section,
2696				    elf_section_data (sec)->sec_info,
2697				    h->root.u.def.value);
2698    }
2699
2700  return TRUE;
2701}
2702
2703/* Returns false if the symbol referred to by H should be considered
2704   to resolve local to the current module, and true if it should be
2705   considered to bind dynamically.  */
2706
2707bfd_boolean
2708_bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
2709			   struct bfd_link_info *info,
2710			   bfd_boolean ignore_protected)
2711{
2712  bfd_boolean binding_stays_local_p;
2713  const struct elf_backend_data *bed;
2714  struct elf_link_hash_table *hash_table;
2715
2716  if (h == NULL)
2717    return FALSE;
2718
2719  while (h->root.type == bfd_link_hash_indirect
2720	 || h->root.type == bfd_link_hash_warning)
2721    h = (struct elf_link_hash_entry *) h->root.u.i.link;
2722
2723  /* If it was forced local, then clearly it's not dynamic.  */
2724  if (h->dynindx == -1)
2725    return FALSE;
2726  if (h->forced_local)
2727    return FALSE;
2728
2729  /* Identify the cases where name binding rules say that a
2730     visible symbol resolves locally.  */
2731  binding_stays_local_p = info->executable || SYMBOLIC_BIND (info, h);
2732
2733  switch (ELF_ST_VISIBILITY (h->other))
2734    {
2735    case STV_INTERNAL:
2736    case STV_HIDDEN:
2737      return FALSE;
2738
2739    case STV_PROTECTED:
2740      hash_table = elf_hash_table (info);
2741      if (!is_elf_hash_table (hash_table))
2742	return FALSE;
2743
2744      bed = get_elf_backend_data (hash_table->dynobj);
2745
2746      /* Proper resolution for function pointer equality may require
2747	 that these symbols perhaps be resolved dynamically, even though
2748	 we should be resolving them to the current module.  */
2749      if (!ignore_protected || !bed->is_function_type (h->type))
2750	binding_stays_local_p = TRUE;
2751      break;
2752
2753    default:
2754      break;
2755    }
2756
2757  /* If it isn't defined locally, then clearly it's dynamic.  */
2758  if (!h->def_regular)
2759    return TRUE;
2760
2761  /* Otherwise, the symbol is dynamic if binding rules don't tell
2762     us that it remains local.  */
2763  return !binding_stays_local_p;
2764}
2765
2766/* Return true if the symbol referred to by H should be considered
2767   to resolve local to the current module, and false otherwise.  Differs
2768   from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
2769   undefined symbols and weak symbols.  */
2770
2771bfd_boolean
2772_bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
2773			      struct bfd_link_info *info,
2774			      bfd_boolean local_protected)
2775{
2776  const struct elf_backend_data *bed;
2777  struct elf_link_hash_table *hash_table;
2778
2779  /* If it's a local sym, of course we resolve locally.  */
2780  if (h == NULL)
2781    return TRUE;
2782
2783  /* Common symbols that become definitions don't get the DEF_REGULAR
2784     flag set, so test it first, and don't bail out.  */
2785  if (ELF_COMMON_DEF_P (h))
2786    /* Do nothing.  */;
2787  /* If we don't have a definition in a regular file, then we can't
2788     resolve locally.  The sym is either undefined or dynamic.  */
2789  else if (!h->def_regular)
2790    return FALSE;
2791
2792  /* Forced local symbols resolve locally.  */
2793  if (h->forced_local)
2794    return TRUE;
2795
2796  /* As do non-dynamic symbols.  */
2797  if (h->dynindx == -1)
2798    return TRUE;
2799
2800  /* At this point, we know the symbol is defined and dynamic.  In an
2801     executable it must resolve locally, likewise when building symbolic
2802     shared libraries.  */
2803  if (info->executable || SYMBOLIC_BIND (info, h))
2804    return TRUE;
2805
2806  /* Now deal with defined dynamic symbols in shared libraries.  Ones
2807     with default visibility might not resolve locally.  */
2808  if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
2809    return FALSE;
2810
2811  /* However, STV_HIDDEN or STV_INTERNAL ones must be local.  */
2812  if (ELF_ST_VISIBILITY (h->other) != STV_PROTECTED)
2813    return TRUE;
2814
2815  hash_table = elf_hash_table (info);
2816  if (!is_elf_hash_table (hash_table))
2817    return TRUE;
2818
2819  bed = get_elf_backend_data (hash_table->dynobj);
2820
2821  /* STV_PROTECTED non-function symbols are local.  */
2822  if (!bed->is_function_type (h->type))
2823    return TRUE;
2824
2825  /* Function pointer equality tests may require that STV_PROTECTED
2826     symbols be treated as dynamic symbols, even when we know that the
2827     dynamic linker will resolve them locally.  */
2828  return local_protected;
2829}
2830
2831/* Caches some TLS segment info, and ensures that the TLS segment vma is
2832   aligned.  Returns the first TLS output section.  */
2833
2834struct bfd_section *
2835_bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
2836{
2837  struct bfd_section *sec, *tls;
2838  unsigned int align = 0;
2839
2840  for (sec = obfd->sections; sec != NULL; sec = sec->next)
2841    if ((sec->flags & SEC_THREAD_LOCAL) != 0)
2842      break;
2843  tls = sec;
2844
2845  for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
2846    if (sec->alignment_power > align)
2847      align = sec->alignment_power;
2848
2849  elf_hash_table (info)->tls_sec = tls;
2850
2851  /* Ensure the alignment of the first section is the largest alignment,
2852     so that the tls segment starts aligned.  */
2853  if (tls != NULL)
2854    tls->alignment_power = align;
2855
2856  return tls;
2857}
2858
2859/* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
2860static bfd_boolean
2861is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
2862				  Elf_Internal_Sym *sym)
2863{
2864  const struct elf_backend_data *bed;
2865
2866  /* Local symbols do not count, but target specific ones might.  */
2867  if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
2868      && ELF_ST_BIND (sym->st_info) < STB_LOOS)
2869    return FALSE;
2870
2871  bed = get_elf_backend_data (abfd);
2872  /* Function symbols do not count.  */
2873  if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
2874    return FALSE;
2875
2876  /* If the section is undefined, then so is the symbol.  */
2877  if (sym->st_shndx == SHN_UNDEF)
2878    return FALSE;
2879
2880  /* If the symbol is defined in the common section, then
2881     it is a common definition and so does not count.  */
2882  if (bed->common_definition (sym))
2883    return FALSE;
2884
2885  /* If the symbol is in a target specific section then we
2886     must rely upon the backend to tell us what it is.  */
2887  if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
2888    /* FIXME - this function is not coded yet:
2889
2890       return _bfd_is_global_symbol_definition (abfd, sym);
2891
2892       Instead for now assume that the definition is not global,
2893       Even if this is wrong, at least the linker will behave
2894       in the same way that it used to do.  */
2895    return FALSE;
2896
2897  return TRUE;
2898}
2899
2900/* Search the symbol table of the archive element of the archive ABFD
2901   whose archive map contains a mention of SYMDEF, and determine if
2902   the symbol is defined in this element.  */
2903static bfd_boolean
2904elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
2905{
2906  Elf_Internal_Shdr * hdr;
2907  bfd_size_type symcount;
2908  bfd_size_type extsymcount;
2909  bfd_size_type extsymoff;
2910  Elf_Internal_Sym *isymbuf;
2911  Elf_Internal_Sym *isym;
2912  Elf_Internal_Sym *isymend;
2913  bfd_boolean result;
2914
2915  abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
2916  if (abfd == NULL)
2917    return FALSE;
2918
2919  if (! bfd_check_format (abfd, bfd_object))
2920    return FALSE;
2921
2922  /* If we have already included the element containing this symbol in the
2923     link then we do not need to include it again.  Just claim that any symbol
2924     it contains is not a definition, so that our caller will not decide to
2925     (re)include this element.  */
2926  if (abfd->archive_pass)
2927    return FALSE;
2928
2929  /* Select the appropriate symbol table.  */
2930  if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
2931    hdr = &elf_tdata (abfd)->symtab_hdr;
2932  else
2933    hdr = &elf_tdata (abfd)->dynsymtab_hdr;
2934
2935  symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
2936
2937  /* The sh_info field of the symtab header tells us where the
2938     external symbols start.  We don't care about the local symbols.  */
2939  if (elf_bad_symtab (abfd))
2940    {
2941      extsymcount = symcount;
2942      extsymoff = 0;
2943    }
2944  else
2945    {
2946      extsymcount = symcount - hdr->sh_info;
2947      extsymoff = hdr->sh_info;
2948    }
2949
2950  if (extsymcount == 0)
2951    return FALSE;
2952
2953  /* Read in the symbol table.  */
2954  isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
2955				  NULL, NULL, NULL);
2956  if (isymbuf == NULL)
2957    return FALSE;
2958
2959  /* Scan the symbol table looking for SYMDEF.  */
2960  result = FALSE;
2961  for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
2962    {
2963      const char *name;
2964
2965      name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
2966					      isym->st_name);
2967      if (name == NULL)
2968	break;
2969
2970      if (strcmp (name, symdef->name) == 0)
2971	{
2972	  result = is_global_data_symbol_definition (abfd, isym);
2973	  break;
2974	}
2975    }
2976
2977  free (isymbuf);
2978
2979  return result;
2980}
2981
2982/* Add an entry to the .dynamic table.  */
2983
2984bfd_boolean
2985_bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
2986			    bfd_vma tag,
2987			    bfd_vma val)
2988{
2989  struct elf_link_hash_table *hash_table;
2990  const struct elf_backend_data *bed;
2991  asection *s;
2992  bfd_size_type newsize;
2993  bfd_byte *newcontents;
2994  Elf_Internal_Dyn dyn;
2995
2996  hash_table = elf_hash_table (info);
2997  if (! is_elf_hash_table (hash_table))
2998    return FALSE;
2999
3000  bed = get_elf_backend_data (hash_table->dynobj);
3001  s = bfd_get_section_by_name (hash_table->dynobj, ".dynamic");
3002  BFD_ASSERT (s != NULL);
3003
3004  newsize = s->size + bed->s->sizeof_dyn;
3005  newcontents = bfd_realloc (s->contents, newsize);
3006  if (newcontents == NULL)
3007    return FALSE;
3008
3009  dyn.d_tag = tag;
3010  dyn.d_un.d_val = val;
3011  bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3012
3013  s->size = newsize;
3014  s->contents = newcontents;
3015
3016  return TRUE;
3017}
3018
3019/* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3020   otherwise just check whether one already exists.  Returns -1 on error,
3021   1 if a DT_NEEDED tag already exists, and 0 on success.  */
3022
3023static int
3024elf_add_dt_needed_tag (bfd *abfd,
3025		       struct bfd_link_info *info,
3026		       const char *soname,
3027		       bfd_boolean do_it)
3028{
3029  struct elf_link_hash_table *hash_table;
3030  bfd_size_type oldsize;
3031  bfd_size_type strindex;
3032
3033  if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3034    return -1;
3035
3036  hash_table = elf_hash_table (info);
3037  oldsize = _bfd_elf_strtab_size (hash_table->dynstr);
3038  strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3039  if (strindex == (bfd_size_type) -1)
3040    return -1;
3041
3042  if (oldsize == _bfd_elf_strtab_size (hash_table->dynstr))
3043    {
3044      asection *sdyn;
3045      const struct elf_backend_data *bed;
3046      bfd_byte *extdyn;
3047
3048      bed = get_elf_backend_data (hash_table->dynobj);
3049      sdyn = bfd_get_section_by_name (hash_table->dynobj, ".dynamic");
3050      if (sdyn != NULL)
3051	for (extdyn = sdyn->contents;
3052	     extdyn < sdyn->contents + sdyn->size;
3053	     extdyn += bed->s->sizeof_dyn)
3054	  {
3055	    Elf_Internal_Dyn dyn;
3056
3057	    bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3058	    if (dyn.d_tag == DT_NEEDED
3059		&& dyn.d_un.d_val == strindex)
3060	      {
3061		_bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3062		return 1;
3063	      }
3064	  }
3065    }
3066
3067  if (do_it)
3068    {
3069      if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3070	return -1;
3071
3072      if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3073	return -1;
3074    }
3075  else
3076    /* We were just checking for existence of the tag.  */
3077    _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3078
3079  return 0;
3080}
3081
3082/* Sort symbol by value and section.  */
3083static int
3084elf_sort_symbol (const void *arg1, const void *arg2)
3085{
3086  const struct elf_link_hash_entry *h1;
3087  const struct elf_link_hash_entry *h2;
3088  bfd_signed_vma vdiff;
3089
3090  h1 = *(const struct elf_link_hash_entry **) arg1;
3091  h2 = *(const struct elf_link_hash_entry **) arg2;
3092  vdiff = h1->root.u.def.value - h2->root.u.def.value;
3093  if (vdiff != 0)
3094    return vdiff > 0 ? 1 : -1;
3095  else
3096    {
3097      long sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3098      if (sdiff != 0)
3099	return sdiff > 0 ? 1 : -1;
3100    }
3101  return 0;
3102}
3103
3104/* This function is used to adjust offsets into .dynstr for
3105   dynamic symbols.  This is called via elf_link_hash_traverse.  */
3106
3107static bfd_boolean
3108elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3109{
3110  struct elf_strtab_hash *dynstr = data;
3111
3112  if (h->root.type == bfd_link_hash_warning)
3113    h = (struct elf_link_hash_entry *) h->root.u.i.link;
3114
3115  if (h->dynindx != -1)
3116    h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3117  return TRUE;
3118}
3119
3120/* Assign string offsets in .dynstr, update all structures referencing
3121   them.  */
3122
3123static bfd_boolean
3124elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3125{
3126  struct elf_link_hash_table *hash_table = elf_hash_table (info);
3127  struct elf_link_local_dynamic_entry *entry;
3128  struct elf_strtab_hash *dynstr = hash_table->dynstr;
3129  bfd *dynobj = hash_table->dynobj;
3130  asection *sdyn;
3131  bfd_size_type size;
3132  const struct elf_backend_data *bed;
3133  bfd_byte *extdyn;
3134
3135  _bfd_elf_strtab_finalize (dynstr);
3136  size = _bfd_elf_strtab_size (dynstr);
3137
3138  bed = get_elf_backend_data (dynobj);
3139  sdyn = bfd_get_section_by_name (dynobj, ".dynamic");
3140  BFD_ASSERT (sdyn != NULL);
3141
3142  /* Update all .dynamic entries referencing .dynstr strings.  */
3143  for (extdyn = sdyn->contents;
3144       extdyn < sdyn->contents + sdyn->size;
3145       extdyn += bed->s->sizeof_dyn)
3146    {
3147      Elf_Internal_Dyn dyn;
3148
3149      bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3150      switch (dyn.d_tag)
3151	{
3152	case DT_STRSZ:
3153	  dyn.d_un.d_val = size;
3154	  break;
3155	case DT_NEEDED:
3156	case DT_SONAME:
3157	case DT_RPATH:
3158	case DT_RUNPATH:
3159	case DT_FILTER:
3160	case DT_AUXILIARY:
3161	  dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3162	  break;
3163	default:
3164	  continue;
3165	}
3166      bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3167    }
3168
3169  /* Now update local dynamic symbols.  */
3170  for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3171    entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3172						  entry->isym.st_name);
3173
3174  /* And the rest of dynamic symbols.  */
3175  elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3176
3177  /* Adjust version definitions.  */
3178  if (elf_tdata (output_bfd)->cverdefs)
3179    {
3180      asection *s;
3181      bfd_byte *p;
3182      bfd_size_type i;
3183      Elf_Internal_Verdef def;
3184      Elf_Internal_Verdaux defaux;
3185
3186      s = bfd_get_section_by_name (dynobj, ".gnu.version_d");
3187      p = s->contents;
3188      do
3189	{
3190	  _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3191				   &def);
3192	  p += sizeof (Elf_External_Verdef);
3193	  if (def.vd_aux != sizeof (Elf_External_Verdef))
3194	    continue;
3195	  for (i = 0; i < def.vd_cnt; ++i)
3196	    {
3197	      _bfd_elf_swap_verdaux_in (output_bfd,
3198					(Elf_External_Verdaux *) p, &defaux);
3199	      defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3200							defaux.vda_name);
3201	      _bfd_elf_swap_verdaux_out (output_bfd,
3202					 &defaux, (Elf_External_Verdaux *) p);
3203	      p += sizeof (Elf_External_Verdaux);
3204	    }
3205	}
3206      while (def.vd_next);
3207    }
3208
3209  /* Adjust version references.  */
3210  if (elf_tdata (output_bfd)->verref)
3211    {
3212      asection *s;
3213      bfd_byte *p;
3214      bfd_size_type i;
3215      Elf_Internal_Verneed need;
3216      Elf_Internal_Vernaux needaux;
3217
3218      s = bfd_get_section_by_name (dynobj, ".gnu.version_r");
3219      p = s->contents;
3220      do
3221	{
3222	  _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3223				    &need);
3224	  need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3225	  _bfd_elf_swap_verneed_out (output_bfd, &need,
3226				     (Elf_External_Verneed *) p);
3227	  p += sizeof (Elf_External_Verneed);
3228	  for (i = 0; i < need.vn_cnt; ++i)
3229	    {
3230	      _bfd_elf_swap_vernaux_in (output_bfd,
3231					(Elf_External_Vernaux *) p, &needaux);
3232	      needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3233							 needaux.vna_name);
3234	      _bfd_elf_swap_vernaux_out (output_bfd,
3235					 &needaux,
3236					 (Elf_External_Vernaux *) p);
3237	      p += sizeof (Elf_External_Vernaux);
3238	    }
3239	}
3240      while (need.vn_next);
3241    }
3242
3243  return TRUE;
3244}
3245
3246/* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3247   The default is to only match when the INPUT and OUTPUT are exactly
3248   the same target.  */
3249
3250bfd_boolean
3251_bfd_elf_default_relocs_compatible (const bfd_target *input,
3252				    const bfd_target *output)
3253{
3254  return input == output;
3255}
3256
3257/* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3258   This version is used when different targets for the same architecture
3259   are virtually identical.  */
3260
3261bfd_boolean
3262_bfd_elf_relocs_compatible (const bfd_target *input,
3263			    const bfd_target *output)
3264{
3265  const struct elf_backend_data *obed, *ibed;
3266
3267  if (input == output)
3268    return TRUE;
3269
3270  ibed = xvec_get_elf_backend_data (input);
3271  obed = xvec_get_elf_backend_data (output);
3272
3273  if (ibed->arch != obed->arch)
3274    return FALSE;
3275
3276  /* If both backends are using this function, deem them compatible.  */
3277  return ibed->relocs_compatible == obed->relocs_compatible;
3278}
3279
3280/* Add symbols from an ELF object file to the linker hash table.  */
3281
3282static bfd_boolean
3283elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3284{
3285  Elf_Internal_Shdr *hdr;
3286  bfd_size_type symcount;
3287  bfd_size_type extsymcount;
3288  bfd_size_type extsymoff;
3289  struct elf_link_hash_entry **sym_hash;
3290  bfd_boolean dynamic;
3291  Elf_External_Versym *extversym = NULL;
3292  Elf_External_Versym *ever;
3293  struct elf_link_hash_entry *weaks;
3294  struct elf_link_hash_entry **nondeflt_vers = NULL;
3295  bfd_size_type nondeflt_vers_cnt = 0;
3296  Elf_Internal_Sym *isymbuf = NULL;
3297  Elf_Internal_Sym *isym;
3298  Elf_Internal_Sym *isymend;
3299  const struct elf_backend_data *bed;
3300  bfd_boolean add_needed;
3301  struct elf_link_hash_table *htab;
3302  bfd_size_type amt;
3303  void *alloc_mark = NULL;
3304  struct bfd_hash_entry **old_table = NULL;
3305  unsigned int old_size = 0;
3306  unsigned int old_count = 0;
3307  void *old_tab = NULL;
3308  void *old_hash;
3309  void *old_ent;
3310  struct bfd_link_hash_entry *old_undefs = NULL;
3311  struct bfd_link_hash_entry *old_undefs_tail = NULL;
3312  long old_dynsymcount = 0;
3313  size_t tabsize = 0;
3314  size_t hashsize = 0;
3315
3316  htab = elf_hash_table (info);
3317  bed = get_elf_backend_data (abfd);
3318
3319  if ((abfd->flags & DYNAMIC) == 0)
3320    dynamic = FALSE;
3321  else
3322    {
3323      dynamic = TRUE;
3324
3325      /* You can't use -r against a dynamic object.  Also, there's no
3326	 hope of using a dynamic object which does not exactly match
3327	 the format of the output file.  */
3328      if (info->relocatable
3329	  || !is_elf_hash_table (htab)
3330	  || htab->root.creator != abfd->xvec)
3331	{
3332	  if (info->relocatable)
3333	    bfd_set_error (bfd_error_invalid_operation);
3334	  else
3335	    bfd_set_error (bfd_error_wrong_format);
3336	  goto error_return;
3337	}
3338    }
3339
3340  /* As a GNU extension, any input sections which are named
3341     .gnu.warning.SYMBOL are treated as warning symbols for the given
3342     symbol.  This differs from .gnu.warning sections, which generate
3343     warnings when they are included in an output file.  */
3344  if (info->executable)
3345    {
3346      asection *s;
3347
3348      for (s = abfd->sections; s != NULL; s = s->next)
3349	{
3350	  const char *name;
3351
3352	  name = bfd_get_section_name (abfd, s);
3353	  if (CONST_STRNEQ (name, ".gnu.warning."))
3354	    {
3355	      char *msg;
3356	      bfd_size_type sz;
3357
3358	      name += sizeof ".gnu.warning." - 1;
3359
3360	      /* If this is a shared object, then look up the symbol
3361		 in the hash table.  If it is there, and it is already
3362		 been defined, then we will not be using the entry
3363		 from this shared object, so we don't need to warn.
3364		 FIXME: If we see the definition in a regular object
3365		 later on, we will warn, but we shouldn't.  The only
3366		 fix is to keep track of what warnings we are supposed
3367		 to emit, and then handle them all at the end of the
3368		 link.  */
3369	      if (dynamic)
3370		{
3371		  struct elf_link_hash_entry *h;
3372
3373		  h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3374
3375		  /* FIXME: What about bfd_link_hash_common?  */
3376		  if (h != NULL
3377		      && (h->root.type == bfd_link_hash_defined
3378			  || h->root.type == bfd_link_hash_defweak))
3379		    {
3380		      /* We don't want to issue this warning.  Clobber
3381			 the section size so that the warning does not
3382			 get copied into the output file.  */
3383		      s->size = 0;
3384		      continue;
3385		    }
3386		}
3387
3388	      sz = s->size;
3389	      msg = bfd_alloc (abfd, sz + 1);
3390	      if (msg == NULL)
3391		goto error_return;
3392
3393	      if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3394		goto error_return;
3395
3396	      msg[sz] = '\0';
3397
3398	      if (! (_bfd_generic_link_add_one_symbol
3399		     (info, abfd, name, BSF_WARNING, s, 0, msg,
3400		      FALSE, bed->collect, NULL)))
3401		goto error_return;
3402
3403	      if (! info->relocatable)
3404		{
3405		  /* Clobber the section size so that the warning does
3406		     not get copied into the output file.  */
3407		  s->size = 0;
3408
3409		  /* Also set SEC_EXCLUDE, so that symbols defined in
3410		     the warning section don't get copied to the output.  */
3411		  s->flags |= SEC_EXCLUDE;
3412		}
3413	    }
3414	}
3415    }
3416
3417  add_needed = TRUE;
3418  if (! dynamic)
3419    {
3420      /* If we are creating a shared library, create all the dynamic
3421	 sections immediately.  We need to attach them to something,
3422	 so we attach them to this BFD, provided it is the right
3423	 format.  FIXME: If there are no input BFD's of the same
3424	 format as the output, we can't make a shared library.  */
3425      if (info->shared
3426	  && is_elf_hash_table (htab)
3427	  && htab->root.creator == abfd->xvec
3428	  && !htab->dynamic_sections_created)
3429	{
3430	  if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3431	    goto error_return;
3432	}
3433    }
3434  else if (!is_elf_hash_table (htab))
3435    goto error_return;
3436  else
3437    {
3438      asection *s;
3439      const char *soname = NULL;
3440      struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3441      int ret;
3442
3443      /* ld --just-symbols and dynamic objects don't mix very well.
3444	 ld shouldn't allow it.  */
3445      if ((s = abfd->sections) != NULL
3446	  && s->sec_info_type == ELF_INFO_TYPE_JUST_SYMS)
3447	abort ();
3448
3449      /* If this dynamic lib was specified on the command line with
3450	 --as-needed in effect, then we don't want to add a DT_NEEDED
3451	 tag unless the lib is actually used.  Similary for libs brought
3452	 in by another lib's DT_NEEDED.  When --no-add-needed is used
3453	 on a dynamic lib, we don't want to add a DT_NEEDED entry for
3454	 any dynamic library in DT_NEEDED tags in the dynamic lib at
3455	 all.  */
3456      add_needed = (elf_dyn_lib_class (abfd)
3457		    & (DYN_AS_NEEDED | DYN_DT_NEEDED
3458		       | DYN_NO_NEEDED)) == 0;
3459
3460      s = bfd_get_section_by_name (abfd, ".dynamic");
3461      if (s != NULL)
3462	{
3463	  bfd_byte *dynbuf;
3464	  bfd_byte *extdyn;
3465	  int elfsec;
3466	  unsigned long shlink;
3467
3468	  if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3469	    goto error_free_dyn;
3470
3471	  elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3472	  if (elfsec == -1)
3473	    goto error_free_dyn;
3474	  shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3475
3476	  for (extdyn = dynbuf;
3477	       extdyn < dynbuf + s->size;
3478	       extdyn += bed->s->sizeof_dyn)
3479	    {
3480	      Elf_Internal_Dyn dyn;
3481
3482	      bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3483	      if (dyn.d_tag == DT_SONAME)
3484		{
3485		  unsigned int tagv = dyn.d_un.d_val;
3486		  soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3487		  if (soname == NULL)
3488		    goto error_free_dyn;
3489		}
3490	      if (dyn.d_tag == DT_NEEDED)
3491		{
3492		  struct bfd_link_needed_list *n, **pn;
3493		  char *fnm, *anm;
3494		  unsigned int tagv = dyn.d_un.d_val;
3495
3496		  amt = sizeof (struct bfd_link_needed_list);
3497		  n = bfd_alloc (abfd, amt);
3498		  fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3499		  if (n == NULL || fnm == NULL)
3500		    goto error_free_dyn;
3501		  amt = strlen (fnm) + 1;
3502		  anm = bfd_alloc (abfd, amt);
3503		  if (anm == NULL)
3504		    goto error_free_dyn;
3505		  memcpy (anm, fnm, amt);
3506		  n->name = anm;
3507		  n->by = abfd;
3508		  n->next = NULL;
3509		  for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
3510		    ;
3511		  *pn = n;
3512		}
3513	      if (dyn.d_tag == DT_RUNPATH)
3514		{
3515		  struct bfd_link_needed_list *n, **pn;
3516		  char *fnm, *anm;
3517		  unsigned int tagv = dyn.d_un.d_val;
3518
3519		  amt = sizeof (struct bfd_link_needed_list);
3520		  n = bfd_alloc (abfd, amt);
3521		  fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3522		  if (n == NULL || fnm == NULL)
3523		    goto error_free_dyn;
3524		  amt = strlen (fnm) + 1;
3525		  anm = bfd_alloc (abfd, amt);
3526		  if (anm == NULL)
3527		    goto error_free_dyn;
3528		  memcpy (anm, fnm, amt);
3529		  n->name = anm;
3530		  n->by = abfd;
3531		  n->next = NULL;
3532		  for (pn = & runpath;
3533		       *pn != NULL;
3534		       pn = &(*pn)->next)
3535		    ;
3536		  *pn = n;
3537		}
3538	      /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
3539	      if (!runpath && dyn.d_tag == DT_RPATH)
3540		{
3541		  struct bfd_link_needed_list *n, **pn;
3542		  char *fnm, *anm;
3543		  unsigned int tagv = dyn.d_un.d_val;
3544
3545		  amt = sizeof (struct bfd_link_needed_list);
3546		  n = bfd_alloc (abfd, amt);
3547		  fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3548		  if (n == NULL || fnm == NULL)
3549		    goto error_free_dyn;
3550		  amt = strlen (fnm) + 1;
3551		  anm = bfd_alloc (abfd, amt);
3552		  if (anm == NULL)
3553		    {
3554		    error_free_dyn:
3555		      free (dynbuf);
3556		      goto error_return;
3557		    }
3558		  memcpy (anm, fnm, amt);
3559		  n->name = anm;
3560		  n->by = abfd;
3561		  n->next = NULL;
3562		  for (pn = & rpath;
3563		       *pn != NULL;
3564		       pn = &(*pn)->next)
3565		    ;
3566		  *pn = n;
3567		}
3568	    }
3569
3570	  free (dynbuf);
3571	}
3572
3573      /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
3574	 frees all more recently bfd_alloc'd blocks as well.  */
3575      if (runpath)
3576	rpath = runpath;
3577
3578      if (rpath)
3579	{
3580	  struct bfd_link_needed_list **pn;
3581	  for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
3582	    ;
3583	  *pn = rpath;
3584	}
3585
3586      /* We do not want to include any of the sections in a dynamic
3587	 object in the output file.  We hack by simply clobbering the
3588	 list of sections in the BFD.  This could be handled more
3589	 cleanly by, say, a new section flag; the existing
3590	 SEC_NEVER_LOAD flag is not the one we want, because that one
3591	 still implies that the section takes up space in the output
3592	 file.  */
3593      bfd_section_list_clear (abfd);
3594
3595      /* Find the name to use in a DT_NEEDED entry that refers to this
3596	 object.  If the object has a DT_SONAME entry, we use it.
3597	 Otherwise, if the generic linker stuck something in
3598	 elf_dt_name, we use that.  Otherwise, we just use the file
3599	 name.  */
3600      if (soname == NULL || *soname == '\0')
3601	{
3602	  soname = elf_dt_name (abfd);
3603	  if (soname == NULL || *soname == '\0')
3604	    soname = bfd_get_filename (abfd);
3605	}
3606
3607      /* Save the SONAME because sometimes the linker emulation code
3608	 will need to know it.  */
3609      elf_dt_name (abfd) = soname;
3610
3611      ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
3612      if (ret < 0)
3613	goto error_return;
3614
3615      /* If we have already included this dynamic object in the
3616	 link, just ignore it.  There is no reason to include a
3617	 particular dynamic object more than once.  */
3618      if (ret > 0)
3619	return TRUE;
3620    }
3621
3622  /* If this is a dynamic object, we always link against the .dynsym
3623     symbol table, not the .symtab symbol table.  The dynamic linker
3624     will only see the .dynsym symbol table, so there is no reason to
3625     look at .symtab for a dynamic object.  */
3626
3627  if (! dynamic || elf_dynsymtab (abfd) == 0)
3628    hdr = &elf_tdata (abfd)->symtab_hdr;
3629  else
3630    hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3631
3632  symcount = hdr->sh_size / bed->s->sizeof_sym;
3633
3634  /* The sh_info field of the symtab header tells us where the
3635     external symbols start.  We don't care about the local symbols at
3636     this point.  */
3637  if (elf_bad_symtab (abfd))
3638    {
3639      extsymcount = symcount;
3640      extsymoff = 0;
3641    }
3642  else
3643    {
3644      extsymcount = symcount - hdr->sh_info;
3645      extsymoff = hdr->sh_info;
3646    }
3647
3648  sym_hash = NULL;
3649  if (extsymcount != 0)
3650    {
3651      isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3652				      NULL, NULL, NULL);
3653      if (isymbuf == NULL)
3654	goto error_return;
3655
3656      /* We store a pointer to the hash table entry for each external
3657	 symbol.  */
3658      amt = extsymcount * sizeof (struct elf_link_hash_entry *);
3659      sym_hash = bfd_alloc (abfd, amt);
3660      if (sym_hash == NULL)
3661	goto error_free_sym;
3662      elf_sym_hashes (abfd) = sym_hash;
3663    }
3664
3665  if (dynamic)
3666    {
3667      /* Read in any version definitions.  */
3668      if (!_bfd_elf_slurp_version_tables (abfd,
3669					  info->default_imported_symver))
3670	goto error_free_sym;
3671
3672      /* Read in the symbol versions, but don't bother to convert them
3673	 to internal format.  */
3674      if (elf_dynversym (abfd) != 0)
3675	{
3676	  Elf_Internal_Shdr *versymhdr;
3677
3678	  versymhdr = &elf_tdata (abfd)->dynversym_hdr;
3679	  extversym = bfd_malloc (versymhdr->sh_size);
3680	  if (extversym == NULL)
3681	    goto error_free_sym;
3682	  amt = versymhdr->sh_size;
3683	  if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
3684	      || bfd_bread (extversym, amt, abfd) != amt)
3685	    goto error_free_vers;
3686	}
3687    }
3688
3689  /* If we are loading an as-needed shared lib, save the symbol table
3690     state before we start adding symbols.  If the lib turns out
3691     to be unneeded, restore the state.  */
3692  if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
3693    {
3694      unsigned int i;
3695      size_t entsize;
3696
3697      for (entsize = 0, i = 0; i < htab->root.table.size; i++)
3698	{
3699	  struct bfd_hash_entry *p;
3700	  struct elf_link_hash_entry *h;
3701
3702	  for (p = htab->root.table.table[i]; p != NULL; p = p->next)
3703	    {
3704	      h = (struct elf_link_hash_entry *) p;
3705	      entsize += htab->root.table.entsize;
3706	      if (h->root.type == bfd_link_hash_warning)
3707		entsize += htab->root.table.entsize;
3708	    }
3709	}
3710
3711      tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
3712      hashsize = extsymcount * sizeof (struct elf_link_hash_entry *);
3713      old_tab = bfd_malloc (tabsize + entsize + hashsize);
3714      if (old_tab == NULL)
3715	goto error_free_vers;
3716
3717      /* Remember the current objalloc pointer, so that all mem for
3718	 symbols added can later be reclaimed.  */
3719      alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
3720      if (alloc_mark == NULL)
3721	goto error_free_vers;
3722
3723      /* Make a special call to the linker "notice" function to
3724	 tell it that we are about to handle an as-needed lib.  */
3725      if (!(*info->callbacks->notice) (info, NULL, abfd, NULL,
3726				       notice_as_needed))
3727	return FALSE;
3728
3729
3730      /* Clone the symbol table and sym hashes.  Remember some
3731	 pointers into the symbol table, and dynamic symbol count.  */
3732      old_hash = (char *) old_tab + tabsize;
3733      old_ent = (char *) old_hash + hashsize;
3734      memcpy (old_tab, htab->root.table.table, tabsize);
3735      memcpy (old_hash, sym_hash, hashsize);
3736      old_undefs = htab->root.undefs;
3737      old_undefs_tail = htab->root.undefs_tail;
3738      old_table = htab->root.table.table;
3739      old_size = htab->root.table.size;
3740      old_count = htab->root.table.count;
3741      old_dynsymcount = htab->dynsymcount;
3742
3743      for (i = 0; i < htab->root.table.size; i++)
3744	{
3745	  struct bfd_hash_entry *p;
3746	  struct elf_link_hash_entry *h;
3747
3748	  for (p = htab->root.table.table[i]; p != NULL; p = p->next)
3749	    {
3750	      memcpy (old_ent, p, htab->root.table.entsize);
3751	      old_ent = (char *) old_ent + htab->root.table.entsize;
3752	      h = (struct elf_link_hash_entry *) p;
3753	      if (h->root.type == bfd_link_hash_warning)
3754		{
3755		  memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
3756		  old_ent = (char *) old_ent + htab->root.table.entsize;
3757		}
3758	    }
3759	}
3760    }
3761
3762  weaks = NULL;
3763  ever = extversym != NULL ? extversym + extsymoff : NULL;
3764  for (isym = isymbuf, isymend = isymbuf + extsymcount;
3765       isym < isymend;
3766       isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
3767    {
3768      int bind;
3769      bfd_vma value;
3770      asection *sec, *new_sec;
3771      flagword flags;
3772      const char *name;
3773      struct elf_link_hash_entry *h;
3774      bfd_boolean definition;
3775      bfd_boolean size_change_ok;
3776      bfd_boolean type_change_ok;
3777      bfd_boolean new_weakdef;
3778      bfd_boolean override;
3779      bfd_boolean common;
3780      unsigned int old_alignment;
3781      bfd *old_bfd;
3782
3783      override = FALSE;
3784
3785      flags = BSF_NO_FLAGS;
3786      sec = NULL;
3787      value = isym->st_value;
3788      *sym_hash = NULL;
3789      common = bed->common_definition (isym);
3790
3791      bind = ELF_ST_BIND (isym->st_info);
3792      if (bind == STB_LOCAL)
3793	{
3794	  /* This should be impossible, since ELF requires that all
3795	     global symbols follow all local symbols, and that sh_info
3796	     point to the first global symbol.  Unfortunately, Irix 5
3797	     screws this up.  */
3798	  continue;
3799	}
3800      else if (bind == STB_GLOBAL)
3801	{
3802	  if (isym->st_shndx != SHN_UNDEF && !common)
3803	    flags = BSF_GLOBAL;
3804	}
3805      else if (bind == STB_WEAK)
3806	flags = BSF_WEAK;
3807      else
3808	{
3809	  /* Leave it up to the processor backend.  */
3810	}
3811
3812      if (isym->st_shndx == SHN_UNDEF)
3813	sec = bfd_und_section_ptr;
3814      else if (isym->st_shndx < SHN_LORESERVE
3815	       || isym->st_shndx > SHN_HIRESERVE)
3816	{
3817	  sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
3818	  if (sec == NULL)
3819	    sec = bfd_abs_section_ptr;
3820	  else if (sec->kept_section)
3821	    {
3822	      /* Symbols from discarded section are undefined.  We keep
3823		 its visibility.  */
3824	      sec = bfd_und_section_ptr;
3825	      isym->st_shndx = SHN_UNDEF;
3826	    }
3827	  else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
3828	    value -= sec->vma;
3829	}
3830      else if (isym->st_shndx == SHN_ABS)
3831	sec = bfd_abs_section_ptr;
3832      else if (isym->st_shndx == SHN_COMMON)
3833	{
3834	  sec = bfd_com_section_ptr;
3835	  /* What ELF calls the size we call the value.  What ELF
3836	     calls the value we call the alignment.  */
3837	  value = isym->st_size;
3838	}
3839      else
3840	{
3841	  /* Leave it up to the processor backend.  */
3842	}
3843
3844      name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3845					      isym->st_name);
3846      if (name == NULL)
3847	goto error_free_vers;
3848
3849      if (isym->st_shndx == SHN_COMMON
3850	  && ELF_ST_TYPE (isym->st_info) == STT_TLS
3851	  && !info->relocatable)
3852	{
3853	  asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
3854
3855	  if (tcomm == NULL)
3856	    {
3857	      tcomm = bfd_make_section_with_flags (abfd, ".tcommon",
3858						   (SEC_ALLOC
3859						    | SEC_IS_COMMON
3860						    | SEC_LINKER_CREATED
3861						    | SEC_THREAD_LOCAL));
3862	      if (tcomm == NULL)
3863		goto error_free_vers;
3864	    }
3865	  sec = tcomm;
3866	}
3867      else if (bed->elf_add_symbol_hook)
3868	{
3869	  if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
3870					     &sec, &value))
3871	    goto error_free_vers;
3872
3873	  /* The hook function sets the name to NULL if this symbol
3874	     should be skipped for some reason.  */
3875	  if (name == NULL)
3876	    continue;
3877	}
3878
3879      /* Sanity check that all possibilities were handled.  */
3880      if (sec == NULL)
3881	{
3882	  bfd_set_error (bfd_error_bad_value);
3883	  goto error_free_vers;
3884	}
3885
3886      if (bfd_is_und_section (sec)
3887	  || bfd_is_com_section (sec))
3888	definition = FALSE;
3889      else
3890	definition = TRUE;
3891
3892      size_change_ok = FALSE;
3893      type_change_ok = bed->type_change_ok;
3894      old_alignment = 0;
3895      old_bfd = NULL;
3896      new_sec = sec;
3897
3898      if (is_elf_hash_table (htab))
3899	{
3900	  Elf_Internal_Versym iver;
3901	  unsigned int vernum = 0;
3902	  bfd_boolean skip;
3903
3904	  if (ever == NULL)
3905	    {
3906	      if (info->default_imported_symver)
3907		/* Use the default symbol version created earlier.  */
3908		iver.vs_vers = elf_tdata (abfd)->cverdefs;
3909	      else
3910		iver.vs_vers = 0;
3911	    }
3912	  else
3913	    _bfd_elf_swap_versym_in (abfd, ever, &iver);
3914
3915	  vernum = iver.vs_vers & VERSYM_VERSION;
3916
3917	  /* If this is a hidden symbol, or if it is not version
3918	     1, we append the version name to the symbol name.
3919	     However, we do not modify a non-hidden absolute symbol
3920	     if it is not a function, because it might be the version
3921	     symbol itself.  FIXME: What if it isn't?  */
3922	  if ((iver.vs_vers & VERSYM_HIDDEN) != 0
3923	      || (vernum > 1
3924		  && (!bfd_is_abs_section (sec)
3925		      || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
3926	    {
3927	      const char *verstr;
3928	      size_t namelen, verlen, newlen;
3929	      char *newname, *p;
3930
3931	      if (isym->st_shndx != SHN_UNDEF)
3932		{
3933		  if (vernum > elf_tdata (abfd)->cverdefs)
3934		    verstr = NULL;
3935		  else if (vernum > 1)
3936		    verstr =
3937		      elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
3938		  else
3939		    verstr = "";
3940
3941		  if (verstr == NULL)
3942		    {
3943		      (*_bfd_error_handler)
3944			(_("%B: %s: invalid version %u (max %d)"),
3945			 abfd, name, vernum,
3946			 elf_tdata (abfd)->cverdefs);
3947		      bfd_set_error (bfd_error_bad_value);
3948		      goto error_free_vers;
3949		    }
3950		}
3951	      else
3952		{
3953		  /* We cannot simply test for the number of
3954		     entries in the VERNEED section since the
3955		     numbers for the needed versions do not start
3956		     at 0.  */
3957		  Elf_Internal_Verneed *t;
3958
3959		  verstr = NULL;
3960		  for (t = elf_tdata (abfd)->verref;
3961		       t != NULL;
3962		       t = t->vn_nextref)
3963		    {
3964		      Elf_Internal_Vernaux *a;
3965
3966		      for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
3967			{
3968			  if (a->vna_other == vernum)
3969			    {
3970			      verstr = a->vna_nodename;
3971			      break;
3972			    }
3973			}
3974		      if (a != NULL)
3975			break;
3976		    }
3977		  if (verstr == NULL)
3978		    {
3979		      (*_bfd_error_handler)
3980			(_("%B: %s: invalid needed version %d"),
3981			 abfd, name, vernum);
3982		      bfd_set_error (bfd_error_bad_value);
3983		      goto error_free_vers;
3984		    }
3985		}
3986
3987	      namelen = strlen (name);
3988	      verlen = strlen (verstr);
3989	      newlen = namelen + verlen + 2;
3990	      if ((iver.vs_vers & VERSYM_HIDDEN) == 0
3991		  && isym->st_shndx != SHN_UNDEF)
3992		++newlen;
3993
3994	      newname = bfd_hash_allocate (&htab->root.table, newlen);
3995	      if (newname == NULL)
3996		goto error_free_vers;
3997	      memcpy (newname, name, namelen);
3998	      p = newname + namelen;
3999	      *p++ = ELF_VER_CHR;
4000	      /* If this is a defined non-hidden version symbol,
4001		 we add another @ to the name.  This indicates the
4002		 default version of the symbol.  */
4003	      if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4004		  && isym->st_shndx != SHN_UNDEF)
4005		*p++ = ELF_VER_CHR;
4006	      memcpy (p, verstr, verlen + 1);
4007
4008	      name = newname;
4009	    }
4010
4011	  if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec,
4012				      &value, &old_alignment,
4013				      sym_hash, &skip, &override,
4014				      &type_change_ok, &size_change_ok))
4015	    goto error_free_vers;
4016
4017	  if (skip)
4018	    continue;
4019
4020	  if (override)
4021	    definition = FALSE;
4022
4023	  h = *sym_hash;
4024	  while (h->root.type == bfd_link_hash_indirect
4025		 || h->root.type == bfd_link_hash_warning)
4026	    h = (struct elf_link_hash_entry *) h->root.u.i.link;
4027
4028	  /* Remember the old alignment if this is a common symbol, so
4029	     that we don't reduce the alignment later on.  We can't
4030	     check later, because _bfd_generic_link_add_one_symbol
4031	     will set a default for the alignment which we want to
4032	     override. We also remember the old bfd where the existing
4033	     definition comes from.  */
4034	  switch (h->root.type)
4035	    {
4036	    default:
4037	      break;
4038
4039	    case bfd_link_hash_defined:
4040	    case bfd_link_hash_defweak:
4041	      old_bfd = h->root.u.def.section->owner;
4042	      break;
4043
4044	    case bfd_link_hash_common:
4045	      old_bfd = h->root.u.c.p->section->owner;
4046	      old_alignment = h->root.u.c.p->alignment_power;
4047	      break;
4048	    }
4049
4050	  if (elf_tdata (abfd)->verdef != NULL
4051	      && ! override
4052	      && vernum > 1
4053	      && definition)
4054	    h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4055	}
4056
4057      if (! (_bfd_generic_link_add_one_symbol
4058	     (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4059	      (struct bfd_link_hash_entry **) sym_hash)))
4060	goto error_free_vers;
4061
4062      h = *sym_hash;
4063      while (h->root.type == bfd_link_hash_indirect
4064	     || h->root.type == bfd_link_hash_warning)
4065	h = (struct elf_link_hash_entry *) h->root.u.i.link;
4066      *sym_hash = h;
4067
4068      new_weakdef = FALSE;
4069      if (dynamic
4070	  && definition
4071	  && (flags & BSF_WEAK) != 0
4072	  && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4073	  && is_elf_hash_table (htab)
4074	  && h->u.weakdef == NULL)
4075	{
4076	  /* Keep a list of all weak defined non function symbols from
4077	     a dynamic object, using the weakdef field.  Later in this
4078	     function we will set the weakdef field to the correct
4079	     value.  We only put non-function symbols from dynamic
4080	     objects on this list, because that happens to be the only
4081	     time we need to know the normal symbol corresponding to a
4082	     weak symbol, and the information is time consuming to
4083	     figure out.  If the weakdef field is not already NULL,
4084	     then this symbol was already defined by some previous
4085	     dynamic object, and we will be using that previous
4086	     definition anyhow.  */
4087
4088	  h->u.weakdef = weaks;
4089	  weaks = h;
4090	  new_weakdef = TRUE;
4091	}
4092
4093      /* Set the alignment of a common symbol.  */
4094      if ((common || bfd_is_com_section (sec))
4095	  && h->root.type == bfd_link_hash_common)
4096	{
4097	  unsigned int align;
4098
4099	  if (common)
4100	    align = bfd_log2 (isym->st_value);
4101	  else
4102	    {
4103	      /* The new symbol is a common symbol in a shared object.
4104		 We need to get the alignment from the section.  */
4105	      align = new_sec->alignment_power;
4106	    }
4107	  if (align > old_alignment
4108	      /* Permit an alignment power of zero if an alignment of one
4109		 is specified and no other alignments have been specified.  */
4110	      || (isym->st_value == 1 && old_alignment == 0))
4111	    h->root.u.c.p->alignment_power = align;
4112	  else
4113	    h->root.u.c.p->alignment_power = old_alignment;
4114	}
4115
4116      if (is_elf_hash_table (htab))
4117	{
4118	  bfd_boolean dynsym;
4119
4120	  /* Check the alignment when a common symbol is involved. This
4121	     can change when a common symbol is overridden by a normal
4122	     definition or a common symbol is ignored due to the old
4123	     normal definition. We need to make sure the maximum
4124	     alignment is maintained.  */
4125	  if ((old_alignment || common)
4126	      && h->root.type != bfd_link_hash_common)
4127	    {
4128	      unsigned int common_align;
4129	      unsigned int normal_align;
4130	      unsigned int symbol_align;
4131	      bfd *normal_bfd;
4132	      bfd *common_bfd;
4133
4134	      symbol_align = ffs (h->root.u.def.value) - 1;
4135	      if (h->root.u.def.section->owner != NULL
4136		  && (h->root.u.def.section->owner->flags & DYNAMIC) == 0)
4137		{
4138		  normal_align = h->root.u.def.section->alignment_power;
4139		  if (normal_align > symbol_align)
4140		    normal_align = symbol_align;
4141		}
4142	      else
4143		normal_align = symbol_align;
4144
4145	      if (old_alignment)
4146		{
4147		  common_align = old_alignment;
4148		  common_bfd = old_bfd;
4149		  normal_bfd = abfd;
4150		}
4151	      else
4152		{
4153		  common_align = bfd_log2 (isym->st_value);
4154		  common_bfd = abfd;
4155		  normal_bfd = old_bfd;
4156		}
4157
4158	      if (normal_align < common_align)
4159		{
4160		  /* PR binutils/2735 */
4161		  if (normal_bfd == NULL)
4162		    (*_bfd_error_handler)
4163		      (_("Warning: alignment %u of common symbol `%s' in %B"
4164			 " is greater than the alignment (%u) of its section %A"),
4165		       common_bfd, h->root.u.def.section,
4166		       1 << common_align, name, 1 << normal_align);
4167		  else
4168		    (*_bfd_error_handler)
4169		      (_("Warning: alignment %u of symbol `%s' in %B"
4170			 " is smaller than %u in %B"),
4171		       normal_bfd, common_bfd,
4172		       1 << normal_align, name, 1 << common_align);
4173		}
4174	    }
4175
4176	  /* Remember the symbol size if it isn't undefined.  */
4177	  if ((isym->st_size != 0 && isym->st_shndx != SHN_UNDEF)
4178	      && (definition || h->size == 0))
4179	    {
4180	      if (h->size != 0
4181		  && h->size != isym->st_size
4182		  && ! size_change_ok)
4183		(*_bfd_error_handler)
4184		  (_("Warning: size of symbol `%s' changed"
4185		     " from %lu in %B to %lu in %B"),
4186		   old_bfd, abfd,
4187		   name, (unsigned long) h->size,
4188		   (unsigned long) isym->st_size);
4189
4190	      h->size = isym->st_size;
4191	    }
4192
4193	  /* If this is a common symbol, then we always want H->SIZE
4194	     to be the size of the common symbol.  The code just above
4195	     won't fix the size if a common symbol becomes larger.  We
4196	     don't warn about a size change here, because that is
4197	     covered by --warn-common.  Allow changed between different
4198	     function types.  */
4199	  if (h->root.type == bfd_link_hash_common)
4200	    h->size = h->root.u.c.size;
4201
4202	  if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4203	      && (definition || h->type == STT_NOTYPE))
4204	    {
4205	      if (h->type != STT_NOTYPE
4206		  && h->type != ELF_ST_TYPE (isym->st_info)
4207		  && ! type_change_ok)
4208		(*_bfd_error_handler)
4209		  (_("Warning: type of symbol `%s' changed"
4210		     " from %d to %d in %B"),
4211		   abfd, name, h->type, ELF_ST_TYPE (isym->st_info));
4212
4213	      h->type = ELF_ST_TYPE (isym->st_info);
4214	    }
4215
4216	  /* If st_other has a processor-specific meaning, specific
4217	     code might be needed here. We never merge the visibility
4218	     attribute with the one from a dynamic object.  */
4219	  if (bed->elf_backend_merge_symbol_attribute)
4220	    (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
4221							dynamic);
4222
4223	  /* If this symbol has default visibility and the user has requested
4224	     we not re-export it, then mark it as hidden.  */
4225	  if (definition && !dynamic
4226	      && (abfd->no_export
4227		  || (abfd->my_archive && abfd->my_archive->no_export))
4228	      && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4229	    isym->st_other = (STV_HIDDEN
4230			      | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4231
4232	  if (ELF_ST_VISIBILITY (isym->st_other) != 0 && !dynamic)
4233	    {
4234	      unsigned char hvis, symvis, other, nvis;
4235
4236	      /* Only merge the visibility. Leave the remainder of the
4237		 st_other field to elf_backend_merge_symbol_attribute.  */
4238	      other = h->other & ~ELF_ST_VISIBILITY (-1);
4239
4240	      /* Combine visibilities, using the most constraining one.  */
4241	      hvis   = ELF_ST_VISIBILITY (h->other);
4242	      symvis = ELF_ST_VISIBILITY (isym->st_other);
4243	      if (! hvis)
4244		nvis = symvis;
4245	      else if (! symvis)
4246		nvis = hvis;
4247	      else
4248		nvis = hvis < symvis ? hvis : symvis;
4249
4250	      h->other = other | nvis;
4251	    }
4252
4253	  /* Set a flag in the hash table entry indicating the type of
4254	     reference or definition we just found.  Keep a count of
4255	     the number of dynamic symbols we find.  A dynamic symbol
4256	     is one which is referenced or defined by both a regular
4257	     object and a shared object.  */
4258	  dynsym = FALSE;
4259	  if (! dynamic)
4260	    {
4261	      if (! definition)
4262		{
4263		  h->ref_regular = 1;
4264		  if (bind != STB_WEAK)
4265		    h->ref_regular_nonweak = 1;
4266		}
4267	      else
4268		h->def_regular = 1;
4269	      if (! info->executable
4270		  || h->def_dynamic
4271		  || h->ref_dynamic)
4272		dynsym = TRUE;
4273	    }
4274	  else
4275	    {
4276	      if (! definition)
4277		h->ref_dynamic = 1;
4278	      else
4279		h->def_dynamic = 1;
4280	      if (h->def_regular
4281		  || h->ref_regular
4282		  || (h->u.weakdef != NULL
4283		      && ! new_weakdef
4284		      && h->u.weakdef->dynindx != -1))
4285		dynsym = TRUE;
4286	    }
4287
4288	  if (definition && (sec->flags & SEC_DEBUGGING))
4289	    {
4290	      /* We don't want to make debug symbol dynamic.  */
4291	      (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4292	      dynsym = FALSE;
4293	    }
4294
4295	  /* Check to see if we need to add an indirect symbol for
4296	     the default name.  */
4297	  if (definition || h->root.type == bfd_link_hash_common)
4298	    if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4299					      &sec, &value, &dynsym,
4300					      override))
4301	      goto error_free_vers;
4302
4303	  if (definition && !dynamic)
4304	    {
4305	      char *p = strchr (name, ELF_VER_CHR);
4306	      if (p != NULL && p[1] != ELF_VER_CHR)
4307		{
4308		  /* Queue non-default versions so that .symver x, x@FOO
4309		     aliases can be checked.  */
4310		  if (!nondeflt_vers)
4311		    {
4312		      amt = ((isymend - isym + 1)
4313			     * sizeof (struct elf_link_hash_entry *));
4314		      nondeflt_vers = bfd_malloc (amt);
4315		    }
4316		  nondeflt_vers[nondeflt_vers_cnt++] = h;
4317		}
4318	    }
4319
4320	  if (dynsym && h->dynindx == -1)
4321	    {
4322	      if (! bfd_elf_link_record_dynamic_symbol (info, h))
4323		goto error_free_vers;
4324	      if (h->u.weakdef != NULL
4325		  && ! new_weakdef
4326		  && h->u.weakdef->dynindx == -1)
4327		{
4328		  if (!bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
4329		    goto error_free_vers;
4330		}
4331	    }
4332	  else if (dynsym && h->dynindx != -1)
4333	    /* If the symbol already has a dynamic index, but
4334	       visibility says it should not be visible, turn it into
4335	       a local symbol.  */
4336	    switch (ELF_ST_VISIBILITY (h->other))
4337	      {
4338	      case STV_INTERNAL:
4339	      case STV_HIDDEN:
4340		(*bed->elf_backend_hide_symbol) (info, h, TRUE);
4341		dynsym = FALSE;
4342		break;
4343	      }
4344
4345	  if (!add_needed
4346	      && definition
4347	      && dynsym
4348	      && h->ref_regular)
4349	    {
4350	      int ret;
4351	      const char *soname = elf_dt_name (abfd);
4352
4353	      /* A symbol from a library loaded via DT_NEEDED of some
4354		 other library is referenced by a regular object.
4355		 Add a DT_NEEDED entry for it.  Issue an error if
4356		 --no-add-needed is used.  */
4357	      if ((elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4358		{
4359		  bfd_boolean looks_soish;
4360		  const char *print_name;
4361		  int print_len;
4362		  size_t len, lend = 0;
4363
4364		  looks_soish = FALSE;
4365		  print_name = soname;
4366		  print_len = strlen(soname);
4367		  if (strncmp(soname, "lib", 3) == 0)
4368		    {
4369		      len = print_len;
4370		      if (len > 5 && strcmp(soname + len - 2, ".a") == 0)
4371			lend = len - 5;
4372		      else
4373			{
4374			  while (len > 6 && (ISDIGIT(soname[len - 1]) ||
4375					     soname[len - 1] == '.'))
4376			    len--;
4377			  if (strncmp(soname + len - 3, ".so", 3) == 0)
4378			    lend = len - 6;
4379			}
4380		      if (lend != 0)
4381			{
4382			  print_name = soname + 3;
4383			  print_len = lend;
4384			  looks_soish = TRUE;
4385		    	}
4386		    }
4387
4388		  (*_bfd_error_handler)
4389		    (_("undefined reference to symbol `%s' (try adding -l%s%.*s)"),
4390		    name, looks_soish? "" : ":", print_len, print_name);
4391		  bfd_set_error (bfd_error_bad_value);
4392		  goto error_free_vers;
4393		}
4394
4395	      elf_dyn_lib_class (abfd) &= ~DYN_AS_NEEDED;
4396
4397	      add_needed = TRUE;
4398	      ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4399	      if (ret < 0)
4400		goto error_free_vers;
4401
4402	      BFD_ASSERT (ret == 0);
4403	    }
4404	}
4405    }
4406
4407  if (extversym != NULL)
4408    {
4409      free (extversym);
4410      extversym = NULL;
4411    }
4412
4413  if (isymbuf != NULL)
4414    {
4415      free (isymbuf);
4416      isymbuf = NULL;
4417    }
4418
4419  if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4420    {
4421      unsigned int i;
4422
4423      /* Restore the symbol table.  */
4424      if (bed->as_needed_cleanup)
4425	(*bed->as_needed_cleanup) (abfd, info);
4426      old_hash = (char *) old_tab + tabsize;
4427      old_ent = (char *) old_hash + hashsize;
4428      sym_hash = elf_sym_hashes (abfd);
4429      htab->root.table.table = old_table;
4430      htab->root.table.size = old_size;
4431      htab->root.table.count = old_count;
4432      memcpy (htab->root.table.table, old_tab, tabsize);
4433      memcpy (sym_hash, old_hash, hashsize);
4434      htab->root.undefs = old_undefs;
4435      htab->root.undefs_tail = old_undefs_tail;
4436      for (i = 0; i < htab->root.table.size; i++)
4437	{
4438	  struct bfd_hash_entry *p;
4439	  struct elf_link_hash_entry *h;
4440
4441	  for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4442	    {
4443	      h = (struct elf_link_hash_entry *) p;
4444	      if (h->root.type == bfd_link_hash_warning)
4445		h = (struct elf_link_hash_entry *) h->root.u.i.link;
4446	      if (h->dynindx >= old_dynsymcount)
4447		_bfd_elf_strtab_delref (htab->dynstr, h->dynstr_index);
4448
4449	      memcpy (p, old_ent, htab->root.table.entsize);
4450	      old_ent = (char *) old_ent + htab->root.table.entsize;
4451	      h = (struct elf_link_hash_entry *) p;
4452	      if (h->root.type == bfd_link_hash_warning)
4453		{
4454		  memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
4455		  old_ent = (char *) old_ent + htab->root.table.entsize;
4456		}
4457	    }
4458	}
4459
4460      /* Make a special call to the linker "notice" function to
4461	 tell it that symbols added for crefs may need to be removed.  */
4462      if (!(*info->callbacks->notice) (info, NULL, abfd, NULL,
4463				       notice_not_needed))
4464	return FALSE;
4465
4466      free (old_tab);
4467      objalloc_free_block ((struct objalloc *) htab->root.table.memory,
4468			   alloc_mark);
4469      if (nondeflt_vers != NULL)
4470	free (nondeflt_vers);
4471      return TRUE;
4472    }
4473
4474  if (old_tab != NULL)
4475    {
4476      if (!(*info->callbacks->notice) (info, NULL, abfd, NULL,
4477				       notice_needed))
4478	return FALSE;
4479      free (old_tab);
4480      old_tab = NULL;
4481    }
4482
4483  /* Now that all the symbols from this input file are created, handle
4484     .symver foo, foo@BAR such that any relocs against foo become foo@BAR.  */
4485  if (nondeflt_vers != NULL)
4486    {
4487      bfd_size_type cnt, symidx;
4488
4489      for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
4490	{
4491	  struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
4492	  char *shortname, *p;
4493
4494	  p = strchr (h->root.root.string, ELF_VER_CHR);
4495	  if (p == NULL
4496	      || (h->root.type != bfd_link_hash_defined
4497		  && h->root.type != bfd_link_hash_defweak))
4498	    continue;
4499
4500	  amt = p - h->root.root.string;
4501	  shortname = bfd_malloc (amt + 1);
4502	  memcpy (shortname, h->root.root.string, amt);
4503	  shortname[amt] = '\0';
4504
4505	  hi = (struct elf_link_hash_entry *)
4506	       bfd_link_hash_lookup (&htab->root, shortname,
4507				     FALSE, FALSE, FALSE);
4508	  if (hi != NULL
4509	      && hi->root.type == h->root.type
4510	      && hi->root.u.def.value == h->root.u.def.value
4511	      && hi->root.u.def.section == h->root.u.def.section)
4512	    {
4513	      (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
4514	      hi->root.type = bfd_link_hash_indirect;
4515	      hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
4516	      (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
4517	      sym_hash = elf_sym_hashes (abfd);
4518	      if (sym_hash)
4519		for (symidx = 0; symidx < extsymcount; ++symidx)
4520		  if (sym_hash[symidx] == hi)
4521		    {
4522		      sym_hash[symidx] = h;
4523		      break;
4524		    }
4525	    }
4526	  free (shortname);
4527	}
4528      free (nondeflt_vers);
4529      nondeflt_vers = NULL;
4530    }
4531
4532  /* Now set the weakdefs field correctly for all the weak defined
4533     symbols we found.  The only way to do this is to search all the
4534     symbols.  Since we only need the information for non functions in
4535     dynamic objects, that's the only time we actually put anything on
4536     the list WEAKS.  We need this information so that if a regular
4537     object refers to a symbol defined weakly in a dynamic object, the
4538     real symbol in the dynamic object is also put in the dynamic
4539     symbols; we also must arrange for both symbols to point to the
4540     same memory location.  We could handle the general case of symbol
4541     aliasing, but a general symbol alias can only be generated in
4542     assembler code, handling it correctly would be very time
4543     consuming, and other ELF linkers don't handle general aliasing
4544     either.  */
4545  if (weaks != NULL)
4546    {
4547      struct elf_link_hash_entry **hpp;
4548      struct elf_link_hash_entry **hppend;
4549      struct elf_link_hash_entry **sorted_sym_hash;
4550      struct elf_link_hash_entry *h;
4551      size_t sym_count;
4552
4553      /* Since we have to search the whole symbol list for each weak
4554	 defined symbol, search time for N weak defined symbols will be
4555	 O(N^2). Binary search will cut it down to O(NlogN).  */
4556      amt = extsymcount * sizeof (struct elf_link_hash_entry *);
4557      sorted_sym_hash = bfd_malloc (amt);
4558      if (sorted_sym_hash == NULL)
4559	goto error_return;
4560      sym_hash = sorted_sym_hash;
4561      hpp = elf_sym_hashes (abfd);
4562      hppend = hpp + extsymcount;
4563      sym_count = 0;
4564      for (; hpp < hppend; hpp++)
4565	{
4566	  h = *hpp;
4567	  if (h != NULL
4568	      && h->root.type == bfd_link_hash_defined
4569	      && !bed->is_function_type (h->type))
4570	    {
4571	      *sym_hash = h;
4572	      sym_hash++;
4573	      sym_count++;
4574	    }
4575	}
4576
4577      qsort (sorted_sym_hash, sym_count,
4578	     sizeof (struct elf_link_hash_entry *),
4579	     elf_sort_symbol);
4580
4581      while (weaks != NULL)
4582	{
4583	  struct elf_link_hash_entry *hlook;
4584	  asection *slook;
4585	  bfd_vma vlook;
4586	  long ilook;
4587	  size_t i, j, idx;
4588
4589	  hlook = weaks;
4590	  weaks = hlook->u.weakdef;
4591	  hlook->u.weakdef = NULL;
4592
4593	  BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
4594		      || hlook->root.type == bfd_link_hash_defweak
4595		      || hlook->root.type == bfd_link_hash_common
4596		      || hlook->root.type == bfd_link_hash_indirect);
4597	  slook = hlook->root.u.def.section;
4598	  vlook = hlook->root.u.def.value;
4599
4600	  ilook = -1;
4601	  i = 0;
4602	  j = sym_count;
4603	  while (i < j)
4604	    {
4605	      bfd_signed_vma vdiff;
4606	      idx = (i + j) / 2;
4607	      h = sorted_sym_hash [idx];
4608	      vdiff = vlook - h->root.u.def.value;
4609	      if (vdiff < 0)
4610		j = idx;
4611	      else if (vdiff > 0)
4612		i = idx + 1;
4613	      else
4614		{
4615		  long sdiff = slook->id - h->root.u.def.section->id;
4616		  if (sdiff < 0)
4617		    j = idx;
4618		  else if (sdiff > 0)
4619		    i = idx + 1;
4620		  else
4621		    {
4622		      ilook = idx;
4623		      break;
4624		    }
4625		}
4626	    }
4627
4628	  /* We didn't find a value/section match.  */
4629	  if (ilook == -1)
4630	    continue;
4631
4632	  for (i = ilook; i < sym_count; i++)
4633	    {
4634	      h = sorted_sym_hash [i];
4635
4636	      /* Stop if value or section doesn't match.  */
4637	      if (h->root.u.def.value != vlook
4638		  || h->root.u.def.section != slook)
4639		break;
4640	      else if (h != hlook)
4641		{
4642		  hlook->u.weakdef = h;
4643
4644		  /* If the weak definition is in the list of dynamic
4645		     symbols, make sure the real definition is put
4646		     there as well.  */
4647		  if (hlook->dynindx != -1 && h->dynindx == -1)
4648		    {
4649		      if (! bfd_elf_link_record_dynamic_symbol (info, h))
4650			goto error_return;
4651		    }
4652
4653		  /* If the real definition is in the list of dynamic
4654		     symbols, make sure the weak definition is put
4655		     there as well.  If we don't do this, then the
4656		     dynamic loader might not merge the entries for the
4657		     real definition and the weak definition.  */
4658		  if (h->dynindx != -1 && hlook->dynindx == -1)
4659		    {
4660		      if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
4661			goto error_return;
4662		    }
4663		  break;
4664		}
4665	    }
4666	}
4667
4668      free (sorted_sym_hash);
4669    }
4670
4671  if (bed->check_directives)
4672    (*bed->check_directives) (abfd, info);
4673
4674  /* If this object is the same format as the output object, and it is
4675     not a shared library, then let the backend look through the
4676     relocs.
4677
4678     This is required to build global offset table entries and to
4679     arrange for dynamic relocs.  It is not required for the
4680     particular common case of linking non PIC code, even when linking
4681     against shared libraries, but unfortunately there is no way of
4682     knowing whether an object file has been compiled PIC or not.
4683     Looking through the relocs is not particularly time consuming.
4684     The problem is that we must either (1) keep the relocs in memory,
4685     which causes the linker to require additional runtime memory or
4686     (2) read the relocs twice from the input file, which wastes time.
4687     This would be a good case for using mmap.
4688
4689     I have no idea how to handle linking PIC code into a file of a
4690     different format.  It probably can't be done.  */
4691  if (! dynamic
4692      && is_elf_hash_table (htab)
4693      && bed->check_relocs != NULL
4694      && (*bed->relocs_compatible) (abfd->xvec, htab->root.creator))
4695    {
4696      asection *o;
4697
4698      for (o = abfd->sections; o != NULL; o = o->next)
4699	{
4700	  Elf_Internal_Rela *internal_relocs;
4701	  bfd_boolean ok;
4702
4703	  if ((o->flags & SEC_RELOC) == 0
4704	      || o->reloc_count == 0
4705	      || ((info->strip == strip_all || info->strip == strip_debugger)
4706		  && (o->flags & SEC_DEBUGGING) != 0)
4707	      || bfd_is_abs_section (o->output_section))
4708	    continue;
4709
4710	  internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
4711						       info->keep_memory);
4712	  if (internal_relocs == NULL)
4713	    goto error_return;
4714
4715	  ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
4716
4717	  if (elf_section_data (o)->relocs != internal_relocs)
4718	    free (internal_relocs);
4719
4720	  if (! ok)
4721	    goto error_return;
4722	}
4723    }
4724
4725  /* If this is a non-traditional link, try to optimize the handling
4726     of the .stab/.stabstr sections.  */
4727  if (! dynamic
4728      && ! info->traditional_format
4729      && is_elf_hash_table (htab)
4730      && (info->strip != strip_all && info->strip != strip_debugger))
4731    {
4732      asection *stabstr;
4733
4734      stabstr = bfd_get_section_by_name (abfd, ".stabstr");
4735      if (stabstr != NULL)
4736	{
4737	  bfd_size_type string_offset = 0;
4738	  asection *stab;
4739
4740	  for (stab = abfd->sections; stab; stab = stab->next)
4741	    if (CONST_STRNEQ (stab->name, ".stab")
4742		&& (!stab->name[5] ||
4743		    (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
4744		&& (stab->flags & SEC_MERGE) == 0
4745		&& !bfd_is_abs_section (stab->output_section))
4746	      {
4747		struct bfd_elf_section_data *secdata;
4748
4749		secdata = elf_section_data (stab);
4750		if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
4751					       stabstr, &secdata->sec_info,
4752					       &string_offset))
4753		  goto error_return;
4754		if (secdata->sec_info)
4755		  stab->sec_info_type = ELF_INFO_TYPE_STABS;
4756	    }
4757	}
4758    }
4759
4760  if (is_elf_hash_table (htab) && add_needed)
4761    {
4762      /* Add this bfd to the loaded list.  */
4763      struct elf_link_loaded_list *n;
4764
4765      n = bfd_alloc (abfd, sizeof (struct elf_link_loaded_list));
4766      if (n == NULL)
4767	goto error_return;
4768      n->abfd = abfd;
4769      n->next = htab->loaded;
4770      htab->loaded = n;
4771    }
4772
4773  return TRUE;
4774
4775 error_free_vers:
4776  if (old_tab != NULL)
4777    free (old_tab);
4778  if (nondeflt_vers != NULL)
4779    free (nondeflt_vers);
4780  if (extversym != NULL)
4781    free (extversym);
4782 error_free_sym:
4783  if (isymbuf != NULL)
4784    free (isymbuf);
4785 error_return:
4786  return FALSE;
4787}
4788
4789/* Return the linker hash table entry of a symbol that might be
4790   satisfied by an archive symbol.  Return -1 on error.  */
4791
4792struct elf_link_hash_entry *
4793_bfd_elf_archive_symbol_lookup (bfd *abfd,
4794				struct bfd_link_info *info,
4795				const char *name)
4796{
4797  struct elf_link_hash_entry *h;
4798  char *p, *copy;
4799  size_t len, first;
4800
4801  h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
4802  if (h != NULL)
4803    return h;
4804
4805  /* If this is a default version (the name contains @@), look up the
4806     symbol again with only one `@' as well as without the version.
4807     The effect is that references to the symbol with and without the
4808     version will be matched by the default symbol in the archive.  */
4809
4810  p = strchr (name, ELF_VER_CHR);
4811  if (p == NULL || p[1] != ELF_VER_CHR)
4812    return h;
4813
4814  /* First check with only one `@'.  */
4815  len = strlen (name);
4816  copy = bfd_alloc (abfd, len);
4817  if (copy == NULL)
4818    return (struct elf_link_hash_entry *)(intptr_t)-1;
4819
4820  first = p - name + 1;
4821  memcpy (copy, name, first);
4822  memcpy (copy + first, name + first + 1, len - first);
4823
4824  h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, FALSE);
4825  if (h == NULL)
4826    {
4827      /* We also need to check references to the symbol without the
4828	 version.  */
4829      copy[first - 1] = '\0';
4830      h = elf_link_hash_lookup (elf_hash_table (info), copy,
4831				FALSE, FALSE, FALSE);
4832    }
4833
4834  bfd_release (abfd, copy);
4835  return h;
4836}
4837
4838/* Add symbols from an ELF archive file to the linker hash table.  We
4839   don't use _bfd_generic_link_add_archive_symbols because of a
4840   problem which arises on UnixWare.  The UnixWare libc.so is an
4841   archive which includes an entry libc.so.1 which defines a bunch of
4842   symbols.  The libc.so archive also includes a number of other
4843   object files, which also define symbols, some of which are the same
4844   as those defined in libc.so.1.  Correct linking requires that we
4845   consider each object file in turn, and include it if it defines any
4846   symbols we need.  _bfd_generic_link_add_archive_symbols does not do
4847   this; it looks through the list of undefined symbols, and includes
4848   any object file which defines them.  When this algorithm is used on
4849   UnixWare, it winds up pulling in libc.so.1 early and defining a
4850   bunch of symbols.  This means that some of the other objects in the
4851   archive are not included in the link, which is incorrect since they
4852   precede libc.so.1 in the archive.
4853
4854   Fortunately, ELF archive handling is simpler than that done by
4855   _bfd_generic_link_add_archive_symbols, which has to allow for a.out
4856   oddities.  In ELF, if we find a symbol in the archive map, and the
4857   symbol is currently undefined, we know that we must pull in that
4858   object file.
4859
4860   Unfortunately, we do have to make multiple passes over the symbol
4861   table until nothing further is resolved.  */
4862
4863static bfd_boolean
4864elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
4865{
4866  symindex c;
4867  bfd_boolean *defined = NULL;
4868  bfd_boolean *included = NULL;
4869  carsym *symdefs;
4870  bfd_boolean loop;
4871  bfd_size_type amt;
4872  const struct elf_backend_data *bed;
4873  struct elf_link_hash_entry * (*archive_symbol_lookup)
4874    (bfd *, struct bfd_link_info *, const char *);
4875
4876  if (! bfd_has_map (abfd))
4877    {
4878      /* An empty archive is a special case.  */
4879      if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
4880	return TRUE;
4881      bfd_set_error (bfd_error_no_armap);
4882      return FALSE;
4883    }
4884
4885  /* Keep track of all symbols we know to be already defined, and all
4886     files we know to be already included.  This is to speed up the
4887     second and subsequent passes.  */
4888  c = bfd_ardata (abfd)->symdef_count;
4889  if (c == 0)
4890    return TRUE;
4891  amt = c;
4892  amt *= sizeof (bfd_boolean);
4893  defined = bfd_zmalloc (amt);
4894  included = bfd_zmalloc (amt);
4895  if (defined == NULL || included == NULL)
4896    goto error_return;
4897
4898  symdefs = bfd_ardata (abfd)->symdefs;
4899  bed = get_elf_backend_data (abfd);
4900  archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
4901
4902  do
4903    {
4904      file_ptr last;
4905      symindex i;
4906      carsym *symdef;
4907      carsym *symdefend;
4908
4909      loop = FALSE;
4910      last = -1;
4911
4912      symdef = symdefs;
4913      symdefend = symdef + c;
4914      for (i = 0; symdef < symdefend; symdef++, i++)
4915	{
4916	  struct elf_link_hash_entry *h;
4917	  bfd *element;
4918	  struct bfd_link_hash_entry *undefs_tail;
4919	  symindex mark;
4920
4921	  if (defined[i] || included[i])
4922	    continue;
4923	  if (symdef->file_offset == last)
4924	    {
4925	      included[i] = TRUE;
4926	      continue;
4927	    }
4928
4929	  h = archive_symbol_lookup (abfd, info, symdef->name);
4930	  if (h == (struct elf_link_hash_entry *)(intptr_t)-1)
4931	    goto error_return;
4932
4933	  if (h == NULL)
4934	    continue;
4935
4936	  if (h->root.type == bfd_link_hash_common)
4937	    {
4938	      /* We currently have a common symbol.  The archive map contains
4939		 a reference to this symbol, so we may want to include it.  We
4940		 only want to include it however, if this archive element
4941		 contains a definition of the symbol, not just another common
4942		 declaration of it.
4943
4944		 Unfortunately some archivers (including GNU ar) will put
4945		 declarations of common symbols into their archive maps, as
4946		 well as real definitions, so we cannot just go by the archive
4947		 map alone.  Instead we must read in the element's symbol
4948		 table and check that to see what kind of symbol definition
4949		 this is.  */
4950	      if (! elf_link_is_defined_archive_symbol (abfd, symdef))
4951		continue;
4952	    }
4953	  else if (h->root.type != bfd_link_hash_undefined)
4954	    {
4955	      if (h->root.type != bfd_link_hash_undefweak)
4956		defined[i] = TRUE;
4957	      continue;
4958	    }
4959
4960	  /* We need to include this archive member.  */
4961	  element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
4962	  if (element == NULL)
4963	    goto error_return;
4964
4965	  if (! bfd_check_format (element, bfd_object))
4966	    goto error_return;
4967
4968	  /* Doublecheck that we have not included this object
4969	     already--it should be impossible, but there may be
4970	     something wrong with the archive.  */
4971	  if (element->archive_pass != 0)
4972	    {
4973	      bfd_set_error (bfd_error_bad_value);
4974	      goto error_return;
4975	    }
4976	  element->archive_pass = 1;
4977
4978	  undefs_tail = info->hash->undefs_tail;
4979
4980	  if (! (*info->callbacks->add_archive_element) (info, element,
4981							 symdef->name))
4982	    goto error_return;
4983	  if (! bfd_link_add_symbols (element, info))
4984	    goto error_return;
4985
4986	  /* If there are any new undefined symbols, we need to make
4987	     another pass through the archive in order to see whether
4988	     they can be defined.  FIXME: This isn't perfect, because
4989	     common symbols wind up on undefs_tail and because an
4990	     undefined symbol which is defined later on in this pass
4991	     does not require another pass.  This isn't a bug, but it
4992	     does make the code less efficient than it could be.  */
4993	  if (undefs_tail != info->hash->undefs_tail)
4994	    loop = TRUE;
4995
4996	  /* Look backward to mark all symbols from this object file
4997	     which we have already seen in this pass.  */
4998	  mark = i;
4999	  do
5000	    {
5001	      included[mark] = TRUE;
5002	      if (mark == 0)
5003		break;
5004	      --mark;
5005	    }
5006	  while (symdefs[mark].file_offset == symdef->file_offset);
5007
5008	  /* We mark subsequent symbols from this object file as we go
5009	     on through the loop.  */
5010	  last = symdef->file_offset;
5011	}
5012    }
5013  while (loop);
5014
5015  free (defined);
5016  free (included);
5017
5018  return TRUE;
5019
5020 error_return:
5021  if (defined != NULL)
5022    free (defined);
5023  if (included != NULL)
5024    free (included);
5025  return FALSE;
5026}
5027
5028/* Given an ELF BFD, add symbols to the global hash table as
5029   appropriate.  */
5030
5031bfd_boolean
5032bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5033{
5034  switch (bfd_get_format (abfd))
5035    {
5036    case bfd_object:
5037      return elf_link_add_object_symbols (abfd, info);
5038    case bfd_archive:
5039      return elf_link_add_archive_symbols (abfd, info);
5040    default:
5041      bfd_set_error (bfd_error_wrong_format);
5042      return FALSE;
5043    }
5044}
5045
5046/* This function will be called though elf_link_hash_traverse to store
5047   all hash value of the exported symbols in an array.  */
5048
5049static bfd_boolean
5050elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5051{
5052  unsigned long **valuep = data;
5053  const char *name;
5054  char *p;
5055  unsigned long ha;
5056  char *alc = NULL;
5057
5058  if (h->root.type == bfd_link_hash_warning)
5059    h = (struct elf_link_hash_entry *) h->root.u.i.link;
5060
5061  /* Ignore indirect symbols.  These are added by the versioning code.  */
5062  if (h->dynindx == -1)
5063    return TRUE;
5064
5065  name = h->root.root.string;
5066  p = strchr (name, ELF_VER_CHR);
5067  if (p != NULL)
5068    {
5069      alc = bfd_malloc (p - name + 1);
5070      memcpy (alc, name, p - name);
5071      alc[p - name] = '\0';
5072      name = alc;
5073    }
5074
5075  /* Compute the hash value.  */
5076  ha = bfd_elf_hash (name);
5077
5078  /* Store the found hash value in the array given as the argument.  */
5079  *(*valuep)++ = ha;
5080
5081  /* And store it in the struct so that we can put it in the hash table
5082     later.  */
5083  h->u.elf_hash_value = ha;
5084
5085  if (alc != NULL)
5086    free (alc);
5087
5088  return TRUE;
5089}
5090
5091struct collect_gnu_hash_codes
5092{
5093  bfd *output_bfd;
5094  const struct elf_backend_data *bed;
5095  unsigned long int nsyms;
5096  unsigned long int maskbits;
5097  unsigned long int *hashcodes;
5098  unsigned long int *hashval;
5099  unsigned long int *indx;
5100  unsigned long int *counts;
5101  bfd_vma *bitmask;
5102  bfd_byte *contents;
5103  long int min_dynindx;
5104  unsigned long int bucketcount;
5105  unsigned long int symindx;
5106  long int local_indx;
5107  long int shift1, shift2;
5108  unsigned long int mask;
5109};
5110
5111/* This function will be called though elf_link_hash_traverse to store
5112   all hash value of the exported symbols in an array.  */
5113
5114static bfd_boolean
5115elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5116{
5117  struct collect_gnu_hash_codes *s = data;
5118  const char *name;
5119  char *p;
5120  unsigned long ha;
5121  char *alc = NULL;
5122
5123  if (h->root.type == bfd_link_hash_warning)
5124    h = (struct elf_link_hash_entry *) h->root.u.i.link;
5125
5126  /* Ignore indirect symbols.  These are added by the versioning code.  */
5127  if (h->dynindx == -1)
5128    return TRUE;
5129
5130  /* Ignore also local symbols and undefined symbols.  */
5131  if (! (*s->bed->elf_hash_symbol) (h))
5132    return TRUE;
5133
5134  name = h->root.root.string;
5135  p = strchr (name, ELF_VER_CHR);
5136  if (p != NULL)
5137    {
5138      alc = bfd_malloc (p - name + 1);
5139      memcpy (alc, name, p - name);
5140      alc[p - name] = '\0';
5141      name = alc;
5142    }
5143
5144  /* Compute the hash value.  */
5145  ha = bfd_elf_gnu_hash (name);
5146
5147  /* Store the found hash value in the array for compute_bucket_count,
5148     and also for .dynsym reordering purposes.  */
5149  s->hashcodes[s->nsyms] = ha;
5150  s->hashval[h->dynindx] = ha;
5151  ++s->nsyms;
5152  if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5153    s->min_dynindx = h->dynindx;
5154
5155  if (alc != NULL)
5156    free (alc);
5157
5158  return TRUE;
5159}
5160
5161/* This function will be called though elf_link_hash_traverse to do
5162   final dynaminc symbol renumbering.  */
5163
5164static bfd_boolean
5165elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5166{
5167  struct collect_gnu_hash_codes *s = data;
5168  unsigned long int bucket;
5169  unsigned long int val;
5170
5171  if (h->root.type == bfd_link_hash_warning)
5172    h = (struct elf_link_hash_entry *) h->root.u.i.link;
5173
5174  /* Ignore indirect symbols.  */
5175  if (h->dynindx == -1)
5176    return TRUE;
5177
5178  /* Ignore also local symbols and undefined symbols.  */
5179  if (! (*s->bed->elf_hash_symbol) (h))
5180    {
5181      if (h->dynindx >= s->min_dynindx)
5182	h->dynindx = s->local_indx++;
5183      return TRUE;
5184    }
5185
5186  bucket = s->hashval[h->dynindx] % s->bucketcount;
5187  val = (s->hashval[h->dynindx] >> s->shift1)
5188	& ((s->maskbits >> s->shift1) - 1);
5189  s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5190  s->bitmask[val]
5191    |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5192  val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5193  if (s->counts[bucket] == 1)
5194    /* Last element terminates the chain.  */
5195    val |= 1;
5196  bfd_put_32 (s->output_bfd, val,
5197	      s->contents + (s->indx[bucket] - s->symindx) * 4);
5198  --s->counts[bucket];
5199  h->dynindx = s->indx[bucket]++;
5200  return TRUE;
5201}
5202
5203/* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5204
5205bfd_boolean
5206_bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5207{
5208  return !(h->forced_local
5209	   || h->root.type == bfd_link_hash_undefined
5210	   || h->root.type == bfd_link_hash_undefweak
5211	   || ((h->root.type == bfd_link_hash_defined
5212		|| h->root.type == bfd_link_hash_defweak)
5213	       && h->root.u.def.section->output_section == NULL));
5214}
5215
5216/* Array used to determine the number of hash table buckets to use
5217   based on the number of symbols there are.  If there are fewer than
5218   3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5219   fewer than 37 we use 17 buckets, and so forth.  We never use more
5220   than 32771 buckets.  */
5221
5222static const size_t elf_buckets[] =
5223{
5224  1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5225  16411, 32771, 0
5226};
5227
5228/* Compute bucket count for hashing table.  We do not use a static set
5229   of possible tables sizes anymore.  Instead we determine for all
5230   possible reasonable sizes of the table the outcome (i.e., the
5231   number of collisions etc) and choose the best solution.  The
5232   weighting functions are not too simple to allow the table to grow
5233   without bounds.  Instead one of the weighting factors is the size.
5234   Therefore the result is always a good payoff between few collisions
5235   (= short chain lengths) and table size.  */
5236static size_t
5237compute_bucket_count (struct bfd_link_info *info, unsigned long int *hashcodes,
5238		      unsigned long int nsyms, int gnu_hash)
5239{
5240  size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5241  size_t best_size = 0;
5242  unsigned long int i;
5243  bfd_size_type amt;
5244
5245  /* We have a problem here.  The following code to optimize the table
5246     size requires an integer type with more the 32 bits.  If
5247     BFD_HOST_U_64_BIT is set we know about such a type.  */
5248#ifdef BFD_HOST_U_64_BIT
5249  if (info->optimize)
5250    {
5251      size_t minsize;
5252      size_t maxsize;
5253      BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5254      bfd *dynobj = elf_hash_table (info)->dynobj;
5255      const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5256      unsigned long int *counts;
5257
5258      /* Possible optimization parameters: if we have NSYMS symbols we say
5259	 that the hashing table must at least have NSYMS/4 and at most
5260	 2*NSYMS buckets.  */
5261      minsize = nsyms / 4;
5262      if (minsize == 0)
5263	minsize = 1;
5264      best_size = maxsize = nsyms * 2;
5265      if (gnu_hash)
5266	{
5267	  if (minsize < 2)
5268	    minsize = 2;
5269	  if ((best_size & 31) == 0)
5270	    ++best_size;
5271	}
5272
5273      /* Create array where we count the collisions in.  We must use bfd_malloc
5274	 since the size could be large.  */
5275      amt = maxsize;
5276      amt *= sizeof (unsigned long int);
5277      counts = bfd_malloc (amt);
5278      if (counts == NULL)
5279	return 0;
5280
5281      /* Compute the "optimal" size for the hash table.  The criteria is a
5282	 minimal chain length.  The minor criteria is (of course) the size
5283	 of the table.  */
5284      for (i = minsize; i < maxsize; ++i)
5285	{
5286	  /* Walk through the array of hashcodes and count the collisions.  */
5287	  BFD_HOST_U_64_BIT max;
5288	  unsigned long int j;
5289	  unsigned long int fact;
5290
5291	  if (gnu_hash && (i & 31) == 0)
5292	    continue;
5293
5294	  memset (counts, '\0', i * sizeof (unsigned long int));
5295
5296	  /* Determine how often each hash bucket is used.  */
5297	  for (j = 0; j < nsyms; ++j)
5298	    ++counts[hashcodes[j] % i];
5299
5300	  /* For the weight function we need some information about the
5301	     pagesize on the target.  This is information need not be 100%
5302	     accurate.  Since this information is not available (so far) we
5303	     define it here to a reasonable default value.  If it is crucial
5304	     to have a better value some day simply define this value.  */
5305# ifndef BFD_TARGET_PAGESIZE
5306#  define BFD_TARGET_PAGESIZE	(4096)
5307# endif
5308
5309	  /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5310	     and the chains.  */
5311	  max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5312
5313# if 1
5314	  /* Variant 1: optimize for short chains.  We add the squares
5315	     of all the chain lengths (which favors many small chain
5316	     over a few long chains).  */
5317	  for (j = 0; j < i; ++j)
5318	    max += counts[j] * counts[j];
5319
5320	  /* This adds penalties for the overall size of the table.  */
5321	  fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5322	  max *= fact * fact;
5323# else
5324	  /* Variant 2: Optimize a lot more for small table.  Here we
5325	     also add squares of the size but we also add penalties for
5326	     empty slots (the +1 term).  */
5327	  for (j = 0; j < i; ++j)
5328	    max += (1 + counts[j]) * (1 + counts[j]);
5329
5330	  /* The overall size of the table is considered, but not as
5331	     strong as in variant 1, where it is squared.  */
5332	  fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5333	  max *= fact;
5334# endif
5335
5336	  /* Compare with current best results.  */
5337	  if (max < best_chlen)
5338	    {
5339	      best_chlen = max;
5340	      best_size = i;
5341	    }
5342	}
5343
5344      free (counts);
5345    }
5346  else
5347#endif /* defined (BFD_HOST_U_64_BIT) */
5348    {
5349      /* This is the fallback solution if no 64bit type is available or if we
5350	 are not supposed to spend much time on optimizations.  We select the
5351	 bucket count using a fixed set of numbers.  */
5352      for (i = 0; elf_buckets[i] != 0; i++)
5353	{
5354	  best_size = elf_buckets[i];
5355	  if (nsyms < elf_buckets[i + 1])
5356	    break;
5357	}
5358      if (gnu_hash && best_size < 2)
5359	best_size = 2;
5360    }
5361
5362  return best_size;
5363}
5364
5365/* Set up the sizes and contents of the ELF dynamic sections.  This is
5366   called by the ELF linker emulation before_allocation routine.  We
5367   must set the sizes of the sections before the linker sets the
5368   addresses of the various sections.  */
5369
5370bfd_boolean
5371bfd_elf_size_dynamic_sections (bfd *output_bfd,
5372			       const char *soname,
5373			       const char *rpath,
5374			       const char *filter_shlib,
5375			       const char * const *auxiliary_filters,
5376			       struct bfd_link_info *info,
5377			       asection **sinterpptr,
5378			       struct bfd_elf_version_tree *verdefs)
5379{
5380  bfd_size_type soname_indx;
5381  bfd *dynobj;
5382  const struct elf_backend_data *bed;
5383  struct elf_assign_sym_version_info asvinfo;
5384
5385  *sinterpptr = NULL;
5386
5387  soname_indx = (bfd_size_type) -1;
5388
5389  if (!is_elf_hash_table (info->hash))
5390    return TRUE;
5391
5392  bed = get_elf_backend_data (output_bfd);
5393  elf_tdata (output_bfd)->relro = info->relro;
5394  if (info->execstack)
5395    elf_tdata (output_bfd)->stack_flags = PF_R | PF_W | PF_X;
5396  else if (info->noexecstack)
5397    elf_tdata (output_bfd)->stack_flags = PF_R | PF_W;
5398  else
5399    {
5400      bfd *inputobj;
5401      asection *notesec = NULL;
5402      int exec = 0;
5403
5404      for (inputobj = info->input_bfds;
5405	   inputobj;
5406	   inputobj = inputobj->link_next)
5407	{
5408	  asection *s;
5409
5410	  if (inputobj->flags & (DYNAMIC | BFD_LINKER_CREATED))
5411	    continue;
5412	  s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
5413	  if (s)
5414	    {
5415	      if (s->flags & SEC_CODE)
5416		exec = PF_X;
5417	      notesec = s;
5418	    }
5419	  else if (bed->default_execstack)
5420	    exec = PF_X;
5421	}
5422      if (notesec)
5423	{
5424	  elf_tdata (output_bfd)->stack_flags = PF_R | PF_W | exec;
5425	  if (exec && info->relocatable
5426	      && notesec->output_section != bfd_abs_section_ptr)
5427	    notesec->output_section->flags |= SEC_CODE;
5428	}
5429    }
5430
5431  /* Any syms created from now on start with -1 in
5432     got.refcount/offset and plt.refcount/offset.  */
5433  elf_hash_table (info)->init_got_refcount
5434    = elf_hash_table (info)->init_got_offset;
5435  elf_hash_table (info)->init_plt_refcount
5436    = elf_hash_table (info)->init_plt_offset;
5437
5438  /* The backend may have to create some sections regardless of whether
5439     we're dynamic or not.  */
5440  if (bed->elf_backend_always_size_sections
5441      && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
5442    return FALSE;
5443
5444  if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
5445    return FALSE;
5446
5447  dynobj = elf_hash_table (info)->dynobj;
5448
5449  /* If there were no dynamic objects in the link, there is nothing to
5450     do here.  */
5451  if (dynobj == NULL)
5452    return TRUE;
5453
5454  if (elf_hash_table (info)->dynamic_sections_created)
5455    {
5456      struct elf_info_failed eif;
5457      struct elf_link_hash_entry *h;
5458      asection *dynstr;
5459      struct bfd_elf_version_tree *t;
5460      struct bfd_elf_version_expr *d;
5461      asection *s;
5462      bfd_boolean all_defined;
5463
5464      *sinterpptr = bfd_get_section_by_name (dynobj, ".interp");
5465      BFD_ASSERT (*sinterpptr != NULL || !info->executable);
5466
5467      if (soname != NULL)
5468	{
5469	  soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5470					     soname, TRUE);
5471	  if (soname_indx == (bfd_size_type) -1
5472	      || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
5473	    return FALSE;
5474	}
5475
5476      if (info->symbolic)
5477	{
5478	  if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
5479	    return FALSE;
5480	  info->flags |= DF_SYMBOLIC;
5481	}
5482
5483      if (rpath != NULL)
5484	{
5485	  bfd_size_type indx;
5486
5487	  indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
5488				      TRUE);
5489	  if (indx == (bfd_size_type) -1
5490	      || !_bfd_elf_add_dynamic_entry (info, DT_RPATH, indx))
5491	    return FALSE;
5492
5493	  if  (info->new_dtags)
5494	    {
5495	      _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr, indx);
5496	      if (!_bfd_elf_add_dynamic_entry (info, DT_RUNPATH, indx))
5497		return FALSE;
5498	    }
5499	}
5500
5501      if (filter_shlib != NULL)
5502	{
5503	  bfd_size_type indx;
5504
5505	  indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5506				      filter_shlib, TRUE);
5507	  if (indx == (bfd_size_type) -1
5508	      || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
5509	    return FALSE;
5510	}
5511
5512      if (auxiliary_filters != NULL)
5513	{
5514	  const char * const *p;
5515
5516	  for (p = auxiliary_filters; *p != NULL; p++)
5517	    {
5518	      bfd_size_type indx;
5519
5520	      indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5521					  *p, TRUE);
5522	      if (indx == (bfd_size_type) -1
5523		  || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
5524		return FALSE;
5525	    }
5526	}
5527
5528      eif.info = info;
5529      eif.verdefs = verdefs;
5530      eif.failed = FALSE;
5531
5532      /* If we are supposed to export all symbols into the dynamic symbol
5533	 table (this is not the normal case), then do so.  */
5534      if (info->export_dynamic
5535	  || (info->executable && info->dynamic))
5536	{
5537	  elf_link_hash_traverse (elf_hash_table (info),
5538				  _bfd_elf_export_symbol,
5539				  &eif);
5540	  if (eif.failed)
5541	    return FALSE;
5542	}
5543
5544      /* Make all global versions with definition.  */
5545      for (t = verdefs; t != NULL; t = t->next)
5546	for (d = t->globals.list; d != NULL; d = d->next)
5547	  if (!d->symver && d->symbol)
5548	    {
5549	      const char *verstr, *name;
5550	      size_t namelen, verlen, newlen;
5551	      char *newname, *p;
5552	      struct elf_link_hash_entry *newh;
5553
5554	      name = d->symbol;
5555	      namelen = strlen (name);
5556	      verstr = t->name;
5557	      verlen = strlen (verstr);
5558	      newlen = namelen + verlen + 3;
5559
5560	      newname = bfd_malloc (newlen);
5561	      if (newname == NULL)
5562		return FALSE;
5563	      memcpy (newname, name, namelen);
5564
5565	      /* Check the hidden versioned definition.  */
5566	      p = newname + namelen;
5567	      *p++ = ELF_VER_CHR;
5568	      memcpy (p, verstr, verlen + 1);
5569	      newh = elf_link_hash_lookup (elf_hash_table (info),
5570					   newname, FALSE, FALSE,
5571					   FALSE);
5572	      if (newh == NULL
5573		  || (newh->root.type != bfd_link_hash_defined
5574		      && newh->root.type != bfd_link_hash_defweak))
5575		{
5576		  /* Check the default versioned definition.  */
5577		  *p++ = ELF_VER_CHR;
5578		  memcpy (p, verstr, verlen + 1);
5579		  newh = elf_link_hash_lookup (elf_hash_table (info),
5580					       newname, FALSE, FALSE,
5581					       FALSE);
5582		}
5583	      free (newname);
5584
5585	      /* Mark this version if there is a definition and it is
5586		 not defined in a shared object.  */
5587	      if (newh != NULL
5588		  && !newh->def_dynamic
5589		  && (newh->root.type == bfd_link_hash_defined
5590		      || newh->root.type == bfd_link_hash_defweak))
5591		d->symver = 1;
5592	    }
5593
5594      /* Attach all the symbols to their version information.  */
5595      asvinfo.output_bfd = output_bfd;
5596      asvinfo.info = info;
5597      asvinfo.verdefs = verdefs;
5598      asvinfo.failed = FALSE;
5599
5600      elf_link_hash_traverse (elf_hash_table (info),
5601			      _bfd_elf_link_assign_sym_version,
5602			      &asvinfo);
5603      if (asvinfo.failed)
5604	return FALSE;
5605
5606      if (!info->allow_undefined_version)
5607	{
5608	  /* Check if all global versions have a definition.  */
5609	  all_defined = TRUE;
5610	  for (t = verdefs; t != NULL; t = t->next)
5611	    for (d = t->globals.list; d != NULL; d = d->next)
5612	      if (!d->symver && !d->script)
5613		{
5614		  (*_bfd_error_handler)
5615		    (_("%s: undefined version: %s"),
5616		     d->pattern, t->name);
5617		  all_defined = FALSE;
5618		}
5619
5620	  if (!all_defined)
5621	    {
5622	      bfd_set_error (bfd_error_bad_value);
5623	      return FALSE;
5624	    }
5625	}
5626
5627      /* Find all symbols which were defined in a dynamic object and make
5628	 the backend pick a reasonable value for them.  */
5629      elf_link_hash_traverse (elf_hash_table (info),
5630			      _bfd_elf_adjust_dynamic_symbol,
5631			      &eif);
5632      if (eif.failed)
5633	return FALSE;
5634
5635      /* Add some entries to the .dynamic section.  We fill in some of the
5636	 values later, in bfd_elf_final_link, but we must add the entries
5637	 now so that we know the final size of the .dynamic section.  */
5638
5639      /* If there are initialization and/or finalization functions to
5640	 call then add the corresponding DT_INIT/DT_FINI entries.  */
5641      h = (info->init_function
5642	   ? elf_link_hash_lookup (elf_hash_table (info),
5643				   info->init_function, FALSE,
5644				   FALSE, FALSE)
5645	   : NULL);
5646      if (h != NULL
5647	  && (h->ref_regular
5648	      || h->def_regular))
5649	{
5650	  if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
5651	    return FALSE;
5652	}
5653      h = (info->fini_function
5654	   ? elf_link_hash_lookup (elf_hash_table (info),
5655				   info->fini_function, FALSE,
5656				   FALSE, FALSE)
5657	   : NULL);
5658      if (h != NULL
5659	  && (h->ref_regular
5660	      || h->def_regular))
5661	{
5662	  if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
5663	    return FALSE;
5664	}
5665
5666      s = bfd_get_section_by_name (output_bfd, ".preinit_array");
5667      if (s != NULL && s->linker_has_input)
5668	{
5669	  /* DT_PREINIT_ARRAY is not allowed in shared library.  */
5670	  if (! info->executable)
5671	    {
5672	      bfd *sub;
5673	      asection *o;
5674
5675	      for (sub = info->input_bfds; sub != NULL;
5676		   sub = sub->link_next)
5677		if (bfd_get_flavour (sub) == bfd_target_elf_flavour)
5678		  for (o = sub->sections; o != NULL; o = o->next)
5679		    if (elf_section_data (o)->this_hdr.sh_type
5680			== SHT_PREINIT_ARRAY)
5681		      {
5682			(*_bfd_error_handler)
5683			  (_("%B: .preinit_array section is not allowed in DSO"),
5684			   sub);
5685			break;
5686		      }
5687
5688	      bfd_set_error (bfd_error_nonrepresentable_section);
5689	      return FALSE;
5690	    }
5691
5692	  if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
5693	      || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
5694	    return FALSE;
5695	}
5696      s = bfd_get_section_by_name (output_bfd, ".init_array");
5697      if (s != NULL && s->linker_has_input)
5698	{
5699	  if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
5700	      || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
5701	    return FALSE;
5702	}
5703      s = bfd_get_section_by_name (output_bfd, ".fini_array");
5704      if (s != NULL && s->linker_has_input)
5705	{
5706	  if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
5707	      || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
5708	    return FALSE;
5709	}
5710
5711      dynstr = bfd_get_section_by_name (dynobj, ".dynstr");
5712      /* If .dynstr is excluded from the link, we don't want any of
5713	 these tags.  Strictly, we should be checking each section
5714	 individually;  This quick check covers for the case where
5715	 someone does a /DISCARD/ : { *(*) }.  */
5716      if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
5717	{
5718	  bfd_size_type strsize;
5719
5720	  strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
5721	  if ((info->emit_hash
5722	       && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
5723	      || (info->emit_gnu_hash
5724		  && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
5725	      || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
5726	      || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
5727	      || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
5728	      || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
5729					      bed->s->sizeof_sym))
5730	    return FALSE;
5731	}
5732    }
5733
5734  /* The backend must work out the sizes of all the other dynamic
5735     sections.  */
5736  if (bed->elf_backend_size_dynamic_sections
5737      && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
5738    return FALSE;
5739
5740  if (elf_hash_table (info)->dynamic_sections_created)
5741    {
5742      unsigned long section_sym_count;
5743      asection *s;
5744
5745      /* Set up the version definition section.  */
5746      s = bfd_get_section_by_name (dynobj, ".gnu.version_d");
5747      BFD_ASSERT (s != NULL);
5748
5749      /* We may have created additional version definitions if we are
5750	 just linking a regular application.  */
5751      verdefs = asvinfo.verdefs;
5752
5753      /* Skip anonymous version tag.  */
5754      if (verdefs != NULL && verdefs->vernum == 0)
5755	verdefs = verdefs->next;
5756
5757      if (verdefs == NULL && !info->create_default_symver)
5758	s->flags |= SEC_EXCLUDE;
5759      else
5760	{
5761	  unsigned int cdefs;
5762	  bfd_size_type size;
5763	  struct bfd_elf_version_tree *t;
5764	  bfd_byte *p;
5765	  Elf_Internal_Verdef def;
5766	  Elf_Internal_Verdaux defaux;
5767	  struct bfd_link_hash_entry *bh;
5768	  struct elf_link_hash_entry *h;
5769	  const char *name;
5770
5771	  cdefs = 0;
5772	  size = 0;
5773
5774	  /* Make space for the base version.  */
5775	  size += sizeof (Elf_External_Verdef);
5776	  size += sizeof (Elf_External_Verdaux);
5777	  ++cdefs;
5778
5779	  /* Make space for the default version.  */
5780	  if (info->create_default_symver)
5781	    {
5782	      size += sizeof (Elf_External_Verdef);
5783	      ++cdefs;
5784	    }
5785
5786	  for (t = verdefs; t != NULL; t = t->next)
5787	    {
5788	      struct bfd_elf_version_deps *n;
5789
5790	      size += sizeof (Elf_External_Verdef);
5791	      size += sizeof (Elf_External_Verdaux);
5792	      ++cdefs;
5793
5794	      for (n = t->deps; n != NULL; n = n->next)
5795		size += sizeof (Elf_External_Verdaux);
5796	    }
5797
5798	  s->size = size;
5799	  s->contents = bfd_alloc (output_bfd, s->size);
5800	  if (s->contents == NULL && s->size != 0)
5801	    return FALSE;
5802
5803	  /* Fill in the version definition section.  */
5804
5805	  p = s->contents;
5806
5807	  def.vd_version = VER_DEF_CURRENT;
5808	  def.vd_flags = VER_FLG_BASE;
5809	  def.vd_ndx = 1;
5810	  def.vd_cnt = 1;
5811	  if (info->create_default_symver)
5812	    {
5813	      def.vd_aux = 2 * sizeof (Elf_External_Verdef);
5814	      def.vd_next = sizeof (Elf_External_Verdef);
5815	    }
5816	  else
5817	    {
5818	      def.vd_aux = sizeof (Elf_External_Verdef);
5819	      def.vd_next = (sizeof (Elf_External_Verdef)
5820			     + sizeof (Elf_External_Verdaux));
5821	    }
5822
5823	  if (soname_indx != (bfd_size_type) -1)
5824	    {
5825	      _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
5826				      soname_indx);
5827	      def.vd_hash = bfd_elf_hash (soname);
5828	      defaux.vda_name = soname_indx;
5829	      name = soname;
5830	    }
5831	  else
5832	    {
5833	      bfd_size_type indx;
5834
5835	      name = lbasename (output_bfd->filename);
5836	      def.vd_hash = bfd_elf_hash (name);
5837	      indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5838					  name, FALSE);
5839	      if (indx == (bfd_size_type) -1)
5840		return FALSE;
5841	      defaux.vda_name = indx;
5842	    }
5843	  defaux.vda_next = 0;
5844
5845	  _bfd_elf_swap_verdef_out (output_bfd, &def,
5846				    (Elf_External_Verdef *) p);
5847	  p += sizeof (Elf_External_Verdef);
5848	  if (info->create_default_symver)
5849	    {
5850	      /* Add a symbol representing this version.  */
5851	      bh = NULL;
5852	      if (! (_bfd_generic_link_add_one_symbol
5853		     (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
5854		      0, NULL, FALSE,
5855		      get_elf_backend_data (dynobj)->collect, &bh)))
5856		return FALSE;
5857	      h = (struct elf_link_hash_entry *) bh;
5858	      h->non_elf = 0;
5859	      h->def_regular = 1;
5860	      h->type = STT_OBJECT;
5861	      h->verinfo.vertree = NULL;
5862
5863	      if (! bfd_elf_link_record_dynamic_symbol (info, h))
5864		return FALSE;
5865
5866	      /* Create a duplicate of the base version with the same
5867		 aux block, but different flags.  */
5868	      def.vd_flags = 0;
5869	      def.vd_ndx = 2;
5870	      def.vd_aux = sizeof (Elf_External_Verdef);
5871	      if (verdefs)
5872		def.vd_next = (sizeof (Elf_External_Verdef)
5873			       + sizeof (Elf_External_Verdaux));
5874	      else
5875		def.vd_next = 0;
5876	      _bfd_elf_swap_verdef_out (output_bfd, &def,
5877					(Elf_External_Verdef *) p);
5878	      p += sizeof (Elf_External_Verdef);
5879	    }
5880	  _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
5881				     (Elf_External_Verdaux *) p);
5882	  p += sizeof (Elf_External_Verdaux);
5883
5884	  for (t = verdefs; t != NULL; t = t->next)
5885	    {
5886	      unsigned int cdeps;
5887	      struct bfd_elf_version_deps *n;
5888
5889	      cdeps = 0;
5890	      for (n = t->deps; n != NULL; n = n->next)
5891		++cdeps;
5892
5893	      /* Add a symbol representing this version.  */
5894	      bh = NULL;
5895	      if (! (_bfd_generic_link_add_one_symbol
5896		     (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
5897		      0, NULL, FALSE,
5898		      get_elf_backend_data (dynobj)->collect, &bh)))
5899		return FALSE;
5900	      h = (struct elf_link_hash_entry *) bh;
5901	      h->non_elf = 0;
5902	      h->def_regular = 1;
5903	      h->type = STT_OBJECT;
5904	      h->verinfo.vertree = t;
5905
5906	      if (! bfd_elf_link_record_dynamic_symbol (info, h))
5907		return FALSE;
5908
5909	      def.vd_version = VER_DEF_CURRENT;
5910	      def.vd_flags = 0;
5911	      if (t->globals.list == NULL
5912		  && t->locals.list == NULL
5913		  && ! t->used)
5914		def.vd_flags |= VER_FLG_WEAK;
5915	      def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
5916	      def.vd_cnt = cdeps + 1;
5917	      def.vd_hash = bfd_elf_hash (t->name);
5918	      def.vd_aux = sizeof (Elf_External_Verdef);
5919	      def.vd_next = 0;
5920	      if (t->next != NULL)
5921		def.vd_next = (sizeof (Elf_External_Verdef)
5922			       + (cdeps + 1) * sizeof (Elf_External_Verdaux));
5923
5924	      _bfd_elf_swap_verdef_out (output_bfd, &def,
5925					(Elf_External_Verdef *) p);
5926	      p += sizeof (Elf_External_Verdef);
5927
5928	      defaux.vda_name = h->dynstr_index;
5929	      _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
5930				      h->dynstr_index);
5931	      defaux.vda_next = 0;
5932	      if (t->deps != NULL)
5933		defaux.vda_next = sizeof (Elf_External_Verdaux);
5934	      t->name_indx = defaux.vda_name;
5935
5936	      _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
5937					 (Elf_External_Verdaux *) p);
5938	      p += sizeof (Elf_External_Verdaux);
5939
5940	      for (n = t->deps; n != NULL; n = n->next)
5941		{
5942		  if (n->version_needed == NULL)
5943		    {
5944		      /* This can happen if there was an error in the
5945			 version script.  */
5946		      defaux.vda_name = 0;
5947		    }
5948		  else
5949		    {
5950		      defaux.vda_name = n->version_needed->name_indx;
5951		      _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
5952					      defaux.vda_name);
5953		    }
5954		  if (n->next == NULL)
5955		    defaux.vda_next = 0;
5956		  else
5957		    defaux.vda_next = sizeof (Elf_External_Verdaux);
5958
5959		  _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
5960					     (Elf_External_Verdaux *) p);
5961		  p += sizeof (Elf_External_Verdaux);
5962		}
5963	    }
5964
5965	  if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
5966	      || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, cdefs))
5967	    return FALSE;
5968
5969	  elf_tdata (output_bfd)->cverdefs = cdefs;
5970	}
5971
5972      if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
5973	{
5974	  if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
5975	    return FALSE;
5976	}
5977      else if (info->flags & DF_BIND_NOW)
5978	{
5979	  if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
5980	    return FALSE;
5981	}
5982
5983      if (info->flags_1)
5984	{
5985	  if (info->executable)
5986	    info->flags_1 &= ~ (DF_1_INITFIRST
5987				| DF_1_NODELETE
5988				| DF_1_NOOPEN);
5989	  if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
5990	    return FALSE;
5991	}
5992
5993      /* Work out the size of the version reference section.  */
5994
5995      s = bfd_get_section_by_name (dynobj, ".gnu.version_r");
5996      BFD_ASSERT (s != NULL);
5997      {
5998	struct elf_find_verdep_info sinfo;
5999
6000	sinfo.output_bfd = output_bfd;
6001	sinfo.info = info;
6002	sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6003	if (sinfo.vers == 0)
6004	  sinfo.vers = 1;
6005	sinfo.failed = FALSE;
6006
6007	elf_link_hash_traverse (elf_hash_table (info),
6008				_bfd_elf_link_find_version_dependencies,
6009				&sinfo);
6010
6011	if (elf_tdata (output_bfd)->verref == NULL)
6012	  s->flags |= SEC_EXCLUDE;
6013	else
6014	  {
6015	    Elf_Internal_Verneed *t;
6016	    unsigned int size;
6017	    unsigned int crefs;
6018	    bfd_byte *p;
6019
6020	    /* Build the version definition section.  */
6021	    size = 0;
6022	    crefs = 0;
6023	    for (t = elf_tdata (output_bfd)->verref;
6024		 t != NULL;
6025		 t = t->vn_nextref)
6026	      {
6027		Elf_Internal_Vernaux *a;
6028
6029		size += sizeof (Elf_External_Verneed);
6030		++crefs;
6031		for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6032		  size += sizeof (Elf_External_Vernaux);
6033	      }
6034
6035	    s->size = size;
6036	    s->contents = bfd_alloc (output_bfd, s->size);
6037	    if (s->contents == NULL)
6038	      return FALSE;
6039
6040	    p = s->contents;
6041	    for (t = elf_tdata (output_bfd)->verref;
6042		 t != NULL;
6043		 t = t->vn_nextref)
6044	      {
6045		unsigned int caux;
6046		Elf_Internal_Vernaux *a;
6047		bfd_size_type indx;
6048
6049		caux = 0;
6050		for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6051		  ++caux;
6052
6053		t->vn_version = VER_NEED_CURRENT;
6054		t->vn_cnt = caux;
6055		indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6056					    elf_dt_name (t->vn_bfd) != NULL
6057					    ? elf_dt_name (t->vn_bfd)
6058					    : lbasename (t->vn_bfd->filename),
6059					    FALSE);
6060		if (indx == (bfd_size_type) -1)
6061		  return FALSE;
6062		t->vn_file = indx;
6063		t->vn_aux = sizeof (Elf_External_Verneed);
6064		if (t->vn_nextref == NULL)
6065		  t->vn_next = 0;
6066		else
6067		  t->vn_next = (sizeof (Elf_External_Verneed)
6068				+ caux * sizeof (Elf_External_Vernaux));
6069
6070		_bfd_elf_swap_verneed_out (output_bfd, t,
6071					   (Elf_External_Verneed *) p);
6072		p += sizeof (Elf_External_Verneed);
6073
6074		for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6075		  {
6076		    a->vna_hash = bfd_elf_hash (a->vna_nodename);
6077		    indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6078						a->vna_nodename, FALSE);
6079		    if (indx == (bfd_size_type) -1)
6080		      return FALSE;
6081		    a->vna_name = indx;
6082		    if (a->vna_nextptr == NULL)
6083		      a->vna_next = 0;
6084		    else
6085		      a->vna_next = sizeof (Elf_External_Vernaux);
6086
6087		    _bfd_elf_swap_vernaux_out (output_bfd, a,
6088					       (Elf_External_Vernaux *) p);
6089		    p += sizeof (Elf_External_Vernaux);
6090		  }
6091	      }
6092
6093	    if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6094		|| !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6095	      return FALSE;
6096
6097	    elf_tdata (output_bfd)->cverrefs = crefs;
6098	  }
6099      }
6100
6101      if ((elf_tdata (output_bfd)->cverrefs == 0
6102	   && elf_tdata (output_bfd)->cverdefs == 0)
6103	  || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6104					     &section_sym_count) == 0)
6105	{
6106	  s = bfd_get_section_by_name (dynobj, ".gnu.version");
6107	  s->flags |= SEC_EXCLUDE;
6108	}
6109    }
6110  return TRUE;
6111}
6112
6113/* Find the first non-excluded output section.  We'll use its
6114   section symbol for some emitted relocs.  */
6115void
6116_bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6117{
6118  asection *s;
6119
6120  for (s = output_bfd->sections; s != NULL; s = s->next)
6121    if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6122	&& !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6123      {
6124	elf_hash_table (info)->text_index_section = s;
6125	break;
6126      }
6127}
6128
6129/* Find two non-excluded output sections, one for code, one for data.
6130   We'll use their section symbols for some emitted relocs.  */
6131void
6132_bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6133{
6134  asection *s;
6135
6136  for (s = output_bfd->sections; s != NULL; s = s->next)
6137    if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6138	 == (SEC_ALLOC | SEC_READONLY))
6139	&& !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6140      {
6141	elf_hash_table (info)->text_index_section = s;
6142	break;
6143      }
6144
6145  for (s = output_bfd->sections; s != NULL; s = s->next)
6146    if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6147	&& !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6148      {
6149	elf_hash_table (info)->data_index_section = s;
6150	break;
6151      }
6152
6153  if (elf_hash_table (info)->text_index_section == NULL)
6154    elf_hash_table (info)->text_index_section
6155      = elf_hash_table (info)->data_index_section;
6156}
6157
6158bfd_boolean
6159bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6160{
6161  const struct elf_backend_data *bed;
6162
6163  if (!is_elf_hash_table (info->hash))
6164    return TRUE;
6165
6166  bed = get_elf_backend_data (output_bfd);
6167  (*bed->elf_backend_init_index_section) (output_bfd, info);
6168
6169  if (elf_hash_table (info)->dynamic_sections_created)
6170    {
6171      bfd *dynobj;
6172      asection *s;
6173      bfd_size_type dynsymcount;
6174      unsigned long section_sym_count;
6175      unsigned int dtagcount;
6176
6177      dynobj = elf_hash_table (info)->dynobj;
6178
6179      /* Assign dynsym indicies.  In a shared library we generate a
6180	 section symbol for each output section, which come first.
6181	 Next come all of the back-end allocated local dynamic syms,
6182	 followed by the rest of the global symbols.  */
6183
6184      dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6185						    &section_sym_count);
6186
6187      /* Work out the size of the symbol version section.  */
6188      s = bfd_get_section_by_name (dynobj, ".gnu.version");
6189      BFD_ASSERT (s != NULL);
6190      if (dynsymcount != 0
6191	  && (s->flags & SEC_EXCLUDE) == 0)
6192	{
6193	  s->size = dynsymcount * sizeof (Elf_External_Versym);
6194	  s->contents = bfd_zalloc (output_bfd, s->size);
6195	  if (s->contents == NULL)
6196	    return FALSE;
6197
6198	  if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6199	    return FALSE;
6200	}
6201
6202      /* Set the size of the .dynsym and .hash sections.  We counted
6203	 the number of dynamic symbols in elf_link_add_object_symbols.
6204	 We will build the contents of .dynsym and .hash when we build
6205	 the final symbol table, because until then we do not know the
6206	 correct value to give the symbols.  We built the .dynstr
6207	 section as we went along in elf_link_add_object_symbols.  */
6208      s = bfd_get_section_by_name (dynobj, ".dynsym");
6209      BFD_ASSERT (s != NULL);
6210      s->size = dynsymcount * bed->s->sizeof_sym;
6211
6212      if (dynsymcount != 0)
6213	{
6214	  s->contents = bfd_alloc (output_bfd, s->size);
6215	  if (s->contents == NULL)
6216	    return FALSE;
6217
6218	  /* The first entry in .dynsym is a dummy symbol.
6219	     Clear all the section syms, in case we don't output them all.  */
6220	  ++section_sym_count;
6221	  memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6222	}
6223
6224      elf_hash_table (info)->bucketcount = 0;
6225
6226      /* Compute the size of the hashing table.  As a side effect this
6227	 computes the hash values for all the names we export.  */
6228      if (info->emit_hash)
6229	{
6230	  unsigned long int *hashcodes;
6231	  unsigned long int *hashcodesp;
6232	  bfd_size_type amt;
6233	  unsigned long int nsyms;
6234	  size_t bucketcount;
6235	  size_t hash_entry_size;
6236
6237	  /* Compute the hash values for all exported symbols.  At the same
6238	     time store the values in an array so that we could use them for
6239	     optimizations.  */
6240	  amt = dynsymcount * sizeof (unsigned long int);
6241	  hashcodes = bfd_malloc (amt);
6242	  if (hashcodes == NULL)
6243	    return FALSE;
6244	  hashcodesp = hashcodes;
6245
6246	  /* Put all hash values in HASHCODES.  */
6247	  elf_link_hash_traverse (elf_hash_table (info),
6248				  elf_collect_hash_codes, &hashcodesp);
6249
6250	  nsyms = hashcodesp - hashcodes;
6251	  bucketcount
6252	    = compute_bucket_count (info, hashcodes, nsyms, 0);
6253	  free (hashcodes);
6254
6255	  if (bucketcount == 0)
6256	    return FALSE;
6257
6258	  elf_hash_table (info)->bucketcount = bucketcount;
6259
6260	  s = bfd_get_section_by_name (dynobj, ".hash");
6261	  BFD_ASSERT (s != NULL);
6262	  hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6263	  s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6264	  s->contents = bfd_zalloc (output_bfd, s->size);
6265	  if (s->contents == NULL)
6266	    return FALSE;
6267
6268	  bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6269	  bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6270		   s->contents + hash_entry_size);
6271	}
6272
6273      if (info->emit_gnu_hash)
6274	{
6275	  size_t i, cnt;
6276	  unsigned char *contents;
6277	  struct collect_gnu_hash_codes cinfo;
6278	  bfd_size_type amt;
6279	  size_t bucketcount;
6280
6281	  memset (&cinfo, 0, sizeof (cinfo));
6282
6283	  /* Compute the hash values for all exported symbols.  At the same
6284	     time store the values in an array so that we could use them for
6285	     optimizations.  */
6286	  amt = dynsymcount * 2 * sizeof (unsigned long int);
6287	  cinfo.hashcodes = bfd_malloc (amt);
6288	  if (cinfo.hashcodes == NULL)
6289	    return FALSE;
6290
6291	  cinfo.hashval = cinfo.hashcodes + dynsymcount;
6292	  cinfo.min_dynindx = -1;
6293	  cinfo.output_bfd = output_bfd;
6294	  cinfo.bed = bed;
6295
6296	  /* Put all hash values in HASHCODES.  */
6297	  elf_link_hash_traverse (elf_hash_table (info),
6298				  elf_collect_gnu_hash_codes, &cinfo);
6299
6300	  bucketcount
6301	    = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
6302
6303	  if (bucketcount == 0)
6304	    {
6305	      free (cinfo.hashcodes);
6306	      return FALSE;
6307	    }
6308
6309	  s = bfd_get_section_by_name (dynobj, ".gnu.hash");
6310	  BFD_ASSERT (s != NULL);
6311
6312	  if (cinfo.nsyms == 0)
6313	    {
6314	      /* Empty .gnu.hash section is special.  */
6315	      BFD_ASSERT (cinfo.min_dynindx == -1);
6316	      free (cinfo.hashcodes);
6317	      s->size = 5 * 4 + bed->s->arch_size / 8;
6318	      contents = bfd_zalloc (output_bfd, s->size);
6319	      if (contents == NULL)
6320		return FALSE;
6321	      s->contents = contents;
6322	      /* 1 empty bucket.  */
6323	      bfd_put_32 (output_bfd, 1, contents);
6324	      /* SYMIDX above the special symbol 0.  */
6325	      bfd_put_32 (output_bfd, 1, contents + 4);
6326	      /* Just one word for bitmask.  */
6327	      bfd_put_32 (output_bfd, 1, contents + 8);
6328	      /* Only hash fn bloom filter.  */
6329	      bfd_put_32 (output_bfd, 0, contents + 12);
6330	      /* No hashes are valid - empty bitmask.  */
6331	      bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
6332	      /* No hashes in the only bucket.  */
6333	      bfd_put_32 (output_bfd, 0,
6334			  contents + 16 + bed->s->arch_size / 8);
6335	    }
6336	  else
6337	    {
6338	      unsigned long int maskwords, maskbitslog2;
6339	      BFD_ASSERT (cinfo.min_dynindx != -1);
6340
6341	      maskbitslog2 = bfd_log2 (cinfo.nsyms) + 1;
6342	      if (maskbitslog2 < 3)
6343		maskbitslog2 = 5;
6344	      else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
6345		maskbitslog2 = maskbitslog2 + 3;
6346	      else
6347		maskbitslog2 = maskbitslog2 + 2;
6348	      if (bed->s->arch_size == 64)
6349		{
6350		  if (maskbitslog2 == 5)
6351		    maskbitslog2 = 6;
6352		  cinfo.shift1 = 6;
6353		}
6354	      else
6355		cinfo.shift1 = 5;
6356	      cinfo.mask = (1 << cinfo.shift1) - 1;
6357	      cinfo.shift2 = maskbitslog2;
6358	      cinfo.maskbits = 1 << maskbitslog2;
6359	      maskwords = 1 << (maskbitslog2 - cinfo.shift1);
6360	      amt = bucketcount * sizeof (unsigned long int) * 2;
6361	      amt += maskwords * sizeof (bfd_vma);
6362	      cinfo.bitmask = bfd_malloc (amt);
6363	      if (cinfo.bitmask == NULL)
6364		{
6365		  free (cinfo.hashcodes);
6366		  return FALSE;
6367		}
6368
6369	      cinfo.counts = (void *) (cinfo.bitmask + maskwords);
6370	      cinfo.indx = cinfo.counts + bucketcount;
6371	      cinfo.symindx = dynsymcount - cinfo.nsyms;
6372	      memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
6373
6374	      /* Determine how often each hash bucket is used.  */
6375	      memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
6376	      for (i = 0; i < cinfo.nsyms; ++i)
6377		++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
6378
6379	      for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
6380		if (cinfo.counts[i] != 0)
6381		  {
6382		    cinfo.indx[i] = cnt;
6383		    cnt += cinfo.counts[i];
6384		  }
6385	      BFD_ASSERT (cnt == dynsymcount);
6386	      cinfo.bucketcount = bucketcount;
6387	      cinfo.local_indx = cinfo.min_dynindx;
6388
6389	      s->size = (4 + bucketcount + cinfo.nsyms) * 4;
6390	      s->size += cinfo.maskbits / 8;
6391	      contents = bfd_zalloc (output_bfd, s->size);
6392	      if (contents == NULL)
6393		{
6394		  free (cinfo.bitmask);
6395		  free (cinfo.hashcodes);
6396		  return FALSE;
6397		}
6398
6399	      s->contents = contents;
6400	      bfd_put_32 (output_bfd, bucketcount, contents);
6401	      bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
6402	      bfd_put_32 (output_bfd, maskwords, contents + 8);
6403	      bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
6404	      contents += 16 + cinfo.maskbits / 8;
6405
6406	      for (i = 0; i < bucketcount; ++i)
6407		{
6408		  if (cinfo.counts[i] == 0)
6409		    bfd_put_32 (output_bfd, 0, contents);
6410		  else
6411		    bfd_put_32 (output_bfd, cinfo.indx[i], contents);
6412		  contents += 4;
6413		}
6414
6415	      cinfo.contents = contents;
6416
6417	      /* Renumber dynamic symbols, populate .gnu.hash section.  */
6418	      elf_link_hash_traverse (elf_hash_table (info),
6419				      elf_renumber_gnu_hash_syms, &cinfo);
6420
6421	      contents = s->contents + 16;
6422	      for (i = 0; i < maskwords; ++i)
6423		{
6424		  bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
6425			   contents);
6426		  contents += bed->s->arch_size / 8;
6427		}
6428
6429	      free (cinfo.bitmask);
6430	      free (cinfo.hashcodes);
6431	    }
6432	}
6433
6434      s = bfd_get_section_by_name (dynobj, ".dynstr");
6435      BFD_ASSERT (s != NULL);
6436
6437      elf_finalize_dynstr (output_bfd, info);
6438
6439      s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6440
6441      for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
6442	if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
6443	  return FALSE;
6444    }
6445
6446  return TRUE;
6447}
6448
6449/* Final phase of ELF linker.  */
6450
6451/* A structure we use to avoid passing large numbers of arguments.  */
6452
6453struct elf_final_link_info
6454{
6455  /* General link information.  */
6456  struct bfd_link_info *info;
6457  /* Output BFD.  */
6458  bfd *output_bfd;
6459  /* Symbol string table.  */
6460  struct bfd_strtab_hash *symstrtab;
6461  /* .dynsym section.  */
6462  asection *dynsym_sec;
6463  /* .hash section.  */
6464  asection *hash_sec;
6465  /* symbol version section (.gnu.version).  */
6466  asection *symver_sec;
6467  /* Buffer large enough to hold contents of any section.  */
6468  bfd_byte *contents;
6469  /* Buffer large enough to hold external relocs of any section.  */
6470  void *external_relocs;
6471  /* Buffer large enough to hold internal relocs of any section.  */
6472  Elf_Internal_Rela *internal_relocs;
6473  /* Buffer large enough to hold external local symbols of any input
6474     BFD.  */
6475  bfd_byte *external_syms;
6476  /* And a buffer for symbol section indices.  */
6477  Elf_External_Sym_Shndx *locsym_shndx;
6478  /* Buffer large enough to hold internal local symbols of any input
6479     BFD.  */
6480  Elf_Internal_Sym *internal_syms;
6481  /* Array large enough to hold a symbol index for each local symbol
6482     of any input BFD.  */
6483  long *indices;
6484  /* Array large enough to hold a section pointer for each local
6485     symbol of any input BFD.  */
6486  asection **sections;
6487  /* Buffer to hold swapped out symbols.  */
6488  bfd_byte *symbuf;
6489  /* And one for symbol section indices.  */
6490  Elf_External_Sym_Shndx *symshndxbuf;
6491  /* Number of swapped out symbols in buffer.  */
6492  size_t symbuf_count;
6493  /* Number of symbols which fit in symbuf.  */
6494  size_t symbuf_size;
6495  /* And same for symshndxbuf.  */
6496  size_t shndxbuf_size;
6497};
6498
6499/* This struct is used to pass information to elf_link_output_extsym.  */
6500
6501struct elf_outext_info
6502{
6503  bfd_boolean failed;
6504  bfd_boolean localsyms;
6505  struct elf_final_link_info *finfo;
6506};
6507
6508
6509/* Support for evaluating a complex relocation.
6510
6511   Complex relocations are generalized, self-describing relocations.  The
6512   implementation of them consists of two parts: complex symbols, and the
6513   relocations themselves.
6514
6515   The relocations are use a reserved elf-wide relocation type code (R_RELC
6516   external / BFD_RELOC_RELC internal) and an encoding of relocation field
6517   information (start bit, end bit, word width, etc) into the addend.  This
6518   information is extracted from CGEN-generated operand tables within gas.
6519
6520   Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
6521   internal) representing prefix-notation expressions, including but not
6522   limited to those sorts of expressions normally encoded as addends in the
6523   addend field.  The symbol mangling format is:
6524
6525   <node> := <literal>
6526          |  <unary-operator> ':' <node>
6527          |  <binary-operator> ':' <node> ':' <node>
6528	  ;
6529
6530   <literal> := 's' <digits=N> ':' <N character symbol name>
6531             |  'S' <digits=N> ':' <N character section name>
6532	     |  '#' <hexdigits>
6533	     ;
6534
6535   <binary-operator> := as in C
6536   <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
6537
6538static void
6539set_symbol_value (bfd *                         bfd_with_globals,
6540		  struct elf_final_link_info *  finfo,
6541		  int                           symidx,
6542		  bfd_vma                       val)
6543{
6544  bfd_boolean                    is_local;
6545  Elf_Internal_Sym *             sym;
6546  struct elf_link_hash_entry **  sym_hashes;
6547  struct elf_link_hash_entry *   h;
6548
6549  sym_hashes = elf_sym_hashes (bfd_with_globals);
6550  sym = finfo->internal_syms + symidx;
6551  is_local = ELF_ST_BIND(sym->st_info) == STB_LOCAL;
6552
6553  if (is_local)
6554    {
6555      /* It is a local symbol: move it to the
6556	 "absolute" section and give it a value.  */
6557      sym->st_shndx = SHN_ABS;
6558      sym->st_value = val;
6559    }
6560  else
6561    {
6562      /* It is a global symbol: set its link type
6563	 to "defined" and give it a value.  */
6564      h = sym_hashes [symidx];
6565      while (h->root.type == bfd_link_hash_indirect
6566	     || h->root.type == bfd_link_hash_warning)
6567	h = (struct elf_link_hash_entry *) h->root.u.i.link;
6568      h->root.type = bfd_link_hash_defined;
6569      h->root.u.def.value = val;
6570      h->root.u.def.section = bfd_abs_section_ptr;
6571    }
6572}
6573
6574static bfd_boolean
6575resolve_symbol (const char *                  name,
6576		bfd *                         input_bfd,
6577		struct elf_final_link_info *  finfo,
6578		bfd_vma *                     result,
6579		size_t                        locsymcount)
6580{
6581  Elf_Internal_Sym *            sym;
6582  struct bfd_link_hash_entry *  global_entry;
6583  const char *                  candidate = NULL;
6584  Elf_Internal_Shdr *           symtab_hdr;
6585  asection *                    sec = NULL;
6586  size_t                        i;
6587
6588  symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
6589
6590  for (i = 0; i < locsymcount; ++ i)
6591    {
6592      sym = finfo->internal_syms + i;
6593      sec = finfo->sections [i];
6594
6595      if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
6596	continue;
6597
6598      candidate = bfd_elf_string_from_elf_section (input_bfd,
6599						   symtab_hdr->sh_link,
6600						   sym->st_name);
6601#ifdef DEBUG
6602      printf ("Comparing string: '%s' vs. '%s' = 0x%x\n",
6603	      name, candidate, (unsigned int)sym->st_value);
6604#endif
6605      if (candidate && strcmp (candidate, name) == 0)
6606	{
6607	  * result = sym->st_value;
6608
6609	  if (sym->st_shndx > SHN_UNDEF &&
6610	      sym->st_shndx < SHN_LORESERVE)
6611	    {
6612#ifdef DEBUG
6613	      printf ("adjusting for sec '%s' @ 0x%x + 0x%x\n",
6614		      sec->output_section->name,
6615		      (unsigned int)sec->output_section->vma,
6616		      (unsigned int)sec->output_offset);
6617#endif
6618	      * result += sec->output_offset + sec->output_section->vma;
6619	    }
6620#ifdef DEBUG
6621	  printf ("Found symbol with effective value %8.8x\n", (unsigned int)* result);
6622#endif
6623	  return TRUE;
6624	}
6625    }
6626
6627  /* Hmm, haven't found it yet. perhaps it is a global.  */
6628  global_entry = bfd_link_hash_lookup (finfo->info->hash, name, FALSE, FALSE, TRUE);
6629  if (!global_entry)
6630    return FALSE;
6631
6632  if (global_entry->type == bfd_link_hash_defined
6633      || global_entry->type == bfd_link_hash_defweak)
6634    {
6635      * result = global_entry->u.def.value
6636	+ global_entry->u.def.section->output_section->vma
6637	+ global_entry->u.def.section->output_offset;
6638#ifdef DEBUG
6639      printf ("Found GLOBAL symbol '%s' with value %8.8x\n",
6640	      global_entry->root.string, (unsigned int)*result);
6641#endif
6642      return TRUE;
6643    }
6644
6645  if (global_entry->type == bfd_link_hash_common)
6646    {
6647      *result = global_entry->u.def.value +
6648	bfd_com_section_ptr->output_section->vma +
6649	bfd_com_section_ptr->output_offset;
6650#ifdef DEBUG
6651      printf ("Found COMMON symbol '%s' with value %8.8x\n",
6652	      global_entry->root.string, (unsigned int)*result);
6653#endif
6654      return TRUE;
6655    }
6656
6657  return FALSE;
6658}
6659
6660static bfd_boolean
6661resolve_section (const char *  name,
6662		 asection *    sections,
6663		 bfd_vma *     result)
6664{
6665  asection *    curr;
6666  unsigned int  len;
6667
6668  for (curr = sections; curr; curr = curr->next)
6669    if (strcmp (curr->name, name) == 0)
6670      {
6671	*result = curr->vma;
6672	return TRUE;
6673      }
6674
6675  /* Hmm. still haven't found it. try pseudo-section names.  */
6676  for (curr = sections; curr; curr = curr->next)
6677    {
6678      len = strlen (curr->name);
6679      if (len > strlen (name))
6680	continue;
6681
6682      if (strncmp (curr->name, name, len) == 0)
6683	{
6684	  if (strncmp (".end", name + len, 4) == 0)
6685	    {
6686	      *result = curr->vma + curr->size;
6687	      return TRUE;
6688	    }
6689
6690	  /* Insert more pseudo-section names here, if you like.  */
6691	}
6692    }
6693
6694  return FALSE;
6695}
6696
6697static void
6698undefined_reference (const char *  reftype,
6699		     const char *  name)
6700{
6701  _bfd_error_handler (_("undefined %s reference in complex symbol: %s"), reftype, name);
6702}
6703
6704static bfd_boolean
6705eval_symbol (bfd_vma *                     result,
6706	     char *                        sym,
6707	     char **                       advanced,
6708	     bfd *                         input_bfd,
6709	     struct elf_final_link_info *  finfo,
6710	     bfd_vma                       addr,
6711	     bfd_vma                       section_offset,
6712	     size_t                        locsymcount,
6713	     int                           signed_p)
6714{
6715  int           len;
6716  int           symlen;
6717  bfd_vma       a;
6718  bfd_vma       b;
6719  const int     bufsz = 4096;
6720  char          symbuf [bufsz];
6721  const char *  symend;
6722  bfd_boolean   symbol_is_section = FALSE;
6723
6724  len = strlen (sym);
6725  symend = sym + len;
6726
6727  if (len < 1 || len > bufsz)
6728    {
6729      bfd_set_error (bfd_error_invalid_operation);
6730      return FALSE;
6731    }
6732
6733  switch (* sym)
6734    {
6735    case '.':
6736      * result = addr + section_offset;
6737      * advanced = sym + 1;
6738      return TRUE;
6739
6740    case '#':
6741      ++ sym;
6742      * result = strtoul (sym, advanced, 16);
6743      return TRUE;
6744
6745    case 'S':
6746      symbol_is_section = TRUE;
6747    case 's':
6748      ++ sym;
6749      symlen = strtol (sym, &sym, 10);
6750      ++ sym; /* Skip the trailing ':'.  */
6751
6752      if ((symend < sym) || ((symlen + 1) > bufsz))
6753	{
6754	  bfd_set_error (bfd_error_invalid_operation);
6755	  return FALSE;
6756	}
6757
6758      memcpy (symbuf, sym, symlen);
6759      symbuf [symlen] = '\0';
6760      * advanced = sym + symlen;
6761
6762      /* Is it always possible, with complex symbols, that gas "mis-guessed"
6763	 the symbol as a section, or vice-versa. so we're pretty liberal in our
6764	 interpretation here; section means "try section first", not "must be a
6765	 section", and likewise with symbol.  */
6766
6767      if (symbol_is_section)
6768	{
6769	  if ((resolve_section (symbuf, finfo->output_bfd->sections, result) != TRUE)
6770	      && (resolve_symbol (symbuf, input_bfd, finfo, result, locsymcount) != TRUE))
6771	    {
6772	      undefined_reference ("section", symbuf);
6773	      return FALSE;
6774	    }
6775	}
6776      else
6777	{
6778	  if ((resolve_symbol (symbuf, input_bfd, finfo, result, locsymcount) != TRUE)
6779	      && (resolve_section (symbuf, finfo->output_bfd->sections,
6780				   result) != TRUE))
6781	    {
6782	      undefined_reference ("symbol", symbuf);
6783	      return FALSE;
6784	    }
6785	}
6786
6787      return TRUE;
6788
6789      /* All that remains are operators.  */
6790
6791#define UNARY_OP(op)						\
6792  if (strncmp (sym, #op, strlen (#op)) == 0)			\
6793    {								\
6794      sym += strlen (#op);					\
6795      if (* sym == ':')						\
6796        ++ sym;							\
6797      if (eval_symbol (& a, sym, & sym, input_bfd, finfo, addr, \
6798                       section_offset, locsymcount, signed_p)   \
6799	                                             != TRUE)	\
6800        return FALSE;						\
6801      if (signed_p)                                             \
6802        * result = op ((signed)a);         			\
6803      else                                                      \
6804        * result = op a;                                        \
6805      * advanced = sym; 					\
6806      return TRUE;						\
6807    }
6808
6809#define BINARY_OP(op)						\
6810  if (strncmp (sym, #op, strlen (#op)) == 0)			\
6811    {								\
6812      sym += strlen (#op);					\
6813      if (* sym == ':')						\
6814        ++ sym;							\
6815      if (eval_symbol (& a, sym, & sym, input_bfd, finfo, addr, \
6816                       section_offset, locsymcount, signed_p)   \
6817                                                     != TRUE)	\
6818        return FALSE;						\
6819      ++ sym;							\
6820      if (eval_symbol (& b, sym, & sym, input_bfd, finfo, addr, \
6821                       section_offset, locsymcount, signed_p)   \
6822                                                     != TRUE)	\
6823        return FALSE;						\
6824      if (signed_p)                                             \
6825        * result = ((signed) a) op ((signed) b);	        \
6826      else                                                      \
6827        * result = a op b;                                      \
6828      * advanced = sym;						\
6829      return TRUE;						\
6830    }
6831
6832    default:
6833      UNARY_OP  (0-);
6834      BINARY_OP (<<);
6835      BINARY_OP (>>);
6836      BINARY_OP (==);
6837      BINARY_OP (!=);
6838      BINARY_OP (<=);
6839      BINARY_OP (>=);
6840      BINARY_OP (&&);
6841      BINARY_OP (||);
6842      UNARY_OP  (~);
6843      UNARY_OP  (!);
6844      BINARY_OP (*);
6845      BINARY_OP (/);
6846      BINARY_OP (%);
6847      BINARY_OP (^);
6848      BINARY_OP (|);
6849      BINARY_OP (&);
6850      BINARY_OP (+);
6851      BINARY_OP (-);
6852      BINARY_OP (<);
6853      BINARY_OP (>);
6854#undef UNARY_OP
6855#undef BINARY_OP
6856      _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
6857      bfd_set_error (bfd_error_invalid_operation);
6858      return FALSE;
6859    }
6860}
6861
6862/* Entry point to evaluator, called from elf_link_input_bfd.  */
6863
6864static bfd_boolean
6865evaluate_complex_relocation_symbols (bfd * input_bfd,
6866				     struct elf_final_link_info * finfo,
6867				     size_t locsymcount)
6868{
6869  const struct elf_backend_data * bed;
6870  Elf_Internal_Shdr *             symtab_hdr;
6871  struct elf_link_hash_entry **   sym_hashes;
6872  asection *                      reloc_sec;
6873  bfd_boolean                     result = TRUE;
6874
6875  /* For each section, we're going to check and see if it has any
6876     complex relocations, and we're going to evaluate any of them
6877     we can.  */
6878
6879  if (finfo->info->relocatable)
6880    return TRUE;
6881
6882  symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
6883  sym_hashes = elf_sym_hashes (input_bfd);
6884  bed = get_elf_backend_data (input_bfd);
6885
6886  for (reloc_sec = input_bfd->sections; reloc_sec; reloc_sec = reloc_sec->next)
6887    {
6888      Elf_Internal_Rela * internal_relocs;
6889      unsigned long i;
6890
6891      /* This section was omitted from the link.  */
6892      if (! reloc_sec->linker_mark)
6893	continue;
6894
6895      /* Only process sections containing relocs.  */
6896      if ((reloc_sec->flags & SEC_RELOC) == 0)
6897	continue;
6898
6899      if (reloc_sec->reloc_count == 0)
6900	continue;
6901
6902      /* Read in the relocs for this section.  */
6903      internal_relocs
6904	= _bfd_elf_link_read_relocs (input_bfd, reloc_sec, NULL,
6905				     (Elf_Internal_Rela *) NULL,
6906				     FALSE);
6907      if (internal_relocs == NULL)
6908	continue;
6909
6910      for (i = reloc_sec->reloc_count; i--;)
6911	{
6912	  Elf_Internal_Rela * rel;
6913	  char * sym_name;
6914	  bfd_vma index;
6915	  Elf_Internal_Sym * sym;
6916	  bfd_vma result;
6917	  bfd_vma section_offset;
6918	  bfd_vma addr;
6919	  int signed_p = 0;
6920
6921	  rel = internal_relocs + i;
6922	  section_offset = reloc_sec->output_section->vma
6923	    + reloc_sec->output_offset;
6924	  addr = rel->r_offset;
6925
6926	  index = ELF32_R_SYM (rel->r_info);
6927	  if (bed->s->arch_size == 64)
6928	    index >>= 24;
6929
6930	  if (index == STN_UNDEF)
6931	    continue;
6932
6933	  if (index < locsymcount)
6934	    {
6935	      /* The symbol is local.  */
6936	      sym = finfo->internal_syms + index;
6937
6938	      /* We're only processing STT_RELC or STT_SRELC type symbols.  */
6939	      if ((ELF_ST_TYPE (sym->st_info) != STT_RELC) &&
6940		  (ELF_ST_TYPE (sym->st_info) != STT_SRELC))
6941		continue;
6942
6943	      sym_name = bfd_elf_string_from_elf_section
6944		(input_bfd, symtab_hdr->sh_link, sym->st_name);
6945
6946	      signed_p = (ELF_ST_TYPE (sym->st_info) == STT_SRELC);
6947	    }
6948	  else
6949	    {
6950	      /* The symbol is global.  */
6951	      struct elf_link_hash_entry * h;
6952
6953	      if (elf_bad_symtab (input_bfd))
6954		continue;
6955
6956	      h = sym_hashes [index - locsymcount];
6957	      while (   h->root.type == bfd_link_hash_indirect
6958		     || h->root.type == bfd_link_hash_warning)
6959		h = (struct elf_link_hash_entry *) h->root.u.i.link;
6960
6961	      if (h->type != STT_RELC && h->type != STT_SRELC)
6962		continue;
6963
6964	      signed_p = (h->type == STT_SRELC);
6965	      sym_name = (char *) h->root.root.string;
6966	    }
6967#ifdef DEBUG
6968	  printf ("Encountered a complex symbol!");
6969	  printf (" (input_bfd %s, section %s, reloc %ld\n",
6970		  input_bfd->filename, reloc_sec->name, i);
6971	  printf (" symbol: idx  %8.8lx, name %s\n",
6972		  index, sym_name);
6973	  printf (" reloc : info %8.8lx, addr %8.8lx\n",
6974		  rel->r_info, addr);
6975	  printf (" Evaluating '%s' ...\n ", sym_name);
6976#endif
6977	  if (eval_symbol (& result, sym_name, & sym_name, input_bfd,
6978			   finfo, addr, section_offset, locsymcount,
6979			   signed_p))
6980	    /* Symbol evaluated OK.  Update to absolute value.  */
6981	    set_symbol_value (input_bfd, finfo, index, result);
6982
6983	  else
6984	    result = FALSE;
6985	}
6986
6987      if (internal_relocs != elf_section_data (reloc_sec)->relocs)
6988	free (internal_relocs);
6989    }
6990
6991  /* If nothing went wrong, then we adjusted
6992     everything we wanted to adjust.  */
6993  return result;
6994}
6995
6996static void
6997put_value (bfd_vma        size,
6998	   unsigned long  chunksz,
6999	   bfd *          input_bfd,
7000	   bfd_vma        x,
7001	   bfd_byte *     location)
7002{
7003  location += (size - chunksz);
7004
7005  for (; size; size -= chunksz, location -= chunksz, x >>= (chunksz * 8))
7006    {
7007      switch (chunksz)
7008	{
7009	default:
7010	case 0:
7011	  abort ();
7012	case 1:
7013	  bfd_put_8 (input_bfd, x, location);
7014	  break;
7015	case 2:
7016	  bfd_put_16 (input_bfd, x, location);
7017	  break;
7018	case 4:
7019	  bfd_put_32 (input_bfd, x, location);
7020	  break;
7021	case 8:
7022#ifdef BFD64
7023	  bfd_put_64 (input_bfd, x, location);
7024#else
7025	  abort ();
7026#endif
7027	  break;
7028	}
7029    }
7030}
7031
7032static bfd_vma
7033get_value (bfd_vma        size,
7034	   unsigned long  chunksz,
7035	   bfd *          input_bfd,
7036	   bfd_byte *     location)
7037{
7038  bfd_vma x = 0;
7039
7040  for (; size; size -= chunksz, location += chunksz)
7041    {
7042      switch (chunksz)
7043	{
7044	default:
7045	case 0:
7046	  abort ();
7047	case 1:
7048	  x = (x << (8 * chunksz)) | bfd_get_8 (input_bfd, location);
7049	  break;
7050	case 2:
7051	  x = (x << (8 * chunksz)) | bfd_get_16 (input_bfd, location);
7052	  break;
7053	case 4:
7054	  x = (x << (8 * chunksz)) | bfd_get_32 (input_bfd, location);
7055	  break;
7056	case 8:
7057#ifdef BFD64
7058	  x = (x << (8 * chunksz)) | bfd_get_64 (input_bfd, location);
7059#else
7060	  abort ();
7061#endif
7062	  break;
7063	}
7064    }
7065  return x;
7066}
7067
7068static void
7069decode_complex_addend
7070    (unsigned long * start,   /* in bits */
7071     unsigned long * oplen,   /* in bits */
7072     unsigned long * len,     /* in bits */
7073     unsigned long * wordsz,  /* in bytes */
7074     unsigned long * chunksz,  /* in bytes */
7075     unsigned long * lsb0_p,
7076     unsigned long * signed_p,
7077     unsigned long * trunc_p,
7078     unsigned long encoded)
7079{
7080  * start     =  encoded        & 0x3F;
7081  * len       = (encoded >>  6) & 0x3F;
7082  * oplen     = (encoded >> 12) & 0x3F;
7083  * wordsz    = (encoded >> 18) & 0xF;
7084  * chunksz   = (encoded >> 22) & 0xF;
7085  * lsb0_p    = (encoded >> 27) & 1;
7086  * signed_p  = (encoded >> 28) & 1;
7087  * trunc_p   = (encoded >> 29) & 1;
7088}
7089
7090void
7091bfd_elf_perform_complex_relocation
7092    (bfd *                   output_bfd ATTRIBUTE_UNUSED,
7093     struct bfd_link_info *  info,
7094     bfd *                   input_bfd,
7095     asection *              input_section,
7096     bfd_byte *              contents,
7097     Elf_Internal_Rela *     rel,
7098     Elf_Internal_Sym *      local_syms,
7099     asection **             local_sections)
7100{
7101  const struct elf_backend_data * bed;
7102  Elf_Internal_Shdr * symtab_hdr;
7103  asection * sec;
7104  bfd_vma relocation = 0, shift, x;
7105  bfd_vma r_symndx;
7106  bfd_vma mask;
7107  unsigned long start, oplen, len, wordsz,
7108    chunksz, lsb0_p, signed_p, trunc_p;
7109
7110  /*  Perform this reloc, since it is complex.
7111      (this is not to say that it necessarily refers to a complex
7112      symbol; merely that it is a self-describing CGEN based reloc.
7113      i.e. the addend has the complete reloc information (bit start, end,
7114      word size, etc) encoded within it.).  */
7115  r_symndx = ELF32_R_SYM (rel->r_info);
7116  bed = get_elf_backend_data (input_bfd);
7117  if (bed->s->arch_size == 64)
7118    r_symndx >>= 24;
7119
7120#ifdef DEBUG
7121  printf ("Performing complex relocation %ld...\n", r_symndx);
7122#endif
7123
7124  symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
7125  if (r_symndx < symtab_hdr->sh_info)
7126    {
7127      /* The symbol is local.  */
7128      Elf_Internal_Sym * sym;
7129
7130      sym = local_syms + r_symndx;
7131      sec = local_sections [r_symndx];
7132      relocation = sym->st_value;
7133      if (sym->st_shndx > SHN_UNDEF &&
7134	  sym->st_shndx < SHN_LORESERVE)
7135	relocation += (sec->output_offset +
7136		       sec->output_section->vma);
7137    }
7138  else
7139    {
7140      /* The symbol is global.  */
7141      struct elf_link_hash_entry **sym_hashes;
7142      struct elf_link_hash_entry * h;
7143
7144      sym_hashes = elf_sym_hashes (input_bfd);
7145      h = sym_hashes [r_symndx];
7146
7147      while (h->root.type == bfd_link_hash_indirect
7148	     || h->root.type == bfd_link_hash_warning)
7149	h = (struct elf_link_hash_entry *) h->root.u.i.link;
7150
7151      if (h->root.type == bfd_link_hash_defined
7152	  || h->root.type == bfd_link_hash_defweak)
7153	{
7154	  sec = h->root.u.def.section;
7155	  relocation = h->root.u.def.value;
7156
7157	  if (! bfd_is_abs_section (sec))
7158	    relocation += (sec->output_section->vma
7159			   + sec->output_offset);
7160	}
7161      if (h->root.type == bfd_link_hash_undefined
7162	  && !((*info->callbacks->undefined_symbol)
7163	       (info, h->root.root.string, input_bfd,
7164		input_section, rel->r_offset,
7165		info->unresolved_syms_in_objects == RM_GENERATE_ERROR
7166		|| ELF_ST_VISIBILITY (h->other))))
7167	return;
7168    }
7169
7170  decode_complex_addend (& start, & oplen, & len, & wordsz,
7171			 & chunksz, & lsb0_p, & signed_p,
7172			 & trunc_p, rel->r_addend);
7173
7174  mask = (((1L << (len - 1)) - 1) << 1) | 1;
7175
7176  if (lsb0_p)
7177    shift = (start + 1) - len;
7178  else
7179    shift = (8 * wordsz) - (start + len);
7180
7181  x = get_value (wordsz, chunksz, input_bfd, contents + rel->r_offset);
7182
7183#ifdef DEBUG
7184  printf ("Doing complex reloc: "
7185	  "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
7186	  "chunksz %ld, start %ld, len %ld, oplen %ld\n"
7187	  "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
7188	  lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
7189	  oplen, x, mask,  relocation);
7190#endif
7191
7192  if (! trunc_p)
7193    {
7194      /* Now do an overflow check.  */
7195      if (bfd_check_overflow ((signed_p ?
7196			       complain_overflow_signed :
7197			       complain_overflow_unsigned),
7198			      len, 0, (8 * wordsz),
7199			      relocation) == bfd_reloc_overflow)
7200	(*_bfd_error_handler)
7201	  ("%s (%s + 0x%lx): relocation overflow: 0x%lx %sdoes not fit "
7202	   "within 0x%lx",
7203	   input_bfd->filename, input_section->name, rel->r_offset,
7204	   relocation, (signed_p ? "(signed) " : ""), mask);
7205    }
7206
7207  /* Do the deed.  */
7208  x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
7209
7210#ifdef DEBUG
7211  printf ("           relocation: %8.8lx\n"
7212	  "         shifted mask: %8.8lx\n"
7213	  " shifted/masked reloc: %8.8lx\n"
7214	  "               result: %8.8lx\n",
7215	  relocation, (mask << shift),
7216	  ((relocation & mask) << shift), x);
7217#endif
7218  put_value (wordsz, chunksz, input_bfd, x, contents + rel->r_offset);
7219}
7220
7221/* When performing a relocatable link, the input relocations are
7222   preserved.  But, if they reference global symbols, the indices
7223   referenced must be updated.  Update all the relocations in
7224   REL_HDR (there are COUNT of them), using the data in REL_HASH.  */
7225
7226static void
7227elf_link_adjust_relocs (bfd *abfd,
7228			Elf_Internal_Shdr *rel_hdr,
7229			unsigned int count,
7230			struct elf_link_hash_entry **rel_hash)
7231{
7232  unsigned int i;
7233  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7234  bfd_byte *erela;
7235  void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
7236  void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
7237  bfd_vma r_type_mask;
7238  int r_sym_shift;
7239
7240  if (rel_hdr->sh_entsize == bed->s->sizeof_rel)
7241    {
7242      swap_in = bed->s->swap_reloc_in;
7243      swap_out = bed->s->swap_reloc_out;
7244    }
7245  else if (rel_hdr->sh_entsize == bed->s->sizeof_rela)
7246    {
7247      swap_in = bed->s->swap_reloca_in;
7248      swap_out = bed->s->swap_reloca_out;
7249    }
7250  else
7251    abort ();
7252
7253  if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
7254    abort ();
7255
7256  if (bed->s->arch_size == 32)
7257    {
7258      r_type_mask = 0xff;
7259      r_sym_shift = 8;
7260    }
7261  else
7262    {
7263      r_type_mask = 0xffffffff;
7264      r_sym_shift = 32;
7265    }
7266
7267  erela = rel_hdr->contents;
7268  for (i = 0; i < count; i++, rel_hash++, erela += rel_hdr->sh_entsize)
7269    {
7270      Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
7271      unsigned int j;
7272
7273      if (*rel_hash == NULL)
7274	continue;
7275
7276      BFD_ASSERT ((*rel_hash)->indx >= 0);
7277
7278      (*swap_in) (abfd, erela, irela);
7279      for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
7280	irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
7281			   | (irela[j].r_info & r_type_mask));
7282      (*swap_out) (abfd, irela, erela);
7283    }
7284}
7285
7286struct elf_link_sort_rela
7287{
7288  union {
7289    bfd_vma offset;
7290    bfd_vma sym_mask;
7291  } u;
7292  enum elf_reloc_type_class type;
7293  /* We use this as an array of size int_rels_per_ext_rel.  */
7294  Elf_Internal_Rela rela[1];
7295};
7296
7297static int
7298elf_link_sort_cmp1 (const void *A, const void *B)
7299{
7300  const struct elf_link_sort_rela *a = A;
7301  const struct elf_link_sort_rela *b = B;
7302  int relativea, relativeb;
7303
7304  relativea = a->type == reloc_class_relative;
7305  relativeb = b->type == reloc_class_relative;
7306
7307  if (relativea < relativeb)
7308    return 1;
7309  if (relativea > relativeb)
7310    return -1;
7311  if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
7312    return -1;
7313  if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
7314    return 1;
7315  if (a->rela->r_offset < b->rela->r_offset)
7316    return -1;
7317  if (a->rela->r_offset > b->rela->r_offset)
7318    return 1;
7319  return 0;
7320}
7321
7322static int
7323elf_link_sort_cmp2 (const void *A, const void *B)
7324{
7325  const struct elf_link_sort_rela *a = A;
7326  const struct elf_link_sort_rela *b = B;
7327  int copya, copyb;
7328
7329  if (a->u.offset < b->u.offset)
7330    return -1;
7331  if (a->u.offset > b->u.offset)
7332    return 1;
7333  copya = (a->type == reloc_class_copy) * 2 + (a->type == reloc_class_plt);
7334  copyb = (b->type == reloc_class_copy) * 2 + (b->type == reloc_class_plt);
7335  if (copya < copyb)
7336    return -1;
7337  if (copya > copyb)
7338    return 1;
7339  if (a->rela->r_offset < b->rela->r_offset)
7340    return -1;
7341  if (a->rela->r_offset > b->rela->r_offset)
7342    return 1;
7343  return 0;
7344}
7345
7346static size_t
7347elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
7348{
7349  asection *dynamic_relocs;
7350  asection *rela_dyn;
7351  asection *rel_dyn;
7352  bfd_size_type count, size;
7353  size_t i, ret, sort_elt, ext_size;
7354  bfd_byte *sort, *s_non_relative, *p;
7355  struct elf_link_sort_rela *sq;
7356  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7357  int i2e = bed->s->int_rels_per_ext_rel;
7358  void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
7359  void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
7360  struct bfd_link_order *lo;
7361  bfd_vma r_sym_mask;
7362  bfd_boolean use_rela;
7363
7364  /* Find a dynamic reloc section.  */
7365  rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
7366  rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
7367  if (rela_dyn != NULL && rela_dyn->size > 0
7368      && rel_dyn != NULL && rel_dyn->size > 0)
7369    {
7370      bfd_boolean use_rela_initialised = FALSE;
7371
7372      /* This is just here to stop gcc from complaining.
7373	 It's initialization checking code is not perfect.  */
7374      use_rela = TRUE;
7375
7376      /* Both sections are present.  Examine the sizes
7377	 of the indirect sections to help us choose.  */
7378      for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
7379	if (lo->type == bfd_indirect_link_order)
7380	  {
7381	    asection *o = lo->u.indirect.section;
7382
7383	    if ((o->size % bed->s->sizeof_rela) == 0)
7384	      {
7385		if ((o->size % bed->s->sizeof_rel) == 0)
7386		  /* Section size is divisible by both rel and rela sizes.
7387		     It is of no help to us.  */
7388		  ;
7389		else
7390		  {
7391		    /* Section size is only divisible by rela.  */
7392		    if (use_rela_initialised && (use_rela == FALSE))
7393		      {
7394			_bfd_error_handler
7395			  (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
7396			bfd_set_error (bfd_error_invalid_operation);
7397			return 0;
7398		      }
7399		    else
7400		      {
7401			use_rela = TRUE;
7402			use_rela_initialised = TRUE;
7403		      }
7404		  }
7405	      }
7406	    else if ((o->size % bed->s->sizeof_rel) == 0)
7407	      {
7408		/* Section size is only divisible by rel.  */
7409		if (use_rela_initialised && (use_rela == TRUE))
7410		  {
7411		    _bfd_error_handler
7412		      (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
7413		    bfd_set_error (bfd_error_invalid_operation);
7414		    return 0;
7415		  }
7416		else
7417		  {
7418		    use_rela = FALSE;
7419		    use_rela_initialised = TRUE;
7420		  }
7421	      }
7422	    else
7423	      {
7424		/* The section size is not divisible by either - something is wrong.  */
7425		_bfd_error_handler
7426		  (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
7427		bfd_set_error (bfd_error_invalid_operation);
7428		return 0;
7429	      }
7430	  }
7431
7432      for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
7433	if (lo->type == bfd_indirect_link_order)
7434	  {
7435	    asection *o = lo->u.indirect.section;
7436
7437	    if ((o->size % bed->s->sizeof_rela) == 0)
7438	      {
7439		if ((o->size % bed->s->sizeof_rel) == 0)
7440		  /* Section size is divisible by both rel and rela sizes.
7441		     It is of no help to us.  */
7442		  ;
7443		else
7444		  {
7445		    /* Section size is only divisible by rela.  */
7446		    if (use_rela_initialised && (use_rela == FALSE))
7447		      {
7448			_bfd_error_handler
7449			  (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
7450			bfd_set_error (bfd_error_invalid_operation);
7451			return 0;
7452		      }
7453		    else
7454		      {
7455			use_rela = TRUE;
7456			use_rela_initialised = TRUE;
7457		      }
7458		  }
7459	      }
7460	    else if ((o->size % bed->s->sizeof_rel) == 0)
7461	      {
7462		/* Section size is only divisible by rel.  */
7463		if (use_rela_initialised && (use_rela == TRUE))
7464		  {
7465		    _bfd_error_handler
7466		      (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
7467		    bfd_set_error (bfd_error_invalid_operation);
7468		    return 0;
7469		  }
7470		else
7471		  {
7472		    use_rela = FALSE;
7473		    use_rela_initialised = TRUE;
7474		  }
7475	      }
7476	    else
7477	      {
7478		/* The section size is not divisible by either - something is wrong.  */
7479		_bfd_error_handler
7480		  (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
7481		bfd_set_error (bfd_error_invalid_operation);
7482		return 0;
7483	      }
7484	  }
7485
7486      if (! use_rela_initialised)
7487	/* Make a guess.  */
7488	use_rela = TRUE;
7489    }
7490  else if (rela_dyn != NULL && rela_dyn->size > 0)
7491    use_rela = TRUE;
7492  else if (rel_dyn != NULL && rel_dyn->size > 0)
7493    use_rela = FALSE;
7494  else
7495    return 0;
7496
7497  if (use_rela)
7498    {
7499      dynamic_relocs = rela_dyn;
7500      ext_size = bed->s->sizeof_rela;
7501      swap_in = bed->s->swap_reloca_in;
7502      swap_out = bed->s->swap_reloca_out;
7503    }
7504  else
7505    {
7506      dynamic_relocs = rel_dyn;
7507      ext_size = bed->s->sizeof_rel;
7508      swap_in = bed->s->swap_reloc_in;
7509      swap_out = bed->s->swap_reloc_out;
7510    }
7511
7512  size = 0;
7513  for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
7514    if (lo->type == bfd_indirect_link_order)
7515      size += lo->u.indirect.section->size;
7516
7517  if (size != dynamic_relocs->size)
7518    return 0;
7519
7520  sort_elt = (sizeof (struct elf_link_sort_rela)
7521	      + (i2e - 1) * sizeof (Elf_Internal_Rela));
7522
7523  count = dynamic_relocs->size / ext_size;
7524  sort = bfd_zmalloc (sort_elt * count);
7525
7526  if (sort == NULL)
7527    {
7528      (*info->callbacks->warning)
7529	(info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
7530      return 0;
7531    }
7532
7533  if (bed->s->arch_size == 32)
7534    r_sym_mask = ~(bfd_vma) 0xff;
7535  else
7536    r_sym_mask = ~(bfd_vma) 0xffffffff;
7537
7538  for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
7539    if (lo->type == bfd_indirect_link_order)
7540      {
7541	bfd_byte *erel, *erelend;
7542	asection *o = lo->u.indirect.section;
7543
7544	if (o->contents == NULL && o->size != 0)
7545	  {
7546	    /* This is a reloc section that is being handled as a normal
7547	       section.  See bfd_section_from_shdr.  We can't combine
7548	       relocs in this case.  */
7549	    free (sort);
7550	    return 0;
7551	  }
7552	erel = o->contents;
7553	erelend = o->contents + o->size;
7554	p = sort + o->output_offset / ext_size * sort_elt;
7555
7556	while (erel < erelend)
7557	  {
7558	    struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
7559
7560	    (*swap_in) (abfd, erel, s->rela);
7561	    s->type = (*bed->elf_backend_reloc_type_class) (s->rela);
7562	    s->u.sym_mask = r_sym_mask;
7563	    p += sort_elt;
7564	    erel += ext_size;
7565	  }
7566      }
7567
7568  qsort (sort, count, sort_elt, elf_link_sort_cmp1);
7569
7570  for (i = 0, p = sort; i < count; i++, p += sort_elt)
7571    {
7572      struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
7573      if (s->type != reloc_class_relative)
7574	break;
7575    }
7576  ret = i;
7577  s_non_relative = p;
7578
7579  sq = (struct elf_link_sort_rela *) s_non_relative;
7580  for (; i < count; i++, p += sort_elt)
7581    {
7582      struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
7583      if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
7584	sq = sp;
7585      sp->u.offset = sq->rela->r_offset;
7586    }
7587
7588  qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
7589
7590  for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
7591    if (lo->type == bfd_indirect_link_order)
7592      {
7593	bfd_byte *erel, *erelend;
7594	asection *o = lo->u.indirect.section;
7595
7596	erel = o->contents;
7597	erelend = o->contents + o->size;
7598	p = sort + o->output_offset / ext_size * sort_elt;
7599	while (erel < erelend)
7600	  {
7601	    struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
7602	    (*swap_out) (abfd, s->rela, erel);
7603	    p += sort_elt;
7604	    erel += ext_size;
7605	  }
7606      }
7607
7608  free (sort);
7609  *psec = dynamic_relocs;
7610  return ret;
7611}
7612
7613/* Flush the output symbols to the file.  */
7614
7615static bfd_boolean
7616elf_link_flush_output_syms (struct elf_final_link_info *finfo,
7617			    const struct elf_backend_data *bed)
7618{
7619  if (finfo->symbuf_count > 0)
7620    {
7621      Elf_Internal_Shdr *hdr;
7622      file_ptr pos;
7623      bfd_size_type amt;
7624
7625      hdr = &elf_tdata (finfo->output_bfd)->symtab_hdr;
7626      pos = hdr->sh_offset + hdr->sh_size;
7627      amt = finfo->symbuf_count * bed->s->sizeof_sym;
7628      if (bfd_seek (finfo->output_bfd, pos, SEEK_SET) != 0
7629	  || bfd_bwrite (finfo->symbuf, amt, finfo->output_bfd) != amt)
7630	return FALSE;
7631
7632      hdr->sh_size += amt;
7633      finfo->symbuf_count = 0;
7634    }
7635
7636  return TRUE;
7637}
7638
7639/* Add a symbol to the output symbol table.  */
7640
7641static bfd_boolean
7642elf_link_output_sym (struct elf_final_link_info *finfo,
7643		     const char *name,
7644		     Elf_Internal_Sym *elfsym,
7645		     asection *input_sec,
7646		     struct elf_link_hash_entry *h)
7647{
7648  bfd_byte *dest;
7649  Elf_External_Sym_Shndx *destshndx;
7650  bfd_boolean (*output_symbol_hook)
7651    (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
7652     struct elf_link_hash_entry *);
7653  const struct elf_backend_data *bed;
7654
7655  bed = get_elf_backend_data (finfo->output_bfd);
7656  output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
7657  if (output_symbol_hook != NULL)
7658    {
7659      if (! (*output_symbol_hook) (finfo->info, name, elfsym, input_sec, h))
7660	return FALSE;
7661    }
7662
7663  if (name == NULL || *name == '\0')
7664    elfsym->st_name = 0;
7665  else if (input_sec->flags & SEC_EXCLUDE)
7666    elfsym->st_name = 0;
7667  else
7668    {
7669      elfsym->st_name = (unsigned long) _bfd_stringtab_add (finfo->symstrtab,
7670							    name, TRUE, FALSE);
7671      if (elfsym->st_name == (unsigned long) -1)
7672	return FALSE;
7673    }
7674
7675  if (finfo->symbuf_count >= finfo->symbuf_size)
7676    {
7677      if (! elf_link_flush_output_syms (finfo, bed))
7678	return FALSE;
7679    }
7680
7681  dest = finfo->symbuf + finfo->symbuf_count * bed->s->sizeof_sym;
7682  destshndx = finfo->symshndxbuf;
7683  if (destshndx != NULL)
7684    {
7685      if (bfd_get_symcount (finfo->output_bfd) >= finfo->shndxbuf_size)
7686	{
7687	  bfd_size_type amt;
7688
7689	  amt = finfo->shndxbuf_size * sizeof (Elf_External_Sym_Shndx);
7690	  finfo->symshndxbuf = destshndx = bfd_realloc (destshndx, amt * 2);
7691	  if (destshndx == NULL)
7692	    return FALSE;
7693	  memset ((char *) destshndx + amt, 0, amt);
7694	  finfo->shndxbuf_size *= 2;
7695	}
7696      destshndx += bfd_get_symcount (finfo->output_bfd);
7697    }
7698
7699  bed->s->swap_symbol_out (finfo->output_bfd, elfsym, dest, destshndx);
7700  finfo->symbuf_count += 1;
7701  bfd_get_symcount (finfo->output_bfd) += 1;
7702
7703  return TRUE;
7704}
7705
7706/* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
7707
7708static bfd_boolean
7709check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
7710{
7711  if (sym->st_shndx > SHN_HIRESERVE)
7712    {
7713      /* The gABI doesn't support dynamic symbols in output sections
7714         beyond 64k.  */
7715      (*_bfd_error_handler)
7716	(_("%B: Too many sections: %d (>= %d)"),
7717	 abfd, bfd_count_sections (abfd), SHN_LORESERVE);
7718      bfd_set_error (bfd_error_nonrepresentable_section);
7719      return FALSE;
7720    }
7721  return TRUE;
7722}
7723
7724/* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
7725   allowing an unsatisfied unversioned symbol in the DSO to match a
7726   versioned symbol that would normally require an explicit version.
7727   We also handle the case that a DSO references a hidden symbol
7728   which may be satisfied by a versioned symbol in another DSO.  */
7729
7730static bfd_boolean
7731elf_link_check_versioned_symbol (struct bfd_link_info *info,
7732				 const struct elf_backend_data *bed,
7733				 struct elf_link_hash_entry *h)
7734{
7735  bfd *abfd;
7736  struct elf_link_loaded_list *loaded;
7737
7738  if (!is_elf_hash_table (info->hash))
7739    return FALSE;
7740
7741  switch (h->root.type)
7742    {
7743    default:
7744      abfd = NULL;
7745      break;
7746
7747    case bfd_link_hash_undefined:
7748    case bfd_link_hash_undefweak:
7749      abfd = h->root.u.undef.abfd;
7750      if ((abfd->flags & DYNAMIC) == 0
7751	  || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
7752	return FALSE;
7753      break;
7754
7755    case bfd_link_hash_defined:
7756    case bfd_link_hash_defweak:
7757      abfd = h->root.u.def.section->owner;
7758      break;
7759
7760    case bfd_link_hash_common:
7761      abfd = h->root.u.c.p->section->owner;
7762      break;
7763    }
7764  BFD_ASSERT (abfd != NULL);
7765
7766  for (loaded = elf_hash_table (info)->loaded;
7767       loaded != NULL;
7768       loaded = loaded->next)
7769    {
7770      bfd *input;
7771      Elf_Internal_Shdr *hdr;
7772      bfd_size_type symcount;
7773      bfd_size_type extsymcount;
7774      bfd_size_type extsymoff;
7775      Elf_Internal_Shdr *versymhdr;
7776      Elf_Internal_Sym *isym;
7777      Elf_Internal_Sym *isymend;
7778      Elf_Internal_Sym *isymbuf;
7779      Elf_External_Versym *ever;
7780      Elf_External_Versym *extversym;
7781
7782      input = loaded->abfd;
7783
7784      /* We check each DSO for a possible hidden versioned definition.  */
7785      if (input == abfd
7786	  || (input->flags & DYNAMIC) == 0
7787	  || elf_dynversym (input) == 0)
7788	continue;
7789
7790      hdr = &elf_tdata (input)->dynsymtab_hdr;
7791
7792      symcount = hdr->sh_size / bed->s->sizeof_sym;
7793      if (elf_bad_symtab (input))
7794	{
7795	  extsymcount = symcount;
7796	  extsymoff = 0;
7797	}
7798      else
7799	{
7800	  extsymcount = symcount - hdr->sh_info;
7801	  extsymoff = hdr->sh_info;
7802	}
7803
7804      if (extsymcount == 0)
7805	continue;
7806
7807      isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
7808				      NULL, NULL, NULL);
7809      if (isymbuf == NULL)
7810	return FALSE;
7811
7812      /* Read in any version definitions.  */
7813      versymhdr = &elf_tdata (input)->dynversym_hdr;
7814      extversym = bfd_malloc (versymhdr->sh_size);
7815      if (extversym == NULL)
7816	goto error_ret;
7817
7818      if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
7819	  || (bfd_bread (extversym, versymhdr->sh_size, input)
7820	      != versymhdr->sh_size))
7821	{
7822	  free (extversym);
7823	error_ret:
7824	  free (isymbuf);
7825	  return FALSE;
7826	}
7827
7828      ever = extversym + extsymoff;
7829      isymend = isymbuf + extsymcount;
7830      for (isym = isymbuf; isym < isymend; isym++, ever++)
7831	{
7832	  const char *name;
7833	  Elf_Internal_Versym iver;
7834	  unsigned short version_index;
7835
7836	  if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
7837	      || isym->st_shndx == SHN_UNDEF)
7838	    continue;
7839
7840	  name = bfd_elf_string_from_elf_section (input,
7841						  hdr->sh_link,
7842						  isym->st_name);
7843	  if (strcmp (name, h->root.root.string) != 0)
7844	    continue;
7845
7846	  _bfd_elf_swap_versym_in (input, ever, &iver);
7847
7848	  if ((iver.vs_vers & VERSYM_HIDDEN) == 0)
7849	    {
7850	      /* If we have a non-hidden versioned sym, then it should
7851		 have provided a definition for the undefined sym.  */
7852	      abort ();
7853	    }
7854
7855	  version_index = iver.vs_vers & VERSYM_VERSION;
7856	  if (version_index == 1 || version_index == 2)
7857	    {
7858	      /* This is the base or first version.  We can use it.  */
7859	      free (extversym);
7860	      free (isymbuf);
7861	      return TRUE;
7862	    }
7863	}
7864
7865      free (extversym);
7866      free (isymbuf);
7867    }
7868
7869  return FALSE;
7870}
7871
7872/* Add an external symbol to the symbol table.  This is called from
7873   the hash table traversal routine.  When generating a shared object,
7874   we go through the symbol table twice.  The first time we output
7875   anything that might have been forced to local scope in a version
7876   script.  The second time we output the symbols that are still
7877   global symbols.  */
7878
7879static bfd_boolean
7880elf_link_output_extsym (struct elf_link_hash_entry *h, void *data)
7881{
7882  struct elf_outext_info *eoinfo = data;
7883  struct elf_final_link_info *finfo = eoinfo->finfo;
7884  bfd_boolean strip;
7885  Elf_Internal_Sym sym;
7886  asection *input_sec;
7887  const struct elf_backend_data *bed;
7888
7889  if (h->root.type == bfd_link_hash_warning)
7890    {
7891      h = (struct elf_link_hash_entry *) h->root.u.i.link;
7892      if (h->root.type == bfd_link_hash_new)
7893	return TRUE;
7894    }
7895
7896  /* Decide whether to output this symbol in this pass.  */
7897  if (eoinfo->localsyms)
7898    {
7899      if (!h->forced_local)
7900	return TRUE;
7901    }
7902  else
7903    {
7904      if (h->forced_local)
7905	return TRUE;
7906    }
7907
7908  bed = get_elf_backend_data (finfo->output_bfd);
7909
7910  if (h->root.type == bfd_link_hash_undefined)
7911    {
7912      /* If we have an undefined symbol reference here then it must have
7913	 come from a shared library that is being linked in.  (Undefined
7914	 references in regular files have already been handled).  */
7915      bfd_boolean ignore_undef = FALSE;
7916
7917      /* Some symbols may be special in that the fact that they're
7918	 undefined can be safely ignored - let backend determine that.  */
7919      if (bed->elf_backend_ignore_undef_symbol)
7920	ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
7921
7922      /* If we are reporting errors for this situation then do so now.  */
7923      if (ignore_undef == FALSE
7924	  && h->ref_dynamic
7925	  && ! h->ref_regular
7926	  && ! elf_link_check_versioned_symbol (finfo->info, bed, h)
7927	  && finfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
7928	{
7929	  if (! (finfo->info->callbacks->undefined_symbol
7930		 (finfo->info, h->root.root.string, h->root.u.undef.abfd,
7931		  NULL, 0, finfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR)))
7932	    {
7933	      eoinfo->failed = TRUE;
7934	      return FALSE;
7935	    }
7936	}
7937    }
7938
7939  /* We should also warn if a forced local symbol is referenced from
7940     shared libraries.  */
7941  if (! finfo->info->relocatable
7942      && (! finfo->info->shared)
7943      && h->forced_local
7944      && h->ref_dynamic
7945      && !h->dynamic_def
7946      && !h->dynamic_weak
7947      && ! elf_link_check_versioned_symbol (finfo->info, bed, h))
7948    {
7949      (*_bfd_error_handler)
7950	(_("%B: %s symbol `%s' in %B is referenced by DSO"),
7951	 finfo->output_bfd,
7952	 h->root.u.def.section == bfd_abs_section_ptr
7953	 ? finfo->output_bfd : h->root.u.def.section->owner,
7954	 ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
7955	 ? "internal"
7956	 : ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
7957	 ? "hidden" : "local",
7958	 h->root.root.string);
7959      eoinfo->failed = TRUE;
7960      return FALSE;
7961    }
7962
7963  /* We don't want to output symbols that have never been mentioned by
7964     a regular file, or that we have been told to strip.  However, if
7965     h->indx is set to -2, the symbol is used by a reloc and we must
7966     output it.  */
7967  if (h->indx == -2)
7968    strip = FALSE;
7969  else if ((h->def_dynamic
7970	    || h->ref_dynamic
7971	    || h->root.type == bfd_link_hash_new)
7972	   && !h->def_regular
7973	   && !h->ref_regular)
7974    strip = TRUE;
7975  else if (finfo->info->strip == strip_all)
7976    strip = TRUE;
7977  else if (finfo->info->strip == strip_some
7978	   && bfd_hash_lookup (finfo->info->keep_hash,
7979			       h->root.root.string, FALSE, FALSE) == NULL)
7980    strip = TRUE;
7981  else if (finfo->info->strip_discarded
7982	   && (h->root.type == bfd_link_hash_defined
7983	       || h->root.type == bfd_link_hash_defweak)
7984	   && elf_discarded_section (h->root.u.def.section))
7985    strip = TRUE;
7986  else
7987    strip = FALSE;
7988
7989  /* If we're stripping it, and it's not a dynamic symbol, there's
7990     nothing else to do unless it is a forced local symbol.  */
7991  if (strip
7992      && h->dynindx == -1
7993      && !h->forced_local)
7994    return TRUE;
7995
7996  sym.st_value = 0;
7997  sym.st_size = h->size;
7998  sym.st_other = h->other;
7999  if (h->forced_local)
8000    sym.st_info = ELF_ST_INFO (STB_LOCAL, h->type);
8001  else if (h->root.type == bfd_link_hash_undefweak
8002	   || h->root.type == bfd_link_hash_defweak)
8003    sym.st_info = ELF_ST_INFO (STB_WEAK, h->type);
8004  else
8005    sym.st_info = ELF_ST_INFO (STB_GLOBAL, h->type);
8006
8007  switch (h->root.type)
8008    {
8009    default:
8010    case bfd_link_hash_new:
8011    case bfd_link_hash_warning:
8012      abort ();
8013      return FALSE;
8014
8015    case bfd_link_hash_undefined:
8016    case bfd_link_hash_undefweak:
8017      input_sec = bfd_und_section_ptr;
8018      sym.st_shndx = SHN_UNDEF;
8019      break;
8020
8021    case bfd_link_hash_defined:
8022    case bfd_link_hash_defweak:
8023      {
8024	input_sec = h->root.u.def.section;
8025	if (input_sec->output_section != NULL)
8026	  {
8027	    sym.st_shndx =
8028	      _bfd_elf_section_from_bfd_section (finfo->output_bfd,
8029						 input_sec->output_section);
8030	    if (sym.st_shndx == SHN_BAD)
8031	      {
8032		(*_bfd_error_handler)
8033		  (_("%B: could not find output section %A for input section %A"),
8034		   finfo->output_bfd, input_sec->output_section, input_sec);
8035		eoinfo->failed = TRUE;
8036		return FALSE;
8037	      }
8038
8039	    /* ELF symbols in relocatable files are section relative,
8040	       but in nonrelocatable files they are virtual
8041	       addresses.  */
8042	    sym.st_value = h->root.u.def.value + input_sec->output_offset;
8043	    if (! finfo->info->relocatable)
8044	      {
8045		sym.st_value += input_sec->output_section->vma;
8046		if (h->type == STT_TLS)
8047		  {
8048		    /* STT_TLS symbols are relative to PT_TLS segment
8049		       base.  */
8050		    BFD_ASSERT (elf_hash_table (finfo->info)->tls_sec != NULL);
8051		    sym.st_value -= elf_hash_table (finfo->info)->tls_sec->vma;
8052		  }
8053	      }
8054	  }
8055	else
8056	  {
8057	    BFD_ASSERT (input_sec->owner == NULL
8058			|| (input_sec->owner->flags & DYNAMIC) != 0);
8059	    sym.st_shndx = SHN_UNDEF;
8060	    input_sec = bfd_und_section_ptr;
8061	  }
8062      }
8063      break;
8064
8065    case bfd_link_hash_common:
8066      input_sec = h->root.u.c.p->section;
8067      sym.st_shndx = bed->common_section_index (input_sec);
8068      sym.st_value = 1 << h->root.u.c.p->alignment_power;
8069      break;
8070
8071    case bfd_link_hash_indirect:
8072      /* These symbols are created by symbol versioning.  They point
8073	 to the decorated version of the name.  For example, if the
8074	 symbol foo@@GNU_1.2 is the default, which should be used when
8075	 foo is used with no version, then we add an indirect symbol
8076	 foo which points to foo@@GNU_1.2.  We ignore these symbols,
8077	 since the indirected symbol is already in the hash table.  */
8078      return TRUE;
8079    }
8080
8081  /* Give the processor backend a chance to tweak the symbol value,
8082     and also to finish up anything that needs to be done for this
8083     symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
8084     forced local syms when non-shared is due to a historical quirk.  */
8085  if ((h->dynindx != -1
8086       || h->forced_local)
8087      && ((finfo->info->shared
8088	   && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
8089	       || h->root.type != bfd_link_hash_undefweak))
8090	  || !h->forced_local)
8091      && elf_hash_table (finfo->info)->dynamic_sections_created)
8092    {
8093      if (! ((*bed->elf_backend_finish_dynamic_symbol)
8094	     (finfo->output_bfd, finfo->info, h, &sym)))
8095	{
8096	  eoinfo->failed = TRUE;
8097	  return FALSE;
8098	}
8099    }
8100
8101  /* If we are marking the symbol as undefined, and there are no
8102     non-weak references to this symbol from a regular object, then
8103     mark the symbol as weak undefined; if there are non-weak
8104     references, mark the symbol as strong.  We can't do this earlier,
8105     because it might not be marked as undefined until the
8106     finish_dynamic_symbol routine gets through with it.  */
8107  if (sym.st_shndx == SHN_UNDEF
8108      && h->ref_regular
8109      && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
8110	  || ELF_ST_BIND (sym.st_info) == STB_WEAK))
8111    {
8112      int bindtype;
8113
8114      if (h->ref_regular_nonweak)
8115	bindtype = STB_GLOBAL;
8116      else
8117	bindtype = STB_WEAK;
8118      sym.st_info = ELF_ST_INFO (bindtype, ELF_ST_TYPE (sym.st_info));
8119    }
8120
8121  /* If a non-weak symbol with non-default visibility is not defined
8122     locally, it is a fatal error.  */
8123  if (! finfo->info->relocatable
8124      && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
8125      && ELF_ST_BIND (sym.st_info) != STB_WEAK
8126      && h->root.type == bfd_link_hash_undefined
8127      && !h->def_regular)
8128    {
8129      (*_bfd_error_handler)
8130	(_("%B: %s symbol `%s' isn't defined"),
8131	 finfo->output_bfd,
8132	 ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED
8133	 ? "protected"
8134	 : ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL
8135	 ? "internal" : "hidden",
8136	 h->root.root.string);
8137      eoinfo->failed = TRUE;
8138      return FALSE;
8139    }
8140
8141  /* If this symbol should be put in the .dynsym section, then put it
8142     there now.  We already know the symbol index.  We also fill in
8143     the entry in the .hash section.  */
8144  if (h->dynindx != -1
8145      && elf_hash_table (finfo->info)->dynamic_sections_created)
8146    {
8147      bfd_byte *esym;
8148
8149      sym.st_name = h->dynstr_index;
8150      esym = finfo->dynsym_sec->contents + h->dynindx * bed->s->sizeof_sym;
8151      if (! check_dynsym (finfo->output_bfd, &sym))
8152	{
8153	  eoinfo->failed = TRUE;
8154	  return FALSE;
8155	}
8156      bed->s->swap_symbol_out (finfo->output_bfd, &sym, esym, 0);
8157
8158      if (finfo->hash_sec != NULL)
8159	{
8160	  size_t hash_entry_size;
8161	  bfd_byte *bucketpos;
8162	  bfd_vma chain;
8163	  size_t bucketcount;
8164	  size_t bucket;
8165
8166	  bucketcount = elf_hash_table (finfo->info)->bucketcount;
8167	  bucket = h->u.elf_hash_value % bucketcount;
8168
8169	  hash_entry_size
8170	    = elf_section_data (finfo->hash_sec)->this_hdr.sh_entsize;
8171	  bucketpos = ((bfd_byte *) finfo->hash_sec->contents
8172		       + (bucket + 2) * hash_entry_size);
8173	  chain = bfd_get (8 * hash_entry_size, finfo->output_bfd, bucketpos);
8174	  bfd_put (8 * hash_entry_size, finfo->output_bfd, h->dynindx, bucketpos);
8175	  bfd_put (8 * hash_entry_size, finfo->output_bfd, chain,
8176		   ((bfd_byte *) finfo->hash_sec->contents
8177		    + (bucketcount + 2 + h->dynindx) * hash_entry_size));
8178	}
8179
8180      if (finfo->symver_sec != NULL && finfo->symver_sec->contents != NULL)
8181	{
8182	  Elf_Internal_Versym iversym;
8183	  Elf_External_Versym *eversym;
8184
8185	  if (!h->def_regular)
8186	    {
8187	      if (h->verinfo.verdef == NULL)
8188		iversym.vs_vers = 0;
8189	      else
8190		iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
8191	    }
8192	  else
8193	    {
8194	      if (h->verinfo.vertree == NULL)
8195		iversym.vs_vers = 1;
8196	      else
8197		iversym.vs_vers = h->verinfo.vertree->vernum + 1;
8198	      if (finfo->info->create_default_symver)
8199		iversym.vs_vers++;
8200	    }
8201
8202	  if (h->hidden)
8203	    iversym.vs_vers |= VERSYM_HIDDEN;
8204
8205	  eversym = (Elf_External_Versym *) finfo->symver_sec->contents;
8206	  eversym += h->dynindx;
8207	  _bfd_elf_swap_versym_out (finfo->output_bfd, &iversym, eversym);
8208	}
8209    }
8210
8211  /* If we're stripping it, then it was just a dynamic symbol, and
8212     there's nothing else to do.  */
8213  if (strip || (input_sec->flags & SEC_EXCLUDE) != 0)
8214    return TRUE;
8215
8216  h->indx = bfd_get_symcount (finfo->output_bfd);
8217
8218  if (! elf_link_output_sym (finfo, h->root.root.string, &sym, input_sec, h))
8219    {
8220      eoinfo->failed = TRUE;
8221      return FALSE;
8222    }
8223
8224  return TRUE;
8225}
8226
8227/* Return TRUE if special handling is done for relocs in SEC against
8228   symbols defined in discarded sections.  */
8229
8230static bfd_boolean
8231elf_section_ignore_discarded_relocs (asection *sec)
8232{
8233  const struct elf_backend_data *bed;
8234
8235  switch (sec->sec_info_type)
8236    {
8237    case ELF_INFO_TYPE_STABS:
8238    case ELF_INFO_TYPE_EH_FRAME:
8239      return TRUE;
8240    default:
8241      break;
8242    }
8243
8244  bed = get_elf_backend_data (sec->owner);
8245  if (bed->elf_backend_ignore_discarded_relocs != NULL
8246      && (*bed->elf_backend_ignore_discarded_relocs) (sec))
8247    return TRUE;
8248
8249  return FALSE;
8250}
8251
8252/* Return a mask saying how ld should treat relocations in SEC against
8253   symbols defined in discarded sections.  If this function returns
8254   COMPLAIN set, ld will issue a warning message.  If this function
8255   returns PRETEND set, and the discarded section was link-once and the
8256   same size as the kept link-once section, ld will pretend that the
8257   symbol was actually defined in the kept section.  Otherwise ld will
8258   zero the reloc (at least that is the intent, but some cooperation by
8259   the target dependent code is needed, particularly for REL targets).  */
8260
8261unsigned int
8262_bfd_elf_default_action_discarded (asection *sec)
8263{
8264  if (sec->flags & SEC_DEBUGGING)
8265    return PRETEND;
8266
8267  if (strcmp (".eh_frame", sec->name) == 0)
8268    return 0;
8269
8270  if (strcmp (".gcc_except_table", sec->name) == 0)
8271    return 0;
8272
8273  return COMPLAIN | PRETEND;
8274}
8275
8276/* Find a match between a section and a member of a section group.  */
8277
8278static asection *
8279match_group_member (asection *sec, asection *group,
8280		    struct bfd_link_info *info)
8281{
8282  asection *first = elf_next_in_group (group);
8283  asection *s = first;
8284
8285  while (s != NULL)
8286    {
8287      if (bfd_elf_match_symbols_in_sections (s, sec, info))
8288	return s;
8289
8290      s = elf_next_in_group (s);
8291      if (s == first)
8292	break;
8293    }
8294
8295  return NULL;
8296}
8297
8298/* Check if the kept section of a discarded section SEC can be used
8299   to replace it.  Return the replacement if it is OK.  Otherwise return
8300   NULL.  */
8301
8302asection *
8303_bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
8304{
8305  asection *kept;
8306
8307  kept = sec->kept_section;
8308  if (kept != NULL)
8309    {
8310      if ((kept->flags & SEC_GROUP) != 0)
8311	kept = match_group_member (sec, kept, info);
8312      if (kept != NULL && sec->size != kept->size)
8313	kept = NULL;
8314      sec->kept_section = kept;
8315    }
8316  return kept;
8317}
8318
8319/* Link an input file into the linker output file.  This function
8320   handles all the sections and relocations of the input file at once.
8321   This is so that we only have to read the local symbols once, and
8322   don't have to keep them in memory.  */
8323
8324static bfd_boolean
8325elf_link_input_bfd (struct elf_final_link_info *finfo, bfd *input_bfd)
8326{
8327  int (*relocate_section)
8328    (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
8329     Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
8330  bfd *output_bfd;
8331  Elf_Internal_Shdr *symtab_hdr;
8332  size_t locsymcount;
8333  size_t extsymoff;
8334  Elf_Internal_Sym *isymbuf;
8335  Elf_Internal_Sym *isym;
8336  Elf_Internal_Sym *isymend;
8337  long *pindex;
8338  asection **ppsection;
8339  asection *o;
8340  const struct elf_backend_data *bed;
8341  struct elf_link_hash_entry **sym_hashes;
8342
8343  output_bfd = finfo->output_bfd;
8344  bed = get_elf_backend_data (output_bfd);
8345  relocate_section = bed->elf_backend_relocate_section;
8346
8347  /* If this is a dynamic object, we don't want to do anything here:
8348     we don't want the local symbols, and we don't want the section
8349     contents.  */
8350  if ((input_bfd->flags & DYNAMIC) != 0)
8351    return TRUE;
8352
8353  symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
8354  if (elf_bad_symtab (input_bfd))
8355    {
8356      locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
8357      extsymoff = 0;
8358    }
8359  else
8360    {
8361      locsymcount = symtab_hdr->sh_info;
8362      extsymoff = symtab_hdr->sh_info;
8363    }
8364
8365  /* Read the local symbols.  */
8366  isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
8367  if (isymbuf == NULL && locsymcount != 0)
8368    {
8369      isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
8370				      finfo->internal_syms,
8371				      finfo->external_syms,
8372				      finfo->locsym_shndx);
8373      if (isymbuf == NULL)
8374	return FALSE;
8375    }
8376  /* evaluate_complex_relocation_symbols looks for symbols in
8377     finfo->internal_syms.  */
8378  else if (isymbuf != NULL && locsymcount != 0)
8379    {
8380      bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
8381			    finfo->internal_syms,
8382			    finfo->external_syms,
8383			    finfo->locsym_shndx);
8384    }
8385
8386  /* Find local symbol sections and adjust values of symbols in
8387     SEC_MERGE sections.  Write out those local symbols we know are
8388     going into the output file.  */
8389  isymend = isymbuf + locsymcount;
8390  for (isym = isymbuf, pindex = finfo->indices, ppsection = finfo->sections;
8391       isym < isymend;
8392       isym++, pindex++, ppsection++)
8393    {
8394      asection *isec;
8395      const char *name;
8396      Elf_Internal_Sym osym;
8397
8398      *pindex = -1;
8399
8400      if (elf_bad_symtab (input_bfd))
8401	{
8402	  if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
8403	    {
8404	      *ppsection = NULL;
8405	      continue;
8406	    }
8407	}
8408
8409      if (isym->st_shndx == SHN_UNDEF)
8410	isec = bfd_und_section_ptr;
8411      else if (isym->st_shndx < SHN_LORESERVE
8412	       || isym->st_shndx > SHN_HIRESERVE)
8413	{
8414	  isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
8415	  if (isec
8416	      && isec->sec_info_type == ELF_INFO_TYPE_MERGE
8417	      && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
8418	    isym->st_value =
8419	      _bfd_merged_section_offset (output_bfd, &isec,
8420					  elf_section_data (isec)->sec_info,
8421					  isym->st_value);
8422	}
8423      else if (isym->st_shndx == SHN_ABS)
8424	isec = bfd_abs_section_ptr;
8425      else if (isym->st_shndx == SHN_COMMON)
8426	isec = bfd_com_section_ptr;
8427      else
8428	{
8429	  /* Don't attempt to output symbols with st_shnx in the
8430	     reserved range other than SHN_ABS and SHN_COMMON.  */
8431	  *ppsection = NULL;
8432	  continue;
8433	}
8434
8435      *ppsection = isec;
8436
8437      /* Don't output the first, undefined, symbol.  */
8438      if (ppsection == finfo->sections)
8439	continue;
8440
8441      if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
8442	{
8443	  /* We never output section symbols.  Instead, we use the
8444	     section symbol of the corresponding section in the output
8445	     file.  */
8446	  continue;
8447	}
8448
8449      /* If we are stripping all symbols, we don't want to output this
8450	 one.  */
8451      if (finfo->info->strip == strip_all)
8452	continue;
8453
8454      /* If we are discarding all local symbols, we don't want to
8455	 output this one.  If we are generating a relocatable output
8456	 file, then some of the local symbols may be required by
8457	 relocs; we output them below as we discover that they are
8458	 needed.  */
8459      if (finfo->info->discard == discard_all)
8460	continue;
8461
8462      /* If this symbol is defined in a section which we are
8463	 discarding, we don't need to keep it.  */
8464      if (isym->st_shndx != SHN_UNDEF
8465	  && (isym->st_shndx < SHN_LORESERVE || isym->st_shndx > SHN_HIRESERVE)
8466	  && (isec == NULL
8467	      || bfd_section_removed_from_list (output_bfd,
8468						isec->output_section)))
8469	continue;
8470
8471      /* Get the name of the symbol.  */
8472      name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
8473					      isym->st_name);
8474      if (name == NULL)
8475	return FALSE;
8476
8477      /* See if we are discarding symbols with this name.  */
8478      if ((finfo->info->strip == strip_some
8479	   && (bfd_hash_lookup (finfo->info->keep_hash, name, FALSE, FALSE)
8480	       == NULL))
8481	  || (((finfo->info->discard == discard_sec_merge
8482		&& (isec->flags & SEC_MERGE) && ! finfo->info->relocatable)
8483	       || finfo->info->discard == discard_l)
8484	      && bfd_is_local_label_name (input_bfd, name)))
8485	continue;
8486
8487      /* If we get here, we are going to output this symbol.  */
8488
8489      osym = *isym;
8490
8491      /* Adjust the section index for the output file.  */
8492      osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
8493							 isec->output_section);
8494      if (osym.st_shndx == SHN_BAD)
8495	return FALSE;
8496
8497      *pindex = bfd_get_symcount (output_bfd);
8498
8499      /* ELF symbols in relocatable files are section relative, but
8500	 in executable files they are virtual addresses.  Note that
8501	 this code assumes that all ELF sections have an associated
8502	 BFD section with a reasonable value for output_offset; below
8503	 we assume that they also have a reasonable value for
8504	 output_section.  Any special sections must be set up to meet
8505	 these requirements.  */
8506      osym.st_value += isec->output_offset;
8507      if (! finfo->info->relocatable)
8508	{
8509	  osym.st_value += isec->output_section->vma;
8510	  if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
8511	    {
8512	      /* STT_TLS symbols are relative to PT_TLS segment base.  */
8513	      BFD_ASSERT (elf_hash_table (finfo->info)->tls_sec != NULL);
8514	      osym.st_value -= elf_hash_table (finfo->info)->tls_sec->vma;
8515	    }
8516	}
8517
8518      if (! elf_link_output_sym (finfo, name, &osym, isec, NULL))
8519	return FALSE;
8520    }
8521
8522  if (! evaluate_complex_relocation_symbols (input_bfd, finfo, locsymcount))
8523    return FALSE;
8524
8525  /* Relocate the contents of each section.  */
8526  sym_hashes = elf_sym_hashes (input_bfd);
8527  for (o = input_bfd->sections; o != NULL; o = o->next)
8528    {
8529      bfd_byte *contents;
8530
8531      if (! o->linker_mark)
8532	{
8533	  /* This section was omitted from the link.  */
8534	  continue;
8535	}
8536
8537      if ((o->flags & SEC_HAS_CONTENTS) == 0
8538	  || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
8539	continue;
8540
8541      if ((o->flags & SEC_LINKER_CREATED) != 0)
8542	{
8543	  /* Section was created by _bfd_elf_link_create_dynamic_sections
8544	     or somesuch.  */
8545	  continue;
8546	}
8547
8548      /* Get the contents of the section.  They have been cached by a
8549	 relaxation routine.  Note that o is a section in an input
8550	 file, so the contents field will not have been set by any of
8551	 the routines which work on output files.  */
8552      if (elf_section_data (o)->this_hdr.contents != NULL)
8553	contents = elf_section_data (o)->this_hdr.contents;
8554      else
8555	{
8556	  bfd_size_type amt = o->rawsize ? o->rawsize : o->size;
8557
8558	  contents = finfo->contents;
8559	  if (! bfd_get_section_contents (input_bfd, o, contents, 0, amt))
8560	    return FALSE;
8561	}
8562
8563      if ((o->flags & SEC_RELOC) != 0)
8564	{
8565	  Elf_Internal_Rela *internal_relocs;
8566	  bfd_vma r_type_mask;
8567	  int r_sym_shift;
8568	  int ret;
8569
8570	  /* Get the swapped relocs.  */
8571	  internal_relocs
8572	    = _bfd_elf_link_read_relocs (input_bfd, o, finfo->external_relocs,
8573					 finfo->internal_relocs, FALSE);
8574	  if (internal_relocs == NULL
8575	      && o->reloc_count > 0)
8576	    return FALSE;
8577
8578	  if (bed->s->arch_size == 32)
8579	    {
8580	      r_type_mask = 0xff;
8581	      r_sym_shift = 8;
8582	    }
8583	  else
8584	    {
8585	      r_type_mask = 0xffffffff;
8586	      r_sym_shift = 32;
8587	    }
8588
8589	  /* Run through the relocs looking for any against symbols
8590	     from discarded sections and section symbols from
8591	     removed link-once sections.  Complain about relocs
8592	     against discarded sections.  Zero relocs against removed
8593	     link-once sections.  */
8594	  if (!elf_section_ignore_discarded_relocs (o))
8595	    {
8596	      Elf_Internal_Rela *rel, *relend;
8597	      unsigned int action = (*bed->action_discarded) (o);
8598
8599	      rel = internal_relocs;
8600	      relend = rel + o->reloc_count * bed->s->int_rels_per_ext_rel;
8601	      for ( ; rel < relend; rel++)
8602		{
8603		  unsigned long r_symndx = rel->r_info >> r_sym_shift;
8604		  asection **ps, *sec;
8605		  struct elf_link_hash_entry *h = NULL;
8606		  const char *sym_name;
8607
8608		  if (r_symndx == STN_UNDEF)
8609		    continue;
8610
8611		  if (r_symndx >= locsymcount
8612		      || (elf_bad_symtab (input_bfd)
8613			  && finfo->sections[r_symndx] == NULL))
8614		    {
8615		      h = sym_hashes[r_symndx - extsymoff];
8616
8617		      /* Badly formatted input files can contain relocs that
8618			 reference non-existant symbols.  Check here so that
8619			 we do not seg fault.  */
8620		      if (h == NULL)
8621			{
8622			  char buffer [32];
8623
8624			  sprintf_vma (buffer, rel->r_info);
8625			  (*_bfd_error_handler)
8626			    (_("error: %B contains a reloc (0x%s) for section %A "
8627			       "that references a non-existent global symbol"),
8628			     input_bfd, o, buffer);
8629			  bfd_set_error (bfd_error_bad_value);
8630			  return FALSE;
8631			}
8632
8633		      while (h->root.type == bfd_link_hash_indirect
8634			     || h->root.type == bfd_link_hash_warning)
8635			h = (struct elf_link_hash_entry *) h->root.u.i.link;
8636
8637		      if (h->root.type != bfd_link_hash_defined
8638			  && h->root.type != bfd_link_hash_defweak)
8639			continue;
8640
8641		      ps = &h->root.u.def.section;
8642		      sym_name = h->root.root.string;
8643		    }
8644		  else
8645		    {
8646		      Elf_Internal_Sym *sym = isymbuf + r_symndx;
8647		      ps = &finfo->sections[r_symndx];
8648		      sym_name = bfd_elf_sym_name (input_bfd,
8649						   symtab_hdr,
8650						   sym, *ps);
8651		    }
8652
8653		  /* Complain if the definition comes from a
8654		     discarded section.  */
8655		  if ((sec = *ps) != NULL && elf_discarded_section (sec))
8656		    {
8657		      BFD_ASSERT (r_symndx != 0);
8658		      if (action & COMPLAIN)
8659			(*finfo->info->callbacks->einfo)
8660			  (_("%X`%s' referenced in section `%A' of %B: "
8661			     "defined in discarded section `%A' of %B\n"),
8662			   sym_name, o, input_bfd, sec, sec->owner);
8663
8664		      /* Try to do the best we can to support buggy old
8665			 versions of gcc.  Pretend that the symbol is
8666			 really defined in the kept linkonce section.
8667			 FIXME: This is quite broken.  Modifying the
8668			 symbol here means we will be changing all later
8669			 uses of the symbol, not just in this section.  */
8670		      if (action & PRETEND)
8671			{
8672			  asection *kept;
8673
8674			  kept = _bfd_elf_check_kept_section (sec,
8675							      finfo->info);
8676			  if (kept != NULL)
8677			    {
8678			      *ps = kept;
8679			      continue;
8680			    }
8681			}
8682		    }
8683		}
8684	    }
8685
8686	  /* Relocate the section by invoking a back end routine.
8687
8688	     The back end routine is responsible for adjusting the
8689	     section contents as necessary, and (if using Rela relocs
8690	     and generating a relocatable output file) adjusting the
8691	     reloc addend as necessary.
8692
8693	     The back end routine does not have to worry about setting
8694	     the reloc address or the reloc symbol index.
8695
8696	     The back end routine is given a pointer to the swapped in
8697	     internal symbols, and can access the hash table entries
8698	     for the external symbols via elf_sym_hashes (input_bfd).
8699
8700	     When generating relocatable output, the back end routine
8701	     must handle STB_LOCAL/STT_SECTION symbols specially.  The
8702	     output symbol is going to be a section symbol
8703	     corresponding to the output section, which will require
8704	     the addend to be adjusted.  */
8705
8706	  ret = (*relocate_section) (output_bfd, finfo->info,
8707				     input_bfd, o, contents,
8708				     internal_relocs,
8709				     isymbuf,
8710				     finfo->sections);
8711	  if (!ret)
8712	    return FALSE;
8713
8714	  if (ret == 2
8715	      || finfo->info->relocatable
8716	      || finfo->info->emitrelocations)
8717	    {
8718	      Elf_Internal_Rela *irela;
8719	      Elf_Internal_Rela *irelaend;
8720	      bfd_vma last_offset;
8721	      struct elf_link_hash_entry **rel_hash;
8722	      struct elf_link_hash_entry **rel_hash_list;
8723	      Elf_Internal_Shdr *input_rel_hdr, *input_rel_hdr2;
8724	      unsigned int next_erel;
8725	      bfd_boolean rela_normal;
8726
8727	      input_rel_hdr = &elf_section_data (o)->rel_hdr;
8728	      rela_normal = (bed->rela_normal
8729			     && (input_rel_hdr->sh_entsize
8730				 == bed->s->sizeof_rela));
8731
8732	      /* Adjust the reloc addresses and symbol indices.  */
8733
8734	      irela = internal_relocs;
8735	      irelaend = irela + o->reloc_count * bed->s->int_rels_per_ext_rel;
8736	      rel_hash = (elf_section_data (o->output_section)->rel_hashes
8737			  + elf_section_data (o->output_section)->rel_count
8738			  + elf_section_data (o->output_section)->rel_count2);
8739	      rel_hash_list = rel_hash;
8740	      last_offset = o->output_offset;
8741	      if (!finfo->info->relocatable)
8742		last_offset += o->output_section->vma;
8743	      for (next_erel = 0; irela < irelaend; irela++, next_erel++)
8744		{
8745		  unsigned long r_symndx;
8746		  asection *sec;
8747		  Elf_Internal_Sym sym;
8748
8749		  if (next_erel == bed->s->int_rels_per_ext_rel)
8750		    {
8751		      rel_hash++;
8752		      next_erel = 0;
8753		    }
8754
8755		  irela->r_offset = _bfd_elf_section_offset (output_bfd,
8756							     finfo->info, o,
8757							     irela->r_offset);
8758		  if (irela->r_offset >= (bfd_vma) -2)
8759		    {
8760		      /* This is a reloc for a deleted entry or somesuch.
8761			 Turn it into an R_*_NONE reloc, at the same
8762			 offset as the last reloc.  elf_eh_frame.c and
8763			 bfd_elf_discard_info rely on reloc offsets
8764			 being ordered.  */
8765		      irela->r_offset = last_offset;
8766		      irela->r_info = 0;
8767		      irela->r_addend = 0;
8768		      continue;
8769		    }
8770
8771		  irela->r_offset += o->output_offset;
8772
8773		  /* Relocs in an executable have to be virtual addresses.  */
8774		  if (!finfo->info->relocatable)
8775		    irela->r_offset += o->output_section->vma;
8776
8777		  last_offset = irela->r_offset;
8778
8779		  r_symndx = irela->r_info >> r_sym_shift;
8780		  if (r_symndx == STN_UNDEF)
8781		    continue;
8782
8783		  if (r_symndx >= locsymcount
8784		      || (elf_bad_symtab (input_bfd)
8785			  && finfo->sections[r_symndx] == NULL))
8786		    {
8787		      struct elf_link_hash_entry *rh;
8788		      unsigned long indx;
8789
8790		      /* This is a reloc against a global symbol.  We
8791			 have not yet output all the local symbols, so
8792			 we do not know the symbol index of any global
8793			 symbol.  We set the rel_hash entry for this
8794			 reloc to point to the global hash table entry
8795			 for this symbol.  The symbol index is then
8796			 set at the end of bfd_elf_final_link.  */
8797		      indx = r_symndx - extsymoff;
8798		      rh = elf_sym_hashes (input_bfd)[indx];
8799		      while (rh->root.type == bfd_link_hash_indirect
8800			     || rh->root.type == bfd_link_hash_warning)
8801			rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
8802
8803		      /* Setting the index to -2 tells
8804			 elf_link_output_extsym that this symbol is
8805			 used by a reloc.  */
8806		      BFD_ASSERT (rh->indx < 0);
8807		      rh->indx = -2;
8808
8809		      *rel_hash = rh;
8810
8811		      continue;
8812		    }
8813
8814		  /* This is a reloc against a local symbol.  */
8815
8816		  *rel_hash = NULL;
8817		  sym = isymbuf[r_symndx];
8818		  sec = finfo->sections[r_symndx];
8819		  if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
8820		    {
8821		      /* I suppose the backend ought to fill in the
8822			 section of any STT_SECTION symbol against a
8823			 processor specific section.  */
8824		      r_symndx = 0;
8825		      if (bfd_is_abs_section (sec))
8826			;
8827		      else if (sec == NULL || sec->owner == NULL)
8828			{
8829			  bfd_set_error (bfd_error_bad_value);
8830			  return FALSE;
8831			}
8832		      else
8833			{
8834			  asection *osec = sec->output_section;
8835
8836			  /* If we have discarded a section, the output
8837			     section will be the absolute section.  In
8838			     case of discarded SEC_MERGE sections, use
8839			     the kept section.  relocate_section should
8840			     have already handled discarded linkonce
8841			     sections.  */
8842			  if (bfd_is_abs_section (osec)
8843			      && sec->kept_section != NULL
8844			      && sec->kept_section->output_section != NULL)
8845			    {
8846			      osec = sec->kept_section->output_section;
8847			      irela->r_addend -= osec->vma;
8848			    }
8849
8850			  if (!bfd_is_abs_section (osec))
8851			    {
8852			      r_symndx = osec->target_index;
8853			      if (r_symndx == 0)
8854				{
8855				  struct elf_link_hash_table *htab;
8856				  asection *oi;
8857
8858				  htab = elf_hash_table (finfo->info);
8859				  oi = htab->text_index_section;
8860				  if ((osec->flags & SEC_READONLY) == 0
8861				      && htab->data_index_section != NULL)
8862				    oi = htab->data_index_section;
8863
8864				  if (oi != NULL)
8865				    {
8866				      irela->r_addend += osec->vma - oi->vma;
8867				      r_symndx = oi->target_index;
8868				    }
8869				}
8870
8871			      BFD_ASSERT (r_symndx != 0);
8872			    }
8873			}
8874
8875		      /* Adjust the addend according to where the
8876			 section winds up in the output section.  */
8877		      if (rela_normal)
8878			irela->r_addend += sec->output_offset;
8879		    }
8880		  else
8881		    {
8882		      if (finfo->indices[r_symndx] == -1)
8883			{
8884			  unsigned long shlink;
8885			  const char *name;
8886			  asection *osec;
8887
8888			  if (finfo->info->strip == strip_all)
8889			    {
8890			      /* You can't do ld -r -s.  */
8891			      bfd_set_error (bfd_error_invalid_operation);
8892			      return FALSE;
8893			    }
8894
8895			  /* This symbol was skipped earlier, but
8896			     since it is needed by a reloc, we
8897			     must output it now.  */
8898			  shlink = symtab_hdr->sh_link;
8899			  name = (bfd_elf_string_from_elf_section
8900				  (input_bfd, shlink, sym.st_name));
8901			  if (name == NULL)
8902			    return FALSE;
8903
8904			  osec = sec->output_section;
8905			  sym.st_shndx =
8906			    _bfd_elf_section_from_bfd_section (output_bfd,
8907							       osec);
8908			  if (sym.st_shndx == SHN_BAD)
8909			    return FALSE;
8910
8911			  sym.st_value += sec->output_offset;
8912			  if (! finfo->info->relocatable)
8913			    {
8914			      sym.st_value += osec->vma;
8915			      if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
8916				{
8917				  /* STT_TLS symbols are relative to PT_TLS
8918				     segment base.  */
8919				  BFD_ASSERT (elf_hash_table (finfo->info)
8920					      ->tls_sec != NULL);
8921				  sym.st_value -= (elf_hash_table (finfo->info)
8922						   ->tls_sec->vma);
8923				}
8924			    }
8925
8926			  finfo->indices[r_symndx]
8927			    = bfd_get_symcount (output_bfd);
8928
8929			  if (! elf_link_output_sym (finfo, name, &sym, sec,
8930						     NULL))
8931			    return FALSE;
8932			}
8933
8934		      r_symndx = finfo->indices[r_symndx];
8935		    }
8936
8937		  irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
8938				   | (irela->r_info & r_type_mask));
8939		}
8940
8941	      /* Swap out the relocs.  */
8942	      if (input_rel_hdr->sh_size != 0
8943		  && !bed->elf_backend_emit_relocs (output_bfd, o,
8944						    input_rel_hdr,
8945						    internal_relocs,
8946						    rel_hash_list))
8947		return FALSE;
8948
8949	      input_rel_hdr2 = elf_section_data (o)->rel_hdr2;
8950	      if (input_rel_hdr2 && input_rel_hdr2->sh_size != 0)
8951		{
8952		  internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
8953				      * bed->s->int_rels_per_ext_rel);
8954		  rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
8955		  if (!bed->elf_backend_emit_relocs (output_bfd, o,
8956						     input_rel_hdr2,
8957						     internal_relocs,
8958						     rel_hash_list))
8959		    return FALSE;
8960		}
8961	    }
8962	}
8963
8964      /* Write out the modified section contents.  */
8965      if (bed->elf_backend_write_section
8966	  && (*bed->elf_backend_write_section) (output_bfd, finfo->info, o,
8967						contents))
8968	{
8969	  /* Section written out.  */
8970	}
8971      else switch (o->sec_info_type)
8972	{
8973	case ELF_INFO_TYPE_STABS:
8974	  if (! (_bfd_write_section_stabs
8975		 (output_bfd,
8976		  &elf_hash_table (finfo->info)->stab_info,
8977		  o, &elf_section_data (o)->sec_info, contents)))
8978	    return FALSE;
8979	  break;
8980	case ELF_INFO_TYPE_MERGE:
8981	  if (! _bfd_write_merged_section (output_bfd, o,
8982					   elf_section_data (o)->sec_info))
8983	    return FALSE;
8984	  break;
8985	case ELF_INFO_TYPE_EH_FRAME:
8986	  {
8987	    if (! _bfd_elf_write_section_eh_frame (output_bfd, finfo->info,
8988						   o, contents))
8989	      return FALSE;
8990	  }
8991	  break;
8992	default:
8993	  {
8994	    if (! (o->flags & SEC_EXCLUDE)
8995		&& ! bfd_set_section_contents (output_bfd, o->output_section,
8996					       contents,
8997					       (file_ptr) o->output_offset,
8998					       o->size))
8999	      return FALSE;
9000	  }
9001	  break;
9002	}
9003    }
9004
9005  return TRUE;
9006}
9007
9008/* Generate a reloc when linking an ELF file.  This is a reloc
9009   requested by the linker, and does not come from any input file.  This
9010   is used to build constructor and destructor tables when linking
9011   with -Ur.  */
9012
9013static bfd_boolean
9014elf_reloc_link_order (bfd *output_bfd,
9015		      struct bfd_link_info *info,
9016		      asection *output_section,
9017		      struct bfd_link_order *link_order)
9018{
9019  reloc_howto_type *howto;
9020  long indx;
9021  bfd_vma offset;
9022  bfd_vma addend;
9023  struct elf_link_hash_entry **rel_hash_ptr;
9024  Elf_Internal_Shdr *rel_hdr;
9025  const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
9026  Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
9027  bfd_byte *erel;
9028  unsigned int i;
9029
9030  howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
9031  if (howto == NULL)
9032    {
9033      bfd_set_error (bfd_error_bad_value);
9034      return FALSE;
9035    }
9036
9037  addend = link_order->u.reloc.p->addend;
9038
9039  /* Figure out the symbol index.  */
9040  rel_hash_ptr = (elf_section_data (output_section)->rel_hashes
9041		  + elf_section_data (output_section)->rel_count
9042		  + elf_section_data (output_section)->rel_count2);
9043  if (link_order->type == bfd_section_reloc_link_order)
9044    {
9045      indx = link_order->u.reloc.p->u.section->target_index;
9046      BFD_ASSERT (indx != 0);
9047      *rel_hash_ptr = NULL;
9048    }
9049  else
9050    {
9051      struct elf_link_hash_entry *h;
9052
9053      /* Treat a reloc against a defined symbol as though it were
9054	 actually against the section.  */
9055      h = ((struct elf_link_hash_entry *)
9056	   bfd_wrapped_link_hash_lookup (output_bfd, info,
9057					 link_order->u.reloc.p->u.name,
9058					 FALSE, FALSE, TRUE));
9059      if (h != NULL
9060	  && (h->root.type == bfd_link_hash_defined
9061	      || h->root.type == bfd_link_hash_defweak))
9062	{
9063	  asection *section;
9064
9065	  section = h->root.u.def.section;
9066	  indx = section->output_section->target_index;
9067	  *rel_hash_ptr = NULL;
9068	  /* It seems that we ought to add the symbol value to the
9069	     addend here, but in practice it has already been added
9070	     because it was passed to constructor_callback.  */
9071	  addend += section->output_section->vma + section->output_offset;
9072	}
9073      else if (h != NULL)
9074	{
9075	  /* Setting the index to -2 tells elf_link_output_extsym that
9076	     this symbol is used by a reloc.  */
9077	  h->indx = -2;
9078	  *rel_hash_ptr = h;
9079	  indx = 0;
9080	}
9081      else
9082	{
9083	  if (! ((*info->callbacks->unattached_reloc)
9084		 (info, link_order->u.reloc.p->u.name, NULL, NULL, 0)))
9085	    return FALSE;
9086	  indx = 0;
9087	}
9088    }
9089
9090  /* If this is an inplace reloc, we must write the addend into the
9091     object file.  */
9092  if (howto->partial_inplace && addend != 0)
9093    {
9094      bfd_size_type size;
9095      bfd_reloc_status_type rstat;
9096      bfd_byte *buf;
9097      bfd_boolean ok;
9098      const char *sym_name;
9099
9100      size = bfd_get_reloc_size (howto);
9101      buf = bfd_zmalloc (size);
9102      if (buf == NULL)
9103	return FALSE;
9104      rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
9105      switch (rstat)
9106	{
9107	case bfd_reloc_ok:
9108	  break;
9109
9110	default:
9111	case bfd_reloc_outofrange:
9112	  abort ();
9113
9114	case bfd_reloc_overflow:
9115	  if (link_order->type == bfd_section_reloc_link_order)
9116	    sym_name = bfd_section_name (output_bfd,
9117					 link_order->u.reloc.p->u.section);
9118	  else
9119	    sym_name = link_order->u.reloc.p->u.name;
9120	  if (! ((*info->callbacks->reloc_overflow)
9121		 (info, NULL, sym_name, howto->name, addend, NULL,
9122		  NULL, (bfd_vma) 0)))
9123	    {
9124	      free (buf);
9125	      return FALSE;
9126	    }
9127	  break;
9128	}
9129      ok = bfd_set_section_contents (output_bfd, output_section, buf,
9130				     link_order->offset, size);
9131      free (buf);
9132      if (! ok)
9133	return FALSE;
9134    }
9135
9136  /* The address of a reloc is relative to the section in a
9137     relocatable file, and is a virtual address in an executable
9138     file.  */
9139  offset = link_order->offset;
9140  if (! info->relocatable)
9141    offset += output_section->vma;
9142
9143  for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
9144    {
9145      irel[i].r_offset = offset;
9146      irel[i].r_info = 0;
9147      irel[i].r_addend = 0;
9148    }
9149  if (bed->s->arch_size == 32)
9150    irel[0].r_info = ELF32_R_INFO (indx, howto->type);
9151  else
9152    irel[0].r_info = ELF64_R_INFO (indx, howto->type);
9153
9154  rel_hdr = &elf_section_data (output_section)->rel_hdr;
9155  erel = rel_hdr->contents;
9156  if (rel_hdr->sh_type == SHT_REL)
9157    {
9158      erel += (elf_section_data (output_section)->rel_count
9159	       * bed->s->sizeof_rel);
9160      (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
9161    }
9162  else
9163    {
9164      irel[0].r_addend = addend;
9165      erel += (elf_section_data (output_section)->rel_count
9166	       * bed->s->sizeof_rela);
9167      (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
9168    }
9169
9170  ++elf_section_data (output_section)->rel_count;
9171
9172  return TRUE;
9173}
9174
9175
9176/* Get the output vma of the section pointed to by the sh_link field.  */
9177
9178static bfd_vma
9179elf_get_linked_section_vma (struct bfd_link_order *p)
9180{
9181  Elf_Internal_Shdr **elf_shdrp;
9182  asection *s;
9183  int elfsec;
9184
9185  s = p->u.indirect.section;
9186  elf_shdrp = elf_elfsections (s->owner);
9187  elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
9188  elfsec = elf_shdrp[elfsec]->sh_link;
9189  /* PR 290:
9190     The Intel C compiler generates SHT_IA_64_UNWIND with
9191     SHF_LINK_ORDER.  But it doesn't set the sh_link or
9192     sh_info fields.  Hence we could get the situation
9193     where elfsec is 0.  */
9194  if (elfsec == 0)
9195    {
9196      const struct elf_backend_data *bed
9197	= get_elf_backend_data (s->owner);
9198      if (bed->link_order_error_handler)
9199	bed->link_order_error_handler
9200	  (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
9201      return 0;
9202    }
9203  else
9204    {
9205      s = elf_shdrp[elfsec]->bfd_section;
9206      return s->output_section->vma + s->output_offset;
9207    }
9208}
9209
9210
9211/* Compare two sections based on the locations of the sections they are
9212   linked to.  Used by elf_fixup_link_order.  */
9213
9214static int
9215compare_link_order (const void * a, const void * b)
9216{
9217  bfd_vma apos;
9218  bfd_vma bpos;
9219
9220  apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
9221  bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
9222  if (apos < bpos)
9223    return -1;
9224  return apos > bpos;
9225}
9226
9227
9228/* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
9229   order as their linked sections.  Returns false if this could not be done
9230   because an output section includes both ordered and unordered
9231   sections.  Ideally we'd do this in the linker proper.  */
9232
9233static bfd_boolean
9234elf_fixup_link_order (bfd *abfd, asection *o)
9235{
9236  int seen_linkorder;
9237  int seen_other;
9238  int n;
9239  struct bfd_link_order *p;
9240  bfd *sub;
9241  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9242  unsigned elfsec;
9243  struct bfd_link_order **sections;
9244  asection *s, *other_sec, *linkorder_sec;
9245  bfd_vma offset;
9246
9247  other_sec = NULL;
9248  linkorder_sec = NULL;
9249  seen_other = 0;
9250  seen_linkorder = 0;
9251  for (p = o->map_head.link_order; p != NULL; p = p->next)
9252    {
9253      if (p->type == bfd_indirect_link_order)
9254	{
9255	  s = p->u.indirect.section;
9256	  sub = s->owner;
9257	  if (bfd_get_flavour (sub) == bfd_target_elf_flavour
9258	      && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
9259	      && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
9260	      && elfsec < elf_numsections (sub)
9261	      && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER)
9262	    {
9263	      seen_linkorder++;
9264	      linkorder_sec = s;
9265	    }
9266	  else
9267	    {
9268	      seen_other++;
9269	      other_sec = s;
9270	    }
9271	}
9272      else
9273	seen_other++;
9274
9275      if (seen_other && seen_linkorder)
9276	{
9277	  if (other_sec && linkorder_sec)
9278	    (*_bfd_error_handler) (_("%A has both ordered [`%A' in %B] and unordered [`%A' in %B] sections"),
9279				   o, linkorder_sec,
9280				   linkorder_sec->owner, other_sec,
9281				   other_sec->owner);
9282	  else
9283	    (*_bfd_error_handler) (_("%A has both ordered and unordered sections"),
9284				   o);
9285	  bfd_set_error (bfd_error_bad_value);
9286	  return FALSE;
9287	}
9288    }
9289
9290  if (!seen_linkorder)
9291    return TRUE;
9292
9293  sections = (struct bfd_link_order **)
9294    xmalloc (seen_linkorder * sizeof (struct bfd_link_order *));
9295  seen_linkorder = 0;
9296
9297  for (p = o->map_head.link_order; p != NULL; p = p->next)
9298    {
9299      sections[seen_linkorder++] = p;
9300    }
9301  /* Sort the input sections in the order of their linked section.  */
9302  qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
9303	 compare_link_order);
9304
9305  /* Change the offsets of the sections.  */
9306  offset = 0;
9307  for (n = 0; n < seen_linkorder; n++)
9308    {
9309      s = sections[n]->u.indirect.section;
9310      offset &= ~(bfd_vma)((1 << s->alignment_power) - 1);
9311      s->output_offset = offset;
9312      sections[n]->offset = offset;
9313      offset += sections[n]->size;
9314    }
9315
9316  return TRUE;
9317}
9318
9319
9320/* Do the final step of an ELF link.  */
9321
9322bfd_boolean
9323bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
9324{
9325  bfd_boolean dynamic;
9326  bfd_boolean emit_relocs;
9327  bfd *dynobj;
9328  struct elf_final_link_info finfo;
9329  register asection *o;
9330  register struct bfd_link_order *p;
9331  register bfd *sub;
9332  bfd_size_type max_contents_size;
9333  bfd_size_type max_external_reloc_size;
9334  bfd_size_type max_internal_reloc_count;
9335  bfd_size_type max_sym_count;
9336  bfd_size_type max_sym_shndx_count;
9337  file_ptr off;
9338  Elf_Internal_Sym elfsym;
9339  unsigned int i;
9340  Elf_Internal_Shdr *symtab_hdr;
9341  Elf_Internal_Shdr *symtab_shndx_hdr;
9342  Elf_Internal_Shdr *symstrtab_hdr;
9343  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9344  struct elf_outext_info eoinfo;
9345  bfd_boolean merged;
9346  size_t relativecount = 0;
9347  asection *reldyn = 0;
9348  bfd_size_type amt;
9349  asection *attr_section = NULL;
9350  bfd_vma attr_size = 0;
9351  const char *std_attrs_section;
9352
9353  if (! is_elf_hash_table (info->hash))
9354    return FALSE;
9355
9356  if (info->shared)
9357    abfd->flags |= DYNAMIC;
9358
9359  dynamic = elf_hash_table (info)->dynamic_sections_created;
9360  dynobj = elf_hash_table (info)->dynobj;
9361
9362  emit_relocs = (info->relocatable
9363		 || info->emitrelocations);
9364
9365  finfo.info = info;
9366  finfo.output_bfd = abfd;
9367  finfo.symstrtab = _bfd_elf_stringtab_init ();
9368  if (finfo.symstrtab == NULL)
9369    return FALSE;
9370
9371  if (! dynamic)
9372    {
9373      finfo.dynsym_sec = NULL;
9374      finfo.hash_sec = NULL;
9375      finfo.symver_sec = NULL;
9376    }
9377  else
9378    {
9379      finfo.dynsym_sec = bfd_get_section_by_name (dynobj, ".dynsym");
9380      finfo.hash_sec = bfd_get_section_by_name (dynobj, ".hash");
9381      BFD_ASSERT (finfo.dynsym_sec != NULL);
9382      finfo.symver_sec = bfd_get_section_by_name (dynobj, ".gnu.version");
9383      /* Note that it is OK if symver_sec is NULL.  */
9384    }
9385
9386  finfo.contents = NULL;
9387  finfo.external_relocs = NULL;
9388  finfo.internal_relocs = NULL;
9389  finfo.external_syms = NULL;
9390  finfo.locsym_shndx = NULL;
9391  finfo.internal_syms = NULL;
9392  finfo.indices = NULL;
9393  finfo.sections = NULL;
9394  finfo.symbuf = NULL;
9395  finfo.symshndxbuf = NULL;
9396  finfo.symbuf_count = 0;
9397  finfo.shndxbuf_size = 0;
9398
9399  /* The object attributes have been merged.  Remove the input
9400     sections from the link, and set the contents of the output
9401     secton.  */
9402  std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
9403  for (o = abfd->sections; o != NULL; o = o->next)
9404    {
9405      if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
9406	  || strcmp (o->name, ".gnu.attributes") == 0)
9407	{
9408	  for (p = o->map_head.link_order; p != NULL; p = p->next)
9409	    {
9410	      asection *input_section;
9411
9412	      if (p->type != bfd_indirect_link_order)
9413		continue;
9414	      input_section = p->u.indirect.section;
9415	      /* Hack: reset the SEC_HAS_CONTENTS flag so that
9416		 elf_link_input_bfd ignores this section.  */
9417	      input_section->flags &= ~SEC_HAS_CONTENTS;
9418	    }
9419
9420	  attr_size = bfd_elf_obj_attr_size (abfd);
9421	  if (attr_size)
9422	    {
9423	      bfd_set_section_size (abfd, o, attr_size);
9424	      attr_section = o;
9425	      /* Skip this section later on.  */
9426	      o->map_head.link_order = NULL;
9427	    }
9428	  else
9429	    o->flags |= SEC_EXCLUDE;
9430	}
9431    }
9432
9433  /* Count up the number of relocations we will output for each output
9434     section, so that we know the sizes of the reloc sections.  We
9435     also figure out some maximum sizes.  */
9436  max_contents_size = 0;
9437  max_external_reloc_size = 0;
9438  max_internal_reloc_count = 0;
9439  max_sym_count = 0;
9440  max_sym_shndx_count = 0;
9441  merged = FALSE;
9442  for (o = abfd->sections; o != NULL; o = o->next)
9443    {
9444      struct bfd_elf_section_data *esdo = elf_section_data (o);
9445      o->reloc_count = 0;
9446
9447      for (p = o->map_head.link_order; p != NULL; p = p->next)
9448	{
9449	  unsigned int reloc_count = 0;
9450	  struct bfd_elf_section_data *esdi = NULL;
9451	  unsigned int *rel_count1;
9452
9453	  if (p->type == bfd_section_reloc_link_order
9454	      || p->type == bfd_symbol_reloc_link_order)
9455	    reloc_count = 1;
9456	  else if (p->type == bfd_indirect_link_order)
9457	    {
9458	      asection *sec;
9459
9460	      sec = p->u.indirect.section;
9461	      esdi = elf_section_data (sec);
9462
9463	      /* Mark all sections which are to be included in the
9464		 link.  This will normally be every section.  We need
9465		 to do this so that we can identify any sections which
9466		 the linker has decided to not include.  */
9467	      sec->linker_mark = TRUE;
9468
9469	      if (sec->flags & SEC_MERGE)
9470		merged = TRUE;
9471
9472	      if (info->relocatable || info->emitrelocations)
9473		reloc_count = sec->reloc_count;
9474	      else if (bed->elf_backend_count_relocs)
9475		{
9476		  Elf_Internal_Rela * relocs;
9477
9478		  relocs = _bfd_elf_link_read_relocs (sec->owner, sec,
9479						      NULL, NULL,
9480						      info->keep_memory);
9481
9482		  if (relocs != NULL)
9483		    {
9484		      reloc_count
9485			= (*bed->elf_backend_count_relocs) (sec, relocs);
9486
9487		      if (elf_section_data (sec)->relocs != relocs)
9488			free (relocs);
9489		    }
9490		}
9491
9492	      if (sec->rawsize > max_contents_size)
9493		max_contents_size = sec->rawsize;
9494	      if (sec->size > max_contents_size)
9495		max_contents_size = sec->size;
9496
9497	      /* We are interested in just local symbols, not all
9498		 symbols.  */
9499	      if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
9500		  && (sec->owner->flags & DYNAMIC) == 0)
9501		{
9502		  size_t sym_count;
9503
9504		  if (elf_bad_symtab (sec->owner))
9505		    sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
9506				 / bed->s->sizeof_sym);
9507		  else
9508		    sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
9509
9510		  if (sym_count > max_sym_count)
9511		    max_sym_count = sym_count;
9512
9513		  if (sym_count > max_sym_shndx_count
9514		      && elf_symtab_shndx (sec->owner) != 0)
9515		    max_sym_shndx_count = sym_count;
9516
9517		  if ((sec->flags & SEC_RELOC) != 0)
9518		    {
9519		      size_t ext_size;
9520
9521		      ext_size = elf_section_data (sec)->rel_hdr.sh_size;
9522		      if (ext_size > max_external_reloc_size)
9523			max_external_reloc_size = ext_size;
9524		      if (sec->reloc_count > max_internal_reloc_count)
9525			max_internal_reloc_count = sec->reloc_count;
9526		    }
9527		}
9528	    }
9529
9530	  if (reloc_count == 0)
9531	    continue;
9532
9533	  o->reloc_count += reloc_count;
9534
9535	  /* MIPS may have a mix of REL and RELA relocs on sections.
9536	     To support this curious ABI we keep reloc counts in
9537	     elf_section_data too.  We must be careful to add the
9538	     relocations from the input section to the right output
9539	     count.  FIXME: Get rid of one count.  We have
9540	     o->reloc_count == esdo->rel_count + esdo->rel_count2.  */
9541	  rel_count1 = &esdo->rel_count;
9542	  if (esdi != NULL)
9543	    {
9544	      bfd_boolean same_size;
9545	      bfd_size_type entsize1;
9546
9547	      entsize1 = esdi->rel_hdr.sh_entsize;
9548	      BFD_ASSERT (entsize1 == bed->s->sizeof_rel
9549			  || entsize1 == bed->s->sizeof_rela);
9550	      same_size = !o->use_rela_p == (entsize1 == bed->s->sizeof_rel);
9551
9552	      if (!same_size)
9553		rel_count1 = &esdo->rel_count2;
9554
9555	      if (esdi->rel_hdr2 != NULL)
9556		{
9557		  bfd_size_type entsize2 = esdi->rel_hdr2->sh_entsize;
9558		  unsigned int alt_count;
9559		  unsigned int *rel_count2;
9560
9561		  BFD_ASSERT (entsize2 != entsize1
9562			      && (entsize2 == bed->s->sizeof_rel
9563				  || entsize2 == bed->s->sizeof_rela));
9564
9565		  rel_count2 = &esdo->rel_count2;
9566		  if (!same_size)
9567		    rel_count2 = &esdo->rel_count;
9568
9569		  /* The following is probably too simplistic if the
9570		     backend counts output relocs unusually.  */
9571		  BFD_ASSERT (bed->elf_backend_count_relocs == NULL);
9572		  alt_count = NUM_SHDR_ENTRIES (esdi->rel_hdr2);
9573		  *rel_count2 += alt_count;
9574		  reloc_count -= alt_count;
9575		}
9576	    }
9577	  *rel_count1 += reloc_count;
9578	}
9579
9580      if (o->reloc_count > 0)
9581	o->flags |= SEC_RELOC;
9582      else
9583	{
9584	  /* Explicitly clear the SEC_RELOC flag.  The linker tends to
9585	     set it (this is probably a bug) and if it is set
9586	     assign_section_numbers will create a reloc section.  */
9587	  o->flags &=~ SEC_RELOC;
9588	}
9589
9590      /* If the SEC_ALLOC flag is not set, force the section VMA to
9591	 zero.  This is done in elf_fake_sections as well, but forcing
9592	 the VMA to 0 here will ensure that relocs against these
9593	 sections are handled correctly.  */
9594      if ((o->flags & SEC_ALLOC) == 0
9595	  && ! o->user_set_vma)
9596	o->vma = 0;
9597    }
9598
9599  if (! info->relocatable && merged)
9600    elf_link_hash_traverse (elf_hash_table (info),
9601			    _bfd_elf_link_sec_merge_syms, abfd);
9602
9603  /* Figure out the file positions for everything but the symbol table
9604     and the relocs.  We set symcount to force assign_section_numbers
9605     to create a symbol table.  */
9606  bfd_get_symcount (abfd) = info->strip == strip_all ? 0 : 1;
9607  BFD_ASSERT (! abfd->output_has_begun);
9608  if (! _bfd_elf_compute_section_file_positions (abfd, info))
9609    goto error_return;
9610
9611  /* Set sizes, and assign file positions for reloc sections.  */
9612  for (o = abfd->sections; o != NULL; o = o->next)
9613    {
9614      if ((o->flags & SEC_RELOC) != 0)
9615	{
9616	  if (!(_bfd_elf_link_size_reloc_section
9617		(abfd, &elf_section_data (o)->rel_hdr, o)))
9618	    goto error_return;
9619
9620	  if (elf_section_data (o)->rel_hdr2
9621	      && !(_bfd_elf_link_size_reloc_section
9622		   (abfd, elf_section_data (o)->rel_hdr2, o)))
9623	    goto error_return;
9624	}
9625
9626      /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
9627	 to count upwards while actually outputting the relocations.  */
9628      elf_section_data (o)->rel_count = 0;
9629      elf_section_data (o)->rel_count2 = 0;
9630    }
9631
9632  _bfd_elf_assign_file_positions_for_relocs (abfd);
9633
9634  /* We have now assigned file positions for all the sections except
9635     .symtab and .strtab.  We start the .symtab section at the current
9636     file position, and write directly to it.  We build the .strtab
9637     section in memory.  */
9638  bfd_get_symcount (abfd) = 0;
9639  symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
9640  /* sh_name is set in prep_headers.  */
9641  symtab_hdr->sh_type = SHT_SYMTAB;
9642  /* sh_flags, sh_addr and sh_size all start off zero.  */
9643  symtab_hdr->sh_entsize = bed->s->sizeof_sym;
9644  /* sh_link is set in assign_section_numbers.  */
9645  /* sh_info is set below.  */
9646  /* sh_offset is set just below.  */
9647  symtab_hdr->sh_addralign = 1 << bed->s->log_file_align;
9648
9649  off = elf_tdata (abfd)->next_file_pos;
9650  off = _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
9651
9652  /* Note that at this point elf_tdata (abfd)->next_file_pos is
9653     incorrect.  We do not yet know the size of the .symtab section.
9654     We correct next_file_pos below, after we do know the size.  */
9655
9656  /* Allocate a buffer to hold swapped out symbols.  This is to avoid
9657     continuously seeking to the right position in the file.  */
9658  if (! info->keep_memory || max_sym_count < 20)
9659    finfo.symbuf_size = 20;
9660  else
9661    finfo.symbuf_size = max_sym_count;
9662  amt = finfo.symbuf_size;
9663  amt *= bed->s->sizeof_sym;
9664  finfo.symbuf = bfd_malloc (amt);
9665  if (finfo.symbuf == NULL)
9666    goto error_return;
9667  if (elf_numsections (abfd) > SHN_LORESERVE)
9668    {
9669      /* Wild guess at number of output symbols.  realloc'd as needed.  */
9670      amt = 2 * max_sym_count + elf_numsections (abfd) + 1000;
9671      finfo.shndxbuf_size = amt;
9672      amt *= sizeof (Elf_External_Sym_Shndx);
9673      finfo.symshndxbuf = bfd_zmalloc (amt);
9674      if (finfo.symshndxbuf == NULL)
9675	goto error_return;
9676    }
9677
9678  /* Start writing out the symbol table.  The first symbol is always a
9679     dummy symbol.  */
9680  if (info->strip != strip_all
9681      || emit_relocs)
9682    {
9683      elfsym.st_value = 0;
9684      elfsym.st_size = 0;
9685      elfsym.st_info = 0;
9686      elfsym.st_other = 0;
9687      elfsym.st_shndx = SHN_UNDEF;
9688      if (! elf_link_output_sym (&finfo, NULL, &elfsym, bfd_und_section_ptr,
9689				 NULL))
9690	goto error_return;
9691    }
9692
9693  /* Output a symbol for each section.  We output these even if we are
9694     discarding local symbols, since they are used for relocs.  These
9695     symbols have no names.  We store the index of each one in the
9696     index field of the section, so that we can find it again when
9697     outputting relocs.  */
9698  if (info->strip != strip_all
9699      || emit_relocs)
9700    {
9701      elfsym.st_size = 0;
9702      elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
9703      elfsym.st_other = 0;
9704      elfsym.st_value = 0;
9705      for (i = 1; i < elf_numsections (abfd); i++)
9706	{
9707	  o = bfd_section_from_elf_index (abfd, i);
9708	  if (o != NULL)
9709	    {
9710	      o->target_index = bfd_get_symcount (abfd);
9711	      elfsym.st_shndx = i;
9712	      if (!info->relocatable)
9713		elfsym.st_value = o->vma;
9714	      if (!elf_link_output_sym (&finfo, NULL, &elfsym, o, NULL))
9715		goto error_return;
9716	    }
9717	  if (i == SHN_LORESERVE - 1)
9718	    i += SHN_HIRESERVE + 1 - SHN_LORESERVE;
9719	}
9720    }
9721
9722  /* Allocate some memory to hold information read in from the input
9723     files.  */
9724  if (max_contents_size != 0)
9725    {
9726      finfo.contents = bfd_malloc (max_contents_size);
9727      if (finfo.contents == NULL)
9728	goto error_return;
9729    }
9730
9731  if (max_external_reloc_size != 0)
9732    {
9733      finfo.external_relocs = bfd_malloc (max_external_reloc_size);
9734      if (finfo.external_relocs == NULL)
9735	goto error_return;
9736    }
9737
9738  if (max_internal_reloc_count != 0)
9739    {
9740      amt = max_internal_reloc_count * bed->s->int_rels_per_ext_rel;
9741      amt *= sizeof (Elf_Internal_Rela);
9742      finfo.internal_relocs = bfd_malloc (amt);
9743      if (finfo.internal_relocs == NULL)
9744	goto error_return;
9745    }
9746
9747  if (max_sym_count != 0)
9748    {
9749      amt = max_sym_count * bed->s->sizeof_sym;
9750      finfo.external_syms = bfd_malloc (amt);
9751      if (finfo.external_syms == NULL)
9752	goto error_return;
9753
9754      amt = max_sym_count * sizeof (Elf_Internal_Sym);
9755      finfo.internal_syms = bfd_malloc (amt);
9756      if (finfo.internal_syms == NULL)
9757	goto error_return;
9758
9759      amt = max_sym_count * sizeof (long);
9760      finfo.indices = bfd_malloc (amt);
9761      if (finfo.indices == NULL)
9762	goto error_return;
9763
9764      amt = max_sym_count * sizeof (asection *);
9765      finfo.sections = bfd_malloc (amt);
9766      if (finfo.sections == NULL)
9767	goto error_return;
9768    }
9769
9770  if (max_sym_shndx_count != 0)
9771    {
9772      amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
9773      finfo.locsym_shndx = bfd_malloc (amt);
9774      if (finfo.locsym_shndx == NULL)
9775	goto error_return;
9776    }
9777
9778  if (elf_hash_table (info)->tls_sec)
9779    {
9780      bfd_vma base, end = 0;
9781      asection *sec;
9782
9783      for (sec = elf_hash_table (info)->tls_sec;
9784	   sec && (sec->flags & SEC_THREAD_LOCAL);
9785	   sec = sec->next)
9786	{
9787	  bfd_size_type size = sec->size;
9788
9789	  if (size == 0
9790	      && (sec->flags & SEC_HAS_CONTENTS) == 0)
9791	    {
9792	      struct bfd_link_order *o = sec->map_tail.link_order;
9793	      if (o != NULL)
9794		size = o->offset + o->size;
9795	    }
9796	  end = sec->vma + size;
9797	}
9798      base = elf_hash_table (info)->tls_sec->vma;
9799      end = align_power (end, elf_hash_table (info)->tls_sec->alignment_power);
9800      elf_hash_table (info)->tls_size = end - base;
9801    }
9802
9803  /* Reorder SHF_LINK_ORDER sections.  */
9804  for (o = abfd->sections; o != NULL; o = o->next)
9805    {
9806      if (!elf_fixup_link_order (abfd, o))
9807	return FALSE;
9808    }
9809
9810  /* Since ELF permits relocations to be against local symbols, we
9811     must have the local symbols available when we do the relocations.
9812     Since we would rather only read the local symbols once, and we
9813     would rather not keep them in memory, we handle all the
9814     relocations for a single input file at the same time.
9815
9816     Unfortunately, there is no way to know the total number of local
9817     symbols until we have seen all of them, and the local symbol
9818     indices precede the global symbol indices.  This means that when
9819     we are generating relocatable output, and we see a reloc against
9820     a global symbol, we can not know the symbol index until we have
9821     finished examining all the local symbols to see which ones we are
9822     going to output.  To deal with this, we keep the relocations in
9823     memory, and don't output them until the end of the link.  This is
9824     an unfortunate waste of memory, but I don't see a good way around
9825     it.  Fortunately, it only happens when performing a relocatable
9826     link, which is not the common case.  FIXME: If keep_memory is set
9827     we could write the relocs out and then read them again; I don't
9828     know how bad the memory loss will be.  */
9829
9830  for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
9831    sub->output_has_begun = FALSE;
9832  for (o = abfd->sections; o != NULL; o = o->next)
9833    {
9834      for (p = o->map_head.link_order; p != NULL; p = p->next)
9835	{
9836	  if (p->type == bfd_indirect_link_order
9837	      && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
9838		  == bfd_target_elf_flavour)
9839	      && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
9840	    {
9841	      if (! sub->output_has_begun)
9842		{
9843		  if (! elf_link_input_bfd (&finfo, sub))
9844		    goto error_return;
9845		  sub->output_has_begun = TRUE;
9846		}
9847	    }
9848	  else if (p->type == bfd_section_reloc_link_order
9849		   || p->type == bfd_symbol_reloc_link_order)
9850	    {
9851	      if (! elf_reloc_link_order (abfd, info, o, p))
9852		goto error_return;
9853	    }
9854	  else
9855	    {
9856	      if (! _bfd_default_link_order (abfd, info, o, p))
9857		goto error_return;
9858	    }
9859	}
9860    }
9861
9862  /* Free symbol buffer if needed.  */
9863  if (!info->reduce_memory_overheads)
9864    {
9865      for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
9866	if (bfd_get_flavour (sub) == bfd_target_elf_flavour
9867	    && elf_tdata (sub)->symbuf)
9868	  {
9869	    free (elf_tdata (sub)->symbuf);
9870	    elf_tdata (sub)->symbuf = NULL;
9871	  }
9872    }
9873
9874  /* Output any global symbols that got converted to local in a
9875     version script or due to symbol visibility.  We do this in a
9876     separate step since ELF requires all local symbols to appear
9877     prior to any global symbols.  FIXME: We should only do this if
9878     some global symbols were, in fact, converted to become local.
9879     FIXME: Will this work correctly with the Irix 5 linker?  */
9880  eoinfo.failed = FALSE;
9881  eoinfo.finfo = &finfo;
9882  eoinfo.localsyms = TRUE;
9883  elf_link_hash_traverse (elf_hash_table (info), elf_link_output_extsym,
9884			  &eoinfo);
9885  if (eoinfo.failed)
9886    return FALSE;
9887
9888  /* If backend needs to output some local symbols not present in the hash
9889     table, do it now.  */
9890  if (bed->elf_backend_output_arch_local_syms)
9891    {
9892      typedef bfd_boolean (*out_sym_func)
9893	(void *, const char *, Elf_Internal_Sym *, asection *,
9894	 struct elf_link_hash_entry *);
9895
9896      if (! ((*bed->elf_backend_output_arch_local_syms)
9897	     (abfd, info, &finfo, (out_sym_func) elf_link_output_sym)))
9898	return FALSE;
9899    }
9900
9901  /* That wrote out all the local symbols.  Finish up the symbol table
9902     with the global symbols. Even if we want to strip everything we
9903     can, we still need to deal with those global symbols that got
9904     converted to local in a version script.  */
9905
9906  /* The sh_info field records the index of the first non local symbol.  */
9907  symtab_hdr->sh_info = bfd_get_symcount (abfd);
9908
9909  if (dynamic
9910      && finfo.dynsym_sec->output_section != bfd_abs_section_ptr)
9911    {
9912      Elf_Internal_Sym sym;
9913      bfd_byte *dynsym = finfo.dynsym_sec->contents;
9914      long last_local = 0;
9915
9916      /* Write out the section symbols for the output sections.  */
9917      if (info->shared || elf_hash_table (info)->is_relocatable_executable)
9918	{
9919	  asection *s;
9920
9921	  sym.st_size = 0;
9922	  sym.st_name = 0;
9923	  sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
9924	  sym.st_other = 0;
9925
9926	  for (s = abfd->sections; s != NULL; s = s->next)
9927	    {
9928	      int indx;
9929	      bfd_byte *dest;
9930	      long dynindx;
9931
9932	      dynindx = elf_section_data (s)->dynindx;
9933	      if (dynindx <= 0)
9934		continue;
9935	      indx = elf_section_data (s)->this_idx;
9936	      BFD_ASSERT (indx > 0);
9937	      sym.st_shndx = indx;
9938	      if (! check_dynsym (abfd, &sym))
9939		return FALSE;
9940	      sym.st_value = s->vma;
9941	      dest = dynsym + dynindx * bed->s->sizeof_sym;
9942	      if (last_local < dynindx)
9943		last_local = dynindx;
9944	      bed->s->swap_symbol_out (abfd, &sym, dest, 0);
9945	    }
9946	}
9947
9948      /* Write out the local dynsyms.  */
9949      if (elf_hash_table (info)->dynlocal)
9950	{
9951	  struct elf_link_local_dynamic_entry *e;
9952	  for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
9953	    {
9954	      asection *s;
9955	      bfd_byte *dest;
9956
9957	      sym.st_size = e->isym.st_size;
9958	      sym.st_other = e->isym.st_other;
9959
9960	      /* Copy the internal symbol as is.
9961		 Note that we saved a word of storage and overwrote
9962		 the original st_name with the dynstr_index.  */
9963	      sym = e->isym;
9964
9965	      if (e->isym.st_shndx != SHN_UNDEF
9966		  && (e->isym.st_shndx < SHN_LORESERVE
9967		      || e->isym.st_shndx > SHN_HIRESERVE))
9968		{
9969		  s = bfd_section_from_elf_index (e->input_bfd,
9970						  e->isym.st_shndx);
9971
9972		  sym.st_shndx =
9973		    elf_section_data (s->output_section)->this_idx;
9974		  if (! check_dynsym (abfd, &sym))
9975		    return FALSE;
9976		  sym.st_value = (s->output_section->vma
9977				  + s->output_offset
9978				  + e->isym.st_value);
9979		}
9980
9981	      if (last_local < e->dynindx)
9982		last_local = e->dynindx;
9983
9984	      dest = dynsym + e->dynindx * bed->s->sizeof_sym;
9985	      bed->s->swap_symbol_out (abfd, &sym, dest, 0);
9986	    }
9987	}
9988
9989      elf_section_data (finfo.dynsym_sec->output_section)->this_hdr.sh_info =
9990	last_local + 1;
9991    }
9992
9993  /* We get the global symbols from the hash table.  */
9994  eoinfo.failed = FALSE;
9995  eoinfo.localsyms = FALSE;
9996  eoinfo.finfo = &finfo;
9997  elf_link_hash_traverse (elf_hash_table (info), elf_link_output_extsym,
9998			  &eoinfo);
9999  if (eoinfo.failed)
10000    return FALSE;
10001
10002  /* If backend needs to output some symbols not present in the hash
10003     table, do it now.  */
10004  if (bed->elf_backend_output_arch_syms)
10005    {
10006      typedef bfd_boolean (*out_sym_func)
10007	(void *, const char *, Elf_Internal_Sym *, asection *,
10008	 struct elf_link_hash_entry *);
10009
10010      if (! ((*bed->elf_backend_output_arch_syms)
10011	     (abfd, info, &finfo, (out_sym_func) elf_link_output_sym)))
10012	return FALSE;
10013    }
10014
10015  /* Flush all symbols to the file.  */
10016  if (! elf_link_flush_output_syms (&finfo, bed))
10017    return FALSE;
10018
10019  /* Now we know the size of the symtab section.  */
10020  off += symtab_hdr->sh_size;
10021
10022  symtab_shndx_hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
10023  if (symtab_shndx_hdr->sh_name != 0)
10024    {
10025      symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
10026      symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
10027      symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
10028      amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
10029      symtab_shndx_hdr->sh_size = amt;
10030
10031      off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
10032						       off, TRUE);
10033
10034      if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
10035	  || (bfd_bwrite (finfo.symshndxbuf, amt, abfd) != amt))
10036	return FALSE;
10037    }
10038
10039
10040  /* Finish up and write out the symbol string table (.strtab)
10041     section.  */
10042  symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
10043  /* sh_name was set in prep_headers.  */
10044  symstrtab_hdr->sh_type = SHT_STRTAB;
10045  symstrtab_hdr->sh_flags = 0;
10046  symstrtab_hdr->sh_addr = 0;
10047  symstrtab_hdr->sh_size = _bfd_stringtab_size (finfo.symstrtab);
10048  symstrtab_hdr->sh_entsize = 0;
10049  symstrtab_hdr->sh_link = 0;
10050  symstrtab_hdr->sh_info = 0;
10051  /* sh_offset is set just below.  */
10052  symstrtab_hdr->sh_addralign = 1;
10053
10054  off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr, off, TRUE);
10055  elf_tdata (abfd)->next_file_pos = off;
10056
10057  if (bfd_get_symcount (abfd) > 0)
10058    {
10059      if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
10060	  || ! _bfd_stringtab_emit (abfd, finfo.symstrtab))
10061	return FALSE;
10062    }
10063
10064  /* Adjust the relocs to have the correct symbol indices.  */
10065  for (o = abfd->sections; o != NULL; o = o->next)
10066    {
10067      if ((o->flags & SEC_RELOC) == 0)
10068	continue;
10069
10070      elf_link_adjust_relocs (abfd, &elf_section_data (o)->rel_hdr,
10071			      elf_section_data (o)->rel_count,
10072			      elf_section_data (o)->rel_hashes);
10073      if (elf_section_data (o)->rel_hdr2 != NULL)
10074	elf_link_adjust_relocs (abfd, elf_section_data (o)->rel_hdr2,
10075				elf_section_data (o)->rel_count2,
10076				(elf_section_data (o)->rel_hashes
10077				 + elf_section_data (o)->rel_count));
10078
10079      /* Set the reloc_count field to 0 to prevent write_relocs from
10080	 trying to swap the relocs out itself.  */
10081      o->reloc_count = 0;
10082    }
10083
10084  if (dynamic && info->combreloc && dynobj != NULL)
10085    relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
10086
10087  /* If we are linking against a dynamic object, or generating a
10088     shared library, finish up the dynamic linking information.  */
10089  if (dynamic)
10090    {
10091      bfd_byte *dyncon, *dynconend;
10092
10093      /* Fix up .dynamic entries.  */
10094      o = bfd_get_section_by_name (dynobj, ".dynamic");
10095      BFD_ASSERT (o != NULL);
10096
10097      dyncon = o->contents;
10098      dynconend = o->contents + o->size;
10099      for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
10100	{
10101	  Elf_Internal_Dyn dyn;
10102	  const char *name;
10103	  unsigned int type;
10104
10105	  bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
10106
10107	  switch (dyn.d_tag)
10108	    {
10109	    default:
10110	      continue;
10111	    case DT_NULL:
10112	      if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
10113		{
10114		  switch (elf_section_data (reldyn)->this_hdr.sh_type)
10115		    {
10116		    case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
10117		    case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
10118		    default: continue;
10119		    }
10120		  dyn.d_un.d_val = relativecount;
10121		  relativecount = 0;
10122		  break;
10123		}
10124	      continue;
10125
10126	    case DT_INIT:
10127	      name = info->init_function;
10128	      goto get_sym;
10129	    case DT_FINI:
10130	      name = info->fini_function;
10131	    get_sym:
10132	      {
10133		struct elf_link_hash_entry *h;
10134
10135		h = elf_link_hash_lookup (elf_hash_table (info), name,
10136					  FALSE, FALSE, TRUE);
10137		if (h != NULL
10138		    && (h->root.type == bfd_link_hash_defined
10139			|| h->root.type == bfd_link_hash_defweak))
10140		  {
10141		    dyn.d_un.d_val = h->root.u.def.value;
10142		    o = h->root.u.def.section;
10143		    if (o->output_section != NULL)
10144		      dyn.d_un.d_val += (o->output_section->vma
10145					 + o->output_offset);
10146		    else
10147		      {
10148			/* The symbol is imported from another shared
10149			   library and does not apply to this one.  */
10150			dyn.d_un.d_val = 0;
10151		      }
10152		    break;
10153		  }
10154	      }
10155	      continue;
10156
10157	    case DT_PREINIT_ARRAYSZ:
10158	      name = ".preinit_array";
10159	      goto get_size;
10160	    case DT_INIT_ARRAYSZ:
10161	      name = ".init_array";
10162	      goto get_size;
10163	    case DT_FINI_ARRAYSZ:
10164	      name = ".fini_array";
10165	    get_size:
10166	      o = bfd_get_section_by_name (abfd, name);
10167	      if (o == NULL)
10168		{
10169		  (*_bfd_error_handler)
10170		    (_("%B: could not find output section %s"), abfd, name);
10171		  goto error_return;
10172		}
10173	      if (o->size == 0)
10174		(*_bfd_error_handler)
10175		  (_("warning: %s section has zero size"), name);
10176	      dyn.d_un.d_val = o->size;
10177	      break;
10178
10179	    case DT_PREINIT_ARRAY:
10180	      name = ".preinit_array";
10181	      goto get_vma;
10182	    case DT_INIT_ARRAY:
10183	      name = ".init_array";
10184	      goto get_vma;
10185	    case DT_FINI_ARRAY:
10186	      name = ".fini_array";
10187	      goto get_vma;
10188
10189	    case DT_HASH:
10190	      name = ".hash";
10191	      goto get_vma;
10192	    case DT_GNU_HASH:
10193	      name = ".gnu.hash";
10194	      goto get_vma;
10195	    case DT_STRTAB:
10196	      name = ".dynstr";
10197	      goto get_vma;
10198	    case DT_SYMTAB:
10199	      name = ".dynsym";
10200	      goto get_vma;
10201	    case DT_VERDEF:
10202	      name = ".gnu.version_d";
10203	      goto get_vma;
10204	    case DT_VERNEED:
10205	      name = ".gnu.version_r";
10206	      goto get_vma;
10207	    case DT_VERSYM:
10208	      name = ".gnu.version";
10209	    get_vma:
10210	      o = bfd_get_section_by_name (abfd, name);
10211	      if (o == NULL)
10212		{
10213		  (*_bfd_error_handler)
10214		    (_("%B: could not find output section %s"), abfd, name);
10215		  goto error_return;
10216		}
10217	      dyn.d_un.d_ptr = o->vma;
10218	      break;
10219
10220	    case DT_REL:
10221	    case DT_RELA:
10222	    case DT_RELSZ:
10223	    case DT_RELASZ:
10224	      if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
10225		type = SHT_REL;
10226	      else
10227		type = SHT_RELA;
10228	      dyn.d_un.d_val = 0;
10229	      for (i = 1; i < elf_numsections (abfd); i++)
10230		{
10231		  Elf_Internal_Shdr *hdr;
10232
10233		  hdr = elf_elfsections (abfd)[i];
10234		  if (hdr->sh_type == type
10235		      && (hdr->sh_flags & SHF_ALLOC) != 0)
10236		    {
10237		      if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
10238			dyn.d_un.d_val += hdr->sh_size;
10239		      else
10240			{
10241			  if (dyn.d_un.d_val == 0
10242			      || hdr->sh_addr < dyn.d_un.d_val)
10243			    dyn.d_un.d_val = hdr->sh_addr;
10244			}
10245		    }
10246		}
10247	      break;
10248	    }
10249	  bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
10250	}
10251    }
10252
10253  /* If we have created any dynamic sections, then output them.  */
10254  if (dynobj != NULL)
10255    {
10256      if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
10257	goto error_return;
10258
10259      /* Check for DT_TEXTREL (late, in case the backend removes it).  */
10260      if (info->warn_shared_textrel && info->shared)
10261	{
10262	  bfd_byte *dyncon, *dynconend;
10263
10264	  /* Fix up .dynamic entries.  */
10265	  o = bfd_get_section_by_name (dynobj, ".dynamic");
10266	  BFD_ASSERT (o != NULL);
10267
10268	  dyncon = o->contents;
10269	  dynconend = o->contents + o->size;
10270	  for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
10271	    {
10272	      Elf_Internal_Dyn dyn;
10273
10274	      bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
10275
10276	      if (dyn.d_tag == DT_TEXTREL)
10277		{
10278		 info->callbacks->einfo
10279		    (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
10280		  break;
10281		}
10282	    }
10283	}
10284
10285      for (o = dynobj->sections; o != NULL; o = o->next)
10286	{
10287	  if ((o->flags & SEC_HAS_CONTENTS) == 0
10288	      || o->size == 0
10289	      || o->output_section == bfd_abs_section_ptr)
10290	    continue;
10291	  if ((o->flags & SEC_LINKER_CREATED) == 0)
10292	    {
10293	      /* At this point, we are only interested in sections
10294		 created by _bfd_elf_link_create_dynamic_sections.  */
10295	      continue;
10296	    }
10297	  if (elf_hash_table (info)->stab_info.stabstr == o)
10298	    continue;
10299	  if (elf_hash_table (info)->eh_info.hdr_sec == o)
10300	    continue;
10301	  if ((elf_section_data (o->output_section)->this_hdr.sh_type
10302	       != SHT_STRTAB)
10303	      || strcmp (bfd_get_section_name (abfd, o), ".dynstr") != 0)
10304	    {
10305	      if (! bfd_set_section_contents (abfd, o->output_section,
10306					      o->contents,
10307					      (file_ptr) o->output_offset,
10308					      o->size))
10309		goto error_return;
10310	    }
10311	  else
10312	    {
10313	      /* The contents of the .dynstr section are actually in a
10314		 stringtab.  */
10315	      off = elf_section_data (o->output_section)->this_hdr.sh_offset;
10316	      if (bfd_seek (abfd, off, SEEK_SET) != 0
10317		  || ! _bfd_elf_strtab_emit (abfd,
10318					     elf_hash_table (info)->dynstr))
10319		goto error_return;
10320	    }
10321	}
10322    }
10323
10324  if (info->relocatable)
10325    {
10326      bfd_boolean failed = FALSE;
10327
10328      bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
10329      if (failed)
10330	goto error_return;
10331    }
10332
10333  /* If we have optimized stabs strings, output them.  */
10334  if (elf_hash_table (info)->stab_info.stabstr != NULL)
10335    {
10336      if (! _bfd_write_stab_strings (abfd, &elf_hash_table (info)->stab_info))
10337	goto error_return;
10338    }
10339
10340  if (info->eh_frame_hdr)
10341    {
10342      if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
10343	goto error_return;
10344    }
10345
10346  if (finfo.symstrtab != NULL)
10347    _bfd_stringtab_free (finfo.symstrtab);
10348  if (finfo.contents != NULL)
10349    free (finfo.contents);
10350  if (finfo.external_relocs != NULL)
10351    free (finfo.external_relocs);
10352  if (finfo.internal_relocs != NULL)
10353    free (finfo.internal_relocs);
10354  if (finfo.external_syms != NULL)
10355    free (finfo.external_syms);
10356  if (finfo.locsym_shndx != NULL)
10357    free (finfo.locsym_shndx);
10358  if (finfo.internal_syms != NULL)
10359    free (finfo.internal_syms);
10360  if (finfo.indices != NULL)
10361    free (finfo.indices);
10362  if (finfo.sections != NULL)
10363    free (finfo.sections);
10364  if (finfo.symbuf != NULL)
10365    free (finfo.symbuf);
10366  if (finfo.symshndxbuf != NULL)
10367    free (finfo.symshndxbuf);
10368  for (o = abfd->sections; o != NULL; o = o->next)
10369    {
10370      if ((o->flags & SEC_RELOC) != 0
10371	  && elf_section_data (o)->rel_hashes != NULL)
10372	free (elf_section_data (o)->rel_hashes);
10373    }
10374
10375  elf_tdata (abfd)->linker = TRUE;
10376
10377  if (attr_section)
10378    {
10379      bfd_byte *contents = bfd_malloc (attr_size);
10380      if (contents == NULL)
10381	goto error_return;
10382      bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
10383      bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
10384      free (contents);
10385    }
10386
10387  return TRUE;
10388
10389 error_return:
10390  if (finfo.symstrtab != NULL)
10391    _bfd_stringtab_free (finfo.symstrtab);
10392  if (finfo.contents != NULL)
10393    free (finfo.contents);
10394  if (finfo.external_relocs != NULL)
10395    free (finfo.external_relocs);
10396  if (finfo.internal_relocs != NULL)
10397    free (finfo.internal_relocs);
10398  if (finfo.external_syms != NULL)
10399    free (finfo.external_syms);
10400  if (finfo.locsym_shndx != NULL)
10401    free (finfo.locsym_shndx);
10402  if (finfo.internal_syms != NULL)
10403    free (finfo.internal_syms);
10404  if (finfo.indices != NULL)
10405    free (finfo.indices);
10406  if (finfo.sections != NULL)
10407    free (finfo.sections);
10408  if (finfo.symbuf != NULL)
10409    free (finfo.symbuf);
10410  if (finfo.symshndxbuf != NULL)
10411    free (finfo.symshndxbuf);
10412  for (o = abfd->sections; o != NULL; o = o->next)
10413    {
10414      if ((o->flags & SEC_RELOC) != 0
10415	  && elf_section_data (o)->rel_hashes != NULL)
10416	free (elf_section_data (o)->rel_hashes);
10417    }
10418
10419  return FALSE;
10420}
10421
10422/* Garbage collect unused sections.  */
10423
10424/* Default gc_mark_hook.  */
10425
10426asection *
10427_bfd_elf_gc_mark_hook (asection *sec,
10428		       struct bfd_link_info *info ATTRIBUTE_UNUSED,
10429		       Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
10430		       struct elf_link_hash_entry *h,
10431		       Elf_Internal_Sym *sym)
10432{
10433  if (h != NULL)
10434    {
10435      switch (h->root.type)
10436	{
10437	case bfd_link_hash_defined:
10438	case bfd_link_hash_defweak:
10439	  return h->root.u.def.section;
10440
10441	case bfd_link_hash_common:
10442	  return h->root.u.c.p->section;
10443
10444	default:
10445	  break;
10446	}
10447    }
10448  else
10449    return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
10450
10451  return NULL;
10452}
10453
10454/* The mark phase of garbage collection.  For a given section, mark
10455   it and any sections in this section's group, and all the sections
10456   which define symbols to which it refers.  */
10457
10458bfd_boolean
10459_bfd_elf_gc_mark (struct bfd_link_info *info,
10460		  asection *sec,
10461		  elf_gc_mark_hook_fn gc_mark_hook)
10462{
10463  bfd_boolean ret;
10464  bfd_boolean is_eh;
10465  asection *group_sec;
10466
10467  sec->gc_mark = 1;
10468
10469  /* Mark all the sections in the group.  */
10470  group_sec = elf_section_data (sec)->next_in_group;
10471  if (group_sec && !group_sec->gc_mark)
10472    if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
10473      return FALSE;
10474
10475  /* Look through the section relocs.  */
10476  ret = TRUE;
10477  is_eh = strcmp (sec->name, ".eh_frame") == 0;
10478  if ((sec->flags & SEC_RELOC) != 0 && sec->reloc_count > 0)
10479    {
10480      Elf_Internal_Rela *relstart, *rel, *relend;
10481      Elf_Internal_Shdr *symtab_hdr;
10482      struct elf_link_hash_entry **sym_hashes;
10483      size_t nlocsyms;
10484      size_t extsymoff;
10485      bfd *input_bfd = sec->owner;
10486      const struct elf_backend_data *bed = get_elf_backend_data (input_bfd);
10487      Elf_Internal_Sym *isym = NULL;
10488      int r_sym_shift;
10489
10490      symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
10491      sym_hashes = elf_sym_hashes (input_bfd);
10492
10493      /* Read the local symbols.  */
10494      if (elf_bad_symtab (input_bfd))
10495	{
10496	  nlocsyms = symtab_hdr->sh_size / bed->s->sizeof_sym;
10497	  extsymoff = 0;
10498	}
10499      else
10500	extsymoff = nlocsyms = symtab_hdr->sh_info;
10501
10502      isym = (Elf_Internal_Sym *) symtab_hdr->contents;
10503      if (isym == NULL && nlocsyms != 0)
10504	{
10505	  isym = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, nlocsyms, 0,
10506				       NULL, NULL, NULL);
10507	  if (isym == NULL)
10508	    return FALSE;
10509	}
10510
10511      /* Read the relocations.  */
10512      relstart = _bfd_elf_link_read_relocs (input_bfd, sec, NULL, NULL,
10513					    info->keep_memory);
10514      if (relstart == NULL)
10515	{
10516	  ret = FALSE;
10517	  goto out1;
10518	}
10519      relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
10520
10521      if (bed->s->arch_size == 32)
10522	r_sym_shift = 8;
10523      else
10524	r_sym_shift = 32;
10525
10526      for (rel = relstart; rel < relend; rel++)
10527	{
10528	  unsigned long r_symndx;
10529	  asection *rsec;
10530	  struct elf_link_hash_entry *h;
10531
10532	  r_symndx = rel->r_info >> r_sym_shift;
10533	  if (r_symndx == 0)
10534	    continue;
10535
10536	  if (r_symndx >= nlocsyms
10537	      || ELF_ST_BIND (isym[r_symndx].st_info) != STB_LOCAL)
10538	    {
10539	      h = sym_hashes[r_symndx - extsymoff];
10540	      while (h->root.type == bfd_link_hash_indirect
10541		     || h->root.type == bfd_link_hash_warning)
10542		h = (struct elf_link_hash_entry *) h->root.u.i.link;
10543	      rsec = (*gc_mark_hook) (sec, info, rel, h, NULL);
10544	    }
10545	  else
10546	    {
10547	      rsec = (*gc_mark_hook) (sec, info, rel, NULL, &isym[r_symndx]);
10548	    }
10549
10550	  if (rsec && !rsec->gc_mark)
10551	    {
10552	      if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour)
10553		rsec->gc_mark = 1;
10554	      else if (is_eh)
10555		rsec->gc_mark_from_eh = 1;
10556	      else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
10557		{
10558		  ret = FALSE;
10559		  goto out2;
10560		}
10561	    }
10562	}
10563
10564    out2:
10565      if (elf_section_data (sec)->relocs != relstart)
10566	free (relstart);
10567    out1:
10568      if (isym != NULL && symtab_hdr->contents != (unsigned char *) isym)
10569	{
10570	  if (! info->keep_memory)
10571	    free (isym);
10572	  else
10573	    symtab_hdr->contents = (unsigned char *) isym;
10574	}
10575    }
10576
10577  return ret;
10578}
10579
10580/* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
10581
10582struct elf_gc_sweep_symbol_info
10583{
10584  struct bfd_link_info *info;
10585  void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
10586		       bfd_boolean);
10587};
10588
10589static bfd_boolean
10590elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
10591{
10592  if (h->root.type == bfd_link_hash_warning)
10593    h = (struct elf_link_hash_entry *) h->root.u.i.link;
10594
10595  if ((h->root.type == bfd_link_hash_defined
10596       || h->root.type == bfd_link_hash_defweak)
10597      && !h->root.u.def.section->gc_mark
10598      && !(h->root.u.def.section->owner->flags & DYNAMIC))
10599    {
10600      struct elf_gc_sweep_symbol_info *inf = data;
10601      (*inf->hide_symbol) (inf->info, h, TRUE);
10602    }
10603
10604  return TRUE;
10605}
10606
10607/* The sweep phase of garbage collection.  Remove all garbage sections.  */
10608
10609typedef bfd_boolean (*gc_sweep_hook_fn)
10610  (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
10611
10612static bfd_boolean
10613elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
10614{
10615  bfd *sub;
10616  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10617  gc_sweep_hook_fn gc_sweep_hook = bed->gc_sweep_hook;
10618  unsigned long section_sym_count;
10619  struct elf_gc_sweep_symbol_info sweep_info;
10620
10621  for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
10622    {
10623      asection *o;
10624
10625      if (bfd_get_flavour (sub) != bfd_target_elf_flavour)
10626	continue;
10627
10628      for (o = sub->sections; o != NULL; o = o->next)
10629	{
10630	  /* Keep debug and special sections.  */
10631	  if ((o->flags & (SEC_DEBUGGING | SEC_LINKER_CREATED)) != 0
10632	      || elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
10633	      || (o->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
10634	    o->gc_mark = 1;
10635
10636	  if (o->gc_mark)
10637	    continue;
10638
10639	  /* Skip sweeping sections already excluded.  */
10640	  if (o->flags & SEC_EXCLUDE)
10641	    continue;
10642
10643	  /* Since this is early in the link process, it is simple
10644	     to remove a section from the output.  */
10645	  o->flags |= SEC_EXCLUDE;
10646
10647	  if (info->print_gc_sections && o->size != 0)
10648	    _bfd_error_handler (_("Removing unused section '%s' in file '%B'"), sub, o->name);
10649
10650	  /* But we also have to update some of the relocation
10651	     info we collected before.  */
10652	  if (gc_sweep_hook
10653	      && (o->flags & SEC_RELOC) != 0
10654	      && o->reloc_count > 0
10655	      && !bfd_is_abs_section (o->output_section))
10656	    {
10657	      Elf_Internal_Rela *internal_relocs;
10658	      bfd_boolean r;
10659
10660	      internal_relocs
10661		= _bfd_elf_link_read_relocs (o->owner, o, NULL, NULL,
10662					     info->keep_memory);
10663	      if (internal_relocs == NULL)
10664		return FALSE;
10665
10666	      r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
10667
10668	      if (elf_section_data (o)->relocs != internal_relocs)
10669		free (internal_relocs);
10670
10671	      if (!r)
10672		return FALSE;
10673	    }
10674	}
10675    }
10676
10677  /* Remove the symbols that were in the swept sections from the dynamic
10678     symbol table.  GCFIXME: Anyone know how to get them out of the
10679     static symbol table as well?  */
10680  sweep_info.info = info;
10681  sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
10682  elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
10683			  &sweep_info);
10684
10685  _bfd_elf_link_renumber_dynsyms (abfd, info, &section_sym_count);
10686  return TRUE;
10687}
10688
10689/* Propagate collected vtable information.  This is called through
10690   elf_link_hash_traverse.  */
10691
10692static bfd_boolean
10693elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
10694{
10695  if (h->root.type == bfd_link_hash_warning)
10696    h = (struct elf_link_hash_entry *) h->root.u.i.link;
10697
10698  /* Those that are not vtables.  */
10699  if (h->vtable == NULL || h->vtable->parent == NULL)
10700    return TRUE;
10701
10702  /* Those vtables that do not have parents, we cannot merge.  */
10703  if (h->vtable->parent == (struct elf_link_hash_entry *) -1)
10704    return TRUE;
10705
10706  /* If we've already been done, exit.  */
10707  if (h->vtable->used && h->vtable->used[-1])
10708    return TRUE;
10709
10710  /* Make sure the parent's table is up to date.  */
10711  elf_gc_propagate_vtable_entries_used (h->vtable->parent, okp);
10712
10713  if (h->vtable->used == NULL)
10714    {
10715      /* None of this table's entries were referenced.  Re-use the
10716	 parent's table.  */
10717      h->vtable->used = h->vtable->parent->vtable->used;
10718      h->vtable->size = h->vtable->parent->vtable->size;
10719    }
10720  else
10721    {
10722      size_t n;
10723      bfd_boolean *cu, *pu;
10724
10725      /* Or the parent's entries into ours.  */
10726      cu = h->vtable->used;
10727      cu[-1] = TRUE;
10728      pu = h->vtable->parent->vtable->used;
10729      if (pu != NULL)
10730	{
10731	  const struct elf_backend_data *bed;
10732	  unsigned int log_file_align;
10733
10734	  bed = get_elf_backend_data (h->root.u.def.section->owner);
10735	  log_file_align = bed->s->log_file_align;
10736	  n = h->vtable->parent->vtable->size >> log_file_align;
10737	  while (n--)
10738	    {
10739	      if (*pu)
10740		*cu = TRUE;
10741	      pu++;
10742	      cu++;
10743	    }
10744	}
10745    }
10746
10747  return TRUE;
10748}
10749
10750static bfd_boolean
10751elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
10752{
10753  asection *sec;
10754  bfd_vma hstart, hend;
10755  Elf_Internal_Rela *relstart, *relend, *rel;
10756  const struct elf_backend_data *bed;
10757  unsigned int log_file_align;
10758
10759  if (h->root.type == bfd_link_hash_warning)
10760    h = (struct elf_link_hash_entry *) h->root.u.i.link;
10761
10762  /* Take care of both those symbols that do not describe vtables as
10763     well as those that are not loaded.  */
10764  if (h->vtable == NULL || h->vtable->parent == NULL)
10765    return TRUE;
10766
10767  BFD_ASSERT (h->root.type == bfd_link_hash_defined
10768	      || h->root.type == bfd_link_hash_defweak);
10769
10770  sec = h->root.u.def.section;
10771  hstart = h->root.u.def.value;
10772  hend = hstart + h->size;
10773
10774  relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
10775  if (!relstart)
10776    return *(bfd_boolean *) okp = FALSE;
10777  bed = get_elf_backend_data (sec->owner);
10778  log_file_align = bed->s->log_file_align;
10779
10780  relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
10781
10782  for (rel = relstart; rel < relend; ++rel)
10783    if (rel->r_offset >= hstart && rel->r_offset < hend)
10784      {
10785	/* If the entry is in use, do nothing.  */
10786	if (h->vtable->used
10787	    && (rel->r_offset - hstart) < h->vtable->size)
10788	  {
10789	    bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
10790	    if (h->vtable->used[entry])
10791	      continue;
10792	  }
10793	/* Otherwise, kill it.  */
10794	rel->r_offset = rel->r_info = rel->r_addend = 0;
10795      }
10796
10797  return TRUE;
10798}
10799
10800/* Mark sections containing dynamically referenced symbols.  When
10801   building shared libraries, we must assume that any visible symbol is
10802   referenced.  */
10803
10804bfd_boolean
10805bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
10806{
10807  struct bfd_link_info *info = (struct bfd_link_info *) inf;
10808
10809  if (h->root.type == bfd_link_hash_warning)
10810    h = (struct elf_link_hash_entry *) h->root.u.i.link;
10811
10812  if ((h->root.type == bfd_link_hash_defined
10813       || h->root.type == bfd_link_hash_defweak)
10814      && (h->ref_dynamic
10815	  || (!info->executable
10816	      && h->def_regular
10817	      && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
10818	      && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN)))
10819    h->root.u.def.section->flags |= SEC_KEEP;
10820
10821  return TRUE;
10822}
10823
10824/* Do mark and sweep of unused sections.  */
10825
10826bfd_boolean
10827bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
10828{
10829  bfd_boolean ok = TRUE;
10830  bfd *sub;
10831  elf_gc_mark_hook_fn gc_mark_hook;
10832  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10833
10834  if (!bed->can_gc_sections
10835      || info->relocatable
10836      || info->emitrelocations
10837      || !is_elf_hash_table (info->hash))
10838    {
10839      (*_bfd_error_handler)(_("Warning: gc-sections option ignored"));
10840      return TRUE;
10841    }
10842
10843  /* Apply transitive closure to the vtable entry usage info.  */
10844  elf_link_hash_traverse (elf_hash_table (info),
10845			  elf_gc_propagate_vtable_entries_used,
10846			  &ok);
10847  if (!ok)
10848    return FALSE;
10849
10850  /* Kill the vtable relocations that were not used.  */
10851  elf_link_hash_traverse (elf_hash_table (info),
10852			  elf_gc_smash_unused_vtentry_relocs,
10853			  &ok);
10854  if (!ok)
10855    return FALSE;
10856
10857  /* Mark dynamically referenced symbols.  */
10858  if (elf_hash_table (info)->dynamic_sections_created)
10859    elf_link_hash_traverse (elf_hash_table (info),
10860			    bed->gc_mark_dynamic_ref,
10861			    info);
10862
10863  /* Grovel through relocs to find out who stays ...  */
10864  gc_mark_hook = bed->gc_mark_hook;
10865  for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
10866    {
10867      asection *o;
10868
10869      if (bfd_get_flavour (sub) != bfd_target_elf_flavour)
10870	continue;
10871
10872      for (o = sub->sections; o != NULL; o = o->next)
10873	if ((o->flags & (SEC_EXCLUDE | SEC_KEEP)) == SEC_KEEP && !o->gc_mark)
10874	  if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
10875	    return FALSE;
10876    }
10877
10878  /* Allow the backend to mark additional target specific sections.  */
10879  if (bed->gc_mark_extra_sections)
10880    bed->gc_mark_extra_sections(info, gc_mark_hook);
10881
10882  /* ... again for sections marked from eh_frame.  */
10883  for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
10884    {
10885      asection *o;
10886
10887      if (bfd_get_flavour (sub) != bfd_target_elf_flavour)
10888	continue;
10889
10890      /* Keep .gcc_except_table.* if the associated .text.* (or the
10891	 associated .gnu.linkonce.t.* if .text.* doesn't exist) is
10892	 marked.  This isn't very nice, but the proper solution,
10893	 splitting .eh_frame up and using comdat doesn't pan out
10894	 easily due to needing special relocs to handle the
10895	 difference of two symbols in separate sections.
10896	 Don't keep code sections referenced by .eh_frame.  */
10897#define TEXT_PREFIX			".text."
10898#define TEXT_PREFIX2			".gnu.linkonce.t."
10899#define GCC_EXCEPT_TABLE_PREFIX		".gcc_except_table."
10900      for (o = sub->sections; o != NULL; o = o->next)
10901	if (!o->gc_mark && o->gc_mark_from_eh && (o->flags & SEC_CODE) == 0)
10902	  {
10903	    if (CONST_STRNEQ (o->name, GCC_EXCEPT_TABLE_PREFIX))
10904	      {
10905		char *fn_name;
10906		const char *sec_name;
10907		asection *fn_text;
10908		unsigned o_name_prefix_len , fn_name_prefix_len, tmp;
10909
10910		o_name_prefix_len = strlen (GCC_EXCEPT_TABLE_PREFIX);
10911		sec_name = o->name + o_name_prefix_len;
10912		fn_name_prefix_len = strlen (TEXT_PREFIX);
10913		tmp = strlen (TEXT_PREFIX2);
10914		if (tmp > fn_name_prefix_len)
10915		  fn_name_prefix_len = tmp;
10916		fn_name
10917		  = bfd_malloc (fn_name_prefix_len + strlen (sec_name) + 1);
10918		if (fn_name == NULL)
10919		  return FALSE;
10920
10921		/* Try the first prefix.  */
10922		sprintf (fn_name, "%s%s", TEXT_PREFIX, sec_name);
10923		fn_text = bfd_get_section_by_name (sub, fn_name);
10924
10925		/* Try the second prefix.  */
10926		if (fn_text == NULL)
10927		  {
10928		    sprintf (fn_name, "%s%s", TEXT_PREFIX2, sec_name);
10929		    fn_text = bfd_get_section_by_name (sub, fn_name);
10930		  }
10931
10932		free (fn_name);
10933		if (fn_text == NULL || !fn_text->gc_mark)
10934		  continue;
10935	      }
10936
10937	    /* If not using specially named exception table section,
10938	       then keep whatever we are using.  */
10939	    if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
10940	      return FALSE;
10941	  }
10942    }
10943
10944  /* ... and mark SEC_EXCLUDE for those that go.  */
10945  return elf_gc_sweep (abfd, info);
10946}
10947
10948/* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
10949
10950bfd_boolean
10951bfd_elf_gc_record_vtinherit (bfd *abfd,
10952			     asection *sec,
10953			     struct elf_link_hash_entry *h,
10954			     bfd_vma offset)
10955{
10956  struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
10957  struct elf_link_hash_entry **search, *child;
10958  bfd_size_type extsymcount;
10959  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10960
10961  /* The sh_info field of the symtab header tells us where the
10962     external symbols start.  We don't care about the local symbols at
10963     this point.  */
10964  extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
10965  if (!elf_bad_symtab (abfd))
10966    extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
10967
10968  sym_hashes = elf_sym_hashes (abfd);
10969  sym_hashes_end = sym_hashes + extsymcount;
10970
10971  /* Hunt down the child symbol, which is in this section at the same
10972     offset as the relocation.  */
10973  for (search = sym_hashes; search != sym_hashes_end; ++search)
10974    {
10975      if ((child = *search) != NULL
10976	  && (child->root.type == bfd_link_hash_defined
10977	      || child->root.type == bfd_link_hash_defweak)
10978	  && child->root.u.def.section == sec
10979	  && child->root.u.def.value == offset)
10980	goto win;
10981    }
10982
10983  (*_bfd_error_handler) ("%B: %A+%lu: No symbol found for INHERIT",
10984			 abfd, sec, (unsigned long) offset);
10985  bfd_set_error (bfd_error_invalid_operation);
10986  return FALSE;
10987
10988 win:
10989  if (!child->vtable)
10990    {
10991      child->vtable = bfd_zalloc (abfd, sizeof (*child->vtable));
10992      if (!child->vtable)
10993	return FALSE;
10994    }
10995  if (!h)
10996    {
10997      /* This *should* only be the absolute section.  It could potentially
10998	 be that someone has defined a non-global vtable though, which
10999	 would be bad.  It isn't worth paging in the local symbols to be
11000	 sure though; that case should simply be handled by the assembler.  */
11001
11002      child->vtable->parent = (struct elf_link_hash_entry *) -1;
11003    }
11004  else
11005    child->vtable->parent = h;
11006
11007  return TRUE;
11008}
11009
11010/* Called from check_relocs to record the existence of a VTENTRY reloc.  */
11011
11012bfd_boolean
11013bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
11014			   asection *sec ATTRIBUTE_UNUSED,
11015			   struct elf_link_hash_entry *h,
11016			   bfd_vma addend)
11017{
11018  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11019  unsigned int log_file_align = bed->s->log_file_align;
11020
11021  if (!h->vtable)
11022    {
11023      h->vtable = bfd_zalloc (abfd, sizeof (*h->vtable));
11024      if (!h->vtable)
11025	return FALSE;
11026    }
11027
11028  if (addend >= h->vtable->size)
11029    {
11030      size_t size, bytes, file_align;
11031      bfd_boolean *ptr = h->vtable->used;
11032
11033      /* While the symbol is undefined, we have to be prepared to handle
11034	 a zero size.  */
11035      file_align = 1 << log_file_align;
11036      if (h->root.type == bfd_link_hash_undefined)
11037	size = addend + file_align;
11038      else
11039	{
11040	  size = h->size;
11041	  if (addend >= size)
11042	    {
11043	      /* Oops!  We've got a reference past the defined end of
11044		 the table.  This is probably a bug -- shall we warn?  */
11045	      size = addend + file_align;
11046	    }
11047	}
11048      size = (size + file_align - 1) & -file_align;
11049
11050      /* Allocate one extra entry for use as a "done" flag for the
11051	 consolidation pass.  */
11052      bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
11053
11054      if (ptr)
11055	{
11056	  ptr = bfd_realloc (ptr - 1, bytes);
11057
11058	  if (ptr != NULL)
11059	    {
11060	      size_t oldbytes;
11061
11062	      oldbytes = (((h->vtable->size >> log_file_align) + 1)
11063			  * sizeof (bfd_boolean));
11064	      memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
11065	    }
11066	}
11067      else
11068	ptr = bfd_zmalloc (bytes);
11069
11070      if (ptr == NULL)
11071	return FALSE;
11072
11073      /* And arrange for that done flag to be at index -1.  */
11074      h->vtable->used = ptr + 1;
11075      h->vtable->size = size;
11076    }
11077
11078  h->vtable->used[addend >> log_file_align] = TRUE;
11079
11080  return TRUE;
11081}
11082
11083struct alloc_got_off_arg {
11084  bfd_vma gotoff;
11085  unsigned int got_elt_size;
11086};
11087
11088/* We need a special top-level link routine to convert got reference counts
11089   to real got offsets.  */
11090
11091static bfd_boolean
11092elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
11093{
11094  struct alloc_got_off_arg *gofarg = arg;
11095
11096  if (h->root.type == bfd_link_hash_warning)
11097    h = (struct elf_link_hash_entry *) h->root.u.i.link;
11098
11099  if (h->got.refcount > 0)
11100    {
11101      h->got.offset = gofarg->gotoff;
11102      gofarg->gotoff += gofarg->got_elt_size;
11103    }
11104  else
11105    h->got.offset = (bfd_vma) -1;
11106
11107  return TRUE;
11108}
11109
11110/* And an accompanying bit to work out final got entry offsets once
11111   we're done.  Should be called from final_link.  */
11112
11113bfd_boolean
11114bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
11115					struct bfd_link_info *info)
11116{
11117  bfd *i;
11118  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11119  bfd_vma gotoff;
11120  unsigned int got_elt_size = bed->s->arch_size / 8;
11121  struct alloc_got_off_arg gofarg;
11122
11123  if (! is_elf_hash_table (info->hash))
11124    return FALSE;
11125
11126  /* The GOT offset is relative to the .got section, but the GOT header is
11127     put into the .got.plt section, if the backend uses it.  */
11128  if (bed->want_got_plt)
11129    gotoff = 0;
11130  else
11131    gotoff = bed->got_header_size;
11132
11133  /* Do the local .got entries first.  */
11134  for (i = info->input_bfds; i; i = i->link_next)
11135    {
11136      bfd_signed_vma *local_got;
11137      bfd_size_type j, locsymcount;
11138      Elf_Internal_Shdr *symtab_hdr;
11139
11140      if (bfd_get_flavour (i) != bfd_target_elf_flavour)
11141	continue;
11142
11143      local_got = elf_local_got_refcounts (i);
11144      if (!local_got)
11145	continue;
11146
11147      symtab_hdr = &elf_tdata (i)->symtab_hdr;
11148      if (elf_bad_symtab (i))
11149	locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
11150      else
11151	locsymcount = symtab_hdr->sh_info;
11152
11153      for (j = 0; j < locsymcount; ++j)
11154	{
11155	  if (local_got[j] > 0)
11156	    {
11157	      local_got[j] = gotoff;
11158	      gotoff += got_elt_size;
11159	    }
11160	  else
11161	    local_got[j] = (bfd_vma) -1;
11162	}
11163    }
11164
11165  /* Then the global .got entries.  .plt refcounts are handled by
11166     adjust_dynamic_symbol  */
11167  gofarg.gotoff = gotoff;
11168  gofarg.got_elt_size = got_elt_size;
11169  elf_link_hash_traverse (elf_hash_table (info),
11170			  elf_gc_allocate_got_offsets,
11171			  &gofarg);
11172  return TRUE;
11173}
11174
11175/* Many folk need no more in the way of final link than this, once
11176   got entry reference counting is enabled.  */
11177
11178bfd_boolean
11179bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
11180{
11181  if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
11182    return FALSE;
11183
11184  /* Invoke the regular ELF backend linker to do all the work.  */
11185  return bfd_elf_final_link (abfd, info);
11186}
11187
11188bfd_boolean
11189bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
11190{
11191  struct elf_reloc_cookie *rcookie = cookie;
11192
11193  if (rcookie->bad_symtab)
11194    rcookie->rel = rcookie->rels;
11195
11196  for (; rcookie->rel < rcookie->relend; rcookie->rel++)
11197    {
11198      unsigned long r_symndx;
11199
11200      if (! rcookie->bad_symtab)
11201	if (rcookie->rel->r_offset > offset)
11202	  return FALSE;
11203      if (rcookie->rel->r_offset != offset)
11204	continue;
11205
11206      r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
11207      if (r_symndx == SHN_UNDEF)
11208	return TRUE;
11209
11210      if (r_symndx >= rcookie->locsymcount
11211	  || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
11212	{
11213	  struct elf_link_hash_entry *h;
11214
11215	  h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
11216
11217	  while (h->root.type == bfd_link_hash_indirect
11218		 || h->root.type == bfd_link_hash_warning)
11219	    h = (struct elf_link_hash_entry *) h->root.u.i.link;
11220
11221	  if ((h->root.type == bfd_link_hash_defined
11222	       || h->root.type == bfd_link_hash_defweak)
11223	      && elf_discarded_section (h->root.u.def.section))
11224	    return TRUE;
11225	  else
11226	    return FALSE;
11227	}
11228      else
11229	{
11230	  /* It's not a relocation against a global symbol,
11231	     but it could be a relocation against a local
11232	     symbol for a discarded section.  */
11233	  asection *isec;
11234	  Elf_Internal_Sym *isym;
11235
11236	  /* Need to: get the symbol; get the section.  */
11237	  isym = &rcookie->locsyms[r_symndx];
11238	  if (isym->st_shndx < SHN_LORESERVE || isym->st_shndx > SHN_HIRESERVE)
11239	    {
11240	      isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
11241	      if (isec != NULL && elf_discarded_section (isec))
11242		return TRUE;
11243	    }
11244	}
11245      return FALSE;
11246    }
11247  return FALSE;
11248}
11249
11250/* Discard unneeded references to discarded sections.
11251   Returns TRUE if any section's size was changed.  */
11252/* This function assumes that the relocations are in sorted order,
11253   which is true for all known assemblers.  */
11254
11255bfd_boolean
11256bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
11257{
11258  struct elf_reloc_cookie cookie;
11259  asection *stab, *eh;
11260  Elf_Internal_Shdr *symtab_hdr;
11261  const struct elf_backend_data *bed;
11262  bfd *abfd;
11263  unsigned int count;
11264  bfd_boolean ret = FALSE;
11265
11266  if (info->traditional_format
11267      || !is_elf_hash_table (info->hash))
11268    return FALSE;
11269
11270  for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link_next)
11271    {
11272      if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
11273	continue;
11274
11275      bed = get_elf_backend_data (abfd);
11276
11277      if ((abfd->flags & DYNAMIC) != 0)
11278	continue;
11279
11280      eh = NULL;
11281      if (!info->relocatable)
11282	{
11283	  eh = bfd_get_section_by_name (abfd, ".eh_frame");
11284	  if (eh != NULL
11285	      && (eh->size == 0
11286		  || bfd_is_abs_section (eh->output_section)))
11287	    eh = NULL;
11288	}
11289
11290      stab = bfd_get_section_by_name (abfd, ".stab");
11291      if (stab != NULL
11292	  && (stab->size == 0
11293	      || bfd_is_abs_section (stab->output_section)
11294	      || stab->sec_info_type != ELF_INFO_TYPE_STABS))
11295	stab = NULL;
11296
11297      if (stab == NULL
11298	  && eh == NULL
11299	  && bed->elf_backend_discard_info == NULL)
11300	continue;
11301
11302      symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11303      cookie.abfd = abfd;
11304      cookie.sym_hashes = elf_sym_hashes (abfd);
11305      cookie.bad_symtab = elf_bad_symtab (abfd);
11306      if (cookie.bad_symtab)
11307	{
11308	  cookie.locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
11309	  cookie.extsymoff = 0;
11310	}
11311      else
11312	{
11313	  cookie.locsymcount = symtab_hdr->sh_info;
11314	  cookie.extsymoff = symtab_hdr->sh_info;
11315	}
11316
11317      if (bed->s->arch_size == 32)
11318	cookie.r_sym_shift = 8;
11319      else
11320	cookie.r_sym_shift = 32;
11321
11322      cookie.locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
11323      if (cookie.locsyms == NULL && cookie.locsymcount != 0)
11324	{
11325	  cookie.locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
11326						 cookie.locsymcount, 0,
11327						 NULL, NULL, NULL);
11328	  if (cookie.locsyms == NULL)
11329	    {
11330	      info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
11331	      return FALSE;
11332	    }
11333	}
11334
11335      if (stab != NULL)
11336	{
11337	  cookie.rels = NULL;
11338	  count = stab->reloc_count;
11339	  if (count != 0)
11340	    cookie.rels = _bfd_elf_link_read_relocs (abfd, stab, NULL, NULL,
11341						     info->keep_memory);
11342	  if (cookie.rels != NULL)
11343	    {
11344	      cookie.rel = cookie.rels;
11345	      cookie.relend = cookie.rels;
11346	      cookie.relend += count * bed->s->int_rels_per_ext_rel;
11347	      if (_bfd_discard_section_stabs (abfd, stab,
11348					      elf_section_data (stab)->sec_info,
11349					      bfd_elf_reloc_symbol_deleted_p,
11350					      &cookie))
11351		ret = TRUE;
11352	      if (elf_section_data (stab)->relocs != cookie.rels)
11353		free (cookie.rels);
11354	    }
11355	}
11356
11357      if (eh != NULL)
11358	{
11359	  cookie.rels = NULL;
11360	  count = eh->reloc_count;
11361	  if (count != 0)
11362	    cookie.rels = _bfd_elf_link_read_relocs (abfd, eh, NULL, NULL,
11363						     info->keep_memory);
11364	  cookie.rel = cookie.rels;
11365	  cookie.relend = cookie.rels;
11366	  if (cookie.rels != NULL)
11367	    cookie.relend += count * bed->s->int_rels_per_ext_rel;
11368
11369	  if (_bfd_elf_discard_section_eh_frame (abfd, info, eh,
11370						 bfd_elf_reloc_symbol_deleted_p,
11371						 &cookie))
11372	    ret = TRUE;
11373
11374	  if (cookie.rels != NULL
11375	      && elf_section_data (eh)->relocs != cookie.rels)
11376	    free (cookie.rels);
11377	}
11378
11379      if (bed->elf_backend_discard_info != NULL
11380	  && (*bed->elf_backend_discard_info) (abfd, &cookie, info))
11381	ret = TRUE;
11382
11383      if (cookie.locsyms != NULL
11384	  && symtab_hdr->contents != (unsigned char *) cookie.locsyms)
11385	{
11386	  if (! info->keep_memory)
11387	    free (cookie.locsyms);
11388	  else
11389	    symtab_hdr->contents = (unsigned char *) cookie.locsyms;
11390	}
11391    }
11392
11393  if (info->eh_frame_hdr
11394      && !info->relocatable
11395      && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
11396    ret = TRUE;
11397
11398  return ret;
11399}
11400
11401void
11402_bfd_elf_section_already_linked (bfd *abfd, struct bfd_section *sec,
11403				 struct bfd_link_info *info)
11404{
11405  flagword flags;
11406  const char *name, *p;
11407  struct bfd_section_already_linked *l;
11408  struct bfd_section_already_linked_hash_entry *already_linked_list;
11409
11410  if (sec->output_section == bfd_abs_section_ptr)
11411    return;
11412
11413  flags = sec->flags;
11414
11415  /* Return if it isn't a linkonce section.  A comdat group section
11416     also has SEC_LINK_ONCE set.  */
11417  if ((flags & SEC_LINK_ONCE) == 0)
11418    return;
11419
11420  /* Don't put group member sections on our list of already linked
11421     sections.  They are handled as a group via their group section.  */
11422  if (elf_sec_group (sec) != NULL)
11423    return;
11424
11425  /* FIXME: When doing a relocatable link, we may have trouble
11426     copying relocations in other sections that refer to local symbols
11427     in the section being discarded.  Those relocations will have to
11428     be converted somehow; as of this writing I'm not sure that any of
11429     the backends handle that correctly.
11430
11431     It is tempting to instead not discard link once sections when
11432     doing a relocatable link (technically, they should be discarded
11433     whenever we are building constructors).  However, that fails,
11434     because the linker winds up combining all the link once sections
11435     into a single large link once section, which defeats the purpose
11436     of having link once sections in the first place.
11437
11438     Also, not merging link once sections in a relocatable link
11439     causes trouble for MIPS ELF, which relies on link once semantics
11440     to handle the .reginfo section correctly.  */
11441
11442  name = bfd_get_section_name (abfd, sec);
11443
11444  if (CONST_STRNEQ (name, ".gnu.linkonce.")
11445      && (p = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
11446    p++;
11447  else
11448    p = name;
11449
11450  already_linked_list = bfd_section_already_linked_table_lookup (p);
11451
11452  for (l = already_linked_list->entry; l != NULL; l = l->next)
11453    {
11454      /* We may have 2 different types of sections on the list: group
11455	 sections and linkonce sections.  Match like sections.  */
11456      if ((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
11457	  && strcmp (name, l->sec->name) == 0
11458	  && bfd_coff_get_comdat_section (l->sec->owner, l->sec) == NULL)
11459	{
11460	  /* The section has already been linked.  See if we should
11461	     issue a warning.  */
11462	  switch (flags & SEC_LINK_DUPLICATES)
11463	    {
11464	    default:
11465	      abort ();
11466
11467	    case SEC_LINK_DUPLICATES_DISCARD:
11468	      break;
11469
11470	    case SEC_LINK_DUPLICATES_ONE_ONLY:
11471	      (*_bfd_error_handler)
11472		(_("%B: ignoring duplicate section `%A'"),
11473		 abfd, sec);
11474	      break;
11475
11476	    case SEC_LINK_DUPLICATES_SAME_SIZE:
11477	      if (sec->size != l->sec->size)
11478		(*_bfd_error_handler)
11479		  (_("%B: duplicate section `%A' has different size"),
11480		   abfd, sec);
11481	      break;
11482
11483	    case SEC_LINK_DUPLICATES_SAME_CONTENTS:
11484	      if (sec->size != l->sec->size)
11485		(*_bfd_error_handler)
11486		  (_("%B: duplicate section `%A' has different size"),
11487		   abfd, sec);
11488	      else if (sec->size != 0)
11489		{
11490		  bfd_byte *sec_contents, *l_sec_contents = NULL;
11491
11492		  if (!bfd_malloc_and_get_section (abfd, sec, &sec_contents))
11493		    (*_bfd_error_handler)
11494		      (_("%B: warning: could not read contents of section `%A'"),
11495		       abfd, sec);
11496		  else if (!bfd_malloc_and_get_section (l->sec->owner, l->sec,
11497							&l_sec_contents))
11498		    (*_bfd_error_handler)
11499		      (_("%B: warning: could not read contents of section `%A'"),
11500		       l->sec->owner, l->sec);
11501		  else if (memcmp (sec_contents, l_sec_contents, sec->size) != 0)
11502		    (*_bfd_error_handler)
11503		      (_("%B: warning: duplicate section `%A' has different contents"),
11504		       abfd, sec);
11505
11506		  if (sec_contents)
11507		    free (sec_contents);
11508		  if (l_sec_contents)
11509		    free (l_sec_contents);
11510		}
11511	      break;
11512	    }
11513
11514	  /* Set the output_section field so that lang_add_section
11515	     does not create a lang_input_section structure for this
11516	     section.  Since there might be a symbol in the section
11517	     being discarded, we must retain a pointer to the section
11518	     which we are really going to use.  */
11519	  sec->output_section = bfd_abs_section_ptr;
11520	  sec->kept_section = l->sec;
11521
11522	  if (flags & SEC_GROUP)
11523	    {
11524	      asection *first = elf_next_in_group (sec);
11525	      asection *s = first;
11526
11527	      while (s != NULL)
11528		{
11529		  s->output_section = bfd_abs_section_ptr;
11530		  /* Record which group discards it.  */
11531		  s->kept_section = l->sec;
11532		  s = elf_next_in_group (s);
11533		  /* These lists are circular.  */
11534		  if (s == first)
11535		    break;
11536		}
11537	    }
11538
11539	  return;
11540	}
11541    }
11542
11543  /* A single member comdat group section may be discarded by a
11544     linkonce section and vice versa.  */
11545
11546  if ((flags & SEC_GROUP) != 0)
11547    {
11548      asection *first = elf_next_in_group (sec);
11549
11550      if (first != NULL && elf_next_in_group (first) == first)
11551	/* Check this single member group against linkonce sections.  */
11552	for (l = already_linked_list->entry; l != NULL; l = l->next)
11553	  if ((l->sec->flags & SEC_GROUP) == 0
11554	      && bfd_coff_get_comdat_section (l->sec->owner, l->sec) == NULL
11555	      && bfd_elf_match_symbols_in_sections (l->sec, first, info))
11556	    {
11557	      first->output_section = bfd_abs_section_ptr;
11558	      first->kept_section = l->sec;
11559	      sec->output_section = bfd_abs_section_ptr;
11560	      break;
11561	    }
11562    }
11563  else
11564    /* Check this linkonce section against single member groups.  */
11565    for (l = already_linked_list->entry; l != NULL; l = l->next)
11566      if (l->sec->flags & SEC_GROUP)
11567	{
11568	  asection *first = elf_next_in_group (l->sec);
11569
11570	  if (first != NULL
11571	      && elf_next_in_group (first) == first
11572	      && bfd_elf_match_symbols_in_sections (first, sec, info))
11573	    {
11574	      sec->output_section = bfd_abs_section_ptr;
11575	      sec->kept_section = first;
11576	      break;
11577	    }
11578	}
11579
11580  /* This is the first section with this name.  Record it.  */
11581  bfd_section_already_linked_table_insert (already_linked_list, sec);
11582}
11583
11584bfd_boolean
11585_bfd_elf_common_definition (Elf_Internal_Sym *sym)
11586{
11587  return sym->st_shndx == SHN_COMMON;
11588}
11589
11590unsigned int
11591_bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
11592{
11593  return SHN_COMMON;
11594}
11595
11596asection *
11597_bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
11598{
11599  return bfd_com_section_ptr;
11600}
11601