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