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