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