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_error_handler)
4360		    (_("%B: invalid DSO for symbol `%s' definition"),
4361		    abfd, name);
4362		  bfd_set_error (bfd_error_bad_value);
4363		  goto error_free_vers;
4364		}
4365
4366	      elf_dyn_lib_class (abfd) &= ~DYN_AS_NEEDED;
4367
4368	      add_needed = TRUE;
4369	      ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4370	      if (ret < 0)
4371		goto error_free_vers;
4372
4373	      BFD_ASSERT (ret == 0);
4374	    }
4375	}
4376    }
4377
4378  if (extversym != NULL)
4379    {
4380      free (extversym);
4381      extversym = NULL;
4382    }
4383
4384  if (isymbuf != NULL)
4385    {
4386      free (isymbuf);
4387      isymbuf = NULL;
4388    }
4389
4390  if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4391    {
4392      unsigned int i;
4393
4394      /* Restore the symbol table.  */
4395      if (bed->as_needed_cleanup)
4396	(*bed->as_needed_cleanup) (abfd, info);
4397      old_hash = (char *) old_tab + tabsize;
4398      old_ent = (char *) old_hash + hashsize;
4399      sym_hash = elf_sym_hashes (abfd);
4400      htab->root.table.table = old_table;
4401      htab->root.table.size = old_size;
4402      htab->root.table.count = old_count;
4403      memcpy (htab->root.table.table, old_tab, tabsize);
4404      memcpy (sym_hash, old_hash, hashsize);
4405      htab->root.undefs = old_undefs;
4406      htab->root.undefs_tail = old_undefs_tail;
4407      for (i = 0; i < htab->root.table.size; i++)
4408	{
4409	  struct bfd_hash_entry *p;
4410	  struct elf_link_hash_entry *h;
4411
4412	  for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4413	    {
4414	      h = (struct elf_link_hash_entry *) p;
4415	      if (h->root.type == bfd_link_hash_warning)
4416		h = (struct elf_link_hash_entry *) h->root.u.i.link;
4417	      if (h->dynindx >= old_dynsymcount)
4418		_bfd_elf_strtab_delref (htab->dynstr, h->dynstr_index);
4419
4420	      memcpy (p, old_ent, htab->root.table.entsize);
4421	      old_ent = (char *) old_ent + htab->root.table.entsize;
4422	      h = (struct elf_link_hash_entry *) p;
4423	      if (h->root.type == bfd_link_hash_warning)
4424		{
4425		  memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
4426		  old_ent = (char *) old_ent + htab->root.table.entsize;
4427		}
4428	    }
4429	}
4430
4431      /* Make a special call to the linker "notice" function to
4432	 tell it that symbols added for crefs may need to be removed.  */
4433      if (!(*info->callbacks->notice) (info, NULL, abfd, NULL,
4434				       notice_not_needed))
4435	return FALSE;
4436
4437      free (old_tab);
4438      objalloc_free_block ((struct objalloc *) htab->root.table.memory,
4439			   alloc_mark);
4440      if (nondeflt_vers != NULL)
4441	free (nondeflt_vers);
4442      return TRUE;
4443    }
4444
4445  if (old_tab != NULL)
4446    {
4447      if (!(*info->callbacks->notice) (info, NULL, abfd, NULL,
4448				       notice_needed))
4449	return FALSE;
4450      free (old_tab);
4451      old_tab = NULL;
4452    }
4453
4454  /* Now that all the symbols from this input file are created, handle
4455     .symver foo, foo@BAR such that any relocs against foo become foo@BAR.  */
4456  if (nondeflt_vers != NULL)
4457    {
4458      bfd_size_type cnt, symidx;
4459
4460      for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
4461	{
4462	  struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
4463	  char *shortname, *p;
4464
4465	  p = strchr (h->root.root.string, ELF_VER_CHR);
4466	  if (p == NULL
4467	      || (h->root.type != bfd_link_hash_defined
4468		  && h->root.type != bfd_link_hash_defweak))
4469	    continue;
4470
4471	  amt = p - h->root.root.string;
4472	  shortname = bfd_malloc (amt + 1);
4473	  memcpy (shortname, h->root.root.string, amt);
4474	  shortname[amt] = '\0';
4475
4476	  hi = (struct elf_link_hash_entry *)
4477	       bfd_link_hash_lookup (&htab->root, shortname,
4478				     FALSE, FALSE, FALSE);
4479	  if (hi != NULL
4480	      && hi->root.type == h->root.type
4481	      && hi->root.u.def.value == h->root.u.def.value
4482	      && hi->root.u.def.section == h->root.u.def.section)
4483	    {
4484	      (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
4485	      hi->root.type = bfd_link_hash_indirect;
4486	      hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
4487	      (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
4488	      sym_hash = elf_sym_hashes (abfd);
4489	      if (sym_hash)
4490		for (symidx = 0; symidx < extsymcount; ++symidx)
4491		  if (sym_hash[symidx] == hi)
4492		    {
4493		      sym_hash[symidx] = h;
4494		      break;
4495		    }
4496	    }
4497	  free (shortname);
4498	}
4499      free (nondeflt_vers);
4500      nondeflt_vers = NULL;
4501    }
4502
4503  /* Now set the weakdefs field correctly for all the weak defined
4504     symbols we found.  The only way to do this is to search all the
4505     symbols.  Since we only need the information for non functions in
4506     dynamic objects, that's the only time we actually put anything on
4507     the list WEAKS.  We need this information so that if a regular
4508     object refers to a symbol defined weakly in a dynamic object, the
4509     real symbol in the dynamic object is also put in the dynamic
4510     symbols; we also must arrange for both symbols to point to the
4511     same memory location.  We could handle the general case of symbol
4512     aliasing, but a general symbol alias can only be generated in
4513     assembler code, handling it correctly would be very time
4514     consuming, and other ELF linkers don't handle general aliasing
4515     either.  */
4516  if (weaks != NULL)
4517    {
4518      struct elf_link_hash_entry **hpp;
4519      struct elf_link_hash_entry **hppend;
4520      struct elf_link_hash_entry **sorted_sym_hash;
4521      struct elf_link_hash_entry *h;
4522      size_t sym_count;
4523
4524      /* Since we have to search the whole symbol list for each weak
4525	 defined symbol, search time for N weak defined symbols will be
4526	 O(N^2). Binary search will cut it down to O(NlogN).  */
4527      amt = extsymcount * sizeof (struct elf_link_hash_entry *);
4528      sorted_sym_hash = bfd_malloc (amt);
4529      if (sorted_sym_hash == NULL)
4530	goto error_return;
4531      sym_hash = sorted_sym_hash;
4532      hpp = elf_sym_hashes (abfd);
4533      hppend = hpp + extsymcount;
4534      sym_count = 0;
4535      for (; hpp < hppend; hpp++)
4536	{
4537	  h = *hpp;
4538	  if (h != NULL
4539	      && h->root.type == bfd_link_hash_defined
4540	      && !bed->is_function_type (h->type))
4541	    {
4542	      *sym_hash = h;
4543	      sym_hash++;
4544	      sym_count++;
4545	    }
4546	}
4547
4548      qsort (sorted_sym_hash, sym_count,
4549	     sizeof (struct elf_link_hash_entry *),
4550	     elf_sort_symbol);
4551
4552      while (weaks != NULL)
4553	{
4554	  struct elf_link_hash_entry *hlook;
4555	  asection *slook;
4556	  bfd_vma vlook;
4557	  long ilook;
4558	  size_t i, j, idx;
4559
4560	  hlook = weaks;
4561	  weaks = hlook->u.weakdef;
4562	  hlook->u.weakdef = NULL;
4563
4564	  BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
4565		      || hlook->root.type == bfd_link_hash_defweak
4566		      || hlook->root.type == bfd_link_hash_common
4567		      || hlook->root.type == bfd_link_hash_indirect);
4568	  slook = hlook->root.u.def.section;
4569	  vlook = hlook->root.u.def.value;
4570
4571	  ilook = -1;
4572	  i = 0;
4573	  j = sym_count;
4574	  while (i < j)
4575	    {
4576	      bfd_signed_vma vdiff;
4577	      idx = (i + j) / 2;
4578	      h = sorted_sym_hash [idx];
4579	      vdiff = vlook - h->root.u.def.value;
4580	      if (vdiff < 0)
4581		j = idx;
4582	      else if (vdiff > 0)
4583		i = idx + 1;
4584	      else
4585		{
4586		  long sdiff = slook->id - h->root.u.def.section->id;
4587		  if (sdiff < 0)
4588		    j = idx;
4589		  else if (sdiff > 0)
4590		    i = idx + 1;
4591		  else
4592		    {
4593		      ilook = idx;
4594		      break;
4595		    }
4596		}
4597	    }
4598
4599	  /* We didn't find a value/section match.  */
4600	  if (ilook == -1)
4601	    continue;
4602
4603	  for (i = ilook; i < sym_count; i++)
4604	    {
4605	      h = sorted_sym_hash [i];
4606
4607	      /* Stop if value or section doesn't match.  */
4608	      if (h->root.u.def.value != vlook
4609		  || h->root.u.def.section != slook)
4610		break;
4611	      else if (h != hlook)
4612		{
4613		  hlook->u.weakdef = h;
4614
4615		  /* If the weak definition is in the list of dynamic
4616		     symbols, make sure the real definition is put
4617		     there as well.  */
4618		  if (hlook->dynindx != -1 && h->dynindx == -1)
4619		    {
4620		      if (! bfd_elf_link_record_dynamic_symbol (info, h))
4621			goto error_return;
4622		    }
4623
4624		  /* If the real definition is in the list of dynamic
4625		     symbols, make sure the weak definition is put
4626		     there as well.  If we don't do this, then the
4627		     dynamic loader might not merge the entries for the
4628		     real definition and the weak definition.  */
4629		  if (h->dynindx != -1 && hlook->dynindx == -1)
4630		    {
4631		      if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
4632			goto error_return;
4633		    }
4634		  break;
4635		}
4636	    }
4637	}
4638
4639      free (sorted_sym_hash);
4640    }
4641
4642  if (bed->check_directives)
4643    (*bed->check_directives) (abfd, info);
4644
4645  /* If this object is the same format as the output object, and it is
4646     not a shared library, then let the backend look through the
4647     relocs.
4648
4649     This is required to build global offset table entries and to
4650     arrange for dynamic relocs.  It is not required for the
4651     particular common case of linking non PIC code, even when linking
4652     against shared libraries, but unfortunately there is no way of
4653     knowing whether an object file has been compiled PIC or not.
4654     Looking through the relocs is not particularly time consuming.
4655     The problem is that we must either (1) keep the relocs in memory,
4656     which causes the linker to require additional runtime memory or
4657     (2) read the relocs twice from the input file, which wastes time.
4658     This would be a good case for using mmap.
4659
4660     I have no idea how to handle linking PIC code into a file of a
4661     different format.  It probably can't be done.  */
4662  if (! dynamic
4663      && is_elf_hash_table (htab)
4664      && bed->check_relocs != NULL
4665      && (*bed->relocs_compatible) (abfd->xvec, htab->root.creator))
4666    {
4667      asection *o;
4668
4669      for (o = abfd->sections; o != NULL; o = o->next)
4670	{
4671	  Elf_Internal_Rela *internal_relocs;
4672	  bfd_boolean ok;
4673
4674	  if ((o->flags & SEC_RELOC) == 0
4675	      || o->reloc_count == 0
4676	      || ((info->strip == strip_all || info->strip == strip_debugger)
4677		  && (o->flags & SEC_DEBUGGING) != 0)
4678	      || bfd_is_abs_section (o->output_section))
4679	    continue;
4680
4681	  internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
4682						       info->keep_memory);
4683	  if (internal_relocs == NULL)
4684	    goto error_return;
4685
4686	  ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
4687
4688	  if (elf_section_data (o)->relocs != internal_relocs)
4689	    free (internal_relocs);
4690
4691	  if (! ok)
4692	    goto error_return;
4693	}
4694    }
4695
4696  /* If this is a non-traditional link, try to optimize the handling
4697     of the .stab/.stabstr sections.  */
4698  if (! dynamic
4699      && ! info->traditional_format
4700      && is_elf_hash_table (htab)
4701      && (info->strip != strip_all && info->strip != strip_debugger))
4702    {
4703      asection *stabstr;
4704
4705      stabstr = bfd_get_section_by_name (abfd, ".stabstr");
4706      if (stabstr != NULL)
4707	{
4708	  bfd_size_type string_offset = 0;
4709	  asection *stab;
4710
4711	  for (stab = abfd->sections; stab; stab = stab->next)
4712	    if (CONST_STRNEQ (stab->name, ".stab")
4713		&& (!stab->name[5] ||
4714		    (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
4715		&& (stab->flags & SEC_MERGE) == 0
4716		&& !bfd_is_abs_section (stab->output_section))
4717	      {
4718		struct bfd_elf_section_data *secdata;
4719
4720		secdata = elf_section_data (stab);
4721		if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
4722					       stabstr, &secdata->sec_info,
4723					       &string_offset))
4724		  goto error_return;
4725		if (secdata->sec_info)
4726		  stab->sec_info_type = ELF_INFO_TYPE_STABS;
4727	    }
4728	}
4729    }
4730
4731  if (is_elf_hash_table (htab) && add_needed)
4732    {
4733      /* Add this bfd to the loaded list.  */
4734      struct elf_link_loaded_list *n;
4735
4736      n = bfd_alloc (abfd, sizeof (struct elf_link_loaded_list));
4737      if (n == NULL)
4738	goto error_return;
4739      n->abfd = abfd;
4740      n->next = htab->loaded;
4741      htab->loaded = n;
4742    }
4743
4744  return TRUE;
4745
4746 error_free_vers:
4747  if (old_tab != NULL)
4748    free (old_tab);
4749  if (nondeflt_vers != NULL)
4750    free (nondeflt_vers);
4751  if (extversym != NULL)
4752    free (extversym);
4753 error_free_sym:
4754  if (isymbuf != NULL)
4755    free (isymbuf);
4756 error_return:
4757  return FALSE;
4758}
4759
4760/* Return the linker hash table entry of a symbol that might be
4761   satisfied by an archive symbol.  Return -1 on error.  */
4762
4763struct elf_link_hash_entry *
4764_bfd_elf_archive_symbol_lookup (bfd *abfd,
4765				struct bfd_link_info *info,
4766				const char *name)
4767{
4768  struct elf_link_hash_entry *h;
4769  char *p, *copy;
4770  size_t len, first;
4771
4772  h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
4773  if (h != NULL)
4774    return h;
4775
4776  /* If this is a default version (the name contains @@), look up the
4777     symbol again with only one `@' as well as without the version.
4778     The effect is that references to the symbol with and without the
4779     version will be matched by the default symbol in the archive.  */
4780
4781  p = strchr (name, ELF_VER_CHR);
4782  if (p == NULL || p[1] != ELF_VER_CHR)
4783    return h;
4784
4785  /* First check with only one `@'.  */
4786  len = strlen (name);
4787  copy = bfd_alloc (abfd, len);
4788  if (copy == NULL)
4789    return (struct elf_link_hash_entry *) 0 - 1;
4790
4791  first = p - name + 1;
4792  memcpy (copy, name, first);
4793  memcpy (copy + first, name + first + 1, len - first);
4794
4795  h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, FALSE);
4796  if (h == NULL)
4797    {
4798      /* We also need to check references to the symbol without the
4799	 version.  */
4800      copy[first - 1] = '\0';
4801      h = elf_link_hash_lookup (elf_hash_table (info), copy,
4802				FALSE, FALSE, FALSE);
4803    }
4804
4805  bfd_release (abfd, copy);
4806  return h;
4807}
4808
4809/* Add symbols from an ELF archive file to the linker hash table.  We
4810   don't use _bfd_generic_link_add_archive_symbols because of a
4811   problem which arises on UnixWare.  The UnixWare libc.so is an
4812   archive which includes an entry libc.so.1 which defines a bunch of
4813   symbols.  The libc.so archive also includes a number of other
4814   object files, which also define symbols, some of which are the same
4815   as those defined in libc.so.1.  Correct linking requires that we
4816   consider each object file in turn, and include it if it defines any
4817   symbols we need.  _bfd_generic_link_add_archive_symbols does not do
4818   this; it looks through the list of undefined symbols, and includes
4819   any object file which defines them.  When this algorithm is used on
4820   UnixWare, it winds up pulling in libc.so.1 early and defining a
4821   bunch of symbols.  This means that some of the other objects in the
4822   archive are not included in the link, which is incorrect since they
4823   precede libc.so.1 in the archive.
4824
4825   Fortunately, ELF archive handling is simpler than that done by
4826   _bfd_generic_link_add_archive_symbols, which has to allow for a.out
4827   oddities.  In ELF, if we find a symbol in the archive map, and the
4828   symbol is currently undefined, we know that we must pull in that
4829   object file.
4830
4831   Unfortunately, we do have to make multiple passes over the symbol
4832   table until nothing further is resolved.  */
4833
4834static bfd_boolean
4835elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
4836{
4837  symindex c;
4838  bfd_boolean *defined = NULL;
4839  bfd_boolean *included = NULL;
4840  carsym *symdefs;
4841  bfd_boolean loop;
4842  bfd_size_type amt;
4843  const struct elf_backend_data *bed;
4844  struct elf_link_hash_entry * (*archive_symbol_lookup)
4845    (bfd *, struct bfd_link_info *, const char *);
4846
4847  if (! bfd_has_map (abfd))
4848    {
4849      /* An empty archive is a special case.  */
4850      if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
4851	return TRUE;
4852      bfd_set_error (bfd_error_no_armap);
4853      return FALSE;
4854    }
4855
4856  /* Keep track of all symbols we know to be already defined, and all
4857     files we know to be already included.  This is to speed up the
4858     second and subsequent passes.  */
4859  c = bfd_ardata (abfd)->symdef_count;
4860  if (c == 0)
4861    return TRUE;
4862  amt = c;
4863  amt *= sizeof (bfd_boolean);
4864  defined = bfd_zmalloc (amt);
4865  included = bfd_zmalloc (amt);
4866  if (defined == NULL || included == NULL)
4867    goto error_return;
4868
4869  symdefs = bfd_ardata (abfd)->symdefs;
4870  bed = get_elf_backend_data (abfd);
4871  archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
4872
4873  do
4874    {
4875      file_ptr last;
4876      symindex i;
4877      carsym *symdef;
4878      carsym *symdefend;
4879
4880      loop = FALSE;
4881      last = -1;
4882
4883      symdef = symdefs;
4884      symdefend = symdef + c;
4885      for (i = 0; symdef < symdefend; symdef++, i++)
4886	{
4887	  struct elf_link_hash_entry *h;
4888	  bfd *element;
4889	  struct bfd_link_hash_entry *undefs_tail;
4890	  symindex mark;
4891
4892	  if (defined[i] || included[i])
4893	    continue;
4894	  if (symdef->file_offset == last)
4895	    {
4896	      included[i] = TRUE;
4897	      continue;
4898	    }
4899
4900	  h = archive_symbol_lookup (abfd, info, symdef->name);
4901	  if (h == (struct elf_link_hash_entry *) 0 - 1)
4902	    goto error_return;
4903
4904	  if (h == NULL)
4905	    continue;
4906
4907	  if (h->root.type == bfd_link_hash_common)
4908	    {
4909	      /* We currently have a common symbol.  The archive map contains
4910		 a reference to this symbol, so we may want to include it.  We
4911		 only want to include it however, if this archive element
4912		 contains a definition of the symbol, not just another common
4913		 declaration of it.
4914
4915		 Unfortunately some archivers (including GNU ar) will put
4916		 declarations of common symbols into their archive maps, as
4917		 well as real definitions, so we cannot just go by the archive
4918		 map alone.  Instead we must read in the element's symbol
4919		 table and check that to see what kind of symbol definition
4920		 this is.  */
4921	      if (! elf_link_is_defined_archive_symbol (abfd, symdef))
4922		continue;
4923	    }
4924	  else if (h->root.type != bfd_link_hash_undefined)
4925	    {
4926	      if (h->root.type != bfd_link_hash_undefweak)
4927		defined[i] = TRUE;
4928	      continue;
4929	    }
4930
4931	  /* We need to include this archive member.  */
4932	  element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
4933	  if (element == NULL)
4934	    goto error_return;
4935
4936	  if (! bfd_check_format (element, bfd_object))
4937	    goto error_return;
4938
4939	  /* Doublecheck that we have not included this object
4940	     already--it should be impossible, but there may be
4941	     something wrong with the archive.  */
4942	  if (element->archive_pass != 0)
4943	    {
4944	      bfd_set_error (bfd_error_bad_value);
4945	      goto error_return;
4946	    }
4947	  element->archive_pass = 1;
4948
4949	  undefs_tail = info->hash->undefs_tail;
4950
4951	  if (! (*info->callbacks->add_archive_element) (info, element,
4952							 symdef->name))
4953	    goto error_return;
4954	  if (! bfd_link_add_symbols (element, info))
4955	    goto error_return;
4956
4957	  /* If there are any new undefined symbols, we need to make
4958	     another pass through the archive in order to see whether
4959	     they can be defined.  FIXME: This isn't perfect, because
4960	     common symbols wind up on undefs_tail and because an
4961	     undefined symbol which is defined later on in this pass
4962	     does not require another pass.  This isn't a bug, but it
4963	     does make the code less efficient than it could be.  */
4964	  if (undefs_tail != info->hash->undefs_tail)
4965	    loop = TRUE;
4966
4967	  /* Look backward to mark all symbols from this object file
4968	     which we have already seen in this pass.  */
4969	  mark = i;
4970	  do
4971	    {
4972	      included[mark] = TRUE;
4973	      if (mark == 0)
4974		break;
4975	      --mark;
4976	    }
4977	  while (symdefs[mark].file_offset == symdef->file_offset);
4978
4979	  /* We mark subsequent symbols from this object file as we go
4980	     on through the loop.  */
4981	  last = symdef->file_offset;
4982	}
4983    }
4984  while (loop);
4985
4986  free (defined);
4987  free (included);
4988
4989  return TRUE;
4990
4991 error_return:
4992  if (defined != NULL)
4993    free (defined);
4994  if (included != NULL)
4995    free (included);
4996  return FALSE;
4997}
4998
4999/* Given an ELF BFD, add symbols to the global hash table as
5000   appropriate.  */
5001
5002bfd_boolean
5003bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5004{
5005  switch (bfd_get_format (abfd))
5006    {
5007    case bfd_object:
5008      return elf_link_add_object_symbols (abfd, info);
5009    case bfd_archive:
5010      return elf_link_add_archive_symbols (abfd, info);
5011    default:
5012      bfd_set_error (bfd_error_wrong_format);
5013      return FALSE;
5014    }
5015}
5016
5017/* This function will be called though elf_link_hash_traverse to store
5018   all hash value of the exported symbols in an array.  */
5019
5020static bfd_boolean
5021elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5022{
5023  unsigned long **valuep = data;
5024  const char *name;
5025  char *p;
5026  unsigned long ha;
5027  char *alc = NULL;
5028
5029  if (h->root.type == bfd_link_hash_warning)
5030    h = (struct elf_link_hash_entry *) h->root.u.i.link;
5031
5032  /* Ignore indirect symbols.  These are added by the versioning code.  */
5033  if (h->dynindx == -1)
5034    return TRUE;
5035
5036  name = h->root.root.string;
5037  p = strchr (name, ELF_VER_CHR);
5038  if (p != NULL)
5039    {
5040      alc = bfd_malloc (p - name + 1);
5041      memcpy (alc, name, p - name);
5042      alc[p - name] = '\0';
5043      name = alc;
5044    }
5045
5046  /* Compute the hash value.  */
5047  ha = bfd_elf_hash (name);
5048
5049  /* Store the found hash value in the array given as the argument.  */
5050  *(*valuep)++ = ha;
5051
5052  /* And store it in the struct so that we can put it in the hash table
5053     later.  */
5054  h->u.elf_hash_value = ha;
5055
5056  if (alc != NULL)
5057    free (alc);
5058
5059  return TRUE;
5060}
5061
5062struct collect_gnu_hash_codes
5063{
5064  bfd *output_bfd;
5065  const struct elf_backend_data *bed;
5066  unsigned long int nsyms;
5067  unsigned long int maskbits;
5068  unsigned long int *hashcodes;
5069  unsigned long int *hashval;
5070  unsigned long int *indx;
5071  unsigned long int *counts;
5072  bfd_vma *bitmask;
5073  bfd_byte *contents;
5074  long int min_dynindx;
5075  unsigned long int bucketcount;
5076  unsigned long int symindx;
5077  long int local_indx;
5078  long int shift1, shift2;
5079  unsigned long int mask;
5080};
5081
5082/* This function will be called though elf_link_hash_traverse to store
5083   all hash value of the exported symbols in an array.  */
5084
5085static bfd_boolean
5086elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5087{
5088  struct collect_gnu_hash_codes *s = data;
5089  const char *name;
5090  char *p;
5091  unsigned long ha;
5092  char *alc = NULL;
5093
5094  if (h->root.type == bfd_link_hash_warning)
5095    h = (struct elf_link_hash_entry *) h->root.u.i.link;
5096
5097  /* Ignore indirect symbols.  These are added by the versioning code.  */
5098  if (h->dynindx == -1)
5099    return TRUE;
5100
5101  /* Ignore also local symbols and undefined symbols.  */
5102  if (! (*s->bed->elf_hash_symbol) (h))
5103    return TRUE;
5104
5105  name = h->root.root.string;
5106  p = strchr (name, ELF_VER_CHR);
5107  if (p != NULL)
5108    {
5109      alc = bfd_malloc (p - name + 1);
5110      memcpy (alc, name, p - name);
5111      alc[p - name] = '\0';
5112      name = alc;
5113    }
5114
5115  /* Compute the hash value.  */
5116  ha = bfd_elf_gnu_hash (name);
5117
5118  /* Store the found hash value in the array for compute_bucket_count,
5119     and also for .dynsym reordering purposes.  */
5120  s->hashcodes[s->nsyms] = ha;
5121  s->hashval[h->dynindx] = ha;
5122  ++s->nsyms;
5123  if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5124    s->min_dynindx = h->dynindx;
5125
5126  if (alc != NULL)
5127    free (alc);
5128
5129  return TRUE;
5130}
5131
5132/* This function will be called though elf_link_hash_traverse to do
5133   final dynaminc symbol renumbering.  */
5134
5135static bfd_boolean
5136elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5137{
5138  struct collect_gnu_hash_codes *s = data;
5139  unsigned long int bucket;
5140  unsigned long int val;
5141
5142  if (h->root.type == bfd_link_hash_warning)
5143    h = (struct elf_link_hash_entry *) h->root.u.i.link;
5144
5145  /* Ignore indirect symbols.  */
5146  if (h->dynindx == -1)
5147    return TRUE;
5148
5149  /* Ignore also local symbols and undefined symbols.  */
5150  if (! (*s->bed->elf_hash_symbol) (h))
5151    {
5152      if (h->dynindx >= s->min_dynindx)
5153	h->dynindx = s->local_indx++;
5154      return TRUE;
5155    }
5156
5157  bucket = s->hashval[h->dynindx] % s->bucketcount;
5158  val = (s->hashval[h->dynindx] >> s->shift1)
5159	& ((s->maskbits >> s->shift1) - 1);
5160  s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5161  s->bitmask[val]
5162    |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5163  val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5164  if (s->counts[bucket] == 1)
5165    /* Last element terminates the chain.  */
5166    val |= 1;
5167  bfd_put_32 (s->output_bfd, val,
5168	      s->contents + (s->indx[bucket] - s->symindx) * 4);
5169  --s->counts[bucket];
5170  h->dynindx = s->indx[bucket]++;
5171  return TRUE;
5172}
5173
5174/* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5175
5176bfd_boolean
5177_bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5178{
5179  return !(h->forced_local
5180	   || h->root.type == bfd_link_hash_undefined
5181	   || h->root.type == bfd_link_hash_undefweak
5182	   || ((h->root.type == bfd_link_hash_defined
5183		|| h->root.type == bfd_link_hash_defweak)
5184	       && h->root.u.def.section->output_section == NULL));
5185}
5186
5187/* Array used to determine the number of hash table buckets to use
5188   based on the number of symbols there are.  If there are fewer than
5189   3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5190   fewer than 37 we use 17 buckets, and so forth.  We never use more
5191   than 32771 buckets.  */
5192
5193static const size_t elf_buckets[] =
5194{
5195  1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5196  16411, 32771, 0
5197};
5198
5199/* Compute bucket count for hashing table.  We do not use a static set
5200   of possible tables sizes anymore.  Instead we determine for all
5201   possible reasonable sizes of the table the outcome (i.e., the
5202   number of collisions etc) and choose the best solution.  The
5203   weighting functions are not too simple to allow the table to grow
5204   without bounds.  Instead one of the weighting factors is the size.
5205   Therefore the result is always a good payoff between few collisions
5206   (= short chain lengths) and table size.  */
5207static size_t
5208compute_bucket_count (struct bfd_link_info *info, unsigned long int *hashcodes,
5209		      unsigned long int nsyms, int gnu_hash)
5210{
5211  size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5212  size_t best_size = 0;
5213  unsigned long int i;
5214  bfd_size_type amt;
5215
5216  /* We have a problem here.  The following code to optimize the table
5217     size requires an integer type with more the 32 bits.  If
5218     BFD_HOST_U_64_BIT is set we know about such a type.  */
5219#ifdef BFD_HOST_U_64_BIT
5220  if (info->optimize)
5221    {
5222      size_t minsize;
5223      size_t maxsize;
5224      BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5225      bfd *dynobj = elf_hash_table (info)->dynobj;
5226      const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5227      unsigned long int *counts;
5228
5229      /* Possible optimization parameters: if we have NSYMS symbols we say
5230	 that the hashing table must at least have NSYMS/4 and at most
5231	 2*NSYMS buckets.  */
5232      minsize = nsyms / 4;
5233      if (minsize == 0)
5234	minsize = 1;
5235      best_size = maxsize = nsyms * 2;
5236      if (gnu_hash)
5237	{
5238	  if (minsize < 2)
5239	    minsize = 2;
5240	  if ((best_size & 31) == 0)
5241	    ++best_size;
5242	}
5243
5244      /* Create array where we count the collisions in.  We must use bfd_malloc
5245	 since the size could be large.  */
5246      amt = maxsize;
5247      amt *= sizeof (unsigned long int);
5248      counts = bfd_malloc (amt);
5249      if (counts == NULL)
5250	return 0;
5251
5252      /* Compute the "optimal" size for the hash table.  The criteria is a
5253	 minimal chain length.  The minor criteria is (of course) the size
5254	 of the table.  */
5255      for (i = minsize; i < maxsize; ++i)
5256	{
5257	  /* Walk through the array of hashcodes and count the collisions.  */
5258	  BFD_HOST_U_64_BIT max;
5259	  unsigned long int j;
5260	  unsigned long int fact;
5261
5262	  if (gnu_hash && (i & 31) == 0)
5263	    continue;
5264
5265	  memset (counts, '\0', i * sizeof (unsigned long int));
5266
5267	  /* Determine how often each hash bucket is used.  */
5268	  for (j = 0; j < nsyms; ++j)
5269	    ++counts[hashcodes[j] % i];
5270
5271	  /* For the weight function we need some information about the
5272	     pagesize on the target.  This is information need not be 100%
5273	     accurate.  Since this information is not available (so far) we
5274	     define it here to a reasonable default value.  If it is crucial
5275	     to have a better value some day simply define this value.  */
5276# ifndef BFD_TARGET_PAGESIZE
5277#  define BFD_TARGET_PAGESIZE	(4096)
5278# endif
5279
5280	  /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5281	     and the chains.  */
5282	  max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5283
5284# if 1
5285	  /* Variant 1: optimize for short chains.  We add the squares
5286	     of all the chain lengths (which favors many small chain
5287	     over a few long chains).  */
5288	  for (j = 0; j < i; ++j)
5289	    max += counts[j] * counts[j];
5290
5291	  /* This adds penalties for the overall size of the table.  */
5292	  fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5293	  max *= fact * fact;
5294# else
5295	  /* Variant 2: Optimize a lot more for small table.  Here we
5296	     also add squares of the size but we also add penalties for
5297	     empty slots (the +1 term).  */
5298	  for (j = 0; j < i; ++j)
5299	    max += (1 + counts[j]) * (1 + counts[j]);
5300
5301	  /* The overall size of the table is considered, but not as
5302	     strong as in variant 1, where it is squared.  */
5303	  fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5304	  max *= fact;
5305# endif
5306
5307	  /* Compare with current best results.  */
5308	  if (max < best_chlen)
5309	    {
5310	      best_chlen = max;
5311	      best_size = i;
5312	    }
5313	}
5314
5315      free (counts);
5316    }
5317  else
5318#endif /* defined (BFD_HOST_U_64_BIT) */
5319    {
5320      /* This is the fallback solution if no 64bit type is available or if we
5321	 are not supposed to spend much time on optimizations.  We select the
5322	 bucket count using a fixed set of numbers.  */
5323      for (i = 0; elf_buckets[i] != 0; i++)
5324	{
5325	  best_size = elf_buckets[i];
5326	  if (nsyms < elf_buckets[i + 1])
5327	    break;
5328	}
5329      if (gnu_hash && best_size < 2)
5330	best_size = 2;
5331    }
5332
5333  return best_size;
5334}
5335
5336/* Set up the sizes and contents of the ELF dynamic sections.  This is
5337   called by the ELF linker emulation before_allocation routine.  We
5338   must set the sizes of the sections before the linker sets the
5339   addresses of the various sections.  */
5340
5341bfd_boolean
5342bfd_elf_size_dynamic_sections (bfd *output_bfd,
5343			       const char *soname,
5344			       const char *rpath,
5345			       const char *filter_shlib,
5346			       const char * const *auxiliary_filters,
5347			       struct bfd_link_info *info,
5348			       asection **sinterpptr,
5349			       struct bfd_elf_version_tree *verdefs)
5350{
5351  bfd_size_type soname_indx;
5352  bfd *dynobj;
5353  const struct elf_backend_data *bed;
5354  struct elf_assign_sym_version_info asvinfo;
5355
5356  *sinterpptr = NULL;
5357
5358  soname_indx = (bfd_size_type) -1;
5359
5360  if (!is_elf_hash_table (info->hash))
5361    return TRUE;
5362
5363  bed = get_elf_backend_data (output_bfd);
5364  elf_tdata (output_bfd)->relro = info->relro;
5365  if (info->execstack)
5366    elf_tdata (output_bfd)->stack_flags = PF_R | PF_W | PF_X;
5367  else if (info->noexecstack)
5368    elf_tdata (output_bfd)->stack_flags = PF_R | PF_W;
5369  else
5370    {
5371      bfd *inputobj;
5372      asection *notesec = NULL;
5373      int exec = 0;
5374
5375      for (inputobj = info->input_bfds;
5376	   inputobj;
5377	   inputobj = inputobj->link_next)
5378	{
5379	  asection *s;
5380
5381	  if (inputobj->flags & (DYNAMIC | BFD_LINKER_CREATED))
5382	    continue;
5383	  s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
5384	  if (s)
5385	    {
5386	      if (s->flags & SEC_CODE)
5387		exec = PF_X;
5388	      notesec = s;
5389	    }
5390	  else if (bed->default_execstack)
5391	    exec = PF_X;
5392	}
5393      if (notesec)
5394	{
5395	  elf_tdata (output_bfd)->stack_flags = PF_R | PF_W | exec;
5396	  if (exec && info->relocatable
5397	      && notesec->output_section != bfd_abs_section_ptr)
5398	    notesec->output_section->flags |= SEC_CODE;
5399	}
5400    }
5401
5402  /* Any syms created from now on start with -1 in
5403     got.refcount/offset and plt.refcount/offset.  */
5404  elf_hash_table (info)->init_got_refcount
5405    = elf_hash_table (info)->init_got_offset;
5406  elf_hash_table (info)->init_plt_refcount
5407    = elf_hash_table (info)->init_plt_offset;
5408
5409  /* The backend may have to create some sections regardless of whether
5410     we're dynamic or not.  */
5411  if (bed->elf_backend_always_size_sections
5412      && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
5413    return FALSE;
5414
5415  if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
5416    return FALSE;
5417
5418  dynobj = elf_hash_table (info)->dynobj;
5419
5420  /* If there were no dynamic objects in the link, there is nothing to
5421     do here.  */
5422  if (dynobj == NULL)
5423    return TRUE;
5424
5425  if (elf_hash_table (info)->dynamic_sections_created)
5426    {
5427      struct elf_info_failed eif;
5428      struct elf_link_hash_entry *h;
5429      asection *dynstr;
5430      struct bfd_elf_version_tree *t;
5431      struct bfd_elf_version_expr *d;
5432      asection *s;
5433      bfd_boolean all_defined;
5434
5435      *sinterpptr = bfd_get_section_by_name (dynobj, ".interp");
5436      BFD_ASSERT (*sinterpptr != NULL || !info->executable);
5437
5438      if (soname != NULL)
5439	{
5440	  soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5441					     soname, TRUE);
5442	  if (soname_indx == (bfd_size_type) -1
5443	      || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
5444	    return FALSE;
5445	}
5446
5447      if (info->symbolic)
5448	{
5449	  if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
5450	    return FALSE;
5451	  info->flags |= DF_SYMBOLIC;
5452	}
5453
5454      if (rpath != NULL)
5455	{
5456	  bfd_size_type indx;
5457
5458	  indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
5459				      TRUE);
5460	  if (indx == (bfd_size_type) -1
5461	      || !_bfd_elf_add_dynamic_entry (info, DT_RPATH, indx))
5462	    return FALSE;
5463
5464	  if  (info->new_dtags)
5465	    {
5466	      _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr, indx);
5467	      if (!_bfd_elf_add_dynamic_entry (info, DT_RUNPATH, indx))
5468		return FALSE;
5469	    }
5470	}
5471
5472      if (filter_shlib != NULL)
5473	{
5474	  bfd_size_type indx;
5475
5476	  indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5477				      filter_shlib, TRUE);
5478	  if (indx == (bfd_size_type) -1
5479	      || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
5480	    return FALSE;
5481	}
5482
5483      if (auxiliary_filters != NULL)
5484	{
5485	  const char * const *p;
5486
5487	  for (p = auxiliary_filters; *p != NULL; p++)
5488	    {
5489	      bfd_size_type indx;
5490
5491	      indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5492					  *p, TRUE);
5493	      if (indx == (bfd_size_type) -1
5494		  || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
5495		return FALSE;
5496	    }
5497	}
5498
5499      eif.info = info;
5500      eif.verdefs = verdefs;
5501      eif.failed = FALSE;
5502
5503      /* If we are supposed to export all symbols into the dynamic symbol
5504	 table (this is not the normal case), then do so.  */
5505      if (info->export_dynamic
5506	  || (info->executable && info->dynamic))
5507	{
5508	  elf_link_hash_traverse (elf_hash_table (info),
5509				  _bfd_elf_export_symbol,
5510				  &eif);
5511	  if (eif.failed)
5512	    return FALSE;
5513	}
5514
5515      /* Make all global versions with definition.  */
5516      for (t = verdefs; t != NULL; t = t->next)
5517	for (d = t->globals.list; d != NULL; d = d->next)
5518	  if (!d->symver && d->symbol)
5519	    {
5520	      const char *verstr, *name;
5521	      size_t namelen, verlen, newlen;
5522	      char *newname, *p;
5523	      struct elf_link_hash_entry *newh;
5524
5525	      name = d->symbol;
5526	      namelen = strlen (name);
5527	      verstr = t->name;
5528	      verlen = strlen (verstr);
5529	      newlen = namelen + verlen + 3;
5530
5531	      newname = bfd_malloc (newlen);
5532	      if (newname == NULL)
5533		return FALSE;
5534	      memcpy (newname, name, namelen);
5535
5536	      /* Check the hidden versioned definition.  */
5537	      p = newname + namelen;
5538	      *p++ = ELF_VER_CHR;
5539	      memcpy (p, verstr, verlen + 1);
5540	      newh = elf_link_hash_lookup (elf_hash_table (info),
5541					   newname, FALSE, FALSE,
5542					   FALSE);
5543	      if (newh == NULL
5544		  || (newh->root.type != bfd_link_hash_defined
5545		      && newh->root.type != bfd_link_hash_defweak))
5546		{
5547		  /* Check the default versioned definition.  */
5548		  *p++ = ELF_VER_CHR;
5549		  memcpy (p, verstr, verlen + 1);
5550		  newh = elf_link_hash_lookup (elf_hash_table (info),
5551					       newname, FALSE, FALSE,
5552					       FALSE);
5553		}
5554	      free (newname);
5555
5556	      /* Mark this version if there is a definition and it is
5557		 not defined in a shared object.  */
5558	      if (newh != NULL
5559		  && !newh->def_dynamic
5560		  && (newh->root.type == bfd_link_hash_defined
5561		      || newh->root.type == bfd_link_hash_defweak))
5562		d->symver = 1;
5563	    }
5564
5565      /* Attach all the symbols to their version information.  */
5566      asvinfo.output_bfd = output_bfd;
5567      asvinfo.info = info;
5568      asvinfo.verdefs = verdefs;
5569      asvinfo.failed = FALSE;
5570
5571      elf_link_hash_traverse (elf_hash_table (info),
5572			      _bfd_elf_link_assign_sym_version,
5573			      &asvinfo);
5574      if (asvinfo.failed)
5575	return FALSE;
5576
5577      if (!info->allow_undefined_version)
5578	{
5579	  /* Check if all global versions have a definition.  */
5580	  all_defined = TRUE;
5581	  for (t = verdefs; t != NULL; t = t->next)
5582	    for (d = t->globals.list; d != NULL; d = d->next)
5583	      if (!d->symver && !d->script)
5584		{
5585		  (*_bfd_error_handler)
5586		    (_("%s: undefined version: %s"),
5587		     d->pattern, t->name);
5588		  all_defined = FALSE;
5589		}
5590
5591	  if (!all_defined)
5592	    {
5593	      bfd_set_error (bfd_error_bad_value);
5594	      return FALSE;
5595	    }
5596	}
5597
5598      /* Find all symbols which were defined in a dynamic object and make
5599	 the backend pick a reasonable value for them.  */
5600      elf_link_hash_traverse (elf_hash_table (info),
5601			      _bfd_elf_adjust_dynamic_symbol,
5602			      &eif);
5603      if (eif.failed)
5604	return FALSE;
5605
5606      /* Add some entries to the .dynamic section.  We fill in some of the
5607	 values later, in bfd_elf_final_link, but we must add the entries
5608	 now so that we know the final size of the .dynamic section.  */
5609
5610      /* If there are initialization and/or finalization functions to
5611	 call then add the corresponding DT_INIT/DT_FINI entries.  */
5612      h = (info->init_function
5613	   ? elf_link_hash_lookup (elf_hash_table (info),
5614				   info->init_function, FALSE,
5615				   FALSE, FALSE)
5616	   : NULL);
5617      if (h != NULL
5618	  && (h->ref_regular
5619	      || h->def_regular))
5620	{
5621	  if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
5622	    return FALSE;
5623	}
5624      h = (info->fini_function
5625	   ? elf_link_hash_lookup (elf_hash_table (info),
5626				   info->fini_function, FALSE,
5627				   FALSE, FALSE)
5628	   : NULL);
5629      if (h != NULL
5630	  && (h->ref_regular
5631	      || h->def_regular))
5632	{
5633	  if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
5634	    return FALSE;
5635	}
5636
5637      s = bfd_get_section_by_name (output_bfd, ".preinit_array");
5638      if (s != NULL && s->linker_has_input)
5639	{
5640	  /* DT_PREINIT_ARRAY is not allowed in shared library.  */
5641	  if (! info->executable)
5642	    {
5643	      bfd *sub;
5644	      asection *o;
5645
5646	      for (sub = info->input_bfds; sub != NULL;
5647		   sub = sub->link_next)
5648		if (bfd_get_flavour (sub) == bfd_target_elf_flavour)
5649		  for (o = sub->sections; o != NULL; o = o->next)
5650		    if (elf_section_data (o)->this_hdr.sh_type
5651			== SHT_PREINIT_ARRAY)
5652		      {
5653			(*_bfd_error_handler)
5654			  (_("%B: .preinit_array section is not allowed in DSO"),
5655			   sub);
5656			break;
5657		      }
5658
5659	      bfd_set_error (bfd_error_nonrepresentable_section);
5660	      return FALSE;
5661	    }
5662
5663	  if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
5664	      || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
5665	    return FALSE;
5666	}
5667      s = bfd_get_section_by_name (output_bfd, ".init_array");
5668      if (s != NULL && s->linker_has_input)
5669	{
5670	  if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
5671	      || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
5672	    return FALSE;
5673	}
5674      s = bfd_get_section_by_name (output_bfd, ".fini_array");
5675      if (s != NULL && s->linker_has_input)
5676	{
5677	  if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
5678	      || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
5679	    return FALSE;
5680	}
5681
5682      dynstr = bfd_get_section_by_name (dynobj, ".dynstr");
5683      /* If .dynstr is excluded from the link, we don't want any of
5684	 these tags.  Strictly, we should be checking each section
5685	 individually;  This quick check covers for the case where
5686	 someone does a /DISCARD/ : { *(*) }.  */
5687      if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
5688	{
5689	  bfd_size_type strsize;
5690
5691	  strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
5692	  if ((info->emit_hash
5693	       && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
5694	      || (info->emit_gnu_hash
5695		  && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
5696	      || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
5697	      || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
5698	      || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
5699	      || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
5700					      bed->s->sizeof_sym))
5701	    return FALSE;
5702	}
5703    }
5704
5705  /* The backend must work out the sizes of all the other dynamic
5706     sections.  */
5707  if (bed->elf_backend_size_dynamic_sections
5708      && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
5709    return FALSE;
5710
5711  if (elf_hash_table (info)->dynamic_sections_created)
5712    {
5713      unsigned long section_sym_count;
5714      asection *s;
5715
5716      /* Set up the version definition section.  */
5717      s = bfd_get_section_by_name (dynobj, ".gnu.version_d");
5718      BFD_ASSERT (s != NULL);
5719
5720      /* We may have created additional version definitions if we are
5721	 just linking a regular application.  */
5722      verdefs = asvinfo.verdefs;
5723
5724      /* Skip anonymous version tag.  */
5725      if (verdefs != NULL && verdefs->vernum == 0)
5726	verdefs = verdefs->next;
5727
5728      if (verdefs == NULL && !info->create_default_symver)
5729	s->flags |= SEC_EXCLUDE;
5730      else
5731	{
5732	  unsigned int cdefs;
5733	  bfd_size_type size;
5734	  struct bfd_elf_version_tree *t;
5735	  bfd_byte *p;
5736	  Elf_Internal_Verdef def;
5737	  Elf_Internal_Verdaux defaux;
5738	  struct bfd_link_hash_entry *bh;
5739	  struct elf_link_hash_entry *h;
5740	  const char *name;
5741
5742	  cdefs = 0;
5743	  size = 0;
5744
5745	  /* Make space for the base version.  */
5746	  size += sizeof (Elf_External_Verdef);
5747	  size += sizeof (Elf_External_Verdaux);
5748	  ++cdefs;
5749
5750	  /* Make space for the default version.  */
5751	  if (info->create_default_symver)
5752	    {
5753	      size += sizeof (Elf_External_Verdef);
5754	      ++cdefs;
5755	    }
5756
5757	  for (t = verdefs; t != NULL; t = t->next)
5758	    {
5759	      struct bfd_elf_version_deps *n;
5760
5761	      size += sizeof (Elf_External_Verdef);
5762	      size += sizeof (Elf_External_Verdaux);
5763	      ++cdefs;
5764
5765	      for (n = t->deps; n != NULL; n = n->next)
5766		size += sizeof (Elf_External_Verdaux);
5767	    }
5768
5769	  s->size = size;
5770	  s->contents = bfd_alloc (output_bfd, s->size);
5771	  if (s->contents == NULL && s->size != 0)
5772	    return FALSE;
5773
5774	  /* Fill in the version definition section.  */
5775
5776	  p = s->contents;
5777
5778	  def.vd_version = VER_DEF_CURRENT;
5779	  def.vd_flags = VER_FLG_BASE;
5780	  def.vd_ndx = 1;
5781	  def.vd_cnt = 1;
5782	  if (info->create_default_symver)
5783	    {
5784	      def.vd_aux = 2 * sizeof (Elf_External_Verdef);
5785	      def.vd_next = sizeof (Elf_External_Verdef);
5786	    }
5787	  else
5788	    {
5789	      def.vd_aux = sizeof (Elf_External_Verdef);
5790	      def.vd_next = (sizeof (Elf_External_Verdef)
5791			     + sizeof (Elf_External_Verdaux));
5792	    }
5793
5794	  if (soname_indx != (bfd_size_type) -1)
5795	    {
5796	      _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
5797				      soname_indx);
5798	      def.vd_hash = bfd_elf_hash (soname);
5799	      defaux.vda_name = soname_indx;
5800	      name = soname;
5801	    }
5802	  else
5803	    {
5804	      bfd_size_type indx;
5805
5806	      name = lbasename (output_bfd->filename);
5807	      def.vd_hash = bfd_elf_hash (name);
5808	      indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5809					  name, FALSE);
5810	      if (indx == (bfd_size_type) -1)
5811		return FALSE;
5812	      defaux.vda_name = indx;
5813	    }
5814	  defaux.vda_next = 0;
5815
5816	  _bfd_elf_swap_verdef_out (output_bfd, &def,
5817				    (Elf_External_Verdef *) p);
5818	  p += sizeof (Elf_External_Verdef);
5819	  if (info->create_default_symver)
5820	    {
5821	      /* Add a symbol representing this version.  */
5822	      bh = NULL;
5823	      if (! (_bfd_generic_link_add_one_symbol
5824		     (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
5825		      0, NULL, FALSE,
5826		      get_elf_backend_data (dynobj)->collect, &bh)))
5827		return FALSE;
5828	      h = (struct elf_link_hash_entry *) bh;
5829	      h->non_elf = 0;
5830	      h->def_regular = 1;
5831	      h->type = STT_OBJECT;
5832	      h->verinfo.vertree = NULL;
5833
5834	      if (! bfd_elf_link_record_dynamic_symbol (info, h))
5835		return FALSE;
5836
5837	      /* Create a duplicate of the base version with the same
5838		 aux block, but different flags.  */
5839	      def.vd_flags = 0;
5840	      def.vd_ndx = 2;
5841	      def.vd_aux = sizeof (Elf_External_Verdef);
5842	      if (verdefs)
5843		def.vd_next = (sizeof (Elf_External_Verdef)
5844			       + sizeof (Elf_External_Verdaux));
5845	      else
5846		def.vd_next = 0;
5847	      _bfd_elf_swap_verdef_out (output_bfd, &def,
5848					(Elf_External_Verdef *) p);
5849	      p += sizeof (Elf_External_Verdef);
5850	    }
5851	  _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
5852				     (Elf_External_Verdaux *) p);
5853	  p += sizeof (Elf_External_Verdaux);
5854
5855	  for (t = verdefs; t != NULL; t = t->next)
5856	    {
5857	      unsigned int cdeps;
5858	      struct bfd_elf_version_deps *n;
5859
5860	      cdeps = 0;
5861	      for (n = t->deps; n != NULL; n = n->next)
5862		++cdeps;
5863
5864	      /* Add a symbol representing this version.  */
5865	      bh = NULL;
5866	      if (! (_bfd_generic_link_add_one_symbol
5867		     (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
5868		      0, NULL, FALSE,
5869		      get_elf_backend_data (dynobj)->collect, &bh)))
5870		return FALSE;
5871	      h = (struct elf_link_hash_entry *) bh;
5872	      h->non_elf = 0;
5873	      h->def_regular = 1;
5874	      h->type = STT_OBJECT;
5875	      h->verinfo.vertree = t;
5876
5877	      if (! bfd_elf_link_record_dynamic_symbol (info, h))
5878		return FALSE;
5879
5880	      def.vd_version = VER_DEF_CURRENT;
5881	      def.vd_flags = 0;
5882	      if (t->globals.list == NULL
5883		  && t->locals.list == NULL
5884		  && ! t->used)
5885		def.vd_flags |= VER_FLG_WEAK;
5886	      def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
5887	      def.vd_cnt = cdeps + 1;
5888	      def.vd_hash = bfd_elf_hash (t->name);
5889	      def.vd_aux = sizeof (Elf_External_Verdef);
5890	      def.vd_next = 0;
5891	      if (t->next != NULL)
5892		def.vd_next = (sizeof (Elf_External_Verdef)
5893			       + (cdeps + 1) * sizeof (Elf_External_Verdaux));
5894
5895	      _bfd_elf_swap_verdef_out (output_bfd, &def,
5896					(Elf_External_Verdef *) p);
5897	      p += sizeof (Elf_External_Verdef);
5898
5899	      defaux.vda_name = h->dynstr_index;
5900	      _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
5901				      h->dynstr_index);
5902	      defaux.vda_next = 0;
5903	      if (t->deps != NULL)
5904		defaux.vda_next = sizeof (Elf_External_Verdaux);
5905	      t->name_indx = defaux.vda_name;
5906
5907	      _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
5908					 (Elf_External_Verdaux *) p);
5909	      p += sizeof (Elf_External_Verdaux);
5910
5911	      for (n = t->deps; n != NULL; n = n->next)
5912		{
5913		  if (n->version_needed == NULL)
5914		    {
5915		      /* This can happen if there was an error in the
5916			 version script.  */
5917		      defaux.vda_name = 0;
5918		    }
5919		  else
5920		    {
5921		      defaux.vda_name = n->version_needed->name_indx;
5922		      _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
5923					      defaux.vda_name);
5924		    }
5925		  if (n->next == NULL)
5926		    defaux.vda_next = 0;
5927		  else
5928		    defaux.vda_next = sizeof (Elf_External_Verdaux);
5929
5930		  _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
5931					     (Elf_External_Verdaux *) p);
5932		  p += sizeof (Elf_External_Verdaux);
5933		}
5934	    }
5935
5936	  if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
5937	      || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, cdefs))
5938	    return FALSE;
5939
5940	  elf_tdata (output_bfd)->cverdefs = cdefs;
5941	}
5942
5943      if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
5944	{
5945	  if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
5946	    return FALSE;
5947	}
5948      else if (info->flags & DF_BIND_NOW)
5949	{
5950	  if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
5951	    return FALSE;
5952	}
5953
5954      if (info->flags_1)
5955	{
5956	  if (info->executable)
5957	    info->flags_1 &= ~ (DF_1_INITFIRST
5958				| DF_1_NODELETE
5959				| DF_1_NOOPEN);
5960	  if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
5961	    return FALSE;
5962	}
5963
5964      /* Work out the size of the version reference section.  */
5965
5966      s = bfd_get_section_by_name (dynobj, ".gnu.version_r");
5967      BFD_ASSERT (s != NULL);
5968      {
5969	struct elf_find_verdep_info sinfo;
5970
5971	sinfo.output_bfd = output_bfd;
5972	sinfo.info = info;
5973	sinfo.vers = elf_tdata (output_bfd)->cverdefs;
5974	if (sinfo.vers == 0)
5975	  sinfo.vers = 1;
5976	sinfo.failed = FALSE;
5977
5978	elf_link_hash_traverse (elf_hash_table (info),
5979				_bfd_elf_link_find_version_dependencies,
5980				&sinfo);
5981
5982	if (elf_tdata (output_bfd)->verref == NULL)
5983	  s->flags |= SEC_EXCLUDE;
5984	else
5985	  {
5986	    Elf_Internal_Verneed *t;
5987	    unsigned int size;
5988	    unsigned int crefs;
5989	    bfd_byte *p;
5990
5991	    /* Build the version definition section.  */
5992	    size = 0;
5993	    crefs = 0;
5994	    for (t = elf_tdata (output_bfd)->verref;
5995		 t != NULL;
5996		 t = t->vn_nextref)
5997	      {
5998		Elf_Internal_Vernaux *a;
5999
6000		size += sizeof (Elf_External_Verneed);
6001		++crefs;
6002		for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6003		  size += sizeof (Elf_External_Vernaux);
6004	      }
6005
6006	    s->size = size;
6007	    s->contents = bfd_alloc (output_bfd, s->size);
6008	    if (s->contents == NULL)
6009	      return FALSE;
6010
6011	    p = s->contents;
6012	    for (t = elf_tdata (output_bfd)->verref;
6013		 t != NULL;
6014		 t = t->vn_nextref)
6015	      {
6016		unsigned int caux;
6017		Elf_Internal_Vernaux *a;
6018		bfd_size_type indx;
6019
6020		caux = 0;
6021		for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6022		  ++caux;
6023
6024		t->vn_version = VER_NEED_CURRENT;
6025		t->vn_cnt = caux;
6026		indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6027					    elf_dt_name (t->vn_bfd) != NULL
6028					    ? elf_dt_name (t->vn_bfd)
6029					    : lbasename (t->vn_bfd->filename),
6030					    FALSE);
6031		if (indx == (bfd_size_type) -1)
6032		  return FALSE;
6033		t->vn_file = indx;
6034		t->vn_aux = sizeof (Elf_External_Verneed);
6035		if (t->vn_nextref == NULL)
6036		  t->vn_next = 0;
6037		else
6038		  t->vn_next = (sizeof (Elf_External_Verneed)
6039				+ caux * sizeof (Elf_External_Vernaux));
6040
6041		_bfd_elf_swap_verneed_out (output_bfd, t,
6042					   (Elf_External_Verneed *) p);
6043		p += sizeof (Elf_External_Verneed);
6044
6045		for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6046		  {
6047		    a->vna_hash = bfd_elf_hash (a->vna_nodename);
6048		    indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6049						a->vna_nodename, FALSE);
6050		    if (indx == (bfd_size_type) -1)
6051		      return FALSE;
6052		    a->vna_name = indx;
6053		    if (a->vna_nextptr == NULL)
6054		      a->vna_next = 0;
6055		    else
6056		      a->vna_next = sizeof (Elf_External_Vernaux);
6057
6058		    _bfd_elf_swap_vernaux_out (output_bfd, a,
6059					       (Elf_External_Vernaux *) p);
6060		    p += sizeof (Elf_External_Vernaux);
6061		  }
6062	      }
6063
6064	    if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6065		|| !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6066	      return FALSE;
6067
6068	    elf_tdata (output_bfd)->cverrefs = crefs;
6069	  }
6070      }
6071
6072      if ((elf_tdata (output_bfd)->cverrefs == 0
6073	   && elf_tdata (output_bfd)->cverdefs == 0)
6074	  || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6075					     &section_sym_count) == 0)
6076	{
6077	  s = bfd_get_section_by_name (dynobj, ".gnu.version");
6078	  s->flags |= SEC_EXCLUDE;
6079	}
6080    }
6081  return TRUE;
6082}
6083
6084/* Find the first non-excluded output section.  We'll use its
6085   section symbol for some emitted relocs.  */
6086void
6087_bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6088{
6089  asection *s;
6090
6091  for (s = output_bfd->sections; s != NULL; s = s->next)
6092    if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6093	&& !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6094      {
6095	elf_hash_table (info)->text_index_section = s;
6096	break;
6097      }
6098}
6099
6100/* Find two non-excluded output sections, one for code, one for data.
6101   We'll use their section symbols for some emitted relocs.  */
6102void
6103_bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6104{
6105  asection *s;
6106
6107  for (s = output_bfd->sections; s != NULL; s = s->next)
6108    if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6109	 == (SEC_ALLOC | SEC_READONLY))
6110	&& !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6111      {
6112	elf_hash_table (info)->text_index_section = s;
6113	break;
6114      }
6115
6116  for (s = output_bfd->sections; s != NULL; s = s->next)
6117    if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6118	&& !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6119      {
6120	elf_hash_table (info)->data_index_section = s;
6121	break;
6122      }
6123
6124  if (elf_hash_table (info)->text_index_section == NULL)
6125    elf_hash_table (info)->text_index_section
6126      = elf_hash_table (info)->data_index_section;
6127}
6128
6129bfd_boolean
6130bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6131{
6132  const struct elf_backend_data *bed;
6133
6134  if (!is_elf_hash_table (info->hash))
6135    return TRUE;
6136
6137  bed = get_elf_backend_data (output_bfd);
6138  (*bed->elf_backend_init_index_section) (output_bfd, info);
6139
6140  if (elf_hash_table (info)->dynamic_sections_created)
6141    {
6142      bfd *dynobj;
6143      asection *s;
6144      bfd_size_type dynsymcount;
6145      unsigned long section_sym_count;
6146      unsigned int dtagcount;
6147
6148      dynobj = elf_hash_table (info)->dynobj;
6149
6150      /* Assign dynsym indicies.  In a shared library we generate a
6151	 section symbol for each output section, which come first.
6152	 Next come all of the back-end allocated local dynamic syms,
6153	 followed by the rest of the global symbols.  */
6154
6155      dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6156						    &section_sym_count);
6157
6158      /* Work out the size of the symbol version section.  */
6159      s = bfd_get_section_by_name (dynobj, ".gnu.version");
6160      BFD_ASSERT (s != NULL);
6161      if (dynsymcount != 0
6162	  && (s->flags & SEC_EXCLUDE) == 0)
6163	{
6164	  s->size = dynsymcount * sizeof (Elf_External_Versym);
6165	  s->contents = bfd_zalloc (output_bfd, s->size);
6166	  if (s->contents == NULL)
6167	    return FALSE;
6168
6169	  if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6170	    return FALSE;
6171	}
6172
6173      /* Set the size of the .dynsym and .hash sections.  We counted
6174	 the number of dynamic symbols in elf_link_add_object_symbols.
6175	 We will build the contents of .dynsym and .hash when we build
6176	 the final symbol table, because until then we do not know the
6177	 correct value to give the symbols.  We built the .dynstr
6178	 section as we went along in elf_link_add_object_symbols.  */
6179      s = bfd_get_section_by_name (dynobj, ".dynsym");
6180      BFD_ASSERT (s != NULL);
6181      s->size = dynsymcount * bed->s->sizeof_sym;
6182
6183      if (dynsymcount != 0)
6184	{
6185	  s->contents = bfd_alloc (output_bfd, s->size);
6186	  if (s->contents == NULL)
6187	    return FALSE;
6188
6189	  /* The first entry in .dynsym is a dummy symbol.
6190	     Clear all the section syms, in case we don't output them all.  */
6191	  ++section_sym_count;
6192	  memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6193	}
6194
6195      elf_hash_table (info)->bucketcount = 0;
6196
6197      /* Compute the size of the hashing table.  As a side effect this
6198	 computes the hash values for all the names we export.  */
6199      if (info->emit_hash)
6200	{
6201	  unsigned long int *hashcodes;
6202	  unsigned long int *hashcodesp;
6203	  bfd_size_type amt;
6204	  unsigned long int nsyms;
6205	  size_t bucketcount;
6206	  size_t hash_entry_size;
6207
6208	  /* Compute the hash values for all exported symbols.  At the same
6209	     time store the values in an array so that we could use them for
6210	     optimizations.  */
6211	  amt = dynsymcount * sizeof (unsigned long int);
6212	  hashcodes = bfd_malloc (amt);
6213	  if (hashcodes == NULL)
6214	    return FALSE;
6215	  hashcodesp = hashcodes;
6216
6217	  /* Put all hash values in HASHCODES.  */
6218	  elf_link_hash_traverse (elf_hash_table (info),
6219				  elf_collect_hash_codes, &hashcodesp);
6220
6221	  nsyms = hashcodesp - hashcodes;
6222	  bucketcount
6223	    = compute_bucket_count (info, hashcodes, nsyms, 0);
6224	  free (hashcodes);
6225
6226	  if (bucketcount == 0)
6227	    return FALSE;
6228
6229	  elf_hash_table (info)->bucketcount = bucketcount;
6230
6231	  s = bfd_get_section_by_name (dynobj, ".hash");
6232	  BFD_ASSERT (s != NULL);
6233	  hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6234	  s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6235	  s->contents = bfd_zalloc (output_bfd, s->size);
6236	  if (s->contents == NULL)
6237	    return FALSE;
6238
6239	  bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6240	  bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6241		   s->contents + hash_entry_size);
6242	}
6243
6244      if (info->emit_gnu_hash)
6245	{
6246	  size_t i, cnt;
6247	  unsigned char *contents;
6248	  struct collect_gnu_hash_codes cinfo;
6249	  bfd_size_type amt;
6250	  size_t bucketcount;
6251
6252	  memset (&cinfo, 0, sizeof (cinfo));
6253
6254	  /* Compute the hash values for all exported symbols.  At the same
6255	     time store the values in an array so that we could use them for
6256	     optimizations.  */
6257	  amt = dynsymcount * 2 * sizeof (unsigned long int);
6258	  cinfo.hashcodes = bfd_malloc (amt);
6259	  if (cinfo.hashcodes == NULL)
6260	    return FALSE;
6261
6262	  cinfo.hashval = cinfo.hashcodes + dynsymcount;
6263	  cinfo.min_dynindx = -1;
6264	  cinfo.output_bfd = output_bfd;
6265	  cinfo.bed = bed;
6266
6267	  /* Put all hash values in HASHCODES.  */
6268	  elf_link_hash_traverse (elf_hash_table (info),
6269				  elf_collect_gnu_hash_codes, &cinfo);
6270
6271	  bucketcount
6272	    = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
6273
6274	  if (bucketcount == 0)
6275	    {
6276	      free (cinfo.hashcodes);
6277	      return FALSE;
6278	    }
6279
6280	  s = bfd_get_section_by_name (dynobj, ".gnu.hash");
6281	  BFD_ASSERT (s != NULL);
6282
6283	  if (cinfo.nsyms == 0)
6284	    {
6285	      /* Empty .gnu.hash section is special.  */
6286	      BFD_ASSERT (cinfo.min_dynindx == -1);
6287	      free (cinfo.hashcodes);
6288	      s->size = 5 * 4 + bed->s->arch_size / 8;
6289	      contents = bfd_zalloc (output_bfd, s->size);
6290	      if (contents == NULL)
6291		return FALSE;
6292	      s->contents = contents;
6293	      /* 1 empty bucket.  */
6294	      bfd_put_32 (output_bfd, 1, contents);
6295	      /* SYMIDX above the special symbol 0.  */
6296	      bfd_put_32 (output_bfd, 1, contents + 4);
6297	      /* Just one word for bitmask.  */
6298	      bfd_put_32 (output_bfd, 1, contents + 8);
6299	      /* Only hash fn bloom filter.  */
6300	      bfd_put_32 (output_bfd, 0, contents + 12);
6301	      /* No hashes are valid - empty bitmask.  */
6302	      bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
6303	      /* No hashes in the only bucket.  */
6304	      bfd_put_32 (output_bfd, 0,
6305			  contents + 16 + bed->s->arch_size / 8);
6306	    }
6307	  else
6308	    {
6309	      unsigned long int maskwords, maskbitslog2;
6310	      BFD_ASSERT (cinfo.min_dynindx != -1);
6311
6312	      maskbitslog2 = bfd_log2 (cinfo.nsyms) + 1;
6313	      if (maskbitslog2 < 3)
6314		maskbitslog2 = 5;
6315	      else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
6316		maskbitslog2 = maskbitslog2 + 3;
6317	      else
6318		maskbitslog2 = maskbitslog2 + 2;
6319	      if (bed->s->arch_size == 64)
6320		{
6321		  if (maskbitslog2 == 5)
6322		    maskbitslog2 = 6;
6323		  cinfo.shift1 = 6;
6324		}
6325	      else
6326		cinfo.shift1 = 5;
6327	      cinfo.mask = (1 << cinfo.shift1) - 1;
6328	      cinfo.shift2 = maskbitslog2;
6329	      cinfo.maskbits = 1 << maskbitslog2;
6330	      maskwords = 1 << (maskbitslog2 - cinfo.shift1);
6331	      amt = bucketcount * sizeof (unsigned long int) * 2;
6332	      amt += maskwords * sizeof (bfd_vma);
6333	      cinfo.bitmask = bfd_malloc (amt);
6334	      if (cinfo.bitmask == NULL)
6335		{
6336		  free (cinfo.hashcodes);
6337		  return FALSE;
6338		}
6339
6340	      cinfo.counts = (void *) (cinfo.bitmask + maskwords);
6341	      cinfo.indx = cinfo.counts + bucketcount;
6342	      cinfo.symindx = dynsymcount - cinfo.nsyms;
6343	      memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
6344
6345	      /* Determine how often each hash bucket is used.  */
6346	      memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
6347	      for (i = 0; i < cinfo.nsyms; ++i)
6348		++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
6349
6350	      for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
6351		if (cinfo.counts[i] != 0)
6352		  {
6353		    cinfo.indx[i] = cnt;
6354		    cnt += cinfo.counts[i];
6355		  }
6356	      BFD_ASSERT (cnt == dynsymcount);
6357	      cinfo.bucketcount = bucketcount;
6358	      cinfo.local_indx = cinfo.min_dynindx;
6359
6360	      s->size = (4 + bucketcount + cinfo.nsyms) * 4;
6361	      s->size += cinfo.maskbits / 8;
6362	      contents = bfd_zalloc (output_bfd, s->size);
6363	      if (contents == NULL)
6364		{
6365		  free (cinfo.bitmask);
6366		  free (cinfo.hashcodes);
6367		  return FALSE;
6368		}
6369
6370	      s->contents = contents;
6371	      bfd_put_32 (output_bfd, bucketcount, contents);
6372	      bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
6373	      bfd_put_32 (output_bfd, maskwords, contents + 8);
6374	      bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
6375	      contents += 16 + cinfo.maskbits / 8;
6376
6377	      for (i = 0; i < bucketcount; ++i)
6378		{
6379		  if (cinfo.counts[i] == 0)
6380		    bfd_put_32 (output_bfd, 0, contents);
6381		  else
6382		    bfd_put_32 (output_bfd, cinfo.indx[i], contents);
6383		  contents += 4;
6384		}
6385
6386	      cinfo.contents = contents;
6387
6388	      /* Renumber dynamic symbols, populate .gnu.hash section.  */
6389	      elf_link_hash_traverse (elf_hash_table (info),
6390				      elf_renumber_gnu_hash_syms, &cinfo);
6391
6392	      contents = s->contents + 16;
6393	      for (i = 0; i < maskwords; ++i)
6394		{
6395		  bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
6396			   contents);
6397		  contents += bed->s->arch_size / 8;
6398		}
6399
6400	      free (cinfo.bitmask);
6401	      free (cinfo.hashcodes);
6402	    }
6403	}
6404
6405      s = bfd_get_section_by_name (dynobj, ".dynstr");
6406      BFD_ASSERT (s != NULL);
6407
6408      elf_finalize_dynstr (output_bfd, info);
6409
6410      s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6411
6412      for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
6413	if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
6414	  return FALSE;
6415    }
6416
6417  return TRUE;
6418}
6419
6420/* Final phase of ELF linker.  */
6421
6422/* A structure we use to avoid passing large numbers of arguments.  */
6423
6424struct elf_final_link_info
6425{
6426  /* General link information.  */
6427  struct bfd_link_info *info;
6428  /* Output BFD.  */
6429  bfd *output_bfd;
6430  /* Symbol string table.  */
6431  struct bfd_strtab_hash *symstrtab;
6432  /* .dynsym section.  */
6433  asection *dynsym_sec;
6434  /* .hash section.  */
6435  asection *hash_sec;
6436  /* symbol version section (.gnu.version).  */
6437  asection *symver_sec;
6438  /* Buffer large enough to hold contents of any section.  */
6439  bfd_byte *contents;
6440  /* Buffer large enough to hold external relocs of any section.  */
6441  void *external_relocs;
6442  /* Buffer large enough to hold internal relocs of any section.  */
6443  Elf_Internal_Rela *internal_relocs;
6444  /* Buffer large enough to hold external local symbols of any input
6445     BFD.  */
6446  bfd_byte *external_syms;
6447  /* And a buffer for symbol section indices.  */
6448  Elf_External_Sym_Shndx *locsym_shndx;
6449  /* Buffer large enough to hold internal local symbols of any input
6450     BFD.  */
6451  Elf_Internal_Sym *internal_syms;
6452  /* Array large enough to hold a symbol index for each local symbol
6453     of any input BFD.  */
6454  long *indices;
6455  /* Array large enough to hold a section pointer for each local
6456     symbol of any input BFD.  */
6457  asection **sections;
6458  /* Buffer to hold swapped out symbols.  */
6459  bfd_byte *symbuf;
6460  /* And one for symbol section indices.  */
6461  Elf_External_Sym_Shndx *symshndxbuf;
6462  /* Number of swapped out symbols in buffer.  */
6463  size_t symbuf_count;
6464  /* Number of symbols which fit in symbuf.  */
6465  size_t symbuf_size;
6466  /* And same for symshndxbuf.  */
6467  size_t shndxbuf_size;
6468};
6469
6470/* This struct is used to pass information to elf_link_output_extsym.  */
6471
6472struct elf_outext_info
6473{
6474  bfd_boolean failed;
6475  bfd_boolean localsyms;
6476  struct elf_final_link_info *finfo;
6477};
6478
6479
6480/* Support for evaluating a complex relocation.
6481
6482   Complex relocations are generalized, self-describing relocations.  The
6483   implementation of them consists of two parts: complex symbols, and the
6484   relocations themselves.
6485
6486   The relocations are use a reserved elf-wide relocation type code (R_RELC
6487   external / BFD_RELOC_RELC internal) and an encoding of relocation field
6488   information (start bit, end bit, word width, etc) into the addend.  This
6489   information is extracted from CGEN-generated operand tables within gas.
6490
6491   Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
6492   internal) representing prefix-notation expressions, including but not
6493   limited to those sorts of expressions normally encoded as addends in the
6494   addend field.  The symbol mangling format is:
6495
6496   <node> := <literal>
6497          |  <unary-operator> ':' <node>
6498          |  <binary-operator> ':' <node> ':' <node>
6499	  ;
6500
6501   <literal> := 's' <digits=N> ':' <N character symbol name>
6502             |  'S' <digits=N> ':' <N character section name>
6503	     |  '#' <hexdigits>
6504	     ;
6505
6506   <binary-operator> := as in C
6507   <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
6508
6509static void
6510set_symbol_value (bfd *                         bfd_with_globals,
6511		  struct elf_final_link_info *  finfo,
6512		  int                           symidx,
6513		  bfd_vma                       val)
6514{
6515  bfd_boolean                    is_local;
6516  Elf_Internal_Sym *             sym;
6517  struct elf_link_hash_entry **  sym_hashes;
6518  struct elf_link_hash_entry *   h;
6519
6520  sym_hashes = elf_sym_hashes (bfd_with_globals);
6521  sym = finfo->internal_syms + symidx;
6522  is_local = ELF_ST_BIND(sym->st_info) == STB_LOCAL;
6523
6524  if (is_local)
6525    {
6526      /* It is a local symbol: move it to the
6527	 "absolute" section and give it a value.  */
6528      sym->st_shndx = SHN_ABS;
6529      sym->st_value = val;
6530    }
6531  else
6532    {
6533      /* It is a global symbol: set its link type
6534	 to "defined" and give it a value.  */
6535      h = sym_hashes [symidx];
6536      while (h->root.type == bfd_link_hash_indirect
6537	     || h->root.type == bfd_link_hash_warning)
6538	h = (struct elf_link_hash_entry *) h->root.u.i.link;
6539      h->root.type = bfd_link_hash_defined;
6540      h->root.u.def.value = val;
6541      h->root.u.def.section = bfd_abs_section_ptr;
6542    }
6543}
6544
6545static bfd_boolean
6546resolve_symbol (const char *                  name,
6547		bfd *                         input_bfd,
6548		struct elf_final_link_info *  finfo,
6549		bfd_vma *                     result,
6550		size_t                        locsymcount)
6551{
6552  Elf_Internal_Sym *            sym;
6553  struct bfd_link_hash_entry *  global_entry;
6554  const char *                  candidate = NULL;
6555  Elf_Internal_Shdr *           symtab_hdr;
6556  asection *                    sec = NULL;
6557  size_t                        i;
6558
6559  symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
6560
6561  for (i = 0; i < locsymcount; ++ i)
6562    {
6563      sym = finfo->internal_syms + i;
6564      sec = finfo->sections [i];
6565
6566      if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
6567	continue;
6568
6569      candidate = bfd_elf_string_from_elf_section (input_bfd,
6570						   symtab_hdr->sh_link,
6571						   sym->st_name);
6572#ifdef DEBUG
6573      printf ("Comparing string: '%s' vs. '%s' = 0x%x\n",
6574	      name, candidate, (unsigned int)sym->st_value);
6575#endif
6576      if (candidate && strcmp (candidate, name) == 0)
6577	{
6578	  * result = sym->st_value;
6579
6580	  if (sym->st_shndx > SHN_UNDEF &&
6581	      sym->st_shndx < SHN_LORESERVE)
6582	    {
6583#ifdef DEBUG
6584	      printf ("adjusting for sec '%s' @ 0x%x + 0x%x\n",
6585		      sec->output_section->name,
6586		      (unsigned int)sec->output_section->vma,
6587		      (unsigned int)sec->output_offset);
6588#endif
6589	      * result += sec->output_offset + sec->output_section->vma;
6590	    }
6591#ifdef DEBUG
6592	  printf ("Found symbol with effective value %8.8x\n", (unsigned int)* result);
6593#endif
6594	  return TRUE;
6595	}
6596    }
6597
6598  /* Hmm, haven't found it yet. perhaps it is a global.  */
6599  global_entry = bfd_link_hash_lookup (finfo->info->hash, name, FALSE, FALSE, TRUE);
6600  if (!global_entry)
6601    return FALSE;
6602
6603  if (global_entry->type == bfd_link_hash_defined
6604      || global_entry->type == bfd_link_hash_defweak)
6605    {
6606      * result = global_entry->u.def.value
6607	+ global_entry->u.def.section->output_section->vma
6608	+ global_entry->u.def.section->output_offset;
6609#ifdef DEBUG
6610      printf ("Found GLOBAL symbol '%s' with value %8.8x\n",
6611	      global_entry->root.string, (unsigned int)*result);
6612#endif
6613      return TRUE;
6614    }
6615
6616  if (global_entry->type == bfd_link_hash_common)
6617    {
6618      *result = global_entry->u.def.value +
6619	bfd_com_section_ptr->output_section->vma +
6620	bfd_com_section_ptr->output_offset;
6621#ifdef DEBUG
6622      printf ("Found COMMON symbol '%s' with value %8.8x\n",
6623	      global_entry->root.string, (unsigned int)*result);
6624#endif
6625      return TRUE;
6626    }
6627
6628  return FALSE;
6629}
6630
6631static bfd_boolean
6632resolve_section (const char *  name,
6633		 asection *    sections,
6634		 bfd_vma *     result)
6635{
6636  asection *    curr;
6637  unsigned int  len;
6638
6639  for (curr = sections; curr; curr = curr->next)
6640    if (strcmp (curr->name, name) == 0)
6641      {
6642	*result = curr->vma;
6643	return TRUE;
6644      }
6645
6646  /* Hmm. still haven't found it. try pseudo-section names.  */
6647  for (curr = sections; curr; curr = curr->next)
6648    {
6649      len = strlen (curr->name);
6650      if (len > strlen (name))
6651	continue;
6652
6653      if (strncmp (curr->name, name, len) == 0)
6654	{
6655	  if (strncmp (".end", name + len, 4) == 0)
6656	    {
6657	      *result = curr->vma + curr->size;
6658	      return TRUE;
6659	    }
6660
6661	  /* Insert more pseudo-section names here, if you like.  */
6662	}
6663    }
6664
6665  return FALSE;
6666}
6667
6668static void
6669undefined_reference (const char *  reftype,
6670		     const char *  name)
6671{
6672  _bfd_error_handler (_("undefined %s reference in complex symbol: %s"), reftype, name);
6673}
6674
6675static bfd_boolean
6676eval_symbol (bfd_vma *                     result,
6677	     char *                        sym,
6678	     char **                       advanced,
6679	     bfd *                         input_bfd,
6680	     struct elf_final_link_info *  finfo,
6681	     bfd_vma                       addr,
6682	     bfd_vma                       section_offset,
6683	     size_t                        locsymcount,
6684	     int                           signed_p)
6685{
6686  int           len;
6687  int           symlen;
6688  bfd_vma       a;
6689  bfd_vma       b;
6690  const int     bufsz = 4096;
6691  char          symbuf [bufsz];
6692  const char *  symend;
6693  bfd_boolean   symbol_is_section = FALSE;
6694
6695  len = strlen (sym);
6696  symend = sym + len;
6697
6698  if (len < 1 || len > bufsz)
6699    {
6700      bfd_set_error (bfd_error_invalid_operation);
6701      return FALSE;
6702    }
6703
6704  switch (* sym)
6705    {
6706    case '.':
6707      * result = addr + section_offset;
6708      * advanced = sym + 1;
6709      return TRUE;
6710
6711    case '#':
6712      ++ sym;
6713      * result = strtoul (sym, advanced, 16);
6714      return TRUE;
6715
6716    case 'S':
6717      symbol_is_section = TRUE;
6718    case 's':
6719      ++ sym;
6720      symlen = strtol (sym, &sym, 10);
6721      ++ sym; /* Skip the trailing ':'.  */
6722
6723      if ((symend < sym) || ((symlen + 1) > bufsz))
6724	{
6725	  bfd_set_error (bfd_error_invalid_operation);
6726	  return FALSE;
6727	}
6728
6729      memcpy (symbuf, sym, symlen);
6730      symbuf [symlen] = '\0';
6731      * advanced = sym + symlen;
6732
6733      /* Is it always possible, with complex symbols, that gas "mis-guessed"
6734	 the symbol as a section, or vice-versa. so we're pretty liberal in our
6735	 interpretation here; section means "try section first", not "must be a
6736	 section", and likewise with symbol.  */
6737
6738      if (symbol_is_section)
6739	{
6740	  if ((resolve_section (symbuf, finfo->output_bfd->sections, result) != TRUE)
6741	      && (resolve_symbol (symbuf, input_bfd, finfo, result, locsymcount) != TRUE))
6742	    {
6743	      undefined_reference ("section", symbuf);
6744	      return FALSE;
6745	    }
6746	}
6747      else
6748	{
6749	  if ((resolve_symbol (symbuf, input_bfd, finfo, result, locsymcount) != TRUE)
6750	      && (resolve_section (symbuf, finfo->output_bfd->sections,
6751				   result) != TRUE))
6752	    {
6753	      undefined_reference ("symbol", symbuf);
6754	      return FALSE;
6755	    }
6756	}
6757
6758      return TRUE;
6759
6760      /* All that remains are operators.  */
6761
6762#define UNARY_OP(op)						\
6763  if (strncmp (sym, #op, strlen (#op)) == 0)			\
6764    {								\
6765      sym += strlen (#op);					\
6766      if (* sym == ':')						\
6767        ++ sym;							\
6768      if (eval_symbol (& a, sym, & sym, input_bfd, finfo, addr, \
6769                       section_offset, locsymcount, signed_p)   \
6770	                                             != TRUE)	\
6771        return FALSE;						\
6772      if (signed_p)                                             \
6773        * result = op ((signed)a);         			\
6774      else                                                      \
6775        * result = op a;                                        \
6776      * advanced = sym; 					\
6777      return TRUE;						\
6778    }
6779
6780#define BINARY_OP(op)						\
6781  if (strncmp (sym, #op, strlen (#op)) == 0)			\
6782    {								\
6783      sym += strlen (#op);					\
6784      if (* sym == ':')						\
6785        ++ sym;							\
6786      if (eval_symbol (& a, sym, & sym, input_bfd, finfo, addr, \
6787                       section_offset, locsymcount, signed_p)   \
6788                                                     != TRUE)	\
6789        return FALSE;						\
6790      ++ sym;							\
6791      if (eval_symbol (& b, sym, & sym, input_bfd, finfo, addr, \
6792                       section_offset, locsymcount, signed_p)   \
6793                                                     != TRUE)	\
6794        return FALSE;						\
6795      if (signed_p)                                             \
6796        * result = ((signed) a) op ((signed) b);	        \
6797      else                                                      \
6798        * result = a op b;                                      \
6799      * advanced = sym;						\
6800      return TRUE;						\
6801    }
6802
6803    default:
6804      UNARY_OP  (0-);
6805      BINARY_OP (<<);
6806      BINARY_OP (>>);
6807      BINARY_OP (==);
6808      BINARY_OP (!=);
6809      BINARY_OP (<=);
6810      BINARY_OP (>=);
6811      BINARY_OP (&&);
6812      BINARY_OP (||);
6813      UNARY_OP  (~);
6814      UNARY_OP  (!);
6815      BINARY_OP (*);
6816      BINARY_OP (/);
6817      BINARY_OP (%);
6818      BINARY_OP (^);
6819      BINARY_OP (|);
6820      BINARY_OP (&);
6821      BINARY_OP (+);
6822      BINARY_OP (-);
6823      BINARY_OP (<);
6824      BINARY_OP (>);
6825#undef UNARY_OP
6826#undef BINARY_OP
6827      _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
6828      bfd_set_error (bfd_error_invalid_operation);
6829      return FALSE;
6830    }
6831}
6832
6833/* Entry point to evaluator, called from elf_link_input_bfd.  */
6834
6835static bfd_boolean
6836evaluate_complex_relocation_symbols (bfd * input_bfd,
6837				     struct elf_final_link_info * finfo,
6838				     size_t locsymcount)
6839{
6840  const struct elf_backend_data * bed;
6841  Elf_Internal_Shdr *             symtab_hdr;
6842  struct elf_link_hash_entry **   sym_hashes;
6843  asection *                      reloc_sec;
6844  bfd_boolean                     result = TRUE;
6845
6846  /* For each section, we're going to check and see if it has any
6847     complex relocations, and we're going to evaluate any of them
6848     we can.  */
6849
6850  if (finfo->info->relocatable)
6851    return TRUE;
6852
6853  symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
6854  sym_hashes = elf_sym_hashes (input_bfd);
6855  bed = get_elf_backend_data (input_bfd);
6856
6857  for (reloc_sec = input_bfd->sections; reloc_sec; reloc_sec = reloc_sec->next)
6858    {
6859      Elf_Internal_Rela * internal_relocs;
6860      unsigned long i;
6861
6862      /* This section was omitted from the link.  */
6863      if (! reloc_sec->linker_mark)
6864	continue;
6865
6866      /* Only process sections containing relocs.  */
6867      if ((reloc_sec->flags & SEC_RELOC) == 0)
6868	continue;
6869
6870      if (reloc_sec->reloc_count == 0)
6871	continue;
6872
6873      /* Read in the relocs for this section.  */
6874      internal_relocs
6875	= _bfd_elf_link_read_relocs (input_bfd, reloc_sec, NULL,
6876				     (Elf_Internal_Rela *) NULL,
6877				     FALSE);
6878      if (internal_relocs == NULL)
6879	continue;
6880
6881      for (i = reloc_sec->reloc_count; i--;)
6882	{
6883	  Elf_Internal_Rela * rel;
6884	  char * sym_name;
6885	  bfd_vma index;
6886	  Elf_Internal_Sym * sym;
6887	  bfd_vma result;
6888	  bfd_vma section_offset;
6889	  bfd_vma addr;
6890	  int signed_p = 0;
6891
6892	  rel = internal_relocs + i;
6893	  section_offset = reloc_sec->output_section->vma
6894	    + reloc_sec->output_offset;
6895	  addr = rel->r_offset;
6896
6897	  index = ELF32_R_SYM (rel->r_info);
6898	  if (bed->s->arch_size == 64)
6899	    index >>= 24;
6900
6901	  if (index == STN_UNDEF)
6902	    continue;
6903
6904	  if (index < locsymcount)
6905	    {
6906	      /* The symbol is local.  */
6907	      sym = finfo->internal_syms + index;
6908
6909	      /* We're only processing STT_RELC or STT_SRELC type symbols.  */
6910	      if ((ELF_ST_TYPE (sym->st_info) != STT_RELC) &&
6911		  (ELF_ST_TYPE (sym->st_info) != STT_SRELC))
6912		continue;
6913
6914	      sym_name = bfd_elf_string_from_elf_section
6915		(input_bfd, symtab_hdr->sh_link, sym->st_name);
6916
6917	      signed_p = (ELF_ST_TYPE (sym->st_info) == STT_SRELC);
6918	    }
6919	  else
6920	    {
6921	      /* The symbol is global.  */
6922	      struct elf_link_hash_entry * h;
6923
6924	      if (elf_bad_symtab (input_bfd))
6925		continue;
6926
6927	      h = sym_hashes [index - locsymcount];
6928	      while (   h->root.type == bfd_link_hash_indirect
6929		     || h->root.type == bfd_link_hash_warning)
6930		h = (struct elf_link_hash_entry *) h->root.u.i.link;
6931
6932	      if (h->type != STT_RELC && h->type != STT_SRELC)
6933		continue;
6934
6935	      signed_p = (h->type == STT_SRELC);
6936	      sym_name = (char *) h->root.root.string;
6937	    }
6938#ifdef DEBUG
6939	  printf ("Encountered a complex symbol!");
6940	  printf (" (input_bfd %s, section %s, reloc %ld\n",
6941		  input_bfd->filename, reloc_sec->name, i);
6942	  printf (" symbol: idx  %8.8lx, name %s\n",
6943		  index, sym_name);
6944	  printf (" reloc : info %8.8lx, addr %8.8lx\n",
6945		  rel->r_info, addr);
6946	  printf (" Evaluating '%s' ...\n ", sym_name);
6947#endif
6948	  if (eval_symbol (& result, sym_name, & sym_name, input_bfd,
6949			   finfo, addr, section_offset, locsymcount,
6950			   signed_p))
6951	    /* Symbol evaluated OK.  Update to absolute value.  */
6952	    set_symbol_value (input_bfd, finfo, index, result);
6953
6954	  else
6955	    result = FALSE;
6956	}
6957
6958      if (internal_relocs != elf_section_data (reloc_sec)->relocs)
6959	free (internal_relocs);
6960    }
6961
6962  /* If nothing went wrong, then we adjusted
6963     everything we wanted to adjust.  */
6964  return result;
6965}
6966
6967static void
6968put_value (bfd_vma        size,
6969	   unsigned long  chunksz,
6970	   bfd *          input_bfd,
6971	   bfd_vma        x,
6972	   bfd_byte *     location)
6973{
6974  location += (size - chunksz);
6975
6976  for (; size; size -= chunksz, location -= chunksz, x >>= (chunksz * 8))
6977    {
6978      switch (chunksz)
6979	{
6980	default:
6981	case 0:
6982	  abort ();
6983	case 1:
6984	  bfd_put_8 (input_bfd, x, location);
6985	  break;
6986	case 2:
6987	  bfd_put_16 (input_bfd, x, location);
6988	  break;
6989	case 4:
6990	  bfd_put_32 (input_bfd, x, location);
6991	  break;
6992	case 8:
6993#ifdef BFD64
6994	  bfd_put_64 (input_bfd, x, location);
6995#else
6996	  abort ();
6997#endif
6998	  break;
6999	}
7000    }
7001}
7002
7003static bfd_vma
7004get_value (bfd_vma        size,
7005	   unsigned long  chunksz,
7006	   bfd *          input_bfd,
7007	   bfd_byte *     location)
7008{
7009  bfd_vma x = 0;
7010
7011  for (; size; size -= chunksz, location += chunksz)
7012    {
7013      switch (chunksz)
7014	{
7015	default:
7016	case 0:
7017	  abort ();
7018	case 1:
7019	  x = (x << (8 * chunksz)) | bfd_get_8 (input_bfd, location);
7020	  break;
7021	case 2:
7022	  x = (x << (8 * chunksz)) | bfd_get_16 (input_bfd, location);
7023	  break;
7024	case 4:
7025	  x = (x << (8 * chunksz)) | bfd_get_32 (input_bfd, location);
7026	  break;
7027	case 8:
7028#ifdef BFD64
7029	  x = (x << (8 * chunksz)) | bfd_get_64 (input_bfd, location);
7030#else
7031	  abort ();
7032#endif
7033	  break;
7034	}
7035    }
7036  return x;
7037}
7038
7039static void
7040decode_complex_addend
7041    (unsigned long * start,   /* in bits */
7042     unsigned long * oplen,   /* in bits */
7043     unsigned long * len,     /* in bits */
7044     unsigned long * wordsz,  /* in bytes */
7045     unsigned long * chunksz,  /* in bytes */
7046     unsigned long * lsb0_p,
7047     unsigned long * signed_p,
7048     unsigned long * trunc_p,
7049     unsigned long encoded)
7050{
7051  * start     =  encoded        & 0x3F;
7052  * len       = (encoded >>  6) & 0x3F;
7053  * oplen     = (encoded >> 12) & 0x3F;
7054  * wordsz    = (encoded >> 18) & 0xF;
7055  * chunksz   = (encoded >> 22) & 0xF;
7056  * lsb0_p    = (encoded >> 27) & 1;
7057  * signed_p  = (encoded >> 28) & 1;
7058  * trunc_p   = (encoded >> 29) & 1;
7059}
7060
7061void
7062bfd_elf_perform_complex_relocation
7063    (bfd *                   output_bfd ATTRIBUTE_UNUSED,
7064     struct bfd_link_info *  info,
7065     bfd *                   input_bfd,
7066     asection *              input_section,
7067     bfd_byte *              contents,
7068     Elf_Internal_Rela *     rel,
7069     Elf_Internal_Sym *      local_syms,
7070     asection **             local_sections)
7071{
7072  const struct elf_backend_data * bed;
7073  Elf_Internal_Shdr * symtab_hdr;
7074  asection * sec;
7075  bfd_vma relocation = 0, shift, x;
7076  bfd_vma r_symndx;
7077  bfd_vma mask;
7078  unsigned long start, oplen, len, wordsz,
7079    chunksz, lsb0_p, signed_p, trunc_p;
7080
7081  /*  Perform this reloc, since it is complex.
7082      (this is not to say that it necessarily refers to a complex
7083      symbol; merely that it is a self-describing CGEN based reloc.
7084      i.e. the addend has the complete reloc information (bit start, end,
7085      word size, etc) encoded within it.).  */
7086  r_symndx = ELF32_R_SYM (rel->r_info);
7087  bed = get_elf_backend_data (input_bfd);
7088  if (bed->s->arch_size == 64)
7089    r_symndx >>= 24;
7090
7091#ifdef DEBUG
7092  printf ("Performing complex relocation %ld...\n", r_symndx);
7093#endif
7094
7095  symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
7096  if (r_symndx < symtab_hdr->sh_info)
7097    {
7098      /* The symbol is local.  */
7099      Elf_Internal_Sym * sym;
7100
7101      sym = local_syms + r_symndx;
7102      sec = local_sections [r_symndx];
7103      relocation = sym->st_value;
7104      if (sym->st_shndx > SHN_UNDEF &&
7105	  sym->st_shndx < SHN_LORESERVE)
7106	relocation += (sec->output_offset +
7107		       sec->output_section->vma);
7108    }
7109  else
7110    {
7111      /* The symbol is global.  */
7112      struct elf_link_hash_entry **sym_hashes;
7113      struct elf_link_hash_entry * h;
7114
7115      sym_hashes = elf_sym_hashes (input_bfd);
7116      h = sym_hashes [r_symndx];
7117
7118      while (h->root.type == bfd_link_hash_indirect
7119	     || h->root.type == bfd_link_hash_warning)
7120	h = (struct elf_link_hash_entry *) h->root.u.i.link;
7121
7122      if (h->root.type == bfd_link_hash_defined
7123	  || h->root.type == bfd_link_hash_defweak)
7124	{
7125	  sec = h->root.u.def.section;
7126	  relocation = h->root.u.def.value;
7127
7128	  if (! bfd_is_abs_section (sec))
7129	    relocation += (sec->output_section->vma
7130			   + sec->output_offset);
7131	}
7132      if (h->root.type == bfd_link_hash_undefined
7133	  && !((*info->callbacks->undefined_symbol)
7134	       (info, h->root.root.string, input_bfd,
7135		input_section, rel->r_offset,
7136		info->unresolved_syms_in_objects == RM_GENERATE_ERROR
7137		|| ELF_ST_VISIBILITY (h->other))))
7138	return;
7139    }
7140
7141  decode_complex_addend (& start, & oplen, & len, & wordsz,
7142			 & chunksz, & lsb0_p, & signed_p,
7143			 & trunc_p, rel->r_addend);
7144
7145  mask = (((1L << (len - 1)) - 1) << 1) | 1;
7146
7147  if (lsb0_p)
7148    shift = (start + 1) - len;
7149  else
7150    shift = (8 * wordsz) - (start + len);
7151
7152  x = get_value (wordsz, chunksz, input_bfd, contents + rel->r_offset);
7153
7154#ifdef DEBUG
7155  printf ("Doing complex reloc: "
7156	  "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
7157	  "chunksz %ld, start %ld, len %ld, oplen %ld\n"
7158	  "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
7159	  lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
7160	  oplen, x, mask,  relocation);
7161#endif
7162
7163  if (! trunc_p)
7164    {
7165      /* Now do an overflow check.  */
7166      if (bfd_check_overflow ((signed_p ?
7167			       complain_overflow_signed :
7168			       complain_overflow_unsigned),
7169			      len, 0, (8 * wordsz),
7170			      relocation) == bfd_reloc_overflow)
7171	(*_bfd_error_handler)
7172	  ("%s (%s + 0x%lx): relocation overflow: 0x%lx %sdoes not fit "
7173	   "within 0x%lx",
7174	   input_bfd->filename, input_section->name, rel->r_offset,
7175	   relocation, (signed_p ? "(signed) " : ""), mask);
7176    }
7177
7178  /* Do the deed.  */
7179  x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
7180
7181#ifdef DEBUG
7182  printf ("           relocation: %8.8lx\n"
7183	  "         shifted mask: %8.8lx\n"
7184	  " shifted/masked reloc: %8.8lx\n"
7185	  "               result: %8.8lx\n",
7186	  relocation, (mask << shift),
7187	  ((relocation & mask) << shift), x);
7188#endif
7189  put_value (wordsz, chunksz, input_bfd, x, contents + rel->r_offset);
7190}
7191
7192/* When performing a relocatable link, the input relocations are
7193   preserved.  But, if they reference global symbols, the indices
7194   referenced must be updated.  Update all the relocations in
7195   REL_HDR (there are COUNT of them), using the data in REL_HASH.  */
7196
7197static void
7198elf_link_adjust_relocs (bfd *abfd,
7199			Elf_Internal_Shdr *rel_hdr,
7200			unsigned int count,
7201			struct elf_link_hash_entry **rel_hash)
7202{
7203  unsigned int i;
7204  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7205  bfd_byte *erela;
7206  void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
7207  void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
7208  bfd_vma r_type_mask;
7209  int r_sym_shift;
7210
7211  if (rel_hdr->sh_entsize == bed->s->sizeof_rel)
7212    {
7213      swap_in = bed->s->swap_reloc_in;
7214      swap_out = bed->s->swap_reloc_out;
7215    }
7216  else if (rel_hdr->sh_entsize == bed->s->sizeof_rela)
7217    {
7218      swap_in = bed->s->swap_reloca_in;
7219      swap_out = bed->s->swap_reloca_out;
7220    }
7221  else
7222    abort ();
7223
7224  if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
7225    abort ();
7226
7227  if (bed->s->arch_size == 32)
7228    {
7229      r_type_mask = 0xff;
7230      r_sym_shift = 8;
7231    }
7232  else
7233    {
7234      r_type_mask = 0xffffffff;
7235      r_sym_shift = 32;
7236    }
7237
7238  erela = rel_hdr->contents;
7239  for (i = 0; i < count; i++, rel_hash++, erela += rel_hdr->sh_entsize)
7240    {
7241      Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
7242      unsigned int j;
7243
7244      if (*rel_hash == NULL)
7245	continue;
7246
7247      BFD_ASSERT ((*rel_hash)->indx >= 0);
7248
7249      (*swap_in) (abfd, erela, irela);
7250      for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
7251	irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
7252			   | (irela[j].r_info & r_type_mask));
7253      (*swap_out) (abfd, irela, erela);
7254    }
7255}
7256
7257struct elf_link_sort_rela
7258{
7259  union {
7260    bfd_vma offset;
7261    bfd_vma sym_mask;
7262  } u;
7263  enum elf_reloc_type_class type;
7264  /* We use this as an array of size int_rels_per_ext_rel.  */
7265  Elf_Internal_Rela rela[1];
7266};
7267
7268static int
7269elf_link_sort_cmp1 (const void *A, const void *B)
7270{
7271  const struct elf_link_sort_rela *a = A;
7272  const struct elf_link_sort_rela *b = B;
7273  int relativea, relativeb;
7274
7275  relativea = a->type == reloc_class_relative;
7276  relativeb = b->type == reloc_class_relative;
7277
7278  if (relativea < relativeb)
7279    return 1;
7280  if (relativea > relativeb)
7281    return -1;
7282  if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
7283    return -1;
7284  if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
7285    return 1;
7286  if (a->rela->r_offset < b->rela->r_offset)
7287    return -1;
7288  if (a->rela->r_offset > b->rela->r_offset)
7289    return 1;
7290  return 0;
7291}
7292
7293static int
7294elf_link_sort_cmp2 (const void *A, const void *B)
7295{
7296  const struct elf_link_sort_rela *a = A;
7297  const struct elf_link_sort_rela *b = B;
7298  int copya, copyb;
7299
7300  if (a->u.offset < b->u.offset)
7301    return -1;
7302  if (a->u.offset > b->u.offset)
7303    return 1;
7304  copya = (a->type == reloc_class_copy) * 2 + (a->type == reloc_class_plt);
7305  copyb = (b->type == reloc_class_copy) * 2 + (b->type == reloc_class_plt);
7306  if (copya < copyb)
7307    return -1;
7308  if (copya > copyb)
7309    return 1;
7310  if (a->rela->r_offset < b->rela->r_offset)
7311    return -1;
7312  if (a->rela->r_offset > b->rela->r_offset)
7313    return 1;
7314  return 0;
7315}
7316
7317static size_t
7318elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
7319{
7320  asection *dynamic_relocs;
7321  asection *rela_dyn;
7322  asection *rel_dyn;
7323  bfd_size_type count, size;
7324  size_t i, ret, sort_elt, ext_size;
7325  bfd_byte *sort, *s_non_relative, *p;
7326  struct elf_link_sort_rela *sq;
7327  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7328  int i2e = bed->s->int_rels_per_ext_rel;
7329  void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
7330  void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
7331  struct bfd_link_order *lo;
7332  bfd_vma r_sym_mask;
7333  bfd_boolean use_rela;
7334
7335  /* Find a dynamic reloc section.  */
7336  rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
7337  rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
7338  if (rela_dyn != NULL && rela_dyn->size > 0
7339      && rel_dyn != NULL && rel_dyn->size > 0)
7340    {
7341      bfd_boolean use_rela_initialised = FALSE;
7342
7343      /* This is just here to stop gcc from complaining.
7344	 It's initialization checking code is not perfect.  */
7345      use_rela = TRUE;
7346
7347      /* Both sections are present.  Examine the sizes
7348	 of the indirect sections to help us choose.  */
7349      for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
7350	if (lo->type == bfd_indirect_link_order)
7351	  {
7352	    asection *o = lo->u.indirect.section;
7353
7354	    if ((o->size % bed->s->sizeof_rela) == 0)
7355	      {
7356		if ((o->size % bed->s->sizeof_rel) == 0)
7357		  /* Section size is divisible by both rel and rela sizes.
7358		     It is of no help to us.  */
7359		  ;
7360		else
7361		  {
7362		    /* Section size is only divisible by rela.  */
7363		    if (use_rela_initialised && (use_rela == FALSE))
7364		      {
7365			_bfd_error_handler
7366			  (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
7367			bfd_set_error (bfd_error_invalid_operation);
7368			return 0;
7369		      }
7370		    else
7371		      {
7372			use_rela = TRUE;
7373			use_rela_initialised = TRUE;
7374		      }
7375		  }
7376	      }
7377	    else if ((o->size % bed->s->sizeof_rel) == 0)
7378	      {
7379		/* Section size is only divisible by rel.  */
7380		if (use_rela_initialised && (use_rela == TRUE))
7381		  {
7382		    _bfd_error_handler
7383		      (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
7384		    bfd_set_error (bfd_error_invalid_operation);
7385		    return 0;
7386		  }
7387		else
7388		  {
7389		    use_rela = FALSE;
7390		    use_rela_initialised = TRUE;
7391		  }
7392	      }
7393	    else
7394	      {
7395		/* The section size is not divisible by either - something is wrong.  */
7396		_bfd_error_handler
7397		  (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
7398		bfd_set_error (bfd_error_invalid_operation);
7399		return 0;
7400	      }
7401	  }
7402
7403      for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
7404	if (lo->type == bfd_indirect_link_order)
7405	  {
7406	    asection *o = lo->u.indirect.section;
7407
7408	    if ((o->size % bed->s->sizeof_rela) == 0)
7409	      {
7410		if ((o->size % bed->s->sizeof_rel) == 0)
7411		  /* Section size is divisible by both rel and rela sizes.
7412		     It is of no help to us.  */
7413		  ;
7414		else
7415		  {
7416		    /* Section size is only divisible by rela.  */
7417		    if (use_rela_initialised && (use_rela == FALSE))
7418		      {
7419			_bfd_error_handler
7420			  (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
7421			bfd_set_error (bfd_error_invalid_operation);
7422			return 0;
7423		      }
7424		    else
7425		      {
7426			use_rela = TRUE;
7427			use_rela_initialised = TRUE;
7428		      }
7429		  }
7430	      }
7431	    else if ((o->size % bed->s->sizeof_rel) == 0)
7432	      {
7433		/* Section size is only divisible by rel.  */
7434		if (use_rela_initialised && (use_rela == TRUE))
7435		  {
7436		    _bfd_error_handler
7437		      (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
7438		    bfd_set_error (bfd_error_invalid_operation);
7439		    return 0;
7440		  }
7441		else
7442		  {
7443		    use_rela = FALSE;
7444		    use_rela_initialised = TRUE;
7445		  }
7446	      }
7447	    else
7448	      {
7449		/* The section size is not divisible by either - something is wrong.  */
7450		_bfd_error_handler
7451		  (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
7452		bfd_set_error (bfd_error_invalid_operation);
7453		return 0;
7454	      }
7455	  }
7456
7457      if (! use_rela_initialised)
7458	/* Make a guess.  */
7459	use_rela = TRUE;
7460    }
7461  else if (rela_dyn != NULL && rela_dyn->size > 0)
7462    use_rela = TRUE;
7463  else if (rel_dyn != NULL && rel_dyn->size > 0)
7464    use_rela = FALSE;
7465  else
7466    return 0;
7467
7468  if (use_rela)
7469    {
7470      dynamic_relocs = rela_dyn;
7471      ext_size = bed->s->sizeof_rela;
7472      swap_in = bed->s->swap_reloca_in;
7473      swap_out = bed->s->swap_reloca_out;
7474    }
7475  else
7476    {
7477      dynamic_relocs = rel_dyn;
7478      ext_size = bed->s->sizeof_rel;
7479      swap_in = bed->s->swap_reloc_in;
7480      swap_out = bed->s->swap_reloc_out;
7481    }
7482
7483  size = 0;
7484  for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
7485    if (lo->type == bfd_indirect_link_order)
7486      size += lo->u.indirect.section->size;
7487
7488  if (size != dynamic_relocs->size)
7489    return 0;
7490
7491  sort_elt = (sizeof (struct elf_link_sort_rela)
7492	      + (i2e - 1) * sizeof (Elf_Internal_Rela));
7493
7494  count = dynamic_relocs->size / ext_size;
7495  sort = bfd_zmalloc (sort_elt * count);
7496
7497  if (sort == NULL)
7498    {
7499      (*info->callbacks->warning)
7500	(info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
7501      return 0;
7502    }
7503
7504  if (bed->s->arch_size == 32)
7505    r_sym_mask = ~(bfd_vma) 0xff;
7506  else
7507    r_sym_mask = ~(bfd_vma) 0xffffffff;
7508
7509  for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
7510    if (lo->type == bfd_indirect_link_order)
7511      {
7512	bfd_byte *erel, *erelend;
7513	asection *o = lo->u.indirect.section;
7514
7515	if (o->contents == NULL && o->size != 0)
7516	  {
7517	    /* This is a reloc section that is being handled as a normal
7518	       section.  See bfd_section_from_shdr.  We can't combine
7519	       relocs in this case.  */
7520	    free (sort);
7521	    return 0;
7522	  }
7523	erel = o->contents;
7524	erelend = o->contents + o->size;
7525	p = sort + o->output_offset / ext_size * sort_elt;
7526
7527	while (erel < erelend)
7528	  {
7529	    struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
7530
7531	    (*swap_in) (abfd, erel, s->rela);
7532	    s->type = (*bed->elf_backend_reloc_type_class) (s->rela);
7533	    s->u.sym_mask = r_sym_mask;
7534	    p += sort_elt;
7535	    erel += ext_size;
7536	  }
7537      }
7538
7539  qsort (sort, count, sort_elt, elf_link_sort_cmp1);
7540
7541  for (i = 0, p = sort; i < count; i++, p += sort_elt)
7542    {
7543      struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
7544      if (s->type != reloc_class_relative)
7545	break;
7546    }
7547  ret = i;
7548  s_non_relative = p;
7549
7550  sq = (struct elf_link_sort_rela *) s_non_relative;
7551  for (; i < count; i++, p += sort_elt)
7552    {
7553      struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
7554      if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
7555	sq = sp;
7556      sp->u.offset = sq->rela->r_offset;
7557    }
7558
7559  qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
7560
7561  for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
7562    if (lo->type == bfd_indirect_link_order)
7563      {
7564	bfd_byte *erel, *erelend;
7565	asection *o = lo->u.indirect.section;
7566
7567	erel = o->contents;
7568	erelend = o->contents + o->size;
7569	p = sort + o->output_offset / ext_size * sort_elt;
7570	while (erel < erelend)
7571	  {
7572	    struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
7573	    (*swap_out) (abfd, s->rela, erel);
7574	    p += sort_elt;
7575	    erel += ext_size;
7576	  }
7577      }
7578
7579  free (sort);
7580  *psec = dynamic_relocs;
7581  return ret;
7582}
7583
7584/* Flush the output symbols to the file.  */
7585
7586static bfd_boolean
7587elf_link_flush_output_syms (struct elf_final_link_info *finfo,
7588			    const struct elf_backend_data *bed)
7589{
7590  if (finfo->symbuf_count > 0)
7591    {
7592      Elf_Internal_Shdr *hdr;
7593      file_ptr pos;
7594      bfd_size_type amt;
7595
7596      hdr = &elf_tdata (finfo->output_bfd)->symtab_hdr;
7597      pos = hdr->sh_offset + hdr->sh_size;
7598      amt = finfo->symbuf_count * bed->s->sizeof_sym;
7599      if (bfd_seek (finfo->output_bfd, pos, SEEK_SET) != 0
7600	  || bfd_bwrite (finfo->symbuf, amt, finfo->output_bfd) != amt)
7601	return FALSE;
7602
7603      hdr->sh_size += amt;
7604      finfo->symbuf_count = 0;
7605    }
7606
7607  return TRUE;
7608}
7609
7610/* Add a symbol to the output symbol table.  */
7611
7612static bfd_boolean
7613elf_link_output_sym (struct elf_final_link_info *finfo,
7614		     const char *name,
7615		     Elf_Internal_Sym *elfsym,
7616		     asection *input_sec,
7617		     struct elf_link_hash_entry *h)
7618{
7619  bfd_byte *dest;
7620  Elf_External_Sym_Shndx *destshndx;
7621  bfd_boolean (*output_symbol_hook)
7622    (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
7623     struct elf_link_hash_entry *);
7624  const struct elf_backend_data *bed;
7625
7626  bed = get_elf_backend_data (finfo->output_bfd);
7627  output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
7628  if (output_symbol_hook != NULL)
7629    {
7630      if (! (*output_symbol_hook) (finfo->info, name, elfsym, input_sec, h))
7631	return FALSE;
7632    }
7633
7634  if (name == NULL || *name == '\0')
7635    elfsym->st_name = 0;
7636  else if (input_sec->flags & SEC_EXCLUDE)
7637    elfsym->st_name = 0;
7638  else
7639    {
7640      elfsym->st_name = (unsigned long) _bfd_stringtab_add (finfo->symstrtab,
7641							    name, TRUE, FALSE);
7642      if (elfsym->st_name == (unsigned long) -1)
7643	return FALSE;
7644    }
7645
7646  if (finfo->symbuf_count >= finfo->symbuf_size)
7647    {
7648      if (! elf_link_flush_output_syms (finfo, bed))
7649	return FALSE;
7650    }
7651
7652  dest = finfo->symbuf + finfo->symbuf_count * bed->s->sizeof_sym;
7653  destshndx = finfo->symshndxbuf;
7654  if (destshndx != NULL)
7655    {
7656      if (bfd_get_symcount (finfo->output_bfd) >= finfo->shndxbuf_size)
7657	{
7658	  bfd_size_type amt;
7659
7660	  amt = finfo->shndxbuf_size * sizeof (Elf_External_Sym_Shndx);
7661	  finfo->symshndxbuf = destshndx = bfd_realloc (destshndx, amt * 2);
7662	  if (destshndx == NULL)
7663	    return FALSE;
7664	  memset ((char *) destshndx + amt, 0, amt);
7665	  finfo->shndxbuf_size *= 2;
7666	}
7667      destshndx += bfd_get_symcount (finfo->output_bfd);
7668    }
7669
7670  bed->s->swap_symbol_out (finfo->output_bfd, elfsym, dest, destshndx);
7671  finfo->symbuf_count += 1;
7672  bfd_get_symcount (finfo->output_bfd) += 1;
7673
7674  return TRUE;
7675}
7676
7677/* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
7678
7679static bfd_boolean
7680check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
7681{
7682  if (sym->st_shndx > SHN_HIRESERVE)
7683    {
7684      /* The gABI doesn't support dynamic symbols in output sections
7685         beyond 64k.  */
7686      (*_bfd_error_handler)
7687	(_("%B: Too many sections: %d (>= %d)"),
7688	 abfd, bfd_count_sections (abfd), SHN_LORESERVE);
7689      bfd_set_error (bfd_error_nonrepresentable_section);
7690      return FALSE;
7691    }
7692  return TRUE;
7693}
7694
7695/* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
7696   allowing an unsatisfied unversioned symbol in the DSO to match a
7697   versioned symbol that would normally require an explicit version.
7698   We also handle the case that a DSO references a hidden symbol
7699   which may be satisfied by a versioned symbol in another DSO.  */
7700
7701static bfd_boolean
7702elf_link_check_versioned_symbol (struct bfd_link_info *info,
7703				 const struct elf_backend_data *bed,
7704				 struct elf_link_hash_entry *h)
7705{
7706  bfd *abfd;
7707  struct elf_link_loaded_list *loaded;
7708
7709  if (!is_elf_hash_table (info->hash))
7710    return FALSE;
7711
7712  switch (h->root.type)
7713    {
7714    default:
7715      abfd = NULL;
7716      break;
7717
7718    case bfd_link_hash_undefined:
7719    case bfd_link_hash_undefweak:
7720      abfd = h->root.u.undef.abfd;
7721      if ((abfd->flags & DYNAMIC) == 0
7722	  || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
7723	return FALSE;
7724      break;
7725
7726    case bfd_link_hash_defined:
7727    case bfd_link_hash_defweak:
7728      abfd = h->root.u.def.section->owner;
7729      break;
7730
7731    case bfd_link_hash_common:
7732      abfd = h->root.u.c.p->section->owner;
7733      break;
7734    }
7735  BFD_ASSERT (abfd != NULL);
7736
7737  for (loaded = elf_hash_table (info)->loaded;
7738       loaded != NULL;
7739       loaded = loaded->next)
7740    {
7741      bfd *input;
7742      Elf_Internal_Shdr *hdr;
7743      bfd_size_type symcount;
7744      bfd_size_type extsymcount;
7745      bfd_size_type extsymoff;
7746      Elf_Internal_Shdr *versymhdr;
7747      Elf_Internal_Sym *isym;
7748      Elf_Internal_Sym *isymend;
7749      Elf_Internal_Sym *isymbuf;
7750      Elf_External_Versym *ever;
7751      Elf_External_Versym *extversym;
7752
7753      input = loaded->abfd;
7754
7755      /* We check each DSO for a possible hidden versioned definition.  */
7756      if (input == abfd
7757	  || (input->flags & DYNAMIC) == 0
7758	  || elf_dynversym (input) == 0)
7759	continue;
7760
7761      hdr = &elf_tdata (input)->dynsymtab_hdr;
7762
7763      symcount = hdr->sh_size / bed->s->sizeof_sym;
7764      if (elf_bad_symtab (input))
7765	{
7766	  extsymcount = symcount;
7767	  extsymoff = 0;
7768	}
7769      else
7770	{
7771	  extsymcount = symcount - hdr->sh_info;
7772	  extsymoff = hdr->sh_info;
7773	}
7774
7775      if (extsymcount == 0)
7776	continue;
7777
7778      isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
7779				      NULL, NULL, NULL);
7780      if (isymbuf == NULL)
7781	return FALSE;
7782
7783      /* Read in any version definitions.  */
7784      versymhdr = &elf_tdata (input)->dynversym_hdr;
7785      extversym = bfd_malloc (versymhdr->sh_size);
7786      if (extversym == NULL)
7787	goto error_ret;
7788
7789      if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
7790	  || (bfd_bread (extversym, versymhdr->sh_size, input)
7791	      != versymhdr->sh_size))
7792	{
7793	  free (extversym);
7794	error_ret:
7795	  free (isymbuf);
7796	  return FALSE;
7797	}
7798
7799      ever = extversym + extsymoff;
7800      isymend = isymbuf + extsymcount;
7801      for (isym = isymbuf; isym < isymend; isym++, ever++)
7802	{
7803	  const char *name;
7804	  Elf_Internal_Versym iver;
7805	  unsigned short version_index;
7806
7807	  if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
7808	      || isym->st_shndx == SHN_UNDEF)
7809	    continue;
7810
7811	  name = bfd_elf_string_from_elf_section (input,
7812						  hdr->sh_link,
7813						  isym->st_name);
7814	  if (strcmp (name, h->root.root.string) != 0)
7815	    continue;
7816
7817	  _bfd_elf_swap_versym_in (input, ever, &iver);
7818
7819	  if ((iver.vs_vers & VERSYM_HIDDEN) == 0)
7820	    {
7821	      /* If we have a non-hidden versioned sym, then it should
7822		 have provided a definition for the undefined sym.  */
7823	      abort ();
7824	    }
7825
7826	  version_index = iver.vs_vers & VERSYM_VERSION;
7827	  if (version_index == 1 || version_index == 2)
7828	    {
7829	      /* This is the base or first version.  We can use it.  */
7830	      free (extversym);
7831	      free (isymbuf);
7832	      return TRUE;
7833	    }
7834	}
7835
7836      free (extversym);
7837      free (isymbuf);
7838    }
7839
7840  return FALSE;
7841}
7842
7843/* Add an external symbol to the symbol table.  This is called from
7844   the hash table traversal routine.  When generating a shared object,
7845   we go through the symbol table twice.  The first time we output
7846   anything that might have been forced to local scope in a version
7847   script.  The second time we output the symbols that are still
7848   global symbols.  */
7849
7850static bfd_boolean
7851elf_link_output_extsym (struct elf_link_hash_entry *h, void *data)
7852{
7853  struct elf_outext_info *eoinfo = data;
7854  struct elf_final_link_info *finfo = eoinfo->finfo;
7855  bfd_boolean strip;
7856  Elf_Internal_Sym sym;
7857  asection *input_sec;
7858  const struct elf_backend_data *bed;
7859
7860  if (h->root.type == bfd_link_hash_warning)
7861    {
7862      h = (struct elf_link_hash_entry *) h->root.u.i.link;
7863      if (h->root.type == bfd_link_hash_new)
7864	return TRUE;
7865    }
7866
7867  /* Decide whether to output this symbol in this pass.  */
7868  if (eoinfo->localsyms)
7869    {
7870      if (!h->forced_local)
7871	return TRUE;
7872    }
7873  else
7874    {
7875      if (h->forced_local)
7876	return TRUE;
7877    }
7878
7879  bed = get_elf_backend_data (finfo->output_bfd);
7880
7881  if (h->root.type == bfd_link_hash_undefined)
7882    {
7883      /* If we have an undefined symbol reference here then it must have
7884	 come from a shared library that is being linked in.  (Undefined
7885	 references in regular files have already been handled).  */
7886      bfd_boolean ignore_undef = FALSE;
7887
7888      /* Some symbols may be special in that the fact that they're
7889	 undefined can be safely ignored - let backend determine that.  */
7890      if (bed->elf_backend_ignore_undef_symbol)
7891	ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
7892
7893      /* If we are reporting errors for this situation then do so now.  */
7894      if (ignore_undef == FALSE
7895	  && h->ref_dynamic
7896	  && ! h->ref_regular
7897	  && ! elf_link_check_versioned_symbol (finfo->info, bed, h)
7898	  && finfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
7899	{
7900	  if (! (finfo->info->callbacks->undefined_symbol
7901		 (finfo->info, h->root.root.string, h->root.u.undef.abfd,
7902		  NULL, 0, finfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR)))
7903	    {
7904	      eoinfo->failed = TRUE;
7905	      return FALSE;
7906	    }
7907	}
7908    }
7909
7910  /* We should also warn if a forced local symbol is referenced from
7911     shared libraries.  */
7912  if (! finfo->info->relocatable
7913      && (! finfo->info->shared)
7914      && h->forced_local
7915      && h->ref_dynamic
7916      && !h->dynamic_def
7917      && !h->dynamic_weak
7918      && ! elf_link_check_versioned_symbol (finfo->info, bed, h))
7919    {
7920      (*_bfd_error_handler)
7921	(_("%B: %s symbol `%s' in %B is referenced by DSO"),
7922	 finfo->output_bfd,
7923	 h->root.u.def.section == bfd_abs_section_ptr
7924	 ? finfo->output_bfd : h->root.u.def.section->owner,
7925	 ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
7926	 ? "internal"
7927	 : ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
7928	 ? "hidden" : "local",
7929	 h->root.root.string);
7930      eoinfo->failed = TRUE;
7931      return FALSE;
7932    }
7933
7934  /* We don't want to output symbols that have never been mentioned by
7935     a regular file, or that we have been told to strip.  However, if
7936     h->indx is set to -2, the symbol is used by a reloc and we must
7937     output it.  */
7938  if (h->indx == -2)
7939    strip = FALSE;
7940  else if ((h->def_dynamic
7941	    || h->ref_dynamic
7942	    || h->root.type == bfd_link_hash_new)
7943	   && !h->def_regular
7944	   && !h->ref_regular)
7945    strip = TRUE;
7946  else if (finfo->info->strip == strip_all)
7947    strip = TRUE;
7948  else if (finfo->info->strip == strip_some
7949	   && bfd_hash_lookup (finfo->info->keep_hash,
7950			       h->root.root.string, FALSE, FALSE) == NULL)
7951    strip = TRUE;
7952  else if (finfo->info->strip_discarded
7953	   && (h->root.type == bfd_link_hash_defined
7954	       || h->root.type == bfd_link_hash_defweak)
7955	   && elf_discarded_section (h->root.u.def.section))
7956    strip = TRUE;
7957  else
7958    strip = FALSE;
7959
7960  /* If we're stripping it, and it's not a dynamic symbol, there's
7961     nothing else to do unless it is a forced local symbol.  */
7962  if (strip
7963      && h->dynindx == -1
7964      && !h->forced_local)
7965    return TRUE;
7966
7967  sym.st_value = 0;
7968  sym.st_size = h->size;
7969  sym.st_other = h->other;
7970  if (h->forced_local)
7971    sym.st_info = ELF_ST_INFO (STB_LOCAL, h->type);
7972  else if (h->root.type == bfd_link_hash_undefweak
7973	   || h->root.type == bfd_link_hash_defweak)
7974    sym.st_info = ELF_ST_INFO (STB_WEAK, h->type);
7975  else
7976    sym.st_info = ELF_ST_INFO (STB_GLOBAL, h->type);
7977
7978  switch (h->root.type)
7979    {
7980    default:
7981    case bfd_link_hash_new:
7982    case bfd_link_hash_warning:
7983      abort ();
7984      return FALSE;
7985
7986    case bfd_link_hash_undefined:
7987    case bfd_link_hash_undefweak:
7988      input_sec = bfd_und_section_ptr;
7989      sym.st_shndx = SHN_UNDEF;
7990      break;
7991
7992    case bfd_link_hash_defined:
7993    case bfd_link_hash_defweak:
7994      {
7995	input_sec = h->root.u.def.section;
7996	if (input_sec->output_section != NULL)
7997	  {
7998	    sym.st_shndx =
7999	      _bfd_elf_section_from_bfd_section (finfo->output_bfd,
8000						 input_sec->output_section);
8001	    if (sym.st_shndx == SHN_BAD)
8002	      {
8003		(*_bfd_error_handler)
8004		  (_("%B: could not find output section %A for input section %A"),
8005		   finfo->output_bfd, input_sec->output_section, input_sec);
8006		eoinfo->failed = TRUE;
8007		return FALSE;
8008	      }
8009
8010	    /* ELF symbols in relocatable files are section relative,
8011	       but in nonrelocatable files they are virtual
8012	       addresses.  */
8013	    sym.st_value = h->root.u.def.value + input_sec->output_offset;
8014	    if (! finfo->info->relocatable)
8015	      {
8016		sym.st_value += input_sec->output_section->vma;
8017		if (h->type == STT_TLS)
8018		  {
8019		    /* STT_TLS symbols are relative to PT_TLS segment
8020		       base.  */
8021		    BFD_ASSERT (elf_hash_table (finfo->info)->tls_sec != NULL);
8022		    sym.st_value -= elf_hash_table (finfo->info)->tls_sec->vma;
8023		  }
8024	      }
8025	  }
8026	else
8027	  {
8028	    BFD_ASSERT (input_sec->owner == NULL
8029			|| (input_sec->owner->flags & DYNAMIC) != 0);
8030	    sym.st_shndx = SHN_UNDEF;
8031	    input_sec = bfd_und_section_ptr;
8032	  }
8033      }
8034      break;
8035
8036    case bfd_link_hash_common:
8037      input_sec = h->root.u.c.p->section;
8038      sym.st_shndx = bed->common_section_index (input_sec);
8039      sym.st_value = 1 << h->root.u.c.p->alignment_power;
8040      break;
8041
8042    case bfd_link_hash_indirect:
8043      /* These symbols are created by symbol versioning.  They point
8044	 to the decorated version of the name.  For example, if the
8045	 symbol foo@@GNU_1.2 is the default, which should be used when
8046	 foo is used with no version, then we add an indirect symbol
8047	 foo which points to foo@@GNU_1.2.  We ignore these symbols,
8048	 since the indirected symbol is already in the hash table.  */
8049      return TRUE;
8050    }
8051
8052  /* Give the processor backend a chance to tweak the symbol value,
8053     and also to finish up anything that needs to be done for this
8054     symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
8055     forced local syms when non-shared is due to a historical quirk.  */
8056  if ((h->dynindx != -1
8057       || h->forced_local)
8058      && ((finfo->info->shared
8059	   && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
8060	       || h->root.type != bfd_link_hash_undefweak))
8061	  || !h->forced_local)
8062      && elf_hash_table (finfo->info)->dynamic_sections_created)
8063    {
8064      if (! ((*bed->elf_backend_finish_dynamic_symbol)
8065	     (finfo->output_bfd, finfo->info, h, &sym)))
8066	{
8067	  eoinfo->failed = TRUE;
8068	  return FALSE;
8069	}
8070    }
8071
8072  /* If we are marking the symbol as undefined, and there are no
8073     non-weak references to this symbol from a regular object, then
8074     mark the symbol as weak undefined; if there are non-weak
8075     references, mark the symbol as strong.  We can't do this earlier,
8076     because it might not be marked as undefined until the
8077     finish_dynamic_symbol routine gets through with it.  */
8078  if (sym.st_shndx == SHN_UNDEF
8079      && h->ref_regular
8080      && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
8081	  || ELF_ST_BIND (sym.st_info) == STB_WEAK))
8082    {
8083      int bindtype;
8084
8085      if (h->ref_regular_nonweak)
8086	bindtype = STB_GLOBAL;
8087      else
8088	bindtype = STB_WEAK;
8089      sym.st_info = ELF_ST_INFO (bindtype, ELF_ST_TYPE (sym.st_info));
8090    }
8091
8092  /* If a non-weak symbol with non-default visibility is not defined
8093     locally, it is a fatal error.  */
8094  if (! finfo->info->relocatable
8095      && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
8096      && ELF_ST_BIND (sym.st_info) != STB_WEAK
8097      && h->root.type == bfd_link_hash_undefined
8098      && !h->def_regular)
8099    {
8100      (*_bfd_error_handler)
8101	(_("%B: %s symbol `%s' isn't defined"),
8102	 finfo->output_bfd,
8103	 ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED
8104	 ? "protected"
8105	 : ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL
8106	 ? "internal" : "hidden",
8107	 h->root.root.string);
8108      eoinfo->failed = TRUE;
8109      return FALSE;
8110    }
8111
8112  /* If this symbol should be put in the .dynsym section, then put it
8113     there now.  We already know the symbol index.  We also fill in
8114     the entry in the .hash section.  */
8115  if (h->dynindx != -1
8116      && elf_hash_table (finfo->info)->dynamic_sections_created)
8117    {
8118      bfd_byte *esym;
8119
8120      sym.st_name = h->dynstr_index;
8121      esym = finfo->dynsym_sec->contents + h->dynindx * bed->s->sizeof_sym;
8122      if (! check_dynsym (finfo->output_bfd, &sym))
8123	{
8124	  eoinfo->failed = TRUE;
8125	  return FALSE;
8126	}
8127      bed->s->swap_symbol_out (finfo->output_bfd, &sym, esym, 0);
8128
8129      if (finfo->hash_sec != NULL)
8130	{
8131	  size_t hash_entry_size;
8132	  bfd_byte *bucketpos;
8133	  bfd_vma chain;
8134	  size_t bucketcount;
8135	  size_t bucket;
8136
8137	  bucketcount = elf_hash_table (finfo->info)->bucketcount;
8138	  bucket = h->u.elf_hash_value % bucketcount;
8139
8140	  hash_entry_size
8141	    = elf_section_data (finfo->hash_sec)->this_hdr.sh_entsize;
8142	  bucketpos = ((bfd_byte *) finfo->hash_sec->contents
8143		       + (bucket + 2) * hash_entry_size);
8144	  chain = bfd_get (8 * hash_entry_size, finfo->output_bfd, bucketpos);
8145	  bfd_put (8 * hash_entry_size, finfo->output_bfd, h->dynindx, bucketpos);
8146	  bfd_put (8 * hash_entry_size, finfo->output_bfd, chain,
8147		   ((bfd_byte *) finfo->hash_sec->contents
8148		    + (bucketcount + 2 + h->dynindx) * hash_entry_size));
8149	}
8150
8151      if (finfo->symver_sec != NULL && finfo->symver_sec->contents != NULL)
8152	{
8153	  Elf_Internal_Versym iversym;
8154	  Elf_External_Versym *eversym;
8155
8156	  if (!h->def_regular)
8157	    {
8158	      if (h->verinfo.verdef == NULL)
8159		iversym.vs_vers = 0;
8160	      else
8161		iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
8162	    }
8163	  else
8164	    {
8165	      if (h->verinfo.vertree == NULL)
8166		iversym.vs_vers = 1;
8167	      else
8168		iversym.vs_vers = h->verinfo.vertree->vernum + 1;
8169	      if (finfo->info->create_default_symver)
8170		iversym.vs_vers++;
8171	    }
8172
8173	  if (h->hidden)
8174	    iversym.vs_vers |= VERSYM_HIDDEN;
8175
8176	  eversym = (Elf_External_Versym *) finfo->symver_sec->contents;
8177	  eversym += h->dynindx;
8178	  _bfd_elf_swap_versym_out (finfo->output_bfd, &iversym, eversym);
8179	}
8180    }
8181
8182  /* If we're stripping it, then it was just a dynamic symbol, and
8183     there's nothing else to do.  */
8184  if (strip || (input_sec->flags & SEC_EXCLUDE) != 0)
8185    return TRUE;
8186
8187  h->indx = bfd_get_symcount (finfo->output_bfd);
8188
8189  if (! elf_link_output_sym (finfo, h->root.root.string, &sym, input_sec, h))
8190    {
8191      eoinfo->failed = TRUE;
8192      return FALSE;
8193    }
8194
8195  return TRUE;
8196}
8197
8198/* Return TRUE if special handling is done for relocs in SEC against
8199   symbols defined in discarded sections.  */
8200
8201static bfd_boolean
8202elf_section_ignore_discarded_relocs (asection *sec)
8203{
8204  const struct elf_backend_data *bed;
8205
8206  switch (sec->sec_info_type)
8207    {
8208    case ELF_INFO_TYPE_STABS:
8209    case ELF_INFO_TYPE_EH_FRAME:
8210      return TRUE;
8211    default:
8212      break;
8213    }
8214
8215  bed = get_elf_backend_data (sec->owner);
8216  if (bed->elf_backend_ignore_discarded_relocs != NULL
8217      && (*bed->elf_backend_ignore_discarded_relocs) (sec))
8218    return TRUE;
8219
8220  return FALSE;
8221}
8222
8223/* Return a mask saying how ld should treat relocations in SEC against
8224   symbols defined in discarded sections.  If this function returns
8225   COMPLAIN set, ld will issue a warning message.  If this function
8226   returns PRETEND set, and the discarded section was link-once and the
8227   same size as the kept link-once section, ld will pretend that the
8228   symbol was actually defined in the kept section.  Otherwise ld will
8229   zero the reloc (at least that is the intent, but some cooperation by
8230   the target dependent code is needed, particularly for REL targets).  */
8231
8232unsigned int
8233_bfd_elf_default_action_discarded (asection *sec)
8234{
8235  if (sec->flags & SEC_DEBUGGING)
8236    return PRETEND;
8237
8238  if (strcmp (".eh_frame", sec->name) == 0)
8239    return 0;
8240
8241  if (strcmp (".gcc_except_table", sec->name) == 0)
8242    return 0;
8243
8244  return COMPLAIN | PRETEND;
8245}
8246
8247/* Find a match between a section and a member of a section group.  */
8248
8249static asection *
8250match_group_member (asection *sec, asection *group,
8251		    struct bfd_link_info *info)
8252{
8253  asection *first = elf_next_in_group (group);
8254  asection *s = first;
8255
8256  while (s != NULL)
8257    {
8258      if (bfd_elf_match_symbols_in_sections (s, sec, info))
8259	return s;
8260
8261      s = elf_next_in_group (s);
8262      if (s == first)
8263	break;
8264    }
8265
8266  return NULL;
8267}
8268
8269/* Check if the kept section of a discarded section SEC can be used
8270   to replace it.  Return the replacement if it is OK.  Otherwise return
8271   NULL.  */
8272
8273asection *
8274_bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
8275{
8276  asection *kept;
8277
8278  kept = sec->kept_section;
8279  if (kept != NULL)
8280    {
8281      if ((kept->flags & SEC_GROUP) != 0)
8282	kept = match_group_member (sec, kept, info);
8283      if (kept != NULL && sec->size != kept->size)
8284	kept = NULL;
8285      sec->kept_section = kept;
8286    }
8287  return kept;
8288}
8289
8290/* Link an input file into the linker output file.  This function
8291   handles all the sections and relocations of the input file at once.
8292   This is so that we only have to read the local symbols once, and
8293   don't have to keep them in memory.  */
8294
8295static bfd_boolean
8296elf_link_input_bfd (struct elf_final_link_info *finfo, bfd *input_bfd)
8297{
8298  int (*relocate_section)
8299    (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
8300     Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
8301  bfd *output_bfd;
8302  Elf_Internal_Shdr *symtab_hdr;
8303  size_t locsymcount;
8304  size_t extsymoff;
8305  Elf_Internal_Sym *isymbuf;
8306  Elf_Internal_Sym *isym;
8307  Elf_Internal_Sym *isymend;
8308  long *pindex;
8309  asection **ppsection;
8310  asection *o;
8311  const struct elf_backend_data *bed;
8312  struct elf_link_hash_entry **sym_hashes;
8313
8314  output_bfd = finfo->output_bfd;
8315  bed = get_elf_backend_data (output_bfd);
8316  relocate_section = bed->elf_backend_relocate_section;
8317
8318  /* If this is a dynamic object, we don't want to do anything here:
8319     we don't want the local symbols, and we don't want the section
8320     contents.  */
8321  if ((input_bfd->flags & DYNAMIC) != 0)
8322    return TRUE;
8323
8324  symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
8325  if (elf_bad_symtab (input_bfd))
8326    {
8327      locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
8328      extsymoff = 0;
8329    }
8330  else
8331    {
8332      locsymcount = symtab_hdr->sh_info;
8333      extsymoff = symtab_hdr->sh_info;
8334    }
8335
8336  /* Read the local symbols.  */
8337  isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
8338  if (isymbuf == NULL && locsymcount != 0)
8339    {
8340      isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
8341				      finfo->internal_syms,
8342				      finfo->external_syms,
8343				      finfo->locsym_shndx);
8344      if (isymbuf == NULL)
8345	return FALSE;
8346    }
8347  /* evaluate_complex_relocation_symbols looks for symbols in
8348     finfo->internal_syms.  */
8349  else if (isymbuf != NULL && locsymcount != 0)
8350    {
8351      bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
8352			    finfo->internal_syms,
8353			    finfo->external_syms,
8354			    finfo->locsym_shndx);
8355    }
8356
8357  /* Find local symbol sections and adjust values of symbols in
8358     SEC_MERGE sections.  Write out those local symbols we know are
8359     going into the output file.  */
8360  isymend = isymbuf + locsymcount;
8361  for (isym = isymbuf, pindex = finfo->indices, ppsection = finfo->sections;
8362       isym < isymend;
8363       isym++, pindex++, ppsection++)
8364    {
8365      asection *isec;
8366      const char *name;
8367      Elf_Internal_Sym osym;
8368
8369      *pindex = -1;
8370
8371      if (elf_bad_symtab (input_bfd))
8372	{
8373	  if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
8374	    {
8375	      *ppsection = NULL;
8376	      continue;
8377	    }
8378	}
8379
8380      if (isym->st_shndx == SHN_UNDEF)
8381	isec = bfd_und_section_ptr;
8382      else if (isym->st_shndx < SHN_LORESERVE
8383	       || isym->st_shndx > SHN_HIRESERVE)
8384	{
8385	  isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
8386	  if (isec
8387	      && isec->sec_info_type == ELF_INFO_TYPE_MERGE
8388	      && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
8389	    isym->st_value =
8390	      _bfd_merged_section_offset (output_bfd, &isec,
8391					  elf_section_data (isec)->sec_info,
8392					  isym->st_value);
8393	}
8394      else if (isym->st_shndx == SHN_ABS)
8395	isec = bfd_abs_section_ptr;
8396      else if (isym->st_shndx == SHN_COMMON)
8397	isec = bfd_com_section_ptr;
8398      else
8399	{
8400	  /* Don't attempt to output symbols with st_shnx in the
8401	     reserved range other than SHN_ABS and SHN_COMMON.  */
8402	  *ppsection = NULL;
8403	  continue;
8404	}
8405
8406      *ppsection = isec;
8407
8408      /* Don't output the first, undefined, symbol.  */
8409      if (ppsection == finfo->sections)
8410	continue;
8411
8412      if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
8413	{
8414	  /* We never output section symbols.  Instead, we use the
8415	     section symbol of the corresponding section in the output
8416	     file.  */
8417	  continue;
8418	}
8419
8420      /* If we are stripping all symbols, we don't want to output this
8421	 one.  */
8422      if (finfo->info->strip == strip_all)
8423	continue;
8424
8425      /* If we are discarding all local symbols, we don't want to
8426	 output this one.  If we are generating a relocatable output
8427	 file, then some of the local symbols may be required by
8428	 relocs; we output them below as we discover that they are
8429	 needed.  */
8430      if (finfo->info->discard == discard_all)
8431	continue;
8432
8433      /* If this symbol is defined in a section which we are
8434	 discarding, we don't need to keep it.  */
8435      if (isym->st_shndx != SHN_UNDEF
8436	  && (isym->st_shndx < SHN_LORESERVE || isym->st_shndx > SHN_HIRESERVE)
8437	  && (isec == NULL
8438	      || bfd_section_removed_from_list (output_bfd,
8439						isec->output_section)))
8440	continue;
8441
8442      /* Get the name of the symbol.  */
8443      name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
8444					      isym->st_name);
8445      if (name == NULL)
8446	return FALSE;
8447
8448      /* See if we are discarding symbols with this name.  */
8449      if ((finfo->info->strip == strip_some
8450	   && (bfd_hash_lookup (finfo->info->keep_hash, name, FALSE, FALSE)
8451	       == NULL))
8452	  || (((finfo->info->discard == discard_sec_merge
8453		&& (isec->flags & SEC_MERGE) && ! finfo->info->relocatable)
8454	       || finfo->info->discard == discard_l)
8455	      && bfd_is_local_label_name (input_bfd, name)))
8456	continue;
8457
8458      /* If we get here, we are going to output this symbol.  */
8459
8460      osym = *isym;
8461
8462      /* Adjust the section index for the output file.  */
8463      osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
8464							 isec->output_section);
8465      if (osym.st_shndx == SHN_BAD)
8466	return FALSE;
8467
8468      *pindex = bfd_get_symcount (output_bfd);
8469
8470      /* ELF symbols in relocatable files are section relative, but
8471	 in executable files they are virtual addresses.  Note that
8472	 this code assumes that all ELF sections have an associated
8473	 BFD section with a reasonable value for output_offset; below
8474	 we assume that they also have a reasonable value for
8475	 output_section.  Any special sections must be set up to meet
8476	 these requirements.  */
8477      osym.st_value += isec->output_offset;
8478      if (! finfo->info->relocatable)
8479	{
8480	  osym.st_value += isec->output_section->vma;
8481	  if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
8482	    {
8483	      /* STT_TLS symbols are relative to PT_TLS segment base.  */
8484	      BFD_ASSERT (elf_hash_table (finfo->info)->tls_sec != NULL);
8485	      osym.st_value -= elf_hash_table (finfo->info)->tls_sec->vma;
8486	    }
8487	}
8488
8489      if (! elf_link_output_sym (finfo, name, &osym, isec, NULL))
8490	return FALSE;
8491    }
8492
8493  if (! evaluate_complex_relocation_symbols (input_bfd, finfo, locsymcount))
8494    return FALSE;
8495
8496  /* Relocate the contents of each section.  */
8497  sym_hashes = elf_sym_hashes (input_bfd);
8498  for (o = input_bfd->sections; o != NULL; o = o->next)
8499    {
8500      bfd_byte *contents;
8501
8502      if (! o->linker_mark)
8503	{
8504	  /* This section was omitted from the link.  */
8505	  continue;
8506	}
8507
8508      if ((o->flags & SEC_HAS_CONTENTS) == 0
8509	  || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
8510	continue;
8511
8512      if ((o->flags & SEC_LINKER_CREATED) != 0)
8513	{
8514	  /* Section was created by _bfd_elf_link_create_dynamic_sections
8515	     or somesuch.  */
8516	  continue;
8517	}
8518
8519      /* Get the contents of the section.  They have been cached by a
8520	 relaxation routine.  Note that o is a section in an input
8521	 file, so the contents field will not have been set by any of
8522	 the routines which work on output files.  */
8523      if (elf_section_data (o)->this_hdr.contents != NULL)
8524	contents = elf_section_data (o)->this_hdr.contents;
8525      else
8526	{
8527	  bfd_size_type amt = o->rawsize ? o->rawsize : o->size;
8528
8529	  contents = finfo->contents;
8530	  if (! bfd_get_section_contents (input_bfd, o, contents, 0, amt))
8531	    return FALSE;
8532	}
8533
8534      if ((o->flags & SEC_RELOC) != 0)
8535	{
8536	  Elf_Internal_Rela *internal_relocs;
8537	  bfd_vma r_type_mask;
8538	  int r_sym_shift;
8539	  int ret;
8540
8541	  /* Get the swapped relocs.  */
8542	  internal_relocs
8543	    = _bfd_elf_link_read_relocs (input_bfd, o, finfo->external_relocs,
8544					 finfo->internal_relocs, FALSE);
8545	  if (internal_relocs == NULL
8546	      && o->reloc_count > 0)
8547	    return FALSE;
8548
8549	  if (bed->s->arch_size == 32)
8550	    {
8551	      r_type_mask = 0xff;
8552	      r_sym_shift = 8;
8553	    }
8554	  else
8555	    {
8556	      r_type_mask = 0xffffffff;
8557	      r_sym_shift = 32;
8558	    }
8559
8560	  /* Run through the relocs looking for any against symbols
8561	     from discarded sections and section symbols from
8562	     removed link-once sections.  Complain about relocs
8563	     against discarded sections.  Zero relocs against removed
8564	     link-once sections.  */
8565	  if (!elf_section_ignore_discarded_relocs (o))
8566	    {
8567	      Elf_Internal_Rela *rel, *relend;
8568	      unsigned int action = (*bed->action_discarded) (o);
8569
8570	      rel = internal_relocs;
8571	      relend = rel + o->reloc_count * bed->s->int_rels_per_ext_rel;
8572	      for ( ; rel < relend; rel++)
8573		{
8574		  unsigned long r_symndx = rel->r_info >> r_sym_shift;
8575		  asection **ps, *sec;
8576		  struct elf_link_hash_entry *h = NULL;
8577		  const char *sym_name;
8578
8579		  if (r_symndx == STN_UNDEF)
8580		    continue;
8581
8582		  if (r_symndx >= locsymcount
8583		      || (elf_bad_symtab (input_bfd)
8584			  && finfo->sections[r_symndx] == NULL))
8585		    {
8586		      h = sym_hashes[r_symndx - extsymoff];
8587
8588		      /* Badly formatted input files can contain relocs that
8589			 reference non-existant symbols.  Check here so that
8590			 we do not seg fault.  */
8591		      if (h == NULL)
8592			{
8593			  char buffer [32];
8594
8595			  sprintf_vma (buffer, rel->r_info);
8596			  (*_bfd_error_handler)
8597			    (_("error: %B contains a reloc (0x%s) for section %A "
8598			       "that references a non-existent global symbol"),
8599			     input_bfd, o, buffer);
8600			  bfd_set_error (bfd_error_bad_value);
8601			  return FALSE;
8602			}
8603
8604		      while (h->root.type == bfd_link_hash_indirect
8605			     || h->root.type == bfd_link_hash_warning)
8606			h = (struct elf_link_hash_entry *) h->root.u.i.link;
8607
8608		      if (h->root.type != bfd_link_hash_defined
8609			  && h->root.type != bfd_link_hash_defweak)
8610			continue;
8611
8612		      ps = &h->root.u.def.section;
8613		      sym_name = h->root.root.string;
8614		    }
8615		  else
8616		    {
8617		      Elf_Internal_Sym *sym = isymbuf + r_symndx;
8618		      ps = &finfo->sections[r_symndx];
8619		      sym_name = bfd_elf_sym_name (input_bfd,
8620						   symtab_hdr,
8621						   sym, *ps);
8622		    }
8623
8624		  /* Complain if the definition comes from a
8625		     discarded section.  */
8626		  if ((sec = *ps) != NULL && elf_discarded_section (sec))
8627		    {
8628		      BFD_ASSERT (r_symndx != 0);
8629		      if (action & COMPLAIN)
8630			(*finfo->info->callbacks->einfo)
8631			  (_("%X`%s' referenced in section `%A' of %B: "
8632			     "defined in discarded section `%A' of %B\n"),
8633			   sym_name, o, input_bfd, sec, sec->owner);
8634
8635		      /* Try to do the best we can to support buggy old
8636			 versions of gcc.  Pretend that the symbol is
8637			 really defined in the kept linkonce section.
8638			 FIXME: This is quite broken.  Modifying the
8639			 symbol here means we will be changing all later
8640			 uses of the symbol, not just in this section.  */
8641		      if (action & PRETEND)
8642			{
8643			  asection *kept;
8644
8645			  kept = _bfd_elf_check_kept_section (sec,
8646							      finfo->info);
8647			  if (kept != NULL)
8648			    {
8649			      *ps = kept;
8650			      continue;
8651			    }
8652			}
8653		    }
8654		}
8655	    }
8656
8657	  /* Relocate the section by invoking a back end routine.
8658
8659	     The back end routine is responsible for adjusting the
8660	     section contents as necessary, and (if using Rela relocs
8661	     and generating a relocatable output file) adjusting the
8662	     reloc addend as necessary.
8663
8664	     The back end routine does not have to worry about setting
8665	     the reloc address or the reloc symbol index.
8666
8667	     The back end routine is given a pointer to the swapped in
8668	     internal symbols, and can access the hash table entries
8669	     for the external symbols via elf_sym_hashes (input_bfd).
8670
8671	     When generating relocatable output, the back end routine
8672	     must handle STB_LOCAL/STT_SECTION symbols specially.  The
8673	     output symbol is going to be a section symbol
8674	     corresponding to the output section, which will require
8675	     the addend to be adjusted.  */
8676
8677	  ret = (*relocate_section) (output_bfd, finfo->info,
8678				     input_bfd, o, contents,
8679				     internal_relocs,
8680				     isymbuf,
8681				     finfo->sections);
8682	  if (!ret)
8683	    return FALSE;
8684
8685	  if (ret == 2
8686	      || finfo->info->relocatable
8687	      || finfo->info->emitrelocations)
8688	    {
8689	      Elf_Internal_Rela *irela;
8690	      Elf_Internal_Rela *irelaend;
8691	      bfd_vma last_offset;
8692	      struct elf_link_hash_entry **rel_hash;
8693	      struct elf_link_hash_entry **rel_hash_list;
8694	      Elf_Internal_Shdr *input_rel_hdr, *input_rel_hdr2;
8695	      unsigned int next_erel;
8696	      bfd_boolean rela_normal;
8697
8698	      input_rel_hdr = &elf_section_data (o)->rel_hdr;
8699	      rela_normal = (bed->rela_normal
8700			     && (input_rel_hdr->sh_entsize
8701				 == bed->s->sizeof_rela));
8702
8703	      /* Adjust the reloc addresses and symbol indices.  */
8704
8705	      irela = internal_relocs;
8706	      irelaend = irela + o->reloc_count * bed->s->int_rels_per_ext_rel;
8707	      rel_hash = (elf_section_data (o->output_section)->rel_hashes
8708			  + elf_section_data (o->output_section)->rel_count
8709			  + elf_section_data (o->output_section)->rel_count2);
8710	      rel_hash_list = rel_hash;
8711	      last_offset = o->output_offset;
8712	      if (!finfo->info->relocatable)
8713		last_offset += o->output_section->vma;
8714	      for (next_erel = 0; irela < irelaend; irela++, next_erel++)
8715		{
8716		  unsigned long r_symndx;
8717		  asection *sec;
8718		  Elf_Internal_Sym sym;
8719
8720		  if (next_erel == bed->s->int_rels_per_ext_rel)
8721		    {
8722		      rel_hash++;
8723		      next_erel = 0;
8724		    }
8725
8726		  irela->r_offset = _bfd_elf_section_offset (output_bfd,
8727							     finfo->info, o,
8728							     irela->r_offset);
8729		  if (irela->r_offset >= (bfd_vma) -2)
8730		    {
8731		      /* This is a reloc for a deleted entry or somesuch.
8732			 Turn it into an R_*_NONE reloc, at the same
8733			 offset as the last reloc.  elf_eh_frame.c and
8734			 bfd_elf_discard_info rely on reloc offsets
8735			 being ordered.  */
8736		      irela->r_offset = last_offset;
8737		      irela->r_info = 0;
8738		      irela->r_addend = 0;
8739		      continue;
8740		    }
8741
8742		  irela->r_offset += o->output_offset;
8743
8744		  /* Relocs in an executable have to be virtual addresses.  */
8745		  if (!finfo->info->relocatable)
8746		    irela->r_offset += o->output_section->vma;
8747
8748		  last_offset = irela->r_offset;
8749
8750		  r_symndx = irela->r_info >> r_sym_shift;
8751		  if (r_symndx == STN_UNDEF)
8752		    continue;
8753
8754		  if (r_symndx >= locsymcount
8755		      || (elf_bad_symtab (input_bfd)
8756			  && finfo->sections[r_symndx] == NULL))
8757		    {
8758		      struct elf_link_hash_entry *rh;
8759		      unsigned long indx;
8760
8761		      /* This is a reloc against a global symbol.  We
8762			 have not yet output all the local symbols, so
8763			 we do not know the symbol index of any global
8764			 symbol.  We set the rel_hash entry for this
8765			 reloc to point to the global hash table entry
8766			 for this symbol.  The symbol index is then
8767			 set at the end of bfd_elf_final_link.  */
8768		      indx = r_symndx - extsymoff;
8769		      rh = elf_sym_hashes (input_bfd)[indx];
8770		      while (rh->root.type == bfd_link_hash_indirect
8771			     || rh->root.type == bfd_link_hash_warning)
8772			rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
8773
8774		      /* Setting the index to -2 tells
8775			 elf_link_output_extsym that this symbol is
8776			 used by a reloc.  */
8777		      BFD_ASSERT (rh->indx < 0);
8778		      rh->indx = -2;
8779
8780		      *rel_hash = rh;
8781
8782		      continue;
8783		    }
8784
8785		  /* This is a reloc against a local symbol.  */
8786
8787		  *rel_hash = NULL;
8788		  sym = isymbuf[r_symndx];
8789		  sec = finfo->sections[r_symndx];
8790		  if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
8791		    {
8792		      /* I suppose the backend ought to fill in the
8793			 section of any STT_SECTION symbol against a
8794			 processor specific section.  */
8795		      r_symndx = 0;
8796		      if (bfd_is_abs_section (sec))
8797			;
8798		      else if (sec == NULL || sec->owner == NULL)
8799			{
8800			  bfd_set_error (bfd_error_bad_value);
8801			  return FALSE;
8802			}
8803		      else
8804			{
8805			  asection *osec = sec->output_section;
8806
8807			  /* If we have discarded a section, the output
8808			     section will be the absolute section.  In
8809			     case of discarded SEC_MERGE sections, use
8810			     the kept section.  relocate_section should
8811			     have already handled discarded linkonce
8812			     sections.  */
8813			  if (bfd_is_abs_section (osec)
8814			      && sec->kept_section != NULL
8815			      && sec->kept_section->output_section != NULL)
8816			    {
8817			      osec = sec->kept_section->output_section;
8818			      irela->r_addend -= osec->vma;
8819			    }
8820
8821			  if (!bfd_is_abs_section (osec))
8822			    {
8823			      r_symndx = osec->target_index;
8824			      if (r_symndx == 0)
8825				{
8826				  struct elf_link_hash_table *htab;
8827				  asection *oi;
8828
8829				  htab = elf_hash_table (finfo->info);
8830				  oi = htab->text_index_section;
8831				  if ((osec->flags & SEC_READONLY) == 0
8832				      && htab->data_index_section != NULL)
8833				    oi = htab->data_index_section;
8834
8835				  if (oi != NULL)
8836				    {
8837				      irela->r_addend += osec->vma - oi->vma;
8838				      r_symndx = oi->target_index;
8839				    }
8840				}
8841
8842			      BFD_ASSERT (r_symndx != 0);
8843			    }
8844			}
8845
8846		      /* Adjust the addend according to where the
8847			 section winds up in the output section.  */
8848		      if (rela_normal)
8849			irela->r_addend += sec->output_offset;
8850		    }
8851		  else
8852		    {
8853		      if (finfo->indices[r_symndx] == -1)
8854			{
8855			  unsigned long shlink;
8856			  const char *name;
8857			  asection *osec;
8858
8859			  if (finfo->info->strip == strip_all)
8860			    {
8861			      /* You can't do ld -r -s.  */
8862			      bfd_set_error (bfd_error_invalid_operation);
8863			      return FALSE;
8864			    }
8865
8866			  /* This symbol was skipped earlier, but
8867			     since it is needed by a reloc, we
8868			     must output it now.  */
8869			  shlink = symtab_hdr->sh_link;
8870			  name = (bfd_elf_string_from_elf_section
8871				  (input_bfd, shlink, sym.st_name));
8872			  if (name == NULL)
8873			    return FALSE;
8874
8875			  osec = sec->output_section;
8876			  sym.st_shndx =
8877			    _bfd_elf_section_from_bfd_section (output_bfd,
8878							       osec);
8879			  if (sym.st_shndx == SHN_BAD)
8880			    return FALSE;
8881
8882			  sym.st_value += sec->output_offset;
8883			  if (! finfo->info->relocatable)
8884			    {
8885			      sym.st_value += osec->vma;
8886			      if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
8887				{
8888				  /* STT_TLS symbols are relative to PT_TLS
8889				     segment base.  */
8890				  BFD_ASSERT (elf_hash_table (finfo->info)
8891					      ->tls_sec != NULL);
8892				  sym.st_value -= (elf_hash_table (finfo->info)
8893						   ->tls_sec->vma);
8894				}
8895			    }
8896
8897			  finfo->indices[r_symndx]
8898			    = bfd_get_symcount (output_bfd);
8899
8900			  if (! elf_link_output_sym (finfo, name, &sym, sec,
8901						     NULL))
8902			    return FALSE;
8903			}
8904
8905		      r_symndx = finfo->indices[r_symndx];
8906		    }
8907
8908		  irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
8909				   | (irela->r_info & r_type_mask));
8910		}
8911
8912	      /* Swap out the relocs.  */
8913	      if (input_rel_hdr->sh_size != 0
8914		  && !bed->elf_backend_emit_relocs (output_bfd, o,
8915						    input_rel_hdr,
8916						    internal_relocs,
8917						    rel_hash_list))
8918		return FALSE;
8919
8920	      input_rel_hdr2 = elf_section_data (o)->rel_hdr2;
8921	      if (input_rel_hdr2 && input_rel_hdr2->sh_size != 0)
8922		{
8923		  internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
8924				      * bed->s->int_rels_per_ext_rel);
8925		  rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
8926		  if (!bed->elf_backend_emit_relocs (output_bfd, o,
8927						     input_rel_hdr2,
8928						     internal_relocs,
8929						     rel_hash_list))
8930		    return FALSE;
8931		}
8932	    }
8933	}
8934
8935      /* Write out the modified section contents.  */
8936      if (bed->elf_backend_write_section
8937	  && (*bed->elf_backend_write_section) (output_bfd, finfo->info, o,
8938						contents))
8939	{
8940	  /* Section written out.  */
8941	}
8942      else switch (o->sec_info_type)
8943	{
8944	case ELF_INFO_TYPE_STABS:
8945	  if (! (_bfd_write_section_stabs
8946		 (output_bfd,
8947		  &elf_hash_table (finfo->info)->stab_info,
8948		  o, &elf_section_data (o)->sec_info, contents)))
8949	    return FALSE;
8950	  break;
8951	case ELF_INFO_TYPE_MERGE:
8952	  if (! _bfd_write_merged_section (output_bfd, o,
8953					   elf_section_data (o)->sec_info))
8954	    return FALSE;
8955	  break;
8956	case ELF_INFO_TYPE_EH_FRAME:
8957	  {
8958	    if (! _bfd_elf_write_section_eh_frame (output_bfd, finfo->info,
8959						   o, contents))
8960	      return FALSE;
8961	  }
8962	  break;
8963	default:
8964	  {
8965	    if (! (o->flags & SEC_EXCLUDE)
8966		&& ! bfd_set_section_contents (output_bfd, o->output_section,
8967					       contents,
8968					       (file_ptr) o->output_offset,
8969					       o->size))
8970	      return FALSE;
8971	  }
8972	  break;
8973	}
8974    }
8975
8976  return TRUE;
8977}
8978
8979/* Generate a reloc when linking an ELF file.  This is a reloc
8980   requested by the linker, and does not come from any input file.  This
8981   is used to build constructor and destructor tables when linking
8982   with -Ur.  */
8983
8984static bfd_boolean
8985elf_reloc_link_order (bfd *output_bfd,
8986		      struct bfd_link_info *info,
8987		      asection *output_section,
8988		      struct bfd_link_order *link_order)
8989{
8990  reloc_howto_type *howto;
8991  long indx;
8992  bfd_vma offset;
8993  bfd_vma addend;
8994  struct elf_link_hash_entry **rel_hash_ptr;
8995  Elf_Internal_Shdr *rel_hdr;
8996  const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
8997  Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
8998  bfd_byte *erel;
8999  unsigned int i;
9000
9001  howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
9002  if (howto == NULL)
9003    {
9004      bfd_set_error (bfd_error_bad_value);
9005      return FALSE;
9006    }
9007
9008  addend = link_order->u.reloc.p->addend;
9009
9010  /* Figure out the symbol index.  */
9011  rel_hash_ptr = (elf_section_data (output_section)->rel_hashes
9012		  + elf_section_data (output_section)->rel_count
9013		  + elf_section_data (output_section)->rel_count2);
9014  if (link_order->type == bfd_section_reloc_link_order)
9015    {
9016      indx = link_order->u.reloc.p->u.section->target_index;
9017      BFD_ASSERT (indx != 0);
9018      *rel_hash_ptr = NULL;
9019    }
9020  else
9021    {
9022      struct elf_link_hash_entry *h;
9023
9024      /* Treat a reloc against a defined symbol as though it were
9025	 actually against the section.  */
9026      h = ((struct elf_link_hash_entry *)
9027	   bfd_wrapped_link_hash_lookup (output_bfd, info,
9028					 link_order->u.reloc.p->u.name,
9029					 FALSE, FALSE, TRUE));
9030      if (h != NULL
9031	  && (h->root.type == bfd_link_hash_defined
9032	      || h->root.type == bfd_link_hash_defweak))
9033	{
9034	  asection *section;
9035
9036	  section = h->root.u.def.section;
9037	  indx = section->output_section->target_index;
9038	  *rel_hash_ptr = NULL;
9039	  /* It seems that we ought to add the symbol value to the
9040	     addend here, but in practice it has already been added
9041	     because it was passed to constructor_callback.  */
9042	  addend += section->output_section->vma + section->output_offset;
9043	}
9044      else if (h != NULL)
9045	{
9046	  /* Setting the index to -2 tells elf_link_output_extsym that
9047	     this symbol is used by a reloc.  */
9048	  h->indx = -2;
9049	  *rel_hash_ptr = h;
9050	  indx = 0;
9051	}
9052      else
9053	{
9054	  if (! ((*info->callbacks->unattached_reloc)
9055		 (info, link_order->u.reloc.p->u.name, NULL, NULL, 0)))
9056	    return FALSE;
9057	  indx = 0;
9058	}
9059    }
9060
9061  /* If this is an inplace reloc, we must write the addend into the
9062     object file.  */
9063  if (howto->partial_inplace && addend != 0)
9064    {
9065      bfd_size_type size;
9066      bfd_reloc_status_type rstat;
9067      bfd_byte *buf;
9068      bfd_boolean ok;
9069      const char *sym_name;
9070
9071      size = bfd_get_reloc_size (howto);
9072      buf = bfd_zmalloc (size);
9073      if (buf == NULL)
9074	return FALSE;
9075      rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
9076      switch (rstat)
9077	{
9078	case bfd_reloc_ok:
9079	  break;
9080
9081	default:
9082	case bfd_reloc_outofrange:
9083	  abort ();
9084
9085	case bfd_reloc_overflow:
9086	  if (link_order->type == bfd_section_reloc_link_order)
9087	    sym_name = bfd_section_name (output_bfd,
9088					 link_order->u.reloc.p->u.section);
9089	  else
9090	    sym_name = link_order->u.reloc.p->u.name;
9091	  if (! ((*info->callbacks->reloc_overflow)
9092		 (info, NULL, sym_name, howto->name, addend, NULL,
9093		  NULL, (bfd_vma) 0)))
9094	    {
9095	      free (buf);
9096	      return FALSE;
9097	    }
9098	  break;
9099	}
9100      ok = bfd_set_section_contents (output_bfd, output_section, buf,
9101				     link_order->offset, size);
9102      free (buf);
9103      if (! ok)
9104	return FALSE;
9105    }
9106
9107  /* The address of a reloc is relative to the section in a
9108     relocatable file, and is a virtual address in an executable
9109     file.  */
9110  offset = link_order->offset;
9111  if (! info->relocatable)
9112    offset += output_section->vma;
9113
9114  for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
9115    {
9116      irel[i].r_offset = offset;
9117      irel[i].r_info = 0;
9118      irel[i].r_addend = 0;
9119    }
9120  if (bed->s->arch_size == 32)
9121    irel[0].r_info = ELF32_R_INFO (indx, howto->type);
9122  else
9123    irel[0].r_info = ELF64_R_INFO (indx, howto->type);
9124
9125  rel_hdr = &elf_section_data (output_section)->rel_hdr;
9126  erel = rel_hdr->contents;
9127  if (rel_hdr->sh_type == SHT_REL)
9128    {
9129      erel += (elf_section_data (output_section)->rel_count
9130	       * bed->s->sizeof_rel);
9131      (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
9132    }
9133  else
9134    {
9135      irel[0].r_addend = addend;
9136      erel += (elf_section_data (output_section)->rel_count
9137	       * bed->s->sizeof_rela);
9138      (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
9139    }
9140
9141  ++elf_section_data (output_section)->rel_count;
9142
9143  return TRUE;
9144}
9145
9146
9147/* Get the output vma of the section pointed to by the sh_link field.  */
9148
9149static bfd_vma
9150elf_get_linked_section_vma (struct bfd_link_order *p)
9151{
9152  Elf_Internal_Shdr **elf_shdrp;
9153  asection *s;
9154  int elfsec;
9155
9156  s = p->u.indirect.section;
9157  elf_shdrp = elf_elfsections (s->owner);
9158  elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
9159  elfsec = elf_shdrp[elfsec]->sh_link;
9160  /* PR 290:
9161     The Intel C compiler generates SHT_IA_64_UNWIND with
9162     SHF_LINK_ORDER.  But it doesn't set the sh_link or
9163     sh_info fields.  Hence we could get the situation
9164     where elfsec is 0.  */
9165  if (elfsec == 0)
9166    {
9167      const struct elf_backend_data *bed
9168	= get_elf_backend_data (s->owner);
9169      if (bed->link_order_error_handler)
9170	bed->link_order_error_handler
9171	  (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
9172      return 0;
9173    }
9174  else
9175    {
9176      s = elf_shdrp[elfsec]->bfd_section;
9177      return s->output_section->vma + s->output_offset;
9178    }
9179}
9180
9181
9182/* Compare two sections based on the locations of the sections they are
9183   linked to.  Used by elf_fixup_link_order.  */
9184
9185static int
9186compare_link_order (const void * a, const void * b)
9187{
9188  bfd_vma apos;
9189  bfd_vma bpos;
9190
9191  apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
9192  bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
9193  if (apos < bpos)
9194    return -1;
9195  return apos > bpos;
9196}
9197
9198
9199/* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
9200   order as their linked sections.  Returns false if this could not be done
9201   because an output section includes both ordered and unordered
9202   sections.  Ideally we'd do this in the linker proper.  */
9203
9204static bfd_boolean
9205elf_fixup_link_order (bfd *abfd, asection *o)
9206{
9207  int seen_linkorder;
9208  int seen_other;
9209  int n;
9210  struct bfd_link_order *p;
9211  bfd *sub;
9212  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9213  unsigned elfsec;
9214  struct bfd_link_order **sections;
9215  asection *s, *other_sec, *linkorder_sec;
9216  bfd_vma offset;
9217
9218  other_sec = NULL;
9219  linkorder_sec = NULL;
9220  seen_other = 0;
9221  seen_linkorder = 0;
9222  for (p = o->map_head.link_order; p != NULL; p = p->next)
9223    {
9224      if (p->type == bfd_indirect_link_order)
9225	{
9226	  s = p->u.indirect.section;
9227	  sub = s->owner;
9228	  if (bfd_get_flavour (sub) == bfd_target_elf_flavour
9229	      && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
9230	      && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
9231	      && elfsec < elf_numsections (sub)
9232	      && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER)
9233	    {
9234	      seen_linkorder++;
9235	      linkorder_sec = s;
9236	    }
9237	  else
9238	    {
9239	      seen_other++;
9240	      other_sec = s;
9241	    }
9242	}
9243      else
9244	seen_other++;
9245
9246      if (seen_other && seen_linkorder)
9247	{
9248	  if (other_sec && linkorder_sec)
9249	    (*_bfd_error_handler) (_("%A has both ordered [`%A' in %B] and unordered [`%A' in %B] sections"),
9250				   o, linkorder_sec,
9251				   linkorder_sec->owner, other_sec,
9252				   other_sec->owner);
9253	  else
9254	    (*_bfd_error_handler) (_("%A has both ordered and unordered sections"),
9255				   o);
9256	  bfd_set_error (bfd_error_bad_value);
9257	  return FALSE;
9258	}
9259    }
9260
9261  if (!seen_linkorder)
9262    return TRUE;
9263
9264  sections = (struct bfd_link_order **)
9265    xmalloc (seen_linkorder * sizeof (struct bfd_link_order *));
9266  seen_linkorder = 0;
9267
9268  for (p = o->map_head.link_order; p != NULL; p = p->next)
9269    {
9270      sections[seen_linkorder++] = p;
9271    }
9272  /* Sort the input sections in the order of their linked section.  */
9273  qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
9274	 compare_link_order);
9275
9276  /* Change the offsets of the sections.  */
9277  offset = 0;
9278  for (n = 0; n < seen_linkorder; n++)
9279    {
9280      s = sections[n]->u.indirect.section;
9281      offset &= ~(bfd_vma)((1 << s->alignment_power) - 1);
9282      s->output_offset = offset;
9283      sections[n]->offset = offset;
9284      offset += sections[n]->size;
9285    }
9286
9287  return TRUE;
9288}
9289
9290
9291/* Do the final step of an ELF link.  */
9292
9293bfd_boolean
9294bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
9295{
9296  bfd_boolean dynamic;
9297  bfd_boolean emit_relocs;
9298  bfd *dynobj;
9299  struct elf_final_link_info finfo;
9300  register asection *o;
9301  register struct bfd_link_order *p;
9302  register bfd *sub;
9303  bfd_size_type max_contents_size;
9304  bfd_size_type max_external_reloc_size;
9305  bfd_size_type max_internal_reloc_count;
9306  bfd_size_type max_sym_count;
9307  bfd_size_type max_sym_shndx_count;
9308  file_ptr off;
9309  Elf_Internal_Sym elfsym;
9310  unsigned int i;
9311  Elf_Internal_Shdr *symtab_hdr;
9312  Elf_Internal_Shdr *symtab_shndx_hdr;
9313  Elf_Internal_Shdr *symstrtab_hdr;
9314  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9315  struct elf_outext_info eoinfo;
9316  bfd_boolean merged;
9317  size_t relativecount = 0;
9318  asection *reldyn = 0;
9319  bfd_size_type amt;
9320  asection *attr_section = NULL;
9321  bfd_vma attr_size = 0;
9322  const char *std_attrs_section;
9323
9324  if (! is_elf_hash_table (info->hash))
9325    return FALSE;
9326
9327  if (info->shared)
9328    abfd->flags |= DYNAMIC;
9329
9330  dynamic = elf_hash_table (info)->dynamic_sections_created;
9331  dynobj = elf_hash_table (info)->dynobj;
9332
9333  emit_relocs = (info->relocatable
9334		 || info->emitrelocations);
9335
9336  finfo.info = info;
9337  finfo.output_bfd = abfd;
9338  finfo.symstrtab = _bfd_elf_stringtab_init ();
9339  if (finfo.symstrtab == NULL)
9340    return FALSE;
9341
9342  if (! dynamic)
9343    {
9344      finfo.dynsym_sec = NULL;
9345      finfo.hash_sec = NULL;
9346      finfo.symver_sec = NULL;
9347    }
9348  else
9349    {
9350      finfo.dynsym_sec = bfd_get_section_by_name (dynobj, ".dynsym");
9351      finfo.hash_sec = bfd_get_section_by_name (dynobj, ".hash");
9352      BFD_ASSERT (finfo.dynsym_sec != NULL);
9353      finfo.symver_sec = bfd_get_section_by_name (dynobj, ".gnu.version");
9354      /* Note that it is OK if symver_sec is NULL.  */
9355    }
9356
9357  finfo.contents = NULL;
9358  finfo.external_relocs = NULL;
9359  finfo.internal_relocs = NULL;
9360  finfo.external_syms = NULL;
9361  finfo.locsym_shndx = NULL;
9362  finfo.internal_syms = NULL;
9363  finfo.indices = NULL;
9364  finfo.sections = NULL;
9365  finfo.symbuf = NULL;
9366  finfo.symshndxbuf = NULL;
9367  finfo.symbuf_count = 0;
9368  finfo.shndxbuf_size = 0;
9369
9370  /* The object attributes have been merged.  Remove the input
9371     sections from the link, and set the contents of the output
9372     secton.  */
9373  std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
9374  for (o = abfd->sections; o != NULL; o = o->next)
9375    {
9376      if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
9377	  || strcmp (o->name, ".gnu.attributes") == 0)
9378	{
9379	  for (p = o->map_head.link_order; p != NULL; p = p->next)
9380	    {
9381	      asection *input_section;
9382
9383	      if (p->type != bfd_indirect_link_order)
9384		continue;
9385	      input_section = p->u.indirect.section;
9386	      /* Hack: reset the SEC_HAS_CONTENTS flag so that
9387		 elf_link_input_bfd ignores this section.  */
9388	      input_section->flags &= ~SEC_HAS_CONTENTS;
9389	    }
9390
9391	  attr_size = bfd_elf_obj_attr_size (abfd);
9392	  if (attr_size)
9393	    {
9394	      bfd_set_section_size (abfd, o, attr_size);
9395	      attr_section = o;
9396	      /* Skip this section later on.  */
9397	      o->map_head.link_order = NULL;
9398	    }
9399	  else
9400	    o->flags |= SEC_EXCLUDE;
9401	}
9402    }
9403
9404  /* Count up the number of relocations we will output for each output
9405     section, so that we know the sizes of the reloc sections.  We
9406     also figure out some maximum sizes.  */
9407  max_contents_size = 0;
9408  max_external_reloc_size = 0;
9409  max_internal_reloc_count = 0;
9410  max_sym_count = 0;
9411  max_sym_shndx_count = 0;
9412  merged = FALSE;
9413  for (o = abfd->sections; o != NULL; o = o->next)
9414    {
9415      struct bfd_elf_section_data *esdo = elf_section_data (o);
9416      o->reloc_count = 0;
9417
9418      for (p = o->map_head.link_order; p != NULL; p = p->next)
9419	{
9420	  unsigned int reloc_count = 0;
9421	  struct bfd_elf_section_data *esdi = NULL;
9422	  unsigned int *rel_count1;
9423
9424	  if (p->type == bfd_section_reloc_link_order
9425	      || p->type == bfd_symbol_reloc_link_order)
9426	    reloc_count = 1;
9427	  else if (p->type == bfd_indirect_link_order)
9428	    {
9429	      asection *sec;
9430
9431	      sec = p->u.indirect.section;
9432	      esdi = elf_section_data (sec);
9433
9434	      /* Mark all sections which are to be included in the
9435		 link.  This will normally be every section.  We need
9436		 to do this so that we can identify any sections which
9437		 the linker has decided to not include.  */
9438	      sec->linker_mark = TRUE;
9439
9440	      if (sec->flags & SEC_MERGE)
9441		merged = TRUE;
9442
9443	      if (info->relocatable || info->emitrelocations)
9444		reloc_count = sec->reloc_count;
9445	      else if (bed->elf_backend_count_relocs)
9446		{
9447		  Elf_Internal_Rela * relocs;
9448
9449		  relocs = _bfd_elf_link_read_relocs (sec->owner, sec,
9450						      NULL, NULL,
9451						      info->keep_memory);
9452
9453		  if (relocs != NULL)
9454		    {
9455		      reloc_count
9456			= (*bed->elf_backend_count_relocs) (sec, relocs);
9457
9458		      if (elf_section_data (sec)->relocs != relocs)
9459			free (relocs);
9460		    }
9461		}
9462
9463	      if (sec->rawsize > max_contents_size)
9464		max_contents_size = sec->rawsize;
9465	      if (sec->size > max_contents_size)
9466		max_contents_size = sec->size;
9467
9468	      /* We are interested in just local symbols, not all
9469		 symbols.  */
9470	      if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
9471		  && (sec->owner->flags & DYNAMIC) == 0)
9472		{
9473		  size_t sym_count;
9474
9475		  if (elf_bad_symtab (sec->owner))
9476		    sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
9477				 / bed->s->sizeof_sym);
9478		  else
9479		    sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
9480
9481		  if (sym_count > max_sym_count)
9482		    max_sym_count = sym_count;
9483
9484		  if (sym_count > max_sym_shndx_count
9485		      && elf_symtab_shndx (sec->owner) != 0)
9486		    max_sym_shndx_count = sym_count;
9487
9488		  if ((sec->flags & SEC_RELOC) != 0)
9489		    {
9490		      size_t ext_size;
9491
9492		      ext_size = elf_section_data (sec)->rel_hdr.sh_size;
9493		      if (ext_size > max_external_reloc_size)
9494			max_external_reloc_size = ext_size;
9495		      if (sec->reloc_count > max_internal_reloc_count)
9496			max_internal_reloc_count = sec->reloc_count;
9497		    }
9498		}
9499	    }
9500
9501	  if (reloc_count == 0)
9502	    continue;
9503
9504	  o->reloc_count += reloc_count;
9505
9506	  /* MIPS may have a mix of REL and RELA relocs on sections.
9507	     To support this curious ABI we keep reloc counts in
9508	     elf_section_data too.  We must be careful to add the
9509	     relocations from the input section to the right output
9510	     count.  FIXME: Get rid of one count.  We have
9511	     o->reloc_count == esdo->rel_count + esdo->rel_count2.  */
9512	  rel_count1 = &esdo->rel_count;
9513	  if (esdi != NULL)
9514	    {
9515	      bfd_boolean same_size;
9516	      bfd_size_type entsize1;
9517
9518	      entsize1 = esdi->rel_hdr.sh_entsize;
9519	      BFD_ASSERT (entsize1 == bed->s->sizeof_rel
9520			  || entsize1 == bed->s->sizeof_rela);
9521	      same_size = !o->use_rela_p == (entsize1 == bed->s->sizeof_rel);
9522
9523	      if (!same_size)
9524		rel_count1 = &esdo->rel_count2;
9525
9526	      if (esdi->rel_hdr2 != NULL)
9527		{
9528		  bfd_size_type entsize2 = esdi->rel_hdr2->sh_entsize;
9529		  unsigned int alt_count;
9530		  unsigned int *rel_count2;
9531
9532		  BFD_ASSERT (entsize2 != entsize1
9533			      && (entsize2 == bed->s->sizeof_rel
9534				  || entsize2 == bed->s->sizeof_rela));
9535
9536		  rel_count2 = &esdo->rel_count2;
9537		  if (!same_size)
9538		    rel_count2 = &esdo->rel_count;
9539
9540		  /* The following is probably too simplistic if the
9541		     backend counts output relocs unusually.  */
9542		  BFD_ASSERT (bed->elf_backend_count_relocs == NULL);
9543		  alt_count = NUM_SHDR_ENTRIES (esdi->rel_hdr2);
9544		  *rel_count2 += alt_count;
9545		  reloc_count -= alt_count;
9546		}
9547	    }
9548	  *rel_count1 += reloc_count;
9549	}
9550
9551      if (o->reloc_count > 0)
9552	o->flags |= SEC_RELOC;
9553      else
9554	{
9555	  /* Explicitly clear the SEC_RELOC flag.  The linker tends to
9556	     set it (this is probably a bug) and if it is set
9557	     assign_section_numbers will create a reloc section.  */
9558	  o->flags &=~ SEC_RELOC;
9559	}
9560
9561      /* If the SEC_ALLOC flag is not set, force the section VMA to
9562	 zero.  This is done in elf_fake_sections as well, but forcing
9563	 the VMA to 0 here will ensure that relocs against these
9564	 sections are handled correctly.  */
9565      if ((o->flags & SEC_ALLOC) == 0
9566	  && ! o->user_set_vma)
9567	o->vma = 0;
9568    }
9569
9570  if (! info->relocatable && merged)
9571    elf_link_hash_traverse (elf_hash_table (info),
9572			    _bfd_elf_link_sec_merge_syms, abfd);
9573
9574  /* Figure out the file positions for everything but the symbol table
9575     and the relocs.  We set symcount to force assign_section_numbers
9576     to create a symbol table.  */
9577  bfd_get_symcount (abfd) = info->strip == strip_all ? 0 : 1;
9578  BFD_ASSERT (! abfd->output_has_begun);
9579  if (! _bfd_elf_compute_section_file_positions (abfd, info))
9580    goto error_return;
9581
9582  /* Set sizes, and assign file positions for reloc sections.  */
9583  for (o = abfd->sections; o != NULL; o = o->next)
9584    {
9585      if ((o->flags & SEC_RELOC) != 0)
9586	{
9587	  if (!(_bfd_elf_link_size_reloc_section
9588		(abfd, &elf_section_data (o)->rel_hdr, o)))
9589	    goto error_return;
9590
9591	  if (elf_section_data (o)->rel_hdr2
9592	      && !(_bfd_elf_link_size_reloc_section
9593		   (abfd, elf_section_data (o)->rel_hdr2, o)))
9594	    goto error_return;
9595	}
9596
9597      /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
9598	 to count upwards while actually outputting the relocations.  */
9599      elf_section_data (o)->rel_count = 0;
9600      elf_section_data (o)->rel_count2 = 0;
9601    }
9602
9603  _bfd_elf_assign_file_positions_for_relocs (abfd);
9604
9605  /* We have now assigned file positions for all the sections except
9606     .symtab and .strtab.  We start the .symtab section at the current
9607     file position, and write directly to it.  We build the .strtab
9608     section in memory.  */
9609  bfd_get_symcount (abfd) = 0;
9610  symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
9611  /* sh_name is set in prep_headers.  */
9612  symtab_hdr->sh_type = SHT_SYMTAB;
9613  /* sh_flags, sh_addr and sh_size all start off zero.  */
9614  symtab_hdr->sh_entsize = bed->s->sizeof_sym;
9615  /* sh_link is set in assign_section_numbers.  */
9616  /* sh_info is set below.  */
9617  /* sh_offset is set just below.  */
9618  symtab_hdr->sh_addralign = 1 << bed->s->log_file_align;
9619
9620  off = elf_tdata (abfd)->next_file_pos;
9621  off = _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
9622
9623  /* Note that at this point elf_tdata (abfd)->next_file_pos is
9624     incorrect.  We do not yet know the size of the .symtab section.
9625     We correct next_file_pos below, after we do know the size.  */
9626
9627  /* Allocate a buffer to hold swapped out symbols.  This is to avoid
9628     continuously seeking to the right position in the file.  */
9629  if (! info->keep_memory || max_sym_count < 20)
9630    finfo.symbuf_size = 20;
9631  else
9632    finfo.symbuf_size = max_sym_count;
9633  amt = finfo.symbuf_size;
9634  amt *= bed->s->sizeof_sym;
9635  finfo.symbuf = bfd_malloc (amt);
9636  if (finfo.symbuf == NULL)
9637    goto error_return;
9638  if (elf_numsections (abfd) > SHN_LORESERVE)
9639    {
9640      /* Wild guess at number of output symbols.  realloc'd as needed.  */
9641      amt = 2 * max_sym_count + elf_numsections (abfd) + 1000;
9642      finfo.shndxbuf_size = amt;
9643      amt *= sizeof (Elf_External_Sym_Shndx);
9644      finfo.symshndxbuf = bfd_zmalloc (amt);
9645      if (finfo.symshndxbuf == NULL)
9646	goto error_return;
9647    }
9648
9649  /* Start writing out the symbol table.  The first symbol is always a
9650     dummy symbol.  */
9651  if (info->strip != strip_all
9652      || emit_relocs)
9653    {
9654      elfsym.st_value = 0;
9655      elfsym.st_size = 0;
9656      elfsym.st_info = 0;
9657      elfsym.st_other = 0;
9658      elfsym.st_shndx = SHN_UNDEF;
9659      if (! elf_link_output_sym (&finfo, NULL, &elfsym, bfd_und_section_ptr,
9660				 NULL))
9661	goto error_return;
9662    }
9663
9664  /* Output a symbol for each section.  We output these even if we are
9665     discarding local symbols, since they are used for relocs.  These
9666     symbols have no names.  We store the index of each one in the
9667     index field of the section, so that we can find it again when
9668     outputting relocs.  */
9669  if (info->strip != strip_all
9670      || emit_relocs)
9671    {
9672      elfsym.st_size = 0;
9673      elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
9674      elfsym.st_other = 0;
9675      elfsym.st_value = 0;
9676      for (i = 1; i < elf_numsections (abfd); i++)
9677	{
9678	  o = bfd_section_from_elf_index (abfd, i);
9679	  if (o != NULL)
9680	    {
9681	      o->target_index = bfd_get_symcount (abfd);
9682	      elfsym.st_shndx = i;
9683	      if (!info->relocatable)
9684		elfsym.st_value = o->vma;
9685	      if (!elf_link_output_sym (&finfo, NULL, &elfsym, o, NULL))
9686		goto error_return;
9687	    }
9688	  if (i == SHN_LORESERVE - 1)
9689	    i += SHN_HIRESERVE + 1 - SHN_LORESERVE;
9690	}
9691    }
9692
9693  /* Allocate some memory to hold information read in from the input
9694     files.  */
9695  if (max_contents_size != 0)
9696    {
9697      finfo.contents = bfd_malloc (max_contents_size);
9698      if (finfo.contents == NULL)
9699	goto error_return;
9700    }
9701
9702  if (max_external_reloc_size != 0)
9703    {
9704      finfo.external_relocs = bfd_malloc (max_external_reloc_size);
9705      if (finfo.external_relocs == NULL)
9706	goto error_return;
9707    }
9708
9709  if (max_internal_reloc_count != 0)
9710    {
9711      amt = max_internal_reloc_count * bed->s->int_rels_per_ext_rel;
9712      amt *= sizeof (Elf_Internal_Rela);
9713      finfo.internal_relocs = bfd_malloc (amt);
9714      if (finfo.internal_relocs == NULL)
9715	goto error_return;
9716    }
9717
9718  if (max_sym_count != 0)
9719    {
9720      amt = max_sym_count * bed->s->sizeof_sym;
9721      finfo.external_syms = bfd_malloc (amt);
9722      if (finfo.external_syms == NULL)
9723	goto error_return;
9724
9725      amt = max_sym_count * sizeof (Elf_Internal_Sym);
9726      finfo.internal_syms = bfd_malloc (amt);
9727      if (finfo.internal_syms == NULL)
9728	goto error_return;
9729
9730      amt = max_sym_count * sizeof (long);
9731      finfo.indices = bfd_malloc (amt);
9732      if (finfo.indices == NULL)
9733	goto error_return;
9734
9735      amt = max_sym_count * sizeof (asection *);
9736      finfo.sections = bfd_malloc (amt);
9737      if (finfo.sections == NULL)
9738	goto error_return;
9739    }
9740
9741  if (max_sym_shndx_count != 0)
9742    {
9743      amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
9744      finfo.locsym_shndx = bfd_malloc (amt);
9745      if (finfo.locsym_shndx == NULL)
9746	goto error_return;
9747    }
9748
9749  if (elf_hash_table (info)->tls_sec)
9750    {
9751      bfd_vma base, end = 0;
9752      asection *sec;
9753
9754      for (sec = elf_hash_table (info)->tls_sec;
9755	   sec && (sec->flags & SEC_THREAD_LOCAL);
9756	   sec = sec->next)
9757	{
9758	  bfd_size_type size = sec->size;
9759
9760	  if (size == 0
9761	      && (sec->flags & SEC_HAS_CONTENTS) == 0)
9762	    {
9763	      struct bfd_link_order *o = sec->map_tail.link_order;
9764	      if (o != NULL)
9765		size = o->offset + o->size;
9766	    }
9767	  end = sec->vma + size;
9768	}
9769      base = elf_hash_table (info)->tls_sec->vma;
9770      end = align_power (end, elf_hash_table (info)->tls_sec->alignment_power);
9771      elf_hash_table (info)->tls_size = end - base;
9772    }
9773
9774  /* Reorder SHF_LINK_ORDER sections.  */
9775  for (o = abfd->sections; o != NULL; o = o->next)
9776    {
9777      if (!elf_fixup_link_order (abfd, o))
9778	return FALSE;
9779    }
9780
9781  /* Since ELF permits relocations to be against local symbols, we
9782     must have the local symbols available when we do the relocations.
9783     Since we would rather only read the local symbols once, and we
9784     would rather not keep them in memory, we handle all the
9785     relocations for a single input file at the same time.
9786
9787     Unfortunately, there is no way to know the total number of local
9788     symbols until we have seen all of them, and the local symbol
9789     indices precede the global symbol indices.  This means that when
9790     we are generating relocatable output, and we see a reloc against
9791     a global symbol, we can not know the symbol index until we have
9792     finished examining all the local symbols to see which ones we are
9793     going to output.  To deal with this, we keep the relocations in
9794     memory, and don't output them until the end of the link.  This is
9795     an unfortunate waste of memory, but I don't see a good way around
9796     it.  Fortunately, it only happens when performing a relocatable
9797     link, which is not the common case.  FIXME: If keep_memory is set
9798     we could write the relocs out and then read them again; I don't
9799     know how bad the memory loss will be.  */
9800
9801  for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
9802    sub->output_has_begun = FALSE;
9803  for (o = abfd->sections; o != NULL; o = o->next)
9804    {
9805      for (p = o->map_head.link_order; p != NULL; p = p->next)
9806	{
9807	  if (p->type == bfd_indirect_link_order
9808	      && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
9809		  == bfd_target_elf_flavour)
9810	      && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
9811	    {
9812	      if (! sub->output_has_begun)
9813		{
9814		  if (! elf_link_input_bfd (&finfo, sub))
9815		    goto error_return;
9816		  sub->output_has_begun = TRUE;
9817		}
9818	    }
9819	  else if (p->type == bfd_section_reloc_link_order
9820		   || p->type == bfd_symbol_reloc_link_order)
9821	    {
9822	      if (! elf_reloc_link_order (abfd, info, o, p))
9823		goto error_return;
9824	    }
9825	  else
9826	    {
9827	      if (! _bfd_default_link_order (abfd, info, o, p))
9828		goto error_return;
9829	    }
9830	}
9831    }
9832
9833  /* Free symbol buffer if needed.  */
9834  if (!info->reduce_memory_overheads)
9835    {
9836      for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
9837	if (bfd_get_flavour (sub) == bfd_target_elf_flavour
9838	    && elf_tdata (sub)->symbuf)
9839	  {
9840	    free (elf_tdata (sub)->symbuf);
9841	    elf_tdata (sub)->symbuf = NULL;
9842	  }
9843    }
9844
9845  /* Output any global symbols that got converted to local in a
9846     version script or due to symbol visibility.  We do this in a
9847     separate step since ELF requires all local symbols to appear
9848     prior to any global symbols.  FIXME: We should only do this if
9849     some global symbols were, in fact, converted to become local.
9850     FIXME: Will this work correctly with the Irix 5 linker?  */
9851  eoinfo.failed = FALSE;
9852  eoinfo.finfo = &finfo;
9853  eoinfo.localsyms = TRUE;
9854  elf_link_hash_traverse (elf_hash_table (info), elf_link_output_extsym,
9855			  &eoinfo);
9856  if (eoinfo.failed)
9857    return FALSE;
9858
9859  /* If backend needs to output some local symbols not present in the hash
9860     table, do it now.  */
9861  if (bed->elf_backend_output_arch_local_syms)
9862    {
9863      typedef bfd_boolean (*out_sym_func)
9864	(void *, const char *, Elf_Internal_Sym *, asection *,
9865	 struct elf_link_hash_entry *);
9866
9867      if (! ((*bed->elf_backend_output_arch_local_syms)
9868	     (abfd, info, &finfo, (out_sym_func) elf_link_output_sym)))
9869	return FALSE;
9870    }
9871
9872  /* That wrote out all the local symbols.  Finish up the symbol table
9873     with the global symbols. Even if we want to strip everything we
9874     can, we still need to deal with those global symbols that got
9875     converted to local in a version script.  */
9876
9877  /* The sh_info field records the index of the first non local symbol.  */
9878  symtab_hdr->sh_info = bfd_get_symcount (abfd);
9879
9880  if (dynamic
9881      && finfo.dynsym_sec->output_section != bfd_abs_section_ptr)
9882    {
9883      Elf_Internal_Sym sym;
9884      bfd_byte *dynsym = finfo.dynsym_sec->contents;
9885      long last_local = 0;
9886
9887      /* Write out the section symbols for the output sections.  */
9888      if (info->shared || elf_hash_table (info)->is_relocatable_executable)
9889	{
9890	  asection *s;
9891
9892	  sym.st_size = 0;
9893	  sym.st_name = 0;
9894	  sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
9895	  sym.st_other = 0;
9896
9897	  for (s = abfd->sections; s != NULL; s = s->next)
9898	    {
9899	      int indx;
9900	      bfd_byte *dest;
9901	      long dynindx;
9902
9903	      dynindx = elf_section_data (s)->dynindx;
9904	      if (dynindx <= 0)
9905		continue;
9906	      indx = elf_section_data (s)->this_idx;
9907	      BFD_ASSERT (indx > 0);
9908	      sym.st_shndx = indx;
9909	      if (! check_dynsym (abfd, &sym))
9910		return FALSE;
9911	      sym.st_value = s->vma;
9912	      dest = dynsym + dynindx * bed->s->sizeof_sym;
9913	      if (last_local < dynindx)
9914		last_local = dynindx;
9915	      bed->s->swap_symbol_out (abfd, &sym, dest, 0);
9916	    }
9917	}
9918
9919      /* Write out the local dynsyms.  */
9920      if (elf_hash_table (info)->dynlocal)
9921	{
9922	  struct elf_link_local_dynamic_entry *e;
9923	  for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
9924	    {
9925	      asection *s;
9926	      bfd_byte *dest;
9927
9928	      sym.st_size = e->isym.st_size;
9929	      sym.st_other = e->isym.st_other;
9930
9931	      /* Copy the internal symbol as is.
9932		 Note that we saved a word of storage and overwrote
9933		 the original st_name with the dynstr_index.  */
9934	      sym = e->isym;
9935
9936	      if (e->isym.st_shndx != SHN_UNDEF
9937		  && (e->isym.st_shndx < SHN_LORESERVE
9938		      || e->isym.st_shndx > SHN_HIRESERVE))
9939		{
9940		  s = bfd_section_from_elf_index (e->input_bfd,
9941						  e->isym.st_shndx);
9942
9943		  sym.st_shndx =
9944		    elf_section_data (s->output_section)->this_idx;
9945		  if (! check_dynsym (abfd, &sym))
9946		    return FALSE;
9947		  sym.st_value = (s->output_section->vma
9948				  + s->output_offset
9949				  + e->isym.st_value);
9950		}
9951
9952	      if (last_local < e->dynindx)
9953		last_local = e->dynindx;
9954
9955	      dest = dynsym + e->dynindx * bed->s->sizeof_sym;
9956	      bed->s->swap_symbol_out (abfd, &sym, dest, 0);
9957	    }
9958	}
9959
9960      elf_section_data (finfo.dynsym_sec->output_section)->this_hdr.sh_info =
9961	last_local + 1;
9962    }
9963
9964  /* We get the global symbols from the hash table.  */
9965  eoinfo.failed = FALSE;
9966  eoinfo.localsyms = FALSE;
9967  eoinfo.finfo = &finfo;
9968  elf_link_hash_traverse (elf_hash_table (info), elf_link_output_extsym,
9969			  &eoinfo);
9970  if (eoinfo.failed)
9971    return FALSE;
9972
9973  /* If backend needs to output some symbols not present in the hash
9974     table, do it now.  */
9975  if (bed->elf_backend_output_arch_syms)
9976    {
9977      typedef bfd_boolean (*out_sym_func)
9978	(void *, const char *, Elf_Internal_Sym *, asection *,
9979	 struct elf_link_hash_entry *);
9980
9981      if (! ((*bed->elf_backend_output_arch_syms)
9982	     (abfd, info, &finfo, (out_sym_func) elf_link_output_sym)))
9983	return FALSE;
9984    }
9985
9986  /* Flush all symbols to the file.  */
9987  if (! elf_link_flush_output_syms (&finfo, bed))
9988    return FALSE;
9989
9990  /* Now we know the size of the symtab section.  */
9991  off += symtab_hdr->sh_size;
9992
9993  symtab_shndx_hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
9994  if (symtab_shndx_hdr->sh_name != 0)
9995    {
9996      symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
9997      symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
9998      symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
9999      amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
10000      symtab_shndx_hdr->sh_size = amt;
10001
10002      off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
10003						       off, TRUE);
10004
10005      if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
10006	  || (bfd_bwrite (finfo.symshndxbuf, amt, abfd) != amt))
10007	return FALSE;
10008    }
10009
10010
10011  /* Finish up and write out the symbol string table (.strtab)
10012     section.  */
10013  symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
10014  /* sh_name was set in prep_headers.  */
10015  symstrtab_hdr->sh_type = SHT_STRTAB;
10016  symstrtab_hdr->sh_flags = 0;
10017  symstrtab_hdr->sh_addr = 0;
10018  symstrtab_hdr->sh_size = _bfd_stringtab_size (finfo.symstrtab);
10019  symstrtab_hdr->sh_entsize = 0;
10020  symstrtab_hdr->sh_link = 0;
10021  symstrtab_hdr->sh_info = 0;
10022  /* sh_offset is set just below.  */
10023  symstrtab_hdr->sh_addralign = 1;
10024
10025  off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr, off, TRUE);
10026  elf_tdata (abfd)->next_file_pos = off;
10027
10028  if (bfd_get_symcount (abfd) > 0)
10029    {
10030      if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
10031	  || ! _bfd_stringtab_emit (abfd, finfo.symstrtab))
10032	return FALSE;
10033    }
10034
10035  /* Adjust the relocs to have the correct symbol indices.  */
10036  for (o = abfd->sections; o != NULL; o = o->next)
10037    {
10038      if ((o->flags & SEC_RELOC) == 0)
10039	continue;
10040
10041      elf_link_adjust_relocs (abfd, &elf_section_data (o)->rel_hdr,
10042			      elf_section_data (o)->rel_count,
10043			      elf_section_data (o)->rel_hashes);
10044      if (elf_section_data (o)->rel_hdr2 != NULL)
10045	elf_link_adjust_relocs (abfd, elf_section_data (o)->rel_hdr2,
10046				elf_section_data (o)->rel_count2,
10047				(elf_section_data (o)->rel_hashes
10048				 + elf_section_data (o)->rel_count));
10049
10050      /* Set the reloc_count field to 0 to prevent write_relocs from
10051	 trying to swap the relocs out itself.  */
10052      o->reloc_count = 0;
10053    }
10054
10055  if (dynamic && info->combreloc && dynobj != NULL)
10056    relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
10057
10058  /* If we are linking against a dynamic object, or generating a
10059     shared library, finish up the dynamic linking information.  */
10060  if (dynamic)
10061    {
10062      bfd_byte *dyncon, *dynconend;
10063
10064      /* Fix up .dynamic entries.  */
10065      o = bfd_get_section_by_name (dynobj, ".dynamic");
10066      BFD_ASSERT (o != NULL);
10067
10068      dyncon = o->contents;
10069      dynconend = o->contents + o->size;
10070      for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
10071	{
10072	  Elf_Internal_Dyn dyn;
10073	  const char *name;
10074	  unsigned int type;
10075
10076	  bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
10077
10078	  switch (dyn.d_tag)
10079	    {
10080	    default:
10081	      continue;
10082	    case DT_NULL:
10083	      if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
10084		{
10085		  switch (elf_section_data (reldyn)->this_hdr.sh_type)
10086		    {
10087		    case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
10088		    case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
10089		    default: continue;
10090		    }
10091		  dyn.d_un.d_val = relativecount;
10092		  relativecount = 0;
10093		  break;
10094		}
10095	      continue;
10096
10097	    case DT_INIT:
10098	      name = info->init_function;
10099	      goto get_sym;
10100	    case DT_FINI:
10101	      name = info->fini_function;
10102	    get_sym:
10103	      {
10104		struct elf_link_hash_entry *h;
10105
10106		h = elf_link_hash_lookup (elf_hash_table (info), name,
10107					  FALSE, FALSE, TRUE);
10108		if (h != NULL
10109		    && (h->root.type == bfd_link_hash_defined
10110			|| h->root.type == bfd_link_hash_defweak))
10111		  {
10112		    dyn.d_un.d_val = h->root.u.def.value;
10113		    o = h->root.u.def.section;
10114		    if (o->output_section != NULL)
10115		      dyn.d_un.d_val += (o->output_section->vma
10116					 + o->output_offset);
10117		    else
10118		      {
10119			/* The symbol is imported from another shared
10120			   library and does not apply to this one.  */
10121			dyn.d_un.d_val = 0;
10122		      }
10123		    break;
10124		  }
10125	      }
10126	      continue;
10127
10128	    case DT_PREINIT_ARRAYSZ:
10129	      name = ".preinit_array";
10130	      goto get_size;
10131	    case DT_INIT_ARRAYSZ:
10132	      name = ".init_array";
10133	      goto get_size;
10134	    case DT_FINI_ARRAYSZ:
10135	      name = ".fini_array";
10136	    get_size:
10137	      o = bfd_get_section_by_name (abfd, name);
10138	      if (o == NULL)
10139		{
10140		  (*_bfd_error_handler)
10141		    (_("%B: could not find output section %s"), abfd, name);
10142		  goto error_return;
10143		}
10144	      if (o->size == 0)
10145		(*_bfd_error_handler)
10146		  (_("warning: %s section has zero size"), name);
10147	      dyn.d_un.d_val = o->size;
10148	      break;
10149
10150	    case DT_PREINIT_ARRAY:
10151	      name = ".preinit_array";
10152	      goto get_vma;
10153	    case DT_INIT_ARRAY:
10154	      name = ".init_array";
10155	      goto get_vma;
10156	    case DT_FINI_ARRAY:
10157	      name = ".fini_array";
10158	      goto get_vma;
10159
10160	    case DT_HASH:
10161	      name = ".hash";
10162	      goto get_vma;
10163	    case DT_GNU_HASH:
10164	      name = ".gnu.hash";
10165	      goto get_vma;
10166	    case DT_STRTAB:
10167	      name = ".dynstr";
10168	      goto get_vma;
10169	    case DT_SYMTAB:
10170	      name = ".dynsym";
10171	      goto get_vma;
10172	    case DT_VERDEF:
10173	      name = ".gnu.version_d";
10174	      goto get_vma;
10175	    case DT_VERNEED:
10176	      name = ".gnu.version_r";
10177	      goto get_vma;
10178	    case DT_VERSYM:
10179	      name = ".gnu.version";
10180	    get_vma:
10181	      o = bfd_get_section_by_name (abfd, name);
10182	      if (o == NULL)
10183		{
10184		  (*_bfd_error_handler)
10185		    (_("%B: could not find output section %s"), abfd, name);
10186		  goto error_return;
10187		}
10188	      dyn.d_un.d_ptr = o->vma;
10189	      break;
10190
10191	    case DT_REL:
10192	    case DT_RELA:
10193	    case DT_RELSZ:
10194	    case DT_RELASZ:
10195	      if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
10196		type = SHT_REL;
10197	      else
10198		type = SHT_RELA;
10199	      dyn.d_un.d_val = 0;
10200	      for (i = 1; i < elf_numsections (abfd); i++)
10201		{
10202		  Elf_Internal_Shdr *hdr;
10203
10204		  hdr = elf_elfsections (abfd)[i];
10205		  if (hdr->sh_type == type
10206		      && (hdr->sh_flags & SHF_ALLOC) != 0)
10207		    {
10208		      if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
10209			dyn.d_un.d_val += hdr->sh_size;
10210		      else
10211			{
10212			  if (dyn.d_un.d_val == 0
10213			      || hdr->sh_addr < dyn.d_un.d_val)
10214			    dyn.d_un.d_val = hdr->sh_addr;
10215			}
10216		    }
10217		}
10218	      break;
10219	    }
10220	  bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
10221	}
10222    }
10223
10224  /* If we have created any dynamic sections, then output them.  */
10225  if (dynobj != NULL)
10226    {
10227      if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
10228	goto error_return;
10229
10230      /* Check for DT_TEXTREL (late, in case the backend removes it).  */
10231      if (info->warn_shared_textrel && info->shared)
10232	{
10233	  bfd_byte *dyncon, *dynconend;
10234
10235	  /* Fix up .dynamic entries.  */
10236	  o = bfd_get_section_by_name (dynobj, ".dynamic");
10237	  BFD_ASSERT (o != NULL);
10238
10239	  dyncon = o->contents;
10240	  dynconend = o->contents + o->size;
10241	  for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
10242	    {
10243	      Elf_Internal_Dyn dyn;
10244
10245	      bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
10246
10247	      if (dyn.d_tag == DT_TEXTREL)
10248		{
10249		 info->callbacks->einfo
10250		    (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
10251		  break;
10252		}
10253	    }
10254	}
10255
10256      for (o = dynobj->sections; o != NULL; o = o->next)
10257	{
10258	  if ((o->flags & SEC_HAS_CONTENTS) == 0
10259	      || o->size == 0
10260	      || o->output_section == bfd_abs_section_ptr)
10261	    continue;
10262	  if ((o->flags & SEC_LINKER_CREATED) == 0)
10263	    {
10264	      /* At this point, we are only interested in sections
10265		 created by _bfd_elf_link_create_dynamic_sections.  */
10266	      continue;
10267	    }
10268	  if (elf_hash_table (info)->stab_info.stabstr == o)
10269	    continue;
10270	  if (elf_hash_table (info)->eh_info.hdr_sec == o)
10271	    continue;
10272	  if ((elf_section_data (o->output_section)->this_hdr.sh_type
10273	       != SHT_STRTAB)
10274	      || strcmp (bfd_get_section_name (abfd, o), ".dynstr") != 0)
10275	    {
10276	      if (! bfd_set_section_contents (abfd, o->output_section,
10277					      o->contents,
10278					      (file_ptr) o->output_offset,
10279					      o->size))
10280		goto error_return;
10281	    }
10282	  else
10283	    {
10284	      /* The contents of the .dynstr section are actually in a
10285		 stringtab.  */
10286	      off = elf_section_data (o->output_section)->this_hdr.sh_offset;
10287	      if (bfd_seek (abfd, off, SEEK_SET) != 0
10288		  || ! _bfd_elf_strtab_emit (abfd,
10289					     elf_hash_table (info)->dynstr))
10290		goto error_return;
10291	    }
10292	}
10293    }
10294
10295  if (info->relocatable)
10296    {
10297      bfd_boolean failed = FALSE;
10298
10299      bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
10300      if (failed)
10301	goto error_return;
10302    }
10303
10304  /* If we have optimized stabs strings, output them.  */
10305  if (elf_hash_table (info)->stab_info.stabstr != NULL)
10306    {
10307      if (! _bfd_write_stab_strings (abfd, &elf_hash_table (info)->stab_info))
10308	goto error_return;
10309    }
10310
10311  if (info->eh_frame_hdr)
10312    {
10313      if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
10314	goto error_return;
10315    }
10316
10317  if (finfo.symstrtab != NULL)
10318    _bfd_stringtab_free (finfo.symstrtab);
10319  if (finfo.contents != NULL)
10320    free (finfo.contents);
10321  if (finfo.external_relocs != NULL)
10322    free (finfo.external_relocs);
10323  if (finfo.internal_relocs != NULL)
10324    free (finfo.internal_relocs);
10325  if (finfo.external_syms != NULL)
10326    free (finfo.external_syms);
10327  if (finfo.locsym_shndx != NULL)
10328    free (finfo.locsym_shndx);
10329  if (finfo.internal_syms != NULL)
10330    free (finfo.internal_syms);
10331  if (finfo.indices != NULL)
10332    free (finfo.indices);
10333  if (finfo.sections != NULL)
10334    free (finfo.sections);
10335  if (finfo.symbuf != NULL)
10336    free (finfo.symbuf);
10337  if (finfo.symshndxbuf != NULL)
10338    free (finfo.symshndxbuf);
10339  for (o = abfd->sections; o != NULL; o = o->next)
10340    {
10341      if ((o->flags & SEC_RELOC) != 0
10342	  && elf_section_data (o)->rel_hashes != NULL)
10343	free (elf_section_data (o)->rel_hashes);
10344    }
10345
10346  elf_tdata (abfd)->linker = TRUE;
10347
10348  if (attr_section)
10349    {
10350      bfd_byte *contents = bfd_malloc (attr_size);
10351      if (contents == NULL)
10352	goto error_return;
10353      bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
10354      bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
10355      free (contents);
10356    }
10357
10358  return TRUE;
10359
10360 error_return:
10361  if (finfo.symstrtab != NULL)
10362    _bfd_stringtab_free (finfo.symstrtab);
10363  if (finfo.contents != NULL)
10364    free (finfo.contents);
10365  if (finfo.external_relocs != NULL)
10366    free (finfo.external_relocs);
10367  if (finfo.internal_relocs != NULL)
10368    free (finfo.internal_relocs);
10369  if (finfo.external_syms != NULL)
10370    free (finfo.external_syms);
10371  if (finfo.locsym_shndx != NULL)
10372    free (finfo.locsym_shndx);
10373  if (finfo.internal_syms != NULL)
10374    free (finfo.internal_syms);
10375  if (finfo.indices != NULL)
10376    free (finfo.indices);
10377  if (finfo.sections != NULL)
10378    free (finfo.sections);
10379  if (finfo.symbuf != NULL)
10380    free (finfo.symbuf);
10381  if (finfo.symshndxbuf != NULL)
10382    free (finfo.symshndxbuf);
10383  for (o = abfd->sections; o != NULL; o = o->next)
10384    {
10385      if ((o->flags & SEC_RELOC) != 0
10386	  && elf_section_data (o)->rel_hashes != NULL)
10387	free (elf_section_data (o)->rel_hashes);
10388    }
10389
10390  return FALSE;
10391}
10392
10393/* Garbage collect unused sections.  */
10394
10395/* Default gc_mark_hook.  */
10396
10397asection *
10398_bfd_elf_gc_mark_hook (asection *sec,
10399		       struct bfd_link_info *info ATTRIBUTE_UNUSED,
10400		       Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
10401		       struct elf_link_hash_entry *h,
10402		       Elf_Internal_Sym *sym)
10403{
10404  if (h != NULL)
10405    {
10406      switch (h->root.type)
10407	{
10408	case bfd_link_hash_defined:
10409	case bfd_link_hash_defweak:
10410	  return h->root.u.def.section;
10411
10412	case bfd_link_hash_common:
10413	  return h->root.u.c.p->section;
10414
10415	default:
10416	  break;
10417	}
10418    }
10419  else
10420    return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
10421
10422  return NULL;
10423}
10424
10425/* The mark phase of garbage collection.  For a given section, mark
10426   it and any sections in this section's group, and all the sections
10427   which define symbols to which it refers.  */
10428
10429bfd_boolean
10430_bfd_elf_gc_mark (struct bfd_link_info *info,
10431		  asection *sec,
10432		  elf_gc_mark_hook_fn gc_mark_hook)
10433{
10434  bfd_boolean ret;
10435  bfd_boolean is_eh;
10436  asection *group_sec;
10437
10438  sec->gc_mark = 1;
10439
10440  /* Mark all the sections in the group.  */
10441  group_sec = elf_section_data (sec)->next_in_group;
10442  if (group_sec && !group_sec->gc_mark)
10443    if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
10444      return FALSE;
10445
10446  /* Look through the section relocs.  */
10447  ret = TRUE;
10448  is_eh = strcmp (sec->name, ".eh_frame") == 0;
10449  if ((sec->flags & SEC_RELOC) != 0 && sec->reloc_count > 0)
10450    {
10451      Elf_Internal_Rela *relstart, *rel, *relend;
10452      Elf_Internal_Shdr *symtab_hdr;
10453      struct elf_link_hash_entry **sym_hashes;
10454      size_t nlocsyms;
10455      size_t extsymoff;
10456      bfd *input_bfd = sec->owner;
10457      const struct elf_backend_data *bed = get_elf_backend_data (input_bfd);
10458      Elf_Internal_Sym *isym = NULL;
10459      int r_sym_shift;
10460
10461      symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
10462      sym_hashes = elf_sym_hashes (input_bfd);
10463
10464      /* Read the local symbols.  */
10465      if (elf_bad_symtab (input_bfd))
10466	{
10467	  nlocsyms = symtab_hdr->sh_size / bed->s->sizeof_sym;
10468	  extsymoff = 0;
10469	}
10470      else
10471	extsymoff = nlocsyms = symtab_hdr->sh_info;
10472
10473      isym = (Elf_Internal_Sym *) symtab_hdr->contents;
10474      if (isym == NULL && nlocsyms != 0)
10475	{
10476	  isym = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, nlocsyms, 0,
10477				       NULL, NULL, NULL);
10478	  if (isym == NULL)
10479	    return FALSE;
10480	}
10481
10482      /* Read the relocations.  */
10483      relstart = _bfd_elf_link_read_relocs (input_bfd, sec, NULL, NULL,
10484					    info->keep_memory);
10485      if (relstart == NULL)
10486	{
10487	  ret = FALSE;
10488	  goto out1;
10489	}
10490      relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
10491
10492      if (bed->s->arch_size == 32)
10493	r_sym_shift = 8;
10494      else
10495	r_sym_shift = 32;
10496
10497      for (rel = relstart; rel < relend; rel++)
10498	{
10499	  unsigned long r_symndx;
10500	  asection *rsec;
10501	  struct elf_link_hash_entry *h;
10502
10503	  r_symndx = rel->r_info >> r_sym_shift;
10504	  if (r_symndx == 0)
10505	    continue;
10506
10507	  if (r_symndx >= nlocsyms
10508	      || ELF_ST_BIND (isym[r_symndx].st_info) != STB_LOCAL)
10509	    {
10510	      h = sym_hashes[r_symndx - extsymoff];
10511	      while (h->root.type == bfd_link_hash_indirect
10512		     || h->root.type == bfd_link_hash_warning)
10513		h = (struct elf_link_hash_entry *) h->root.u.i.link;
10514	      rsec = (*gc_mark_hook) (sec, info, rel, h, NULL);
10515	    }
10516	  else
10517	    {
10518	      rsec = (*gc_mark_hook) (sec, info, rel, NULL, &isym[r_symndx]);
10519	    }
10520
10521	  if (rsec && !rsec->gc_mark)
10522	    {
10523	      if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour)
10524		rsec->gc_mark = 1;
10525	      else if (is_eh)
10526		rsec->gc_mark_from_eh = 1;
10527	      else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
10528		{
10529		  ret = FALSE;
10530		  goto out2;
10531		}
10532	    }
10533	}
10534
10535    out2:
10536      if (elf_section_data (sec)->relocs != relstart)
10537	free (relstart);
10538    out1:
10539      if (isym != NULL && symtab_hdr->contents != (unsigned char *) isym)
10540	{
10541	  if (! info->keep_memory)
10542	    free (isym);
10543	  else
10544	    symtab_hdr->contents = (unsigned char *) isym;
10545	}
10546    }
10547
10548  return ret;
10549}
10550
10551/* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
10552
10553struct elf_gc_sweep_symbol_info
10554{
10555  struct bfd_link_info *info;
10556  void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
10557		       bfd_boolean);
10558};
10559
10560static bfd_boolean
10561elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
10562{
10563  if (h->root.type == bfd_link_hash_warning)
10564    h = (struct elf_link_hash_entry *) h->root.u.i.link;
10565
10566  if ((h->root.type == bfd_link_hash_defined
10567       || h->root.type == bfd_link_hash_defweak)
10568      && !h->root.u.def.section->gc_mark
10569      && !(h->root.u.def.section->owner->flags & DYNAMIC))
10570    {
10571      struct elf_gc_sweep_symbol_info *inf = data;
10572      (*inf->hide_symbol) (inf->info, h, TRUE);
10573    }
10574
10575  return TRUE;
10576}
10577
10578/* The sweep phase of garbage collection.  Remove all garbage sections.  */
10579
10580typedef bfd_boolean (*gc_sweep_hook_fn)
10581  (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
10582
10583static bfd_boolean
10584elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
10585{
10586  bfd *sub;
10587  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10588  gc_sweep_hook_fn gc_sweep_hook = bed->gc_sweep_hook;
10589  unsigned long section_sym_count;
10590  struct elf_gc_sweep_symbol_info sweep_info;
10591
10592  for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
10593    {
10594      asection *o;
10595
10596      if (bfd_get_flavour (sub) != bfd_target_elf_flavour)
10597	continue;
10598
10599      for (o = sub->sections; o != NULL; o = o->next)
10600	{
10601	  /* Keep debug and special sections.  */
10602	  if ((o->flags & (SEC_DEBUGGING | SEC_LINKER_CREATED)) != 0
10603	      || elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
10604	      || (o->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
10605	    o->gc_mark = 1;
10606
10607	  if (o->gc_mark)
10608	    continue;
10609
10610	  /* Skip sweeping sections already excluded.  */
10611	  if (o->flags & SEC_EXCLUDE)
10612	    continue;
10613
10614	  /* Since this is early in the link process, it is simple
10615	     to remove a section from the output.  */
10616	  o->flags |= SEC_EXCLUDE;
10617
10618	  if (info->print_gc_sections && o->size != 0)
10619	    _bfd_error_handler (_("Removing unused section '%s' in file '%B'"), sub, o->name);
10620
10621	  /* But we also have to update some of the relocation
10622	     info we collected before.  */
10623	  if (gc_sweep_hook
10624	      && (o->flags & SEC_RELOC) != 0
10625	      && o->reloc_count > 0
10626	      && !bfd_is_abs_section (o->output_section))
10627	    {
10628	      Elf_Internal_Rela *internal_relocs;
10629	      bfd_boolean r;
10630
10631	      internal_relocs
10632		= _bfd_elf_link_read_relocs (o->owner, o, NULL, NULL,
10633					     info->keep_memory);
10634	      if (internal_relocs == NULL)
10635		return FALSE;
10636
10637	      r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
10638
10639	      if (elf_section_data (o)->relocs != internal_relocs)
10640		free (internal_relocs);
10641
10642	      if (!r)
10643		return FALSE;
10644	    }
10645	}
10646    }
10647
10648  /* Remove the symbols that were in the swept sections from the dynamic
10649     symbol table.  GCFIXME: Anyone know how to get them out of the
10650     static symbol table as well?  */
10651  sweep_info.info = info;
10652  sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
10653  elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
10654			  &sweep_info);
10655
10656  _bfd_elf_link_renumber_dynsyms (abfd, info, &section_sym_count);
10657  return TRUE;
10658}
10659
10660/* Propagate collected vtable information.  This is called through
10661   elf_link_hash_traverse.  */
10662
10663static bfd_boolean
10664elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
10665{
10666  if (h->root.type == bfd_link_hash_warning)
10667    h = (struct elf_link_hash_entry *) h->root.u.i.link;
10668
10669  /* Those that are not vtables.  */
10670  if (h->vtable == NULL || h->vtable->parent == NULL)
10671    return TRUE;
10672
10673  /* Those vtables that do not have parents, we cannot merge.  */
10674  if (h->vtable->parent == (struct elf_link_hash_entry *) -1)
10675    return TRUE;
10676
10677  /* If we've already been done, exit.  */
10678  if (h->vtable->used && h->vtable->used[-1])
10679    return TRUE;
10680
10681  /* Make sure the parent's table is up to date.  */
10682  elf_gc_propagate_vtable_entries_used (h->vtable->parent, okp);
10683
10684  if (h->vtable->used == NULL)
10685    {
10686      /* None of this table's entries were referenced.  Re-use the
10687	 parent's table.  */
10688      h->vtable->used = h->vtable->parent->vtable->used;
10689      h->vtable->size = h->vtable->parent->vtable->size;
10690    }
10691  else
10692    {
10693      size_t n;
10694      bfd_boolean *cu, *pu;
10695
10696      /* Or the parent's entries into ours.  */
10697      cu = h->vtable->used;
10698      cu[-1] = TRUE;
10699      pu = h->vtable->parent->vtable->used;
10700      if (pu != NULL)
10701	{
10702	  const struct elf_backend_data *bed;
10703	  unsigned int log_file_align;
10704
10705	  bed = get_elf_backend_data (h->root.u.def.section->owner);
10706	  log_file_align = bed->s->log_file_align;
10707	  n = h->vtable->parent->vtable->size >> log_file_align;
10708	  while (n--)
10709	    {
10710	      if (*pu)
10711		*cu = TRUE;
10712	      pu++;
10713	      cu++;
10714	    }
10715	}
10716    }
10717
10718  return TRUE;
10719}
10720
10721static bfd_boolean
10722elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
10723{
10724  asection *sec;
10725  bfd_vma hstart, hend;
10726  Elf_Internal_Rela *relstart, *relend, *rel;
10727  const struct elf_backend_data *bed;
10728  unsigned int log_file_align;
10729
10730  if (h->root.type == bfd_link_hash_warning)
10731    h = (struct elf_link_hash_entry *) h->root.u.i.link;
10732
10733  /* Take care of both those symbols that do not describe vtables as
10734     well as those that are not loaded.  */
10735  if (h->vtable == NULL || h->vtable->parent == NULL)
10736    return TRUE;
10737
10738  BFD_ASSERT (h->root.type == bfd_link_hash_defined
10739	      || h->root.type == bfd_link_hash_defweak);
10740
10741  sec = h->root.u.def.section;
10742  hstart = h->root.u.def.value;
10743  hend = hstart + h->size;
10744
10745  relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
10746  if (!relstart)
10747    return *(bfd_boolean *) okp = FALSE;
10748  bed = get_elf_backend_data (sec->owner);
10749  log_file_align = bed->s->log_file_align;
10750
10751  relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
10752
10753  for (rel = relstart; rel < relend; ++rel)
10754    if (rel->r_offset >= hstart && rel->r_offset < hend)
10755      {
10756	/* If the entry is in use, do nothing.  */
10757	if (h->vtable->used
10758	    && (rel->r_offset - hstart) < h->vtable->size)
10759	  {
10760	    bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
10761	    if (h->vtable->used[entry])
10762	      continue;
10763	  }
10764	/* Otherwise, kill it.  */
10765	rel->r_offset = rel->r_info = rel->r_addend = 0;
10766      }
10767
10768  return TRUE;
10769}
10770
10771/* Mark sections containing dynamically referenced symbols.  When
10772   building shared libraries, we must assume that any visible symbol is
10773   referenced.  */
10774
10775bfd_boolean
10776bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
10777{
10778  struct bfd_link_info *info = (struct bfd_link_info *) inf;
10779
10780  if (h->root.type == bfd_link_hash_warning)
10781    h = (struct elf_link_hash_entry *) h->root.u.i.link;
10782
10783  if ((h->root.type == bfd_link_hash_defined
10784       || h->root.type == bfd_link_hash_defweak)
10785      && (h->ref_dynamic
10786	  || (!info->executable
10787	      && h->def_regular
10788	      && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
10789	      && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN)))
10790    h->root.u.def.section->flags |= SEC_KEEP;
10791
10792  return TRUE;
10793}
10794
10795/* Do mark and sweep of unused sections.  */
10796
10797bfd_boolean
10798bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
10799{
10800  bfd_boolean ok = TRUE;
10801  bfd *sub;
10802  elf_gc_mark_hook_fn gc_mark_hook;
10803  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10804
10805  if (!bed->can_gc_sections
10806      || info->relocatable
10807      || info->emitrelocations
10808      || !is_elf_hash_table (info->hash))
10809    {
10810      (*_bfd_error_handler)(_("Warning: gc-sections option ignored"));
10811      return TRUE;
10812    }
10813
10814  /* Apply transitive closure to the vtable entry usage info.  */
10815  elf_link_hash_traverse (elf_hash_table (info),
10816			  elf_gc_propagate_vtable_entries_used,
10817			  &ok);
10818  if (!ok)
10819    return FALSE;
10820
10821  /* Kill the vtable relocations that were not used.  */
10822  elf_link_hash_traverse (elf_hash_table (info),
10823			  elf_gc_smash_unused_vtentry_relocs,
10824			  &ok);
10825  if (!ok)
10826    return FALSE;
10827
10828  /* Mark dynamically referenced symbols.  */
10829  if (elf_hash_table (info)->dynamic_sections_created)
10830    elf_link_hash_traverse (elf_hash_table (info),
10831			    bed->gc_mark_dynamic_ref,
10832			    info);
10833
10834  /* Grovel through relocs to find out who stays ...  */
10835  gc_mark_hook = bed->gc_mark_hook;
10836  for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
10837    {
10838      asection *o;
10839
10840      if (bfd_get_flavour (sub) != bfd_target_elf_flavour)
10841	continue;
10842
10843      for (o = sub->sections; o != NULL; o = o->next)
10844	if ((o->flags & (SEC_EXCLUDE | SEC_KEEP)) == SEC_KEEP && !o->gc_mark)
10845	  if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
10846	    return FALSE;
10847    }
10848
10849  /* Allow the backend to mark additional target specific sections.  */
10850  if (bed->gc_mark_extra_sections)
10851    bed->gc_mark_extra_sections(info, gc_mark_hook);
10852
10853  /* ... again for sections marked from eh_frame.  */
10854  for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
10855    {
10856      asection *o;
10857
10858      if (bfd_get_flavour (sub) != bfd_target_elf_flavour)
10859	continue;
10860
10861      /* Keep .gcc_except_table.* if the associated .text.* (or the
10862	 associated .gnu.linkonce.t.* if .text.* doesn't exist) is
10863	 marked.  This isn't very nice, but the proper solution,
10864	 splitting .eh_frame up and using comdat doesn't pan out
10865	 easily due to needing special relocs to handle the
10866	 difference of two symbols in separate sections.
10867	 Don't keep code sections referenced by .eh_frame.  */
10868#define TEXT_PREFIX			".text."
10869#define TEXT_PREFIX2			".gnu.linkonce.t."
10870#define GCC_EXCEPT_TABLE_PREFIX		".gcc_except_table."
10871      for (o = sub->sections; o != NULL; o = o->next)
10872	if (!o->gc_mark && o->gc_mark_from_eh && (o->flags & SEC_CODE) == 0)
10873	  {
10874	    if (CONST_STRNEQ (o->name, GCC_EXCEPT_TABLE_PREFIX))
10875	      {
10876		char *fn_name;
10877		const char *sec_name;
10878		asection *fn_text;
10879		unsigned o_name_prefix_len , fn_name_prefix_len, tmp;
10880
10881		o_name_prefix_len = strlen (GCC_EXCEPT_TABLE_PREFIX);
10882		sec_name = o->name + o_name_prefix_len;
10883		fn_name_prefix_len = strlen (TEXT_PREFIX);
10884		tmp = strlen (TEXT_PREFIX2);
10885		if (tmp > fn_name_prefix_len)
10886		  fn_name_prefix_len = tmp;
10887		fn_name
10888		  = bfd_malloc (fn_name_prefix_len + strlen (sec_name) + 1);
10889		if (fn_name == NULL)
10890		  return FALSE;
10891
10892		/* Try the first prefix.  */
10893		sprintf (fn_name, "%s%s", TEXT_PREFIX, sec_name);
10894		fn_text = bfd_get_section_by_name (sub, fn_name);
10895
10896		/* Try the second prefix.  */
10897		if (fn_text == NULL)
10898		  {
10899		    sprintf (fn_name, "%s%s", TEXT_PREFIX2, sec_name);
10900		    fn_text = bfd_get_section_by_name (sub, fn_name);
10901		  }
10902
10903		free (fn_name);
10904		if (fn_text == NULL || !fn_text->gc_mark)
10905		  continue;
10906	      }
10907
10908	    /* If not using specially named exception table section,
10909	       then keep whatever we are using.  */
10910	    if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
10911	      return FALSE;
10912	  }
10913    }
10914
10915  /* ... and mark SEC_EXCLUDE for those that go.  */
10916  return elf_gc_sweep (abfd, info);
10917}
10918
10919/* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
10920
10921bfd_boolean
10922bfd_elf_gc_record_vtinherit (bfd *abfd,
10923			     asection *sec,
10924			     struct elf_link_hash_entry *h,
10925			     bfd_vma offset)
10926{
10927  struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
10928  struct elf_link_hash_entry **search, *child;
10929  bfd_size_type extsymcount;
10930  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10931
10932  /* The sh_info field of the symtab header tells us where the
10933     external symbols start.  We don't care about the local symbols at
10934     this point.  */
10935  extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
10936  if (!elf_bad_symtab (abfd))
10937    extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
10938
10939  sym_hashes = elf_sym_hashes (abfd);
10940  sym_hashes_end = sym_hashes + extsymcount;
10941
10942  /* Hunt down the child symbol, which is in this section at the same
10943     offset as the relocation.  */
10944  for (search = sym_hashes; search != sym_hashes_end; ++search)
10945    {
10946      if ((child = *search) != NULL
10947	  && (child->root.type == bfd_link_hash_defined
10948	      || child->root.type == bfd_link_hash_defweak)
10949	  && child->root.u.def.section == sec
10950	  && child->root.u.def.value == offset)
10951	goto win;
10952    }
10953
10954  (*_bfd_error_handler) ("%B: %A+%lu: No symbol found for INHERIT",
10955			 abfd, sec, (unsigned long) offset);
10956  bfd_set_error (bfd_error_invalid_operation);
10957  return FALSE;
10958
10959 win:
10960  if (!child->vtable)
10961    {
10962      child->vtable = bfd_zalloc (abfd, sizeof (*child->vtable));
10963      if (!child->vtable)
10964	return FALSE;
10965    }
10966  if (!h)
10967    {
10968      /* This *should* only be the absolute section.  It could potentially
10969	 be that someone has defined a non-global vtable though, which
10970	 would be bad.  It isn't worth paging in the local symbols to be
10971	 sure though; that case should simply be handled by the assembler.  */
10972
10973      child->vtable->parent = (struct elf_link_hash_entry *) -1;
10974    }
10975  else
10976    child->vtable->parent = h;
10977
10978  return TRUE;
10979}
10980
10981/* Called from check_relocs to record the existence of a VTENTRY reloc.  */
10982
10983bfd_boolean
10984bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
10985			   asection *sec ATTRIBUTE_UNUSED,
10986			   struct elf_link_hash_entry *h,
10987			   bfd_vma addend)
10988{
10989  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10990  unsigned int log_file_align = bed->s->log_file_align;
10991
10992  if (!h->vtable)
10993    {
10994      h->vtable = bfd_zalloc (abfd, sizeof (*h->vtable));
10995      if (!h->vtable)
10996	return FALSE;
10997    }
10998
10999  if (addend >= h->vtable->size)
11000    {
11001      size_t size, bytes, file_align;
11002      bfd_boolean *ptr = h->vtable->used;
11003
11004      /* While the symbol is undefined, we have to be prepared to handle
11005	 a zero size.  */
11006      file_align = 1 << log_file_align;
11007      if (h->root.type == bfd_link_hash_undefined)
11008	size = addend + file_align;
11009      else
11010	{
11011	  size = h->size;
11012	  if (addend >= size)
11013	    {
11014	      /* Oops!  We've got a reference past the defined end of
11015		 the table.  This is probably a bug -- shall we warn?  */
11016	      size = addend + file_align;
11017	    }
11018	}
11019      size = (size + file_align - 1) & -file_align;
11020
11021      /* Allocate one extra entry for use as a "done" flag for the
11022	 consolidation pass.  */
11023      bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
11024
11025      if (ptr)
11026	{
11027	  ptr = bfd_realloc (ptr - 1, bytes);
11028
11029	  if (ptr != NULL)
11030	    {
11031	      size_t oldbytes;
11032
11033	      oldbytes = (((h->vtable->size >> log_file_align) + 1)
11034			  * sizeof (bfd_boolean));
11035	      memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
11036	    }
11037	}
11038      else
11039	ptr = bfd_zmalloc (bytes);
11040
11041      if (ptr == NULL)
11042	return FALSE;
11043
11044      /* And arrange for that done flag to be at index -1.  */
11045      h->vtable->used = ptr + 1;
11046      h->vtable->size = size;
11047    }
11048
11049  h->vtable->used[addend >> log_file_align] = TRUE;
11050
11051  return TRUE;
11052}
11053
11054struct alloc_got_off_arg {
11055  bfd_vma gotoff;
11056  unsigned int got_elt_size;
11057};
11058
11059/* We need a special top-level link routine to convert got reference counts
11060   to real got offsets.  */
11061
11062static bfd_boolean
11063elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
11064{
11065  struct alloc_got_off_arg *gofarg = arg;
11066
11067  if (h->root.type == bfd_link_hash_warning)
11068    h = (struct elf_link_hash_entry *) h->root.u.i.link;
11069
11070  if (h->got.refcount > 0)
11071    {
11072      h->got.offset = gofarg->gotoff;
11073      gofarg->gotoff += gofarg->got_elt_size;
11074    }
11075  else
11076    h->got.offset = (bfd_vma) -1;
11077
11078  return TRUE;
11079}
11080
11081/* And an accompanying bit to work out final got entry offsets once
11082   we're done.  Should be called from final_link.  */
11083
11084bfd_boolean
11085bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
11086					struct bfd_link_info *info)
11087{
11088  bfd *i;
11089  const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11090  bfd_vma gotoff;
11091  unsigned int got_elt_size = bed->s->arch_size / 8;
11092  struct alloc_got_off_arg gofarg;
11093
11094  if (! is_elf_hash_table (info->hash))
11095    return FALSE;
11096
11097  /* The GOT offset is relative to the .got section, but the GOT header is
11098     put into the .got.plt section, if the backend uses it.  */
11099  if (bed->want_got_plt)
11100    gotoff = 0;
11101  else
11102    gotoff = bed->got_header_size;
11103
11104  /* Do the local .got entries first.  */
11105  for (i = info->input_bfds; i; i = i->link_next)
11106    {
11107      bfd_signed_vma *local_got;
11108      bfd_size_type j, locsymcount;
11109      Elf_Internal_Shdr *symtab_hdr;
11110
11111      if (bfd_get_flavour (i) != bfd_target_elf_flavour)
11112	continue;
11113
11114      local_got = elf_local_got_refcounts (i);
11115      if (!local_got)
11116	continue;
11117
11118      symtab_hdr = &elf_tdata (i)->symtab_hdr;
11119      if (elf_bad_symtab (i))
11120	locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
11121      else
11122	locsymcount = symtab_hdr->sh_info;
11123
11124      for (j = 0; j < locsymcount; ++j)
11125	{
11126	  if (local_got[j] > 0)
11127	    {
11128	      local_got[j] = gotoff;
11129	      gotoff += got_elt_size;
11130	    }
11131	  else
11132	    local_got[j] = (bfd_vma) -1;
11133	}
11134    }
11135
11136  /* Then the global .got entries.  .plt refcounts are handled by
11137     adjust_dynamic_symbol  */
11138  gofarg.gotoff = gotoff;
11139  gofarg.got_elt_size = got_elt_size;
11140  elf_link_hash_traverse (elf_hash_table (info),
11141			  elf_gc_allocate_got_offsets,
11142			  &gofarg);
11143  return TRUE;
11144}
11145
11146/* Many folk need no more in the way of final link than this, once
11147   got entry reference counting is enabled.  */
11148
11149bfd_boolean
11150bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
11151{
11152  if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
11153    return FALSE;
11154
11155  /* Invoke the regular ELF backend linker to do all the work.  */
11156  return bfd_elf_final_link (abfd, info);
11157}
11158
11159bfd_boolean
11160bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
11161{
11162  struct elf_reloc_cookie *rcookie = cookie;
11163
11164  if (rcookie->bad_symtab)
11165    rcookie->rel = rcookie->rels;
11166
11167  for (; rcookie->rel < rcookie->relend; rcookie->rel++)
11168    {
11169      unsigned long r_symndx;
11170
11171      if (! rcookie->bad_symtab)
11172	if (rcookie->rel->r_offset > offset)
11173	  return FALSE;
11174      if (rcookie->rel->r_offset != offset)
11175	continue;
11176
11177      r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
11178      if (r_symndx == SHN_UNDEF)
11179	return TRUE;
11180
11181      if (r_symndx >= rcookie->locsymcount
11182	  || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
11183	{
11184	  struct elf_link_hash_entry *h;
11185
11186	  h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
11187
11188	  while (h->root.type == bfd_link_hash_indirect
11189		 || h->root.type == bfd_link_hash_warning)
11190	    h = (struct elf_link_hash_entry *) h->root.u.i.link;
11191
11192	  if ((h->root.type == bfd_link_hash_defined
11193	       || h->root.type == bfd_link_hash_defweak)
11194	      && elf_discarded_section (h->root.u.def.section))
11195	    return TRUE;
11196	  else
11197	    return FALSE;
11198	}
11199      else
11200	{
11201	  /* It's not a relocation against a global symbol,
11202	     but it could be a relocation against a local
11203	     symbol for a discarded section.  */
11204	  asection *isec;
11205	  Elf_Internal_Sym *isym;
11206
11207	  /* Need to: get the symbol; get the section.  */
11208	  isym = &rcookie->locsyms[r_symndx];
11209	  if (isym->st_shndx < SHN_LORESERVE || isym->st_shndx > SHN_HIRESERVE)
11210	    {
11211	      isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
11212	      if (isec != NULL && elf_discarded_section (isec))
11213		return TRUE;
11214	    }
11215	}
11216      return FALSE;
11217    }
11218  return FALSE;
11219}
11220
11221/* Discard unneeded references to discarded sections.
11222   Returns TRUE if any section's size was changed.  */
11223/* This function assumes that the relocations are in sorted order,
11224   which is true for all known assemblers.  */
11225
11226bfd_boolean
11227bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
11228{
11229  struct elf_reloc_cookie cookie;
11230  asection *stab, *eh;
11231  Elf_Internal_Shdr *symtab_hdr;
11232  const struct elf_backend_data *bed;
11233  bfd *abfd;
11234  unsigned int count;
11235  bfd_boolean ret = FALSE;
11236
11237  if (info->traditional_format
11238      || !is_elf_hash_table (info->hash))
11239    return FALSE;
11240
11241  for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link_next)
11242    {
11243      if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
11244	continue;
11245
11246      bed = get_elf_backend_data (abfd);
11247
11248      if ((abfd->flags & DYNAMIC) != 0)
11249	continue;
11250
11251      eh = NULL;
11252      if (!info->relocatable)
11253	{
11254	  eh = bfd_get_section_by_name (abfd, ".eh_frame");
11255	  if (eh != NULL
11256	      && (eh->size == 0
11257		  || bfd_is_abs_section (eh->output_section)))
11258	    eh = NULL;
11259	}
11260
11261      stab = bfd_get_section_by_name (abfd, ".stab");
11262      if (stab != NULL
11263	  && (stab->size == 0
11264	      || bfd_is_abs_section (stab->output_section)
11265	      || stab->sec_info_type != ELF_INFO_TYPE_STABS))
11266	stab = NULL;
11267
11268      if (stab == NULL
11269	  && eh == NULL
11270	  && bed->elf_backend_discard_info == NULL)
11271	continue;
11272
11273      symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11274      cookie.abfd = abfd;
11275      cookie.sym_hashes = elf_sym_hashes (abfd);
11276      cookie.bad_symtab = elf_bad_symtab (abfd);
11277      if (cookie.bad_symtab)
11278	{
11279	  cookie.locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
11280	  cookie.extsymoff = 0;
11281	}
11282      else
11283	{
11284	  cookie.locsymcount = symtab_hdr->sh_info;
11285	  cookie.extsymoff = symtab_hdr->sh_info;
11286	}
11287
11288      if (bed->s->arch_size == 32)
11289	cookie.r_sym_shift = 8;
11290      else
11291	cookie.r_sym_shift = 32;
11292
11293      cookie.locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
11294      if (cookie.locsyms == NULL && cookie.locsymcount != 0)
11295	{
11296	  cookie.locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
11297						 cookie.locsymcount, 0,
11298						 NULL, NULL, NULL);
11299	  if (cookie.locsyms == NULL)
11300	    {
11301	      info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
11302	      return FALSE;
11303	    }
11304	}
11305
11306      if (stab != NULL)
11307	{
11308	  cookie.rels = NULL;
11309	  count = stab->reloc_count;
11310	  if (count != 0)
11311	    cookie.rels = _bfd_elf_link_read_relocs (abfd, stab, NULL, NULL,
11312						     info->keep_memory);
11313	  if (cookie.rels != NULL)
11314	    {
11315	      cookie.rel = cookie.rels;
11316	      cookie.relend = cookie.rels;
11317	      cookie.relend += count * bed->s->int_rels_per_ext_rel;
11318	      if (_bfd_discard_section_stabs (abfd, stab,
11319					      elf_section_data (stab)->sec_info,
11320					      bfd_elf_reloc_symbol_deleted_p,
11321					      &cookie))
11322		ret = TRUE;
11323	      if (elf_section_data (stab)->relocs != cookie.rels)
11324		free (cookie.rels);
11325	    }
11326	}
11327
11328      if (eh != NULL)
11329	{
11330	  cookie.rels = NULL;
11331	  count = eh->reloc_count;
11332	  if (count != 0)
11333	    cookie.rels = _bfd_elf_link_read_relocs (abfd, eh, NULL, NULL,
11334						     info->keep_memory);
11335	  cookie.rel = cookie.rels;
11336	  cookie.relend = cookie.rels;
11337	  if (cookie.rels != NULL)
11338	    cookie.relend += count * bed->s->int_rels_per_ext_rel;
11339
11340	  if (_bfd_elf_discard_section_eh_frame (abfd, info, eh,
11341						 bfd_elf_reloc_symbol_deleted_p,
11342						 &cookie))
11343	    ret = TRUE;
11344
11345	  if (cookie.rels != NULL
11346	      && elf_section_data (eh)->relocs != cookie.rels)
11347	    free (cookie.rels);
11348	}
11349
11350      if (bed->elf_backend_discard_info != NULL
11351	  && (*bed->elf_backend_discard_info) (abfd, &cookie, info))
11352	ret = TRUE;
11353
11354      if (cookie.locsyms != NULL
11355	  && symtab_hdr->contents != (unsigned char *) cookie.locsyms)
11356	{
11357	  if (! info->keep_memory)
11358	    free (cookie.locsyms);
11359	  else
11360	    symtab_hdr->contents = (unsigned char *) cookie.locsyms;
11361	}
11362    }
11363
11364  if (info->eh_frame_hdr
11365      && !info->relocatable
11366      && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
11367    ret = TRUE;
11368
11369  return ret;
11370}
11371
11372void
11373_bfd_elf_section_already_linked (bfd *abfd, struct bfd_section *sec,
11374				 struct bfd_link_info *info)
11375{
11376  flagword flags;
11377  const char *name, *p;
11378  struct bfd_section_already_linked *l;
11379  struct bfd_section_already_linked_hash_entry *already_linked_list;
11380
11381  if (sec->output_section == bfd_abs_section_ptr)
11382    return;
11383
11384  flags = sec->flags;
11385
11386  /* Return if it isn't a linkonce section.  A comdat group section
11387     also has SEC_LINK_ONCE set.  */
11388  if ((flags & SEC_LINK_ONCE) == 0)
11389    return;
11390
11391  /* Don't put group member sections on our list of already linked
11392     sections.  They are handled as a group via their group section.  */
11393  if (elf_sec_group (sec) != NULL)
11394    return;
11395
11396  /* FIXME: When doing a relocatable link, we may have trouble
11397     copying relocations in other sections that refer to local symbols
11398     in the section being discarded.  Those relocations will have to
11399     be converted somehow; as of this writing I'm not sure that any of
11400     the backends handle that correctly.
11401
11402     It is tempting to instead not discard link once sections when
11403     doing a relocatable link (technically, they should be discarded
11404     whenever we are building constructors).  However, that fails,
11405     because the linker winds up combining all the link once sections
11406     into a single large link once section, which defeats the purpose
11407     of having link once sections in the first place.
11408
11409     Also, not merging link once sections in a relocatable link
11410     causes trouble for MIPS ELF, which relies on link once semantics
11411     to handle the .reginfo section correctly.  */
11412
11413  name = bfd_get_section_name (abfd, sec);
11414
11415  if (CONST_STRNEQ (name, ".gnu.linkonce.")
11416      && (p = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
11417    p++;
11418  else
11419    p = name;
11420
11421  already_linked_list = bfd_section_already_linked_table_lookup (p);
11422
11423  for (l = already_linked_list->entry; l != NULL; l = l->next)
11424    {
11425      /* We may have 2 different types of sections on the list: group
11426	 sections and linkonce sections.  Match like sections.  */
11427      if ((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
11428	  && strcmp (name, l->sec->name) == 0
11429	  && bfd_coff_get_comdat_section (l->sec->owner, l->sec) == NULL)
11430	{
11431	  /* The section has already been linked.  See if we should
11432	     issue a warning.  */
11433	  switch (flags & SEC_LINK_DUPLICATES)
11434	    {
11435	    default:
11436	      abort ();
11437
11438	    case SEC_LINK_DUPLICATES_DISCARD:
11439	      break;
11440
11441	    case SEC_LINK_DUPLICATES_ONE_ONLY:
11442	      (*_bfd_error_handler)
11443		(_("%B: ignoring duplicate section `%A'"),
11444		 abfd, sec);
11445	      break;
11446
11447	    case SEC_LINK_DUPLICATES_SAME_SIZE:
11448	      if (sec->size != l->sec->size)
11449		(*_bfd_error_handler)
11450		  (_("%B: duplicate section `%A' has different size"),
11451		   abfd, sec);
11452	      break;
11453
11454	    case SEC_LINK_DUPLICATES_SAME_CONTENTS:
11455	      if (sec->size != l->sec->size)
11456		(*_bfd_error_handler)
11457		  (_("%B: duplicate section `%A' has different size"),
11458		   abfd, sec);
11459	      else if (sec->size != 0)
11460		{
11461		  bfd_byte *sec_contents, *l_sec_contents;
11462
11463		  if (!bfd_malloc_and_get_section (abfd, sec, &sec_contents))
11464		    (*_bfd_error_handler)
11465		      (_("%B: warning: could not read contents of section `%A'"),
11466		       abfd, sec);
11467		  else if (!bfd_malloc_and_get_section (l->sec->owner, l->sec,
11468							&l_sec_contents))
11469		    (*_bfd_error_handler)
11470		      (_("%B: warning: could not read contents of section `%A'"),
11471		       l->sec->owner, l->sec);
11472		  else if (memcmp (sec_contents, l_sec_contents, sec->size) != 0)
11473		    (*_bfd_error_handler)
11474		      (_("%B: warning: duplicate section `%A' has different contents"),
11475		       abfd, sec);
11476
11477		  if (sec_contents)
11478		    free (sec_contents);
11479		  if (l_sec_contents)
11480		    free (l_sec_contents);
11481		}
11482	      break;
11483	    }
11484
11485	  /* Set the output_section field so that lang_add_section
11486	     does not create a lang_input_section structure for this
11487	     section.  Since there might be a symbol in the section
11488	     being discarded, we must retain a pointer to the section
11489	     which we are really going to use.  */
11490	  sec->output_section = bfd_abs_section_ptr;
11491	  sec->kept_section = l->sec;
11492
11493	  if (flags & SEC_GROUP)
11494	    {
11495	      asection *first = elf_next_in_group (sec);
11496	      asection *s = first;
11497
11498	      while (s != NULL)
11499		{
11500		  s->output_section = bfd_abs_section_ptr;
11501		  /* Record which group discards it.  */
11502		  s->kept_section = l->sec;
11503		  s = elf_next_in_group (s);
11504		  /* These lists are circular.  */
11505		  if (s == first)
11506		    break;
11507		}
11508	    }
11509
11510	  return;
11511	}
11512    }
11513
11514  /* A single member comdat group section may be discarded by a
11515     linkonce section and vice versa.  */
11516
11517  if ((flags & SEC_GROUP) != 0)
11518    {
11519      asection *first = elf_next_in_group (sec);
11520
11521      if (first != NULL && elf_next_in_group (first) == first)
11522	/* Check this single member group against linkonce sections.  */
11523	for (l = already_linked_list->entry; l != NULL; l = l->next)
11524	  if ((l->sec->flags & SEC_GROUP) == 0
11525	      && bfd_coff_get_comdat_section (l->sec->owner, l->sec) == NULL
11526	      && bfd_elf_match_symbols_in_sections (l->sec, first, info))
11527	    {
11528	      first->output_section = bfd_abs_section_ptr;
11529	      first->kept_section = l->sec;
11530	      sec->output_section = bfd_abs_section_ptr;
11531	      break;
11532	    }
11533    }
11534  else
11535    /* Check this linkonce section against single member groups.  */
11536    for (l = already_linked_list->entry; l != NULL; l = l->next)
11537      if (l->sec->flags & SEC_GROUP)
11538	{
11539	  asection *first = elf_next_in_group (l->sec);
11540
11541	  if (first != NULL
11542	      && elf_next_in_group (first) == first
11543	      && bfd_elf_match_symbols_in_sections (first, sec, info))
11544	    {
11545	      sec->output_section = bfd_abs_section_ptr;
11546	      sec->kept_section = first;
11547	      break;
11548	    }
11549	}
11550
11551  /* This is the first section with this name.  Record it.  */
11552  bfd_section_already_linked_table_insert (already_linked_list, sec);
11553}
11554
11555bfd_boolean
11556_bfd_elf_common_definition (Elf_Internal_Sym *sym)
11557{
11558  return sym->st_shndx == SHN_COMMON;
11559}
11560
11561unsigned int
11562_bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
11563{
11564  return SHN_COMMON;
11565}
11566
11567asection *
11568_bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
11569{
11570  return bfd_com_section_ptr;
11571}
11572