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