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