Initial import of binutils 2.22 on the new vendor branch
[dragonfly.git] / contrib / binutils-2.22 / 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_anyway_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_anyway_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_anyway_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_anyway_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_anyway_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_anyway_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_anyway_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_anyway_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_anyway_with_flags (abfd, ".dynstr",
242                                           flags | SEC_READONLY);
243   if (s == NULL)
244     return FALSE;
245
246   s = bfd_make_section_anyway_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_anyway_with_flags (abfd, ".hash",
263                                               flags | SEC_READONLY);
264       if (s == NULL
265           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
266         return FALSE;
267       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
268     }
269
270   if (info->emit_gnu_hash)
271     {
272       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
273                                               flags | SEC_READONLY);
274       if (s == NULL
275           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
276         return FALSE;
277       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
278          4 32-bit words followed by variable count of 64-bit words, then
279          variable count of 32-bit words.  */
280       if (bed->s->arch_size == 64)
281         elf_section_data (s)->this_hdr.sh_entsize = 0;
282       else
283         elf_section_data (s)->this_hdr.sh_entsize = 4;
284     }
285
286   /* Let the backend create the rest of the sections.  This lets the
287      backend set the right flags.  The backend will normally create
288      the .got and .plt sections.  */
289   if (bed->elf_backend_create_dynamic_sections == NULL
290       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
291     return FALSE;
292
293   elf_hash_table (info)->dynamic_sections_created = TRUE;
294
295   return TRUE;
296 }
297
298 /* Create dynamic sections when linking against a dynamic object.  */
299
300 bfd_boolean
301 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
302 {
303   flagword flags, pltflags;
304   struct elf_link_hash_entry *h;
305   asection *s;
306   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
307   struct elf_link_hash_table *htab = elf_hash_table (info);
308
309   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
310      .rel[a].bss sections.  */
311   flags = bed->dynamic_sec_flags;
312
313   pltflags = flags;
314   if (bed->plt_not_loaded)
315     /* We do not clear SEC_ALLOC here because we still want the OS to
316        allocate space for the section; it's just that there's nothing
317        to read in from the object file.  */
318     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
319   else
320     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
321   if (bed->plt_readonly)
322     pltflags |= SEC_READONLY;
323
324   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
325   if (s == NULL
326       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
327     return FALSE;
328   htab->splt = s;
329
330   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
331      .plt section.  */
332   if (bed->want_plt_sym)
333     {
334       h = _bfd_elf_define_linkage_sym (abfd, info, s,
335                                        "_PROCEDURE_LINKAGE_TABLE_");
336       elf_hash_table (info)->hplt = h;
337       if (h == NULL)
338         return FALSE;
339     }
340
341   s = bfd_make_section_anyway_with_flags (abfd,
342                                           (bed->rela_plts_and_copies_p
343                                            ? ".rela.plt" : ".rel.plt"),
344                                           flags | SEC_READONLY);
345   if (s == NULL
346       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
347     return FALSE;
348   htab->srelplt = s;
349
350   if (! _bfd_elf_create_got_section (abfd, info))
351     return FALSE;
352
353   if (bed->want_dynbss)
354     {
355       /* The .dynbss section is a place to put symbols which are defined
356          by dynamic objects, are referenced by regular objects, and are
357          not functions.  We must allocate space for them in the process
358          image and use a R_*_COPY reloc to tell the dynamic linker to
359          initialize them at run time.  The linker script puts the .dynbss
360          section into the .bss section of the final image.  */
361       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
362                                               (SEC_ALLOC | 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_anyway_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           bfd_size_type size;
4519           unsigned int alignment_power;
4520
4521           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4522             {
4523               h = (struct elf_link_hash_entry *) p;
4524               if (h->root.type == bfd_link_hash_warning)
4525                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
4526               if (h->dynindx >= old_dynsymcount)
4527                 _bfd_elf_strtab_delref (htab->dynstr, h->dynstr_index);
4528
4529               /* Preserve the maximum alignment and size for common
4530                  symbols even if this dynamic lib isn't on DT_NEEDED
4531                  since it can still be loaded at the run-time by another
4532                  dynamic lib.  */
4533               if (h->root.type == bfd_link_hash_common)
4534                 {
4535                   size = h->root.u.c.size;
4536                   alignment_power = h->root.u.c.p->alignment_power;
4537                 }
4538               else
4539                 {
4540                   size = 0;
4541                   alignment_power = 0;
4542                 }
4543               memcpy (p, old_ent, htab->root.table.entsize);
4544               old_ent = (char *) old_ent + htab->root.table.entsize;
4545               h = (struct elf_link_hash_entry *) p;
4546               if (h->root.type == bfd_link_hash_warning)
4547                 {
4548                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
4549                   old_ent = (char *) old_ent + htab->root.table.entsize;
4550                 }
4551               else if (h->root.type == bfd_link_hash_common)
4552                 {
4553                   if (size > h->root.u.c.size)
4554                     h->root.u.c.size = size;
4555                   if (alignment_power > h->root.u.c.p->alignment_power)
4556                     h->root.u.c.p->alignment_power = alignment_power;
4557                 }
4558             }
4559         }
4560
4561       /* Make a special call to the linker "notice" function to
4562          tell it that symbols added for crefs may need to be removed.  */
4563       if (!(*info->callbacks->notice) (info, NULL, abfd, NULL,
4564                                        notice_not_needed, 0, NULL))
4565         goto error_free_vers;
4566
4567       free (old_tab);
4568       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
4569                            alloc_mark);
4570       if (nondeflt_vers != NULL)
4571         free (nondeflt_vers);
4572       return TRUE;
4573     }
4574
4575   if (old_tab != NULL)
4576     {
4577       if (!(*info->callbacks->notice) (info, NULL, abfd, NULL,
4578                                        notice_needed, 0, NULL))
4579         goto error_free_vers;
4580       free (old_tab);
4581       old_tab = NULL;
4582     }
4583
4584   /* Now that all the symbols from this input file are created, handle
4585      .symver foo, foo@BAR such that any relocs against foo become foo@BAR.  */
4586   if (nondeflt_vers != NULL)
4587     {
4588       bfd_size_type cnt, symidx;
4589
4590       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
4591         {
4592           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
4593           char *shortname, *p;
4594
4595           p = strchr (h->root.root.string, ELF_VER_CHR);
4596           if (p == NULL
4597               || (h->root.type != bfd_link_hash_defined
4598                   && h->root.type != bfd_link_hash_defweak))
4599             continue;
4600
4601           amt = p - h->root.root.string;
4602           shortname = (char *) bfd_malloc (amt + 1);
4603           if (!shortname)
4604             goto error_free_vers;
4605           memcpy (shortname, h->root.root.string, amt);
4606           shortname[amt] = '\0';
4607
4608           hi = (struct elf_link_hash_entry *)
4609                bfd_link_hash_lookup (&htab->root, shortname,
4610                                      FALSE, FALSE, FALSE);
4611           if (hi != NULL
4612               && hi->root.type == h->root.type
4613               && hi->root.u.def.value == h->root.u.def.value
4614               && hi->root.u.def.section == h->root.u.def.section)
4615             {
4616               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
4617               hi->root.type = bfd_link_hash_indirect;
4618               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
4619               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
4620               sym_hash = elf_sym_hashes (abfd);
4621               if (sym_hash)
4622                 for (symidx = 0; symidx < extsymcount; ++symidx)
4623                   if (sym_hash[symidx] == hi)
4624                     {
4625                       sym_hash[symidx] = h;
4626                       break;
4627                     }
4628             }
4629           free (shortname);
4630         }
4631       free (nondeflt_vers);
4632       nondeflt_vers = NULL;
4633     }
4634
4635   /* Now set the weakdefs field correctly for all the weak defined
4636      symbols we found.  The only way to do this is to search all the
4637      symbols.  Since we only need the information for non functions in
4638      dynamic objects, that's the only time we actually put anything on
4639      the list WEAKS.  We need this information so that if a regular
4640      object refers to a symbol defined weakly in a dynamic object, the
4641      real symbol in the dynamic object is also put in the dynamic
4642      symbols; we also must arrange for both symbols to point to the
4643      same memory location.  We could handle the general case of symbol
4644      aliasing, but a general symbol alias can only be generated in
4645      assembler code, handling it correctly would be very time
4646      consuming, and other ELF linkers don't handle general aliasing
4647      either.  */
4648   if (weaks != NULL)
4649     {
4650       struct elf_link_hash_entry **hpp;
4651       struct elf_link_hash_entry **hppend;
4652       struct elf_link_hash_entry **sorted_sym_hash;
4653       struct elf_link_hash_entry *h;
4654       size_t sym_count;
4655
4656       /* Since we have to search the whole symbol list for each weak
4657          defined symbol, search time for N weak defined symbols will be
4658          O(N^2). Binary search will cut it down to O(NlogN).  */
4659       amt = extsymcount * sizeof (struct elf_link_hash_entry *);
4660       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
4661       if (sorted_sym_hash == NULL)
4662         goto error_return;
4663       sym_hash = sorted_sym_hash;
4664       hpp = elf_sym_hashes (abfd);
4665       hppend = hpp + extsymcount;
4666       sym_count = 0;
4667       for (; hpp < hppend; hpp++)
4668         {
4669           h = *hpp;
4670           if (h != NULL
4671               && h->root.type == bfd_link_hash_defined
4672               && !bed->is_function_type (h->type))
4673             {
4674               *sym_hash = h;
4675               sym_hash++;
4676               sym_count++;
4677             }
4678         }
4679
4680       qsort (sorted_sym_hash, sym_count,
4681              sizeof (struct elf_link_hash_entry *),
4682              elf_sort_symbol);
4683
4684       while (weaks != NULL)
4685         {
4686           struct elf_link_hash_entry *hlook;
4687           asection *slook;
4688           bfd_vma vlook;
4689           long ilook;
4690           size_t i, j, idx;
4691
4692           hlook = weaks;
4693           weaks = hlook->u.weakdef;
4694           hlook->u.weakdef = NULL;
4695
4696           BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
4697                       || hlook->root.type == bfd_link_hash_defweak
4698                       || hlook->root.type == bfd_link_hash_common
4699                       || hlook->root.type == bfd_link_hash_indirect);
4700           slook = hlook->root.u.def.section;
4701           vlook = hlook->root.u.def.value;
4702
4703           ilook = -1;
4704           i = 0;
4705           j = sym_count;
4706           while (i < j)
4707             {
4708               bfd_signed_vma vdiff;
4709               idx = (i + j) / 2;
4710               h = sorted_sym_hash [idx];
4711               vdiff = vlook - h->root.u.def.value;
4712               if (vdiff < 0)
4713                 j = idx;
4714               else if (vdiff > 0)
4715                 i = idx + 1;
4716               else
4717                 {
4718                   long sdiff = slook->id - h->root.u.def.section->id;
4719                   if (sdiff < 0)
4720                     j = idx;
4721                   else if (sdiff > 0)
4722                     i = idx + 1;
4723                   else
4724                     {
4725                       ilook = idx;
4726                       break;
4727                     }
4728                 }
4729             }
4730
4731           /* We didn't find a value/section match.  */
4732           if (ilook == -1)
4733             continue;
4734
4735           for (i = ilook; i < sym_count; i++)
4736             {
4737               h = sorted_sym_hash [i];
4738
4739               /* Stop if value or section doesn't match.  */
4740               if (h->root.u.def.value != vlook
4741                   || h->root.u.def.section != slook)
4742                 break;
4743               else if (h != hlook)
4744                 {
4745                   hlook->u.weakdef = h;
4746
4747                   /* If the weak definition is in the list of dynamic
4748                      symbols, make sure the real definition is put
4749                      there as well.  */
4750                   if (hlook->dynindx != -1 && h->dynindx == -1)
4751                     {
4752                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
4753                         {
4754                         err_free_sym_hash:
4755                           free (sorted_sym_hash);
4756                           goto error_return;
4757                         }
4758                     }
4759
4760                   /* If the real definition is in the list of dynamic
4761                      symbols, make sure the weak definition is put
4762                      there as well.  If we don't do this, then the
4763                      dynamic loader might not merge the entries for the
4764                      real definition and the weak definition.  */
4765                   if (h->dynindx != -1 && hlook->dynindx == -1)
4766                     {
4767                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
4768                         goto err_free_sym_hash;
4769                     }
4770                   break;
4771                 }
4772             }
4773         }
4774
4775       free (sorted_sym_hash);
4776     }
4777
4778   if (bed->check_directives
4779       && !(*bed->check_directives) (abfd, info))
4780     return FALSE;
4781
4782   /* If this object is the same format as the output object, and it is
4783      not a shared library, then let the backend look through the
4784      relocs.
4785
4786      This is required to build global offset table entries and to
4787      arrange for dynamic relocs.  It is not required for the
4788      particular common case of linking non PIC code, even when linking
4789      against shared libraries, but unfortunately there is no way of
4790      knowing whether an object file has been compiled PIC or not.
4791      Looking through the relocs is not particularly time consuming.
4792      The problem is that we must either (1) keep the relocs in memory,
4793      which causes the linker to require additional runtime memory or
4794      (2) read the relocs twice from the input file, which wastes time.
4795      This would be a good case for using mmap.
4796
4797      I have no idea how to handle linking PIC code into a file of a
4798      different format.  It probably can't be done.  */
4799   if (! dynamic
4800       && is_elf_hash_table (htab)
4801       && bed->check_relocs != NULL
4802       && elf_object_id (abfd) == elf_hash_table_id (htab)
4803       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
4804     {
4805       asection *o;
4806
4807       for (o = abfd->sections; o != NULL; o = o->next)
4808         {
4809           Elf_Internal_Rela *internal_relocs;
4810           bfd_boolean ok;
4811
4812           if ((o->flags & SEC_RELOC) == 0
4813               || o->reloc_count == 0
4814               || ((info->strip == strip_all || info->strip == strip_debugger)
4815                   && (o->flags & SEC_DEBUGGING) != 0)
4816               || bfd_is_abs_section (o->output_section))
4817             continue;
4818
4819           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
4820                                                        info->keep_memory);
4821           if (internal_relocs == NULL)
4822             goto error_return;
4823
4824           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
4825
4826           if (elf_section_data (o)->relocs != internal_relocs)
4827             free (internal_relocs);
4828
4829           if (! ok)
4830             goto error_return;
4831         }
4832     }
4833
4834   /* If this is a non-traditional link, try to optimize the handling
4835      of the .stab/.stabstr sections.  */
4836   if (! dynamic
4837       && ! info->traditional_format
4838       && is_elf_hash_table (htab)
4839       && (info->strip != strip_all && info->strip != strip_debugger))
4840     {
4841       asection *stabstr;
4842
4843       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
4844       if (stabstr != NULL)
4845         {
4846           bfd_size_type string_offset = 0;
4847           asection *stab;
4848
4849           for (stab = abfd->sections; stab; stab = stab->next)
4850             if (CONST_STRNEQ (stab->name, ".stab")
4851                 && (!stab->name[5] ||
4852                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
4853                 && (stab->flags & SEC_MERGE) == 0
4854                 && !bfd_is_abs_section (stab->output_section))
4855               {
4856                 struct bfd_elf_section_data *secdata;
4857
4858                 secdata = elf_section_data (stab);
4859                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
4860                                                stabstr, &secdata->sec_info,
4861                                                &string_offset))
4862                   goto error_return;
4863                 if (secdata->sec_info)
4864                   stab->sec_info_type = ELF_INFO_TYPE_STABS;
4865             }
4866         }
4867     }
4868
4869   if (is_elf_hash_table (htab) && add_needed)
4870     {
4871       /* Add this bfd to the loaded list.  */
4872       struct elf_link_loaded_list *n;
4873
4874       n = (struct elf_link_loaded_list *)
4875           bfd_alloc (abfd, sizeof (struct elf_link_loaded_list));
4876       if (n == NULL)
4877         goto error_return;
4878       n->abfd = abfd;
4879       n->next = htab->loaded;
4880       htab->loaded = n;
4881     }
4882
4883   return TRUE;
4884
4885  error_free_vers:
4886   if (old_tab != NULL)
4887     free (old_tab);
4888   if (nondeflt_vers != NULL)
4889     free (nondeflt_vers);
4890   if (extversym != NULL)
4891     free (extversym);
4892  error_free_sym:
4893   if (isymbuf != NULL)
4894     free (isymbuf);
4895  error_return:
4896   return FALSE;
4897 }
4898
4899 /* Return the linker hash table entry of a symbol that might be
4900    satisfied by an archive symbol.  Return -1 on error.  */
4901
4902 struct elf_link_hash_entry *
4903 _bfd_elf_archive_symbol_lookup (bfd *abfd,
4904                                 struct bfd_link_info *info,
4905                                 const char *name)
4906 {
4907   struct elf_link_hash_entry *h;
4908   char *p, *copy;
4909   size_t len, first;
4910
4911   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
4912   if (h != NULL)
4913     return h;
4914
4915   /* If this is a default version (the name contains @@), look up the
4916      symbol again with only one `@' as well as without the version.
4917      The effect is that references to the symbol with and without the
4918      version will be matched by the default symbol in the archive.  */
4919
4920   p = strchr (name, ELF_VER_CHR);
4921   if (p == NULL || p[1] != ELF_VER_CHR)
4922     return h;
4923
4924   /* First check with only one `@'.  */
4925   len = strlen (name);
4926   copy = (char *) bfd_alloc (abfd, len);
4927   if (copy == NULL)
4928     return (struct elf_link_hash_entry *) 0 - 1;
4929
4930   first = p - name + 1;
4931   memcpy (copy, name, first);
4932   memcpy (copy + first, name + first + 1, len - first);
4933
4934   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
4935   if (h == NULL)
4936     {
4937       /* We also need to check references to the symbol without the
4938          version.  */
4939       copy[first - 1] = '\0';
4940       h = elf_link_hash_lookup (elf_hash_table (info), copy,
4941                                 FALSE, FALSE, TRUE);
4942     }
4943
4944   bfd_release (abfd, copy);
4945   return h;
4946 }
4947
4948 /* Add symbols from an ELF archive file to the linker hash table.  We
4949    don't use _bfd_generic_link_add_archive_symbols because of a
4950    problem which arises on UnixWare.  The UnixWare libc.so is an
4951    archive which includes an entry libc.so.1 which defines a bunch of
4952    symbols.  The libc.so archive also includes a number of other
4953    object files, which also define symbols, some of which are the same
4954    as those defined in libc.so.1.  Correct linking requires that we
4955    consider each object file in turn, and include it if it defines any
4956    symbols we need.  _bfd_generic_link_add_archive_symbols does not do
4957    this; it looks through the list of undefined symbols, and includes
4958    any object file which defines them.  When this algorithm is used on
4959    UnixWare, it winds up pulling in libc.so.1 early and defining a
4960    bunch of symbols.  This means that some of the other objects in the
4961    archive are not included in the link, which is incorrect since they
4962    precede libc.so.1 in the archive.
4963
4964    Fortunately, ELF archive handling is simpler than that done by
4965    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
4966    oddities.  In ELF, if we find a symbol in the archive map, and the
4967    symbol is currently undefined, we know that we must pull in that
4968    object file.
4969
4970    Unfortunately, we do have to make multiple passes over the symbol
4971    table until nothing further is resolved.  */
4972
4973 static bfd_boolean
4974 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
4975 {
4976   symindex c;
4977   bfd_boolean *defined = NULL;
4978   bfd_boolean *included = NULL;
4979   carsym *symdefs;
4980   bfd_boolean loop;
4981   bfd_size_type amt;
4982   const struct elf_backend_data *bed;
4983   struct elf_link_hash_entry * (*archive_symbol_lookup)
4984     (bfd *, struct bfd_link_info *, const char *);
4985
4986   if (! bfd_has_map (abfd))
4987     {
4988       /* An empty archive is a special case.  */
4989       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
4990         return TRUE;
4991       bfd_set_error (bfd_error_no_armap);
4992       return FALSE;
4993     }
4994
4995   /* Keep track of all symbols we know to be already defined, and all
4996      files we know to be already included.  This is to speed up the
4997      second and subsequent passes.  */
4998   c = bfd_ardata (abfd)->symdef_count;
4999   if (c == 0)
5000     return TRUE;
5001   amt = c;
5002   amt *= sizeof (bfd_boolean);
5003   defined = (bfd_boolean *) bfd_zmalloc (amt);
5004   included = (bfd_boolean *) bfd_zmalloc (amt);
5005   if (defined == NULL || included == NULL)
5006     goto error_return;
5007
5008   symdefs = bfd_ardata (abfd)->symdefs;
5009   bed = get_elf_backend_data (abfd);
5010   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5011
5012   do
5013     {
5014       file_ptr last;
5015       symindex i;
5016       carsym *symdef;
5017       carsym *symdefend;
5018
5019       loop = FALSE;
5020       last = -1;
5021
5022       symdef = symdefs;
5023       symdefend = symdef + c;
5024       for (i = 0; symdef < symdefend; symdef++, i++)
5025         {
5026           struct elf_link_hash_entry *h;
5027           bfd *element;
5028           struct bfd_link_hash_entry *undefs_tail;
5029           symindex mark;
5030
5031           if (defined[i] || included[i])
5032             continue;
5033           if (symdef->file_offset == last)
5034             {
5035               included[i] = TRUE;
5036               continue;
5037             }
5038
5039           h = archive_symbol_lookup (abfd, info, symdef->name);
5040           if (h == (struct elf_link_hash_entry *) 0 - 1)
5041             goto error_return;
5042
5043           if (h == NULL)
5044             continue;
5045
5046           if (h->root.type == bfd_link_hash_common)
5047             {
5048               /* We currently have a common symbol.  The archive map contains
5049                  a reference to this symbol, so we may want to include it.  We
5050                  only want to include it however, if this archive element
5051                  contains a definition of the symbol, not just another common
5052                  declaration of it.
5053
5054                  Unfortunately some archivers (including GNU ar) will put
5055                  declarations of common symbols into their archive maps, as
5056                  well as real definitions, so we cannot just go by the archive
5057                  map alone.  Instead we must read in the element's symbol
5058                  table and check that to see what kind of symbol definition
5059                  this is.  */
5060               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5061                 continue;
5062             }
5063           else if (h->root.type != bfd_link_hash_undefined)
5064             {
5065               if (h->root.type != bfd_link_hash_undefweak)
5066                 defined[i] = TRUE;
5067               continue;
5068             }
5069
5070           /* We need to include this archive member.  */
5071           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5072           if (element == NULL)
5073             goto error_return;
5074
5075           if (! bfd_check_format (element, bfd_object))
5076             goto error_return;
5077
5078           /* Doublecheck that we have not included this object
5079              already--it should be impossible, but there may be
5080              something wrong with the archive.  */
5081           if (element->archive_pass != 0)
5082             {
5083               bfd_set_error (bfd_error_bad_value);
5084               goto error_return;
5085             }
5086           element->archive_pass = 1;
5087
5088           undefs_tail = info->hash->undefs_tail;
5089
5090           if (!(*info->callbacks
5091                 ->add_archive_element) (info, element, symdef->name, &element))
5092             goto error_return;
5093           if (!bfd_link_add_symbols (element, info))
5094             goto error_return;
5095
5096           /* If there are any new undefined symbols, we need to make
5097              another pass through the archive in order to see whether
5098              they can be defined.  FIXME: This isn't perfect, because
5099              common symbols wind up on undefs_tail and because an
5100              undefined symbol which is defined later on in this pass
5101              does not require another pass.  This isn't a bug, but it
5102              does make the code less efficient than it could be.  */
5103           if (undefs_tail != info->hash->undefs_tail)
5104             loop = TRUE;
5105
5106           /* Look backward to mark all symbols from this object file
5107              which we have already seen in this pass.  */
5108           mark = i;
5109           do
5110             {
5111               included[mark] = TRUE;
5112               if (mark == 0)
5113                 break;
5114               --mark;
5115             }
5116           while (symdefs[mark].file_offset == symdef->file_offset);
5117
5118           /* We mark subsequent symbols from this object file as we go
5119              on through the loop.  */
5120           last = symdef->file_offset;
5121         }
5122     }
5123   while (loop);
5124
5125   free (defined);
5126   free (included);
5127
5128   return TRUE;
5129
5130  error_return:
5131   if (defined != NULL)
5132     free (defined);
5133   if (included != NULL)
5134     free (included);
5135   return FALSE;
5136 }
5137
5138 /* Given an ELF BFD, add symbols to the global hash table as
5139    appropriate.  */
5140
5141 bfd_boolean
5142 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5143 {
5144   switch (bfd_get_format (abfd))
5145     {
5146     case bfd_object:
5147       return elf_link_add_object_symbols (abfd, info);
5148     case bfd_archive:
5149       return elf_link_add_archive_symbols (abfd, info);
5150     default:
5151       bfd_set_error (bfd_error_wrong_format);
5152       return FALSE;
5153     }
5154 }
5155 \f
5156 struct hash_codes_info
5157 {
5158   unsigned long *hashcodes;
5159   bfd_boolean error;
5160 };
5161
5162 /* This function will be called though elf_link_hash_traverse to store
5163    all hash value of the exported symbols in an array.  */
5164
5165 static bfd_boolean
5166 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5167 {
5168   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5169   const char *name;
5170   char *p;
5171   unsigned long ha;
5172   char *alc = NULL;
5173
5174   /* Ignore indirect symbols.  These are added by the versioning code.  */
5175   if (h->dynindx == -1)
5176     return TRUE;
5177
5178   name = h->root.root.string;
5179   p = strchr (name, ELF_VER_CHR);
5180   if (p != NULL)
5181     {
5182       alc = (char *) bfd_malloc (p - name + 1);
5183       if (alc == NULL)
5184         {
5185           inf->error = TRUE;
5186           return FALSE;
5187         }
5188       memcpy (alc, name, p - name);
5189       alc[p - name] = '\0';
5190       name = alc;
5191     }
5192
5193   /* Compute the hash value.  */
5194   ha = bfd_elf_hash (name);
5195
5196   /* Store the found hash value in the array given as the argument.  */
5197   *(inf->hashcodes)++ = ha;
5198
5199   /* And store it in the struct so that we can put it in the hash table
5200      later.  */
5201   h->u.elf_hash_value = ha;
5202
5203   if (alc != NULL)
5204     free (alc);
5205
5206   return TRUE;
5207 }
5208
5209 struct collect_gnu_hash_codes
5210 {
5211   bfd *output_bfd;
5212   const struct elf_backend_data *bed;
5213   unsigned long int nsyms;
5214   unsigned long int maskbits;
5215   unsigned long int *hashcodes;
5216   unsigned long int *hashval;
5217   unsigned long int *indx;
5218   unsigned long int *counts;
5219   bfd_vma *bitmask;
5220   bfd_byte *contents;
5221   long int min_dynindx;
5222   unsigned long int bucketcount;
5223   unsigned long int symindx;
5224   long int local_indx;
5225   long int shift1, shift2;
5226   unsigned long int mask;
5227   bfd_boolean error;
5228 };
5229
5230 /* This function will be called though elf_link_hash_traverse to store
5231    all hash value of the exported symbols in an array.  */
5232
5233 static bfd_boolean
5234 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5235 {
5236   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5237   const char *name;
5238   char *p;
5239   unsigned long ha;
5240   char *alc = NULL;
5241
5242   /* Ignore indirect symbols.  These are added by the versioning code.  */
5243   if (h->dynindx == -1)
5244     return TRUE;
5245
5246   /* Ignore also local symbols and undefined symbols.  */
5247   if (! (*s->bed->elf_hash_symbol) (h))
5248     return TRUE;
5249
5250   name = h->root.root.string;
5251   p = strchr (name, ELF_VER_CHR);
5252   if (p != NULL)
5253     {
5254       alc = (char *) bfd_malloc (p - name + 1);
5255       if (alc == NULL)
5256         {
5257           s->error = TRUE;
5258           return FALSE;
5259         }
5260       memcpy (alc, name, p - name);
5261       alc[p - name] = '\0';
5262       name = alc;
5263     }
5264
5265   /* Compute the hash value.  */
5266   ha = bfd_elf_gnu_hash (name);
5267
5268   /* Store the found hash value in the array for compute_bucket_count,
5269      and also for .dynsym reordering purposes.  */
5270   s->hashcodes[s->nsyms] = ha;
5271   s->hashval[h->dynindx] = ha;
5272   ++s->nsyms;
5273   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5274     s->min_dynindx = h->dynindx;
5275
5276   if (alc != NULL)
5277     free (alc);
5278
5279   return TRUE;
5280 }
5281
5282 /* This function will be called though elf_link_hash_traverse to do
5283    final dynaminc symbol renumbering.  */
5284
5285 static bfd_boolean
5286 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5287 {
5288   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5289   unsigned long int bucket;
5290   unsigned long int val;
5291
5292   /* Ignore indirect symbols.  */
5293   if (h->dynindx == -1)
5294     return TRUE;
5295
5296   /* Ignore also local symbols and undefined symbols.  */
5297   if (! (*s->bed->elf_hash_symbol) (h))
5298     {
5299       if (h->dynindx >= s->min_dynindx)
5300         h->dynindx = s->local_indx++;
5301       return TRUE;
5302     }
5303
5304   bucket = s->hashval[h->dynindx] % s->bucketcount;
5305   val = (s->hashval[h->dynindx] >> s->shift1)
5306         & ((s->maskbits >> s->shift1) - 1);
5307   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5308   s->bitmask[val]
5309     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5310   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5311   if (s->counts[bucket] == 1)
5312     /* Last element terminates the chain.  */
5313     val |= 1;
5314   bfd_put_32 (s->output_bfd, val,
5315               s->contents + (s->indx[bucket] - s->symindx) * 4);
5316   --s->counts[bucket];
5317   h->dynindx = s->indx[bucket]++;
5318   return TRUE;
5319 }
5320
5321 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5322
5323 bfd_boolean
5324 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5325 {
5326   return !(h->forced_local
5327            || h->root.type == bfd_link_hash_undefined
5328            || h->root.type == bfd_link_hash_undefweak
5329            || ((h->root.type == bfd_link_hash_defined
5330                 || h->root.type == bfd_link_hash_defweak)
5331                && h->root.u.def.section->output_section == NULL));
5332 }
5333
5334 /* Array used to determine the number of hash table buckets to use
5335    based on the number of symbols there are.  If there are fewer than
5336    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5337    fewer than 37 we use 17 buckets, and so forth.  We never use more
5338    than 32771 buckets.  */
5339
5340 static const size_t elf_buckets[] =
5341 {
5342   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5343   16411, 32771, 0
5344 };
5345
5346 /* Compute bucket count for hashing table.  We do not use a static set
5347    of possible tables sizes anymore.  Instead we determine for all
5348    possible reasonable sizes of the table the outcome (i.e., the
5349    number of collisions etc) and choose the best solution.  The
5350    weighting functions are not too simple to allow the table to grow
5351    without bounds.  Instead one of the weighting factors is the size.
5352    Therefore the result is always a good payoff between few collisions
5353    (= short chain lengths) and table size.  */
5354 static size_t
5355 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5356                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5357                       unsigned long int nsyms,
5358                       int gnu_hash)
5359 {
5360   size_t best_size = 0;
5361   unsigned long int i;
5362
5363   /* We have a problem here.  The following code to optimize the table
5364      size requires an integer type with more the 32 bits.  If
5365      BFD_HOST_U_64_BIT is set we know about such a type.  */
5366 #ifdef BFD_HOST_U_64_BIT
5367   if (info->optimize)
5368     {
5369       size_t minsize;
5370       size_t maxsize;
5371       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5372       bfd *dynobj = elf_hash_table (info)->dynobj;
5373       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5374       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5375       unsigned long int *counts;
5376       bfd_size_type amt;
5377       unsigned int no_improvement_count = 0;
5378
5379       /* Possible optimization parameters: if we have NSYMS symbols we say
5380          that the hashing table must at least have NSYMS/4 and at most
5381          2*NSYMS buckets.  */
5382       minsize = nsyms / 4;
5383       if (minsize == 0)
5384         minsize = 1;
5385       best_size = maxsize = nsyms * 2;
5386       if (gnu_hash)
5387         {
5388           if (minsize < 2)
5389             minsize = 2;
5390           if ((best_size & 31) == 0)
5391             ++best_size;
5392         }
5393
5394       /* Create array where we count the collisions in.  We must use bfd_malloc
5395          since the size could be large.  */
5396       amt = maxsize;
5397       amt *= sizeof (unsigned long int);
5398       counts = (unsigned long int *) bfd_malloc (amt);
5399       if (counts == NULL)
5400         return 0;
5401
5402       /* Compute the "optimal" size for the hash table.  The criteria is a
5403          minimal chain length.  The minor criteria is (of course) the size
5404          of the table.  */
5405       for (i = minsize; i < maxsize; ++i)
5406         {
5407           /* Walk through the array of hashcodes and count the collisions.  */
5408           BFD_HOST_U_64_BIT max;
5409           unsigned long int j;
5410           unsigned long int fact;
5411
5412           if (gnu_hash && (i & 31) == 0)
5413             continue;
5414
5415           memset (counts, '\0', i * sizeof (unsigned long int));
5416
5417           /* Determine how often each hash bucket is used.  */
5418           for (j = 0; j < nsyms; ++j)
5419             ++counts[hashcodes[j] % i];
5420
5421           /* For the weight function we need some information about the
5422              pagesize on the target.  This is information need not be 100%
5423              accurate.  Since this information is not available (so far) we
5424              define it here to a reasonable default value.  If it is crucial
5425              to have a better value some day simply define this value.  */
5426 # ifndef BFD_TARGET_PAGESIZE
5427 #  define BFD_TARGET_PAGESIZE   (4096)
5428 # endif
5429
5430           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5431              and the chains.  */
5432           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5433
5434 # if 1
5435           /* Variant 1: optimize for short chains.  We add the squares
5436              of all the chain lengths (which favors many small chain
5437              over a few long chains).  */
5438           for (j = 0; j < i; ++j)
5439             max += counts[j] * counts[j];
5440
5441           /* This adds penalties for the overall size of the table.  */
5442           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5443           max *= fact * fact;
5444 # else
5445           /* Variant 2: Optimize a lot more for small table.  Here we
5446              also add squares of the size but we also add penalties for
5447              empty slots (the +1 term).  */
5448           for (j = 0; j < i; ++j)
5449             max += (1 + counts[j]) * (1 + counts[j]);
5450
5451           /* The overall size of the table is considered, but not as
5452              strong as in variant 1, where it is squared.  */
5453           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5454           max *= fact;
5455 # endif
5456
5457           /* Compare with current best results.  */
5458           if (max < best_chlen)
5459             {
5460               best_chlen = max;
5461               best_size = i;
5462               no_improvement_count = 0;
5463             }
5464           /* PR 11843: Avoid futile long searches for the best bucket size
5465              when there are a large number of symbols.  */
5466           else if (++no_improvement_count == 100)
5467             break;
5468         }
5469
5470       free (counts);
5471     }
5472   else
5473 #endif /* defined (BFD_HOST_U_64_BIT) */
5474     {
5475       /* This is the fallback solution if no 64bit type is available or if we
5476          are not supposed to spend much time on optimizations.  We select the
5477          bucket count using a fixed set of numbers.  */
5478       for (i = 0; elf_buckets[i] != 0; i++)
5479         {
5480           best_size = elf_buckets[i];
5481           if (nsyms < elf_buckets[i + 1])
5482             break;
5483         }
5484       if (gnu_hash && best_size < 2)
5485         best_size = 2;
5486     }
5487
5488   return best_size;
5489 }
5490
5491 /* Size any SHT_GROUP section for ld -r.  */
5492
5493 bfd_boolean
5494 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5495 {
5496   bfd *ibfd;
5497
5498   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link_next)
5499     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5500         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5501       return FALSE;
5502   return TRUE;
5503 }
5504
5505 /* Set up the sizes and contents of the ELF dynamic sections.  This is
5506    called by the ELF linker emulation before_allocation routine.  We
5507    must set the sizes of the sections before the linker sets the
5508    addresses of the various sections.  */
5509
5510 bfd_boolean
5511 bfd_elf_size_dynamic_sections (bfd *output_bfd,
5512                                const char *soname,
5513                                const char *rpath,
5514                                const char *filter_shlib,
5515                                const char *audit,
5516                                const char *depaudit,
5517                                const char * const *auxiliary_filters,
5518                                struct bfd_link_info *info,
5519                                asection **sinterpptr)
5520 {
5521   bfd_size_type soname_indx;
5522   bfd *dynobj;
5523   const struct elf_backend_data *bed;
5524   struct elf_info_failed asvinfo;
5525
5526   *sinterpptr = NULL;
5527
5528   soname_indx = (bfd_size_type) -1;
5529
5530   if (!is_elf_hash_table (info->hash))
5531     return TRUE;
5532
5533   bed = get_elf_backend_data (output_bfd);
5534   if (info->execstack)
5535     elf_tdata (output_bfd)->stack_flags = PF_R | PF_W | PF_X;
5536   else if (info->noexecstack)
5537     elf_tdata (output_bfd)->stack_flags = PF_R | PF_W;
5538   else
5539     {
5540       bfd *inputobj;
5541       asection *notesec = NULL;
5542       int exec = 0;
5543
5544       for (inputobj = info->input_bfds;
5545            inputobj;
5546            inputobj = inputobj->link_next)
5547         {
5548           asection *s;
5549
5550           if (inputobj->flags
5551               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
5552             continue;
5553           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
5554           if (s)
5555             {
5556               if (s->flags & SEC_CODE)
5557                 exec = PF_X;
5558               notesec = s;
5559             }
5560           else if (bed->default_execstack)
5561             exec = PF_X;
5562         }
5563       if (notesec)
5564         {
5565           elf_tdata (output_bfd)->stack_flags = PF_R | PF_W | exec;
5566           if (exec && info->relocatable
5567               && notesec->output_section != bfd_abs_section_ptr)
5568             notesec->output_section->flags |= SEC_CODE;
5569         }
5570     }
5571
5572   /* Any syms created from now on start with -1 in
5573      got.refcount/offset and plt.refcount/offset.  */
5574   elf_hash_table (info)->init_got_refcount
5575     = elf_hash_table (info)->init_got_offset;
5576   elf_hash_table (info)->init_plt_refcount
5577     = elf_hash_table (info)->init_plt_offset;
5578
5579   if (info->relocatable
5580       && !_bfd_elf_size_group_sections (info))
5581     return FALSE;
5582
5583   /* The backend may have to create some sections regardless of whether
5584      we're dynamic or not.  */
5585   if (bed->elf_backend_always_size_sections
5586       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
5587     return FALSE;
5588
5589   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
5590     return FALSE;
5591
5592   dynobj = elf_hash_table (info)->dynobj;
5593
5594   /* If there were no dynamic objects in the link, there is nothing to
5595      do here.  */
5596   if (dynobj == NULL)
5597     return TRUE;
5598
5599   if (elf_hash_table (info)->dynamic_sections_created)
5600     {
5601       struct elf_info_failed eif;
5602       struct elf_link_hash_entry *h;
5603       asection *dynstr;
5604       struct bfd_elf_version_tree *t;
5605       struct bfd_elf_version_expr *d;
5606       asection *s;
5607       bfd_boolean all_defined;
5608
5609       *sinterpptr = bfd_get_section_by_name (dynobj, ".interp");
5610       BFD_ASSERT (*sinterpptr != NULL || !info->executable);
5611
5612       if (soname != NULL)
5613         {
5614           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5615                                              soname, TRUE);
5616           if (soname_indx == (bfd_size_type) -1
5617               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
5618             return FALSE;
5619         }
5620
5621       if (info->symbolic)
5622         {
5623           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
5624             return FALSE;
5625           info->flags |= DF_SYMBOLIC;
5626         }
5627
5628       if (rpath != NULL)
5629         {
5630           bfd_size_type indx;
5631
5632           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
5633                                       TRUE);
5634           if (indx == (bfd_size_type) -1
5635               || !_bfd_elf_add_dynamic_entry (info, DT_RPATH, indx))
5636             return FALSE;
5637
5638           if  (info->new_dtags)
5639             {
5640               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr, indx);
5641               if (!_bfd_elf_add_dynamic_entry (info, DT_RUNPATH, indx))
5642                 return FALSE;
5643             }
5644         }
5645
5646       if (filter_shlib != NULL)
5647         {
5648           bfd_size_type indx;
5649
5650           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5651                                       filter_shlib, TRUE);
5652           if (indx == (bfd_size_type) -1
5653               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
5654             return FALSE;
5655         }
5656
5657       if (auxiliary_filters != NULL)
5658         {
5659           const char * const *p;
5660
5661           for (p = auxiliary_filters; *p != NULL; p++)
5662             {
5663               bfd_size_type indx;
5664
5665               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5666                                           *p, TRUE);
5667               if (indx == (bfd_size_type) -1
5668                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
5669                 return FALSE;
5670             }
5671         }
5672
5673       if (audit != NULL)
5674         {
5675           bfd_size_type indx;
5676
5677           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
5678                                       TRUE);
5679           if (indx == (bfd_size_type) -1
5680               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
5681             return FALSE;
5682         }
5683
5684       if (depaudit != NULL)
5685         {
5686           bfd_size_type indx;
5687
5688           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
5689                                       TRUE);
5690           if (indx == (bfd_size_type) -1
5691               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
5692             return FALSE;
5693         }
5694
5695       eif.info = info;
5696       eif.failed = FALSE;
5697
5698       /* If we are supposed to export all symbols into the dynamic symbol
5699          table (this is not the normal case), then do so.  */
5700       if (info->export_dynamic
5701           || (info->executable && info->dynamic))
5702         {
5703           elf_link_hash_traverse (elf_hash_table (info),
5704                                   _bfd_elf_export_symbol,
5705                                   &eif);
5706           if (eif.failed)
5707             return FALSE;
5708         }
5709
5710       /* Make all global versions with definition.  */
5711       for (t = info->version_info; t != NULL; t = t->next)
5712         for (d = t->globals.list; d != NULL; d = d->next)
5713           if (!d->symver && d->literal)
5714             {
5715               const char *verstr, *name;
5716               size_t namelen, verlen, newlen;
5717               char *newname, *p, leading_char;
5718               struct elf_link_hash_entry *newh;
5719
5720               leading_char = bfd_get_symbol_leading_char (output_bfd);
5721               name = d->pattern;
5722               namelen = strlen (name) + (leading_char != '\0');
5723               verstr = t->name;
5724               verlen = strlen (verstr);
5725               newlen = namelen + verlen + 3;
5726
5727               newname = (char *) bfd_malloc (newlen);
5728               if (newname == NULL)
5729                 return FALSE;
5730               newname[0] = leading_char;
5731               memcpy (newname + (leading_char != '\0'), name, namelen);
5732
5733               /* Check the hidden versioned definition.  */
5734               p = newname + namelen;
5735               *p++ = ELF_VER_CHR;
5736               memcpy (p, verstr, verlen + 1);
5737               newh = elf_link_hash_lookup (elf_hash_table (info),
5738                                            newname, FALSE, FALSE,
5739                                            FALSE);
5740               if (newh == NULL
5741                   || (newh->root.type != bfd_link_hash_defined
5742                       && newh->root.type != bfd_link_hash_defweak))
5743                 {
5744                   /* Check the default versioned definition.  */
5745                   *p++ = ELF_VER_CHR;
5746                   memcpy (p, verstr, verlen + 1);
5747                   newh = elf_link_hash_lookup (elf_hash_table (info),
5748                                                newname, FALSE, FALSE,
5749                                                FALSE);
5750                 }
5751               free (newname);
5752
5753               /* Mark this version if there is a definition and it is
5754                  not defined in a shared object.  */
5755               if (newh != NULL
5756                   && !newh->def_dynamic
5757                   && (newh->root.type == bfd_link_hash_defined
5758                       || newh->root.type == bfd_link_hash_defweak))
5759                 d->symver = 1;
5760             }
5761
5762       /* Attach all the symbols to their version information.  */
5763       asvinfo.info = info;
5764       asvinfo.failed = FALSE;
5765
5766       elf_link_hash_traverse (elf_hash_table (info),
5767                               _bfd_elf_link_assign_sym_version,
5768                               &asvinfo);
5769       if (asvinfo.failed)
5770         return FALSE;
5771
5772       if (!info->allow_undefined_version)
5773         {
5774           /* Check if all global versions have a definition.  */
5775           all_defined = TRUE;
5776           for (t = info->version_info; t != NULL; t = t->next)
5777             for (d = t->globals.list; d != NULL; d = d->next)
5778               if (d->literal && !d->symver && !d->script)
5779                 {
5780                   (*_bfd_error_handler)
5781                     (_("%s: undefined version: %s"),
5782                      d->pattern, t->name);
5783                   all_defined = FALSE;
5784                 }
5785
5786           if (!all_defined)
5787             {
5788               bfd_set_error (bfd_error_bad_value);
5789               return FALSE;
5790             }
5791         }
5792
5793       /* Find all symbols which were defined in a dynamic object and make
5794          the backend pick a reasonable value for them.  */
5795       elf_link_hash_traverse (elf_hash_table (info),
5796                               _bfd_elf_adjust_dynamic_symbol,
5797                               &eif);
5798       if (eif.failed)
5799         return FALSE;
5800
5801       /* Add some entries to the .dynamic section.  We fill in some of the
5802          values later, in bfd_elf_final_link, but we must add the entries
5803          now so that we know the final size of the .dynamic section.  */
5804
5805       /* If there are initialization and/or finalization functions to
5806          call then add the corresponding DT_INIT/DT_FINI entries.  */
5807       h = (info->init_function
5808            ? elf_link_hash_lookup (elf_hash_table (info),
5809                                    info->init_function, FALSE,
5810                                    FALSE, FALSE)
5811            : NULL);
5812       if (h != NULL
5813           && (h->ref_regular
5814               || h->def_regular))
5815         {
5816           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
5817             return FALSE;
5818         }
5819       h = (info->fini_function
5820            ? elf_link_hash_lookup (elf_hash_table (info),
5821                                    info->fini_function, FALSE,
5822                                    FALSE, FALSE)
5823            : NULL);
5824       if (h != NULL
5825           && (h->ref_regular
5826               || h->def_regular))
5827         {
5828           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
5829             return FALSE;
5830         }
5831
5832       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
5833       if (s != NULL && s->linker_has_input)
5834         {
5835           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
5836           if (! info->executable)
5837             {
5838               bfd *sub;
5839               asection *o;
5840
5841               for (sub = info->input_bfds; sub != NULL;
5842                    sub = sub->link_next)
5843                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour)
5844                   for (o = sub->sections; o != NULL; o = o->next)
5845                     if (elf_section_data (o)->this_hdr.sh_type
5846                         == SHT_PREINIT_ARRAY)
5847                       {
5848                         (*_bfd_error_handler)
5849                           (_("%B: .preinit_array section is not allowed in DSO"),
5850                            sub);
5851                         break;
5852                       }
5853
5854               bfd_set_error (bfd_error_nonrepresentable_section);
5855               return FALSE;
5856             }
5857
5858           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
5859               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
5860             return FALSE;
5861         }
5862       s = bfd_get_section_by_name (output_bfd, ".init_array");
5863       if (s != NULL && s->linker_has_input)
5864         {
5865           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
5866               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
5867             return FALSE;
5868         }
5869       s = bfd_get_section_by_name (output_bfd, ".fini_array");
5870       if (s != NULL && s->linker_has_input)
5871         {
5872           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
5873               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
5874             return FALSE;
5875         }
5876
5877       dynstr = bfd_get_section_by_name (dynobj, ".dynstr");
5878       /* If .dynstr is excluded from the link, we don't want any of
5879          these tags.  Strictly, we should be checking each section
5880          individually;  This quick check covers for the case where
5881          someone does a /DISCARD/ : { *(*) }.  */
5882       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
5883         {
5884           bfd_size_type strsize;
5885
5886           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
5887           if ((info->emit_hash
5888                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
5889               || (info->emit_gnu_hash
5890                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
5891               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
5892               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
5893               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
5894               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
5895                                               bed->s->sizeof_sym))
5896             return FALSE;
5897         }
5898     }
5899
5900   /* The backend must work out the sizes of all the other dynamic
5901      sections.  */
5902   if (bed->elf_backend_size_dynamic_sections
5903       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
5904     return FALSE;
5905
5906   if (elf_hash_table (info)->dynamic_sections_created)
5907     {
5908       unsigned long section_sym_count;
5909       struct bfd_elf_version_tree *verdefs;
5910       asection *s;
5911
5912       /* Set up the version definition section.  */
5913       s = bfd_get_section_by_name (dynobj, ".gnu.version_d");
5914       BFD_ASSERT (s != NULL);
5915
5916       /* We may have created additional version definitions if we are
5917          just linking a regular application.  */
5918       verdefs = info->version_info;
5919
5920       /* Skip anonymous version tag.  */
5921       if (verdefs != NULL && verdefs->vernum == 0)
5922         verdefs = verdefs->next;
5923
5924       if (verdefs == NULL && !info->create_default_symver)
5925         s->flags |= SEC_EXCLUDE;
5926       else
5927         {
5928           unsigned int cdefs;
5929           bfd_size_type size;
5930           struct bfd_elf_version_tree *t;
5931           bfd_byte *p;
5932           Elf_Internal_Verdef def;
5933           Elf_Internal_Verdaux defaux;
5934           struct bfd_link_hash_entry *bh;
5935           struct elf_link_hash_entry *h;
5936           const char *name;
5937
5938           cdefs = 0;
5939           size = 0;
5940
5941           /* Make space for the base version.  */
5942           size += sizeof (Elf_External_Verdef);
5943           size += sizeof (Elf_External_Verdaux);
5944           ++cdefs;
5945
5946           /* Make space for the default version.  */
5947           if (info->create_default_symver)
5948             {
5949               size += sizeof (Elf_External_Verdef);
5950               ++cdefs;
5951             }
5952
5953           for (t = verdefs; t != NULL; t = t->next)
5954             {
5955               struct bfd_elf_version_deps *n;
5956
5957               /* Don't emit base version twice.  */
5958               if (t->vernum == 0)
5959                 continue;
5960
5961               size += sizeof (Elf_External_Verdef);
5962               size += sizeof (Elf_External_Verdaux);
5963               ++cdefs;
5964
5965               for (n = t->deps; n != NULL; n = n->next)
5966                 size += sizeof (Elf_External_Verdaux);
5967             }
5968
5969           s->size = size;
5970           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
5971           if (s->contents == NULL && s->size != 0)
5972             return FALSE;
5973
5974           /* Fill in the version definition section.  */
5975
5976           p = s->contents;
5977
5978           def.vd_version = VER_DEF_CURRENT;
5979           def.vd_flags = VER_FLG_BASE;
5980           def.vd_ndx = 1;
5981           def.vd_cnt = 1;
5982           if (info->create_default_symver)
5983             {
5984               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
5985               def.vd_next = sizeof (Elf_External_Verdef);
5986             }
5987           else
5988             {
5989               def.vd_aux = sizeof (Elf_External_Verdef);
5990               def.vd_next = (sizeof (Elf_External_Verdef)
5991                              + sizeof (Elf_External_Verdaux));
5992             }
5993
5994           if (soname_indx != (bfd_size_type) -1)
5995             {
5996               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
5997                                       soname_indx);
5998               def.vd_hash = bfd_elf_hash (soname);
5999               defaux.vda_name = soname_indx;
6000               name = soname;
6001             }
6002           else
6003             {
6004               bfd_size_type indx;
6005
6006               name = lbasename (output_bfd->filename);
6007               def.vd_hash = bfd_elf_hash (name);
6008               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6009                                           name, FALSE);
6010               if (indx == (bfd_size_type) -1)
6011                 return FALSE;
6012               defaux.vda_name = indx;
6013             }
6014           defaux.vda_next = 0;
6015
6016           _bfd_elf_swap_verdef_out (output_bfd, &def,
6017                                     (Elf_External_Verdef *) p);
6018           p += sizeof (Elf_External_Verdef);
6019           if (info->create_default_symver)
6020             {
6021               /* Add a symbol representing this version.  */
6022               bh = NULL;
6023               if (! (_bfd_generic_link_add_one_symbol
6024                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6025                       0, NULL, FALSE,
6026                       get_elf_backend_data (dynobj)->collect, &bh)))
6027                 return FALSE;
6028               h = (struct elf_link_hash_entry *) bh;
6029               h->non_elf = 0;
6030               h->def_regular = 1;
6031               h->type = STT_OBJECT;
6032               h->verinfo.vertree = NULL;
6033
6034               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6035                 return FALSE;
6036
6037               /* Create a duplicate of the base version with the same
6038                  aux block, but different flags.  */
6039               def.vd_flags = 0;
6040               def.vd_ndx = 2;
6041               def.vd_aux = sizeof (Elf_External_Verdef);
6042               if (verdefs)
6043                 def.vd_next = (sizeof (Elf_External_Verdef)
6044                                + sizeof (Elf_External_Verdaux));
6045               else
6046                 def.vd_next = 0;
6047               _bfd_elf_swap_verdef_out (output_bfd, &def,
6048                                         (Elf_External_Verdef *) p);
6049               p += sizeof (Elf_External_Verdef);
6050             }
6051           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6052                                      (Elf_External_Verdaux *) p);
6053           p += sizeof (Elf_External_Verdaux);
6054
6055           for (t = verdefs; t != NULL; t = t->next)
6056             {
6057               unsigned int cdeps;
6058               struct bfd_elf_version_deps *n;
6059
6060               /* Don't emit the base version twice.  */
6061               if (t->vernum == 0)
6062                 continue;
6063
6064               cdeps = 0;
6065               for (n = t->deps; n != NULL; n = n->next)
6066                 ++cdeps;
6067
6068               /* Add a symbol representing this version.  */
6069               bh = NULL;
6070               if (! (_bfd_generic_link_add_one_symbol
6071                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6072                       0, NULL, FALSE,
6073                       get_elf_backend_data (dynobj)->collect, &bh)))
6074                 return FALSE;
6075               h = (struct elf_link_hash_entry *) bh;
6076               h->non_elf = 0;
6077               h->def_regular = 1;
6078               h->type = STT_OBJECT;
6079               h->verinfo.vertree = t;
6080
6081               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6082                 return FALSE;
6083
6084               def.vd_version = VER_DEF_CURRENT;
6085               def.vd_flags = 0;
6086               if (t->globals.list == NULL
6087                   && t->locals.list == NULL
6088                   && ! t->used)
6089                 def.vd_flags |= VER_FLG_WEAK;
6090               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6091               def.vd_cnt = cdeps + 1;
6092               def.vd_hash = bfd_elf_hash (t->name);
6093               def.vd_aux = sizeof (Elf_External_Verdef);
6094               def.vd_next = 0;
6095
6096               /* If a basever node is next, it *must* be the last node in
6097                  the chain, otherwise Verdef construction breaks.  */
6098               if (t->next != NULL && t->next->vernum == 0)
6099                 BFD_ASSERT (t->next->next == NULL);
6100
6101               if (t->next != NULL && t->next->vernum != 0)
6102                 def.vd_next = (sizeof (Elf_External_Verdef)
6103                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6104
6105               _bfd_elf_swap_verdef_out (output_bfd, &def,
6106                                         (Elf_External_Verdef *) p);
6107               p += sizeof (Elf_External_Verdef);
6108
6109               defaux.vda_name = h->dynstr_index;
6110               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6111                                       h->dynstr_index);
6112               defaux.vda_next = 0;
6113               if (t->deps != NULL)
6114                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6115               t->name_indx = defaux.vda_name;
6116
6117               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6118                                          (Elf_External_Verdaux *) p);
6119               p += sizeof (Elf_External_Verdaux);
6120
6121               for (n = t->deps; n != NULL; n = n->next)
6122                 {
6123                   if (n->version_needed == NULL)
6124                     {
6125                       /* This can happen if there was an error in the
6126                          version script.  */
6127                       defaux.vda_name = 0;
6128                     }
6129                   else
6130                     {
6131                       defaux.vda_name = n->version_needed->name_indx;
6132                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6133                                               defaux.vda_name);
6134                     }
6135                   if (n->next == NULL)
6136                     defaux.vda_next = 0;
6137                   else
6138                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6139
6140                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6141                                              (Elf_External_Verdaux *) p);
6142                   p += sizeof (Elf_External_Verdaux);
6143                 }
6144             }
6145
6146           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6147               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, cdefs))
6148             return FALSE;
6149
6150           elf_tdata (output_bfd)->cverdefs = cdefs;
6151         }
6152
6153       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6154         {
6155           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6156             return FALSE;
6157         }
6158       else if (info->flags & DF_BIND_NOW)
6159         {
6160           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6161             return FALSE;
6162         }
6163
6164       if (info->flags_1)
6165         {
6166           if (info->executable)
6167             info->flags_1 &= ~ (DF_1_INITFIRST
6168                                 | DF_1_NODELETE
6169                                 | DF_1_NOOPEN);
6170           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6171             return FALSE;
6172         }
6173
6174       /* Work out the size of the version reference section.  */
6175
6176       s = bfd_get_section_by_name (dynobj, ".gnu.version_r");
6177       BFD_ASSERT (s != NULL);
6178       {
6179         struct elf_find_verdep_info sinfo;
6180
6181         sinfo.info = info;
6182         sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6183         if (sinfo.vers == 0)
6184           sinfo.vers = 1;
6185         sinfo.failed = FALSE;
6186
6187         elf_link_hash_traverse (elf_hash_table (info),
6188                                 _bfd_elf_link_find_version_dependencies,
6189                                 &sinfo);
6190         if (sinfo.failed)
6191           return FALSE;
6192
6193         if (elf_tdata (output_bfd)->verref == NULL)
6194           s->flags |= SEC_EXCLUDE;
6195         else
6196           {
6197             Elf_Internal_Verneed *t;
6198             unsigned int size;
6199             unsigned int crefs;
6200             bfd_byte *p;
6201
6202             /* Build the version dependency section.  */
6203             size = 0;
6204             crefs = 0;
6205             for (t = elf_tdata (output_bfd)->verref;
6206                  t != NULL;
6207                  t = t->vn_nextref)
6208               {
6209                 Elf_Internal_Vernaux *a;
6210
6211                 size += sizeof (Elf_External_Verneed);
6212                 ++crefs;
6213                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6214                   size += sizeof (Elf_External_Vernaux);
6215               }
6216
6217             s->size = size;
6218             s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6219             if (s->contents == NULL)
6220               return FALSE;
6221
6222             p = s->contents;
6223             for (t = elf_tdata (output_bfd)->verref;
6224                  t != NULL;
6225                  t = t->vn_nextref)
6226               {
6227                 unsigned int caux;
6228                 Elf_Internal_Vernaux *a;
6229                 bfd_size_type indx;
6230
6231                 caux = 0;
6232                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6233                   ++caux;
6234
6235                 t->vn_version = VER_NEED_CURRENT;
6236                 t->vn_cnt = caux;
6237                 indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6238                                             elf_dt_name (t->vn_bfd) != NULL
6239                                             ? elf_dt_name (t->vn_bfd)
6240                                             : lbasename (t->vn_bfd->filename),
6241                                             FALSE);
6242                 if (indx == (bfd_size_type) -1)
6243                   return FALSE;
6244                 t->vn_file = indx;
6245                 t->vn_aux = sizeof (Elf_External_Verneed);
6246                 if (t->vn_nextref == NULL)
6247                   t->vn_next = 0;
6248                 else
6249                   t->vn_next = (sizeof (Elf_External_Verneed)
6250                                 + caux * sizeof (Elf_External_Vernaux));
6251
6252                 _bfd_elf_swap_verneed_out (output_bfd, t,
6253                                            (Elf_External_Verneed *) p);
6254                 p += sizeof (Elf_External_Verneed);
6255
6256                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6257                   {
6258                     a->vna_hash = bfd_elf_hash (a->vna_nodename);
6259                     indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6260                                                 a->vna_nodename, FALSE);
6261                     if (indx == (bfd_size_type) -1)
6262                       return FALSE;
6263                     a->vna_name = indx;
6264                     if (a->vna_nextptr == NULL)
6265                       a->vna_next = 0;
6266                     else
6267                       a->vna_next = sizeof (Elf_External_Vernaux);
6268
6269                     _bfd_elf_swap_vernaux_out (output_bfd, a,
6270                                                (Elf_External_Vernaux *) p);
6271                     p += sizeof (Elf_External_Vernaux);
6272                   }
6273               }
6274
6275             if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6276                 || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6277               return FALSE;
6278
6279             elf_tdata (output_bfd)->cverrefs = crefs;
6280           }
6281       }
6282
6283       if ((elf_tdata (output_bfd)->cverrefs == 0
6284            && elf_tdata (output_bfd)->cverdefs == 0)
6285           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6286                                              &section_sym_count) == 0)
6287         {
6288           s = bfd_get_section_by_name (dynobj, ".gnu.version");
6289           s->flags |= SEC_EXCLUDE;
6290         }
6291     }
6292   return TRUE;
6293 }
6294
6295 /* Find the first non-excluded output section.  We'll use its
6296    section symbol for some emitted relocs.  */
6297 void
6298 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6299 {
6300   asection *s;
6301
6302   for (s = output_bfd->sections; s != NULL; s = s->next)
6303     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6304         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6305       {
6306         elf_hash_table (info)->text_index_section = s;
6307         break;
6308       }
6309 }
6310
6311 /* Find two non-excluded output sections, one for code, one for data.
6312    We'll use their section symbols for some emitted relocs.  */
6313 void
6314 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6315 {
6316   asection *s;
6317
6318   /* Data first, since setting text_index_section changes
6319      _bfd_elf_link_omit_section_dynsym.  */
6320   for (s = output_bfd->sections; s != NULL; s = s->next)
6321     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6322         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6323       {
6324         elf_hash_table (info)->data_index_section = s;
6325         break;
6326       }
6327
6328   for (s = output_bfd->sections; s != NULL; s = s->next)
6329     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6330          == (SEC_ALLOC | SEC_READONLY))
6331         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6332       {
6333         elf_hash_table (info)->text_index_section = s;
6334         break;
6335       }
6336
6337   if (elf_hash_table (info)->text_index_section == NULL)
6338     elf_hash_table (info)->text_index_section
6339       = elf_hash_table (info)->data_index_section;
6340 }
6341
6342 bfd_boolean
6343 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6344 {
6345   const struct elf_backend_data *bed;
6346
6347   if (!is_elf_hash_table (info->hash))
6348     return TRUE;
6349
6350   bed = get_elf_backend_data (output_bfd);
6351   (*bed->elf_backend_init_index_section) (output_bfd, info);
6352
6353   if (elf_hash_table (info)->dynamic_sections_created)
6354     {
6355       bfd *dynobj;
6356       asection *s;
6357       bfd_size_type dynsymcount;
6358       unsigned long section_sym_count;
6359       unsigned int dtagcount;
6360
6361       dynobj = elf_hash_table (info)->dynobj;
6362
6363       /* Assign dynsym indicies.  In a shared library we generate a
6364          section symbol for each output section, which come first.
6365          Next come all of the back-end allocated local dynamic syms,
6366          followed by the rest of the global symbols.  */
6367
6368       dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6369                                                     &section_sym_count);
6370
6371       /* Work out the size of the symbol version section.  */
6372       s = bfd_get_section_by_name (dynobj, ".gnu.version");
6373       BFD_ASSERT (s != NULL);
6374       if (dynsymcount != 0
6375           && (s->flags & SEC_EXCLUDE) == 0)
6376         {
6377           s->size = dynsymcount * sizeof (Elf_External_Versym);
6378           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6379           if (s->contents == NULL)
6380             return FALSE;
6381
6382           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6383             return FALSE;
6384         }
6385
6386       /* Set the size of the .dynsym and .hash sections.  We counted
6387          the number of dynamic symbols in elf_link_add_object_symbols.
6388          We will build the contents of .dynsym and .hash when we build
6389          the final symbol table, because until then we do not know the
6390          correct value to give the symbols.  We built the .dynstr
6391          section as we went along in elf_link_add_object_symbols.  */
6392       s = bfd_get_section_by_name (dynobj, ".dynsym");
6393       BFD_ASSERT (s != NULL);
6394       s->size = dynsymcount * bed->s->sizeof_sym;
6395
6396       if (dynsymcount != 0)
6397         {
6398           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6399           if (s->contents == NULL)
6400             return FALSE;
6401
6402           /* The first entry in .dynsym is a dummy symbol.
6403              Clear all the section syms, in case we don't output them all.  */
6404           ++section_sym_count;
6405           memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6406         }
6407
6408       elf_hash_table (info)->bucketcount = 0;
6409
6410       /* Compute the size of the hashing table.  As a side effect this
6411          computes the hash values for all the names we export.  */
6412       if (info->emit_hash)
6413         {
6414           unsigned long int *hashcodes;
6415           struct hash_codes_info hashinf;
6416           bfd_size_type amt;
6417           unsigned long int nsyms;
6418           size_t bucketcount;
6419           size_t hash_entry_size;
6420
6421           /* Compute the hash values for all exported symbols.  At the same
6422              time store the values in an array so that we could use them for
6423              optimizations.  */
6424           amt = dynsymcount * sizeof (unsigned long int);
6425           hashcodes = (unsigned long int *) bfd_malloc (amt);
6426           if (hashcodes == NULL)
6427             return FALSE;
6428           hashinf.hashcodes = hashcodes;
6429           hashinf.error = FALSE;
6430
6431           /* Put all hash values in HASHCODES.  */
6432           elf_link_hash_traverse (elf_hash_table (info),
6433                                   elf_collect_hash_codes, &hashinf);
6434           if (hashinf.error)
6435             {
6436               free (hashcodes);
6437               return FALSE;
6438             }
6439
6440           nsyms = hashinf.hashcodes - hashcodes;
6441           bucketcount
6442             = compute_bucket_count (info, hashcodes, nsyms, 0);
6443           free (hashcodes);
6444
6445           if (bucketcount == 0)
6446             return FALSE;
6447
6448           elf_hash_table (info)->bucketcount = bucketcount;
6449
6450           s = bfd_get_section_by_name (dynobj, ".hash");
6451           BFD_ASSERT (s != NULL);
6452           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6453           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6454           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6455           if (s->contents == NULL)
6456             return FALSE;
6457
6458           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6459           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6460                    s->contents + hash_entry_size);
6461         }
6462
6463       if (info->emit_gnu_hash)
6464         {
6465           size_t i, cnt;
6466           unsigned char *contents;
6467           struct collect_gnu_hash_codes cinfo;
6468           bfd_size_type amt;
6469           size_t bucketcount;
6470
6471           memset (&cinfo, 0, sizeof (cinfo));
6472
6473           /* Compute the hash values for all exported symbols.  At the same
6474              time store the values in an array so that we could use them for
6475              optimizations.  */
6476           amt = dynsymcount * 2 * sizeof (unsigned long int);
6477           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
6478           if (cinfo.hashcodes == NULL)
6479             return FALSE;
6480
6481           cinfo.hashval = cinfo.hashcodes + dynsymcount;
6482           cinfo.min_dynindx = -1;
6483           cinfo.output_bfd = output_bfd;
6484           cinfo.bed = bed;
6485
6486           /* Put all hash values in HASHCODES.  */
6487           elf_link_hash_traverse (elf_hash_table (info),
6488                                   elf_collect_gnu_hash_codes, &cinfo);
6489           if (cinfo.error)
6490             {
6491               free (cinfo.hashcodes);
6492               return FALSE;
6493             }
6494
6495           bucketcount
6496             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
6497
6498           if (bucketcount == 0)
6499             {
6500               free (cinfo.hashcodes);
6501               return FALSE;
6502             }
6503
6504           s = bfd_get_section_by_name (dynobj, ".gnu.hash");
6505           BFD_ASSERT (s != NULL);
6506
6507           if (cinfo.nsyms == 0)
6508             {
6509               /* Empty .gnu.hash section is special.  */
6510               BFD_ASSERT (cinfo.min_dynindx == -1);
6511               free (cinfo.hashcodes);
6512               s->size = 5 * 4 + bed->s->arch_size / 8;
6513               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6514               if (contents == NULL)
6515                 return FALSE;
6516               s->contents = contents;
6517               /* 1 empty bucket.  */
6518               bfd_put_32 (output_bfd, 1, contents);
6519               /* SYMIDX above the special symbol 0.  */
6520               bfd_put_32 (output_bfd, 1, contents + 4);
6521               /* Just one word for bitmask.  */
6522               bfd_put_32 (output_bfd, 1, contents + 8);
6523               /* Only hash fn bloom filter.  */
6524               bfd_put_32 (output_bfd, 0, contents + 12);
6525               /* No hashes are valid - empty bitmask.  */
6526               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
6527               /* No hashes in the only bucket.  */
6528               bfd_put_32 (output_bfd, 0,
6529                           contents + 16 + bed->s->arch_size / 8);
6530             }
6531           else
6532             {
6533               unsigned long int maskwords, maskbitslog2, x;
6534               BFD_ASSERT (cinfo.min_dynindx != -1);
6535
6536               x = cinfo.nsyms;
6537               maskbitslog2 = 1;
6538               while ((x >>= 1) != 0)
6539                 ++maskbitslog2;
6540               if (maskbitslog2 < 3)
6541                 maskbitslog2 = 5;
6542               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
6543                 maskbitslog2 = maskbitslog2 + 3;
6544               else
6545                 maskbitslog2 = maskbitslog2 + 2;
6546               if (bed->s->arch_size == 64)
6547                 {
6548                   if (maskbitslog2 == 5)
6549                     maskbitslog2 = 6;
6550                   cinfo.shift1 = 6;
6551                 }
6552               else
6553                 cinfo.shift1 = 5;
6554               cinfo.mask = (1 << cinfo.shift1) - 1;
6555               cinfo.shift2 = maskbitslog2;
6556               cinfo.maskbits = 1 << maskbitslog2;
6557               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
6558               amt = bucketcount * sizeof (unsigned long int) * 2;
6559               amt += maskwords * sizeof (bfd_vma);
6560               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
6561               if (cinfo.bitmask == NULL)
6562                 {
6563                   free (cinfo.hashcodes);
6564                   return FALSE;
6565                 }
6566
6567               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
6568               cinfo.indx = cinfo.counts + bucketcount;
6569               cinfo.symindx = dynsymcount - cinfo.nsyms;
6570               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
6571
6572               /* Determine how often each hash bucket is used.  */
6573               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
6574               for (i = 0; i < cinfo.nsyms; ++i)
6575                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
6576
6577               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
6578                 if (cinfo.counts[i] != 0)
6579                   {
6580                     cinfo.indx[i] = cnt;
6581                     cnt += cinfo.counts[i];
6582                   }
6583               BFD_ASSERT (cnt == dynsymcount);
6584               cinfo.bucketcount = bucketcount;
6585               cinfo.local_indx = cinfo.min_dynindx;
6586
6587               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
6588               s->size += cinfo.maskbits / 8;
6589               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6590               if (contents == NULL)
6591                 {
6592                   free (cinfo.bitmask);
6593                   free (cinfo.hashcodes);
6594                   return FALSE;
6595                 }
6596
6597               s->contents = contents;
6598               bfd_put_32 (output_bfd, bucketcount, contents);
6599               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
6600               bfd_put_32 (output_bfd, maskwords, contents + 8);
6601               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
6602               contents += 16 + cinfo.maskbits / 8;
6603
6604               for (i = 0; i < bucketcount; ++i)
6605                 {
6606                   if (cinfo.counts[i] == 0)
6607                     bfd_put_32 (output_bfd, 0, contents);
6608                   else
6609                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
6610                   contents += 4;
6611                 }
6612
6613               cinfo.contents = contents;
6614
6615               /* Renumber dynamic symbols, populate .gnu.hash section.  */
6616               elf_link_hash_traverse (elf_hash_table (info),
6617                                       elf_renumber_gnu_hash_syms, &cinfo);
6618
6619               contents = s->contents + 16;
6620               for (i = 0; i < maskwords; ++i)
6621                 {
6622                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
6623                            contents);
6624                   contents += bed->s->arch_size / 8;
6625                 }
6626
6627               free (cinfo.bitmask);
6628               free (cinfo.hashcodes);
6629             }
6630         }
6631
6632       s = bfd_get_section_by_name (dynobj, ".dynstr");
6633       BFD_ASSERT (s != NULL);
6634
6635       elf_finalize_dynstr (output_bfd, info);
6636
6637       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6638
6639       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
6640         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
6641           return FALSE;
6642     }
6643
6644   return TRUE;
6645 }
6646 \f
6647 /* Indicate that we are only retrieving symbol values from this
6648    section.  */
6649
6650 void
6651 _bfd_elf_link_just_syms (asection *sec, struct bfd_link_info *info)
6652 {
6653   if (is_elf_hash_table (info->hash))
6654     sec->sec_info_type = ELF_INFO_TYPE_JUST_SYMS;
6655   _bfd_generic_link_just_syms (sec, info);
6656 }
6657
6658 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
6659
6660 static void
6661 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
6662                             asection *sec)
6663 {
6664   BFD_ASSERT (sec->sec_info_type == ELF_INFO_TYPE_MERGE);
6665   sec->sec_info_type = ELF_INFO_TYPE_NONE;
6666 }
6667
6668 /* Finish SHF_MERGE section merging.  */
6669
6670 bfd_boolean
6671 _bfd_elf_merge_sections (bfd *abfd, struct bfd_link_info *info)
6672 {
6673   bfd *ibfd;
6674   asection *sec;
6675
6676   if (!is_elf_hash_table (info->hash))
6677     return FALSE;
6678
6679   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link_next)
6680     if ((ibfd->flags & DYNAMIC) == 0)
6681       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
6682         if ((sec->flags & SEC_MERGE) != 0
6683             && !bfd_is_abs_section (sec->output_section))
6684           {
6685             struct bfd_elf_section_data *secdata;
6686
6687             secdata = elf_section_data (sec);
6688             if (! _bfd_add_merge_section (abfd,
6689                                           &elf_hash_table (info)->merge_info,
6690                                           sec, &secdata->sec_info))
6691               return FALSE;
6692             else if (secdata->sec_info)
6693               sec->sec_info_type = ELF_INFO_TYPE_MERGE;
6694           }
6695
6696   if (elf_hash_table (info)->merge_info != NULL)
6697     _bfd_merge_sections (abfd, info, elf_hash_table (info)->merge_info,
6698                          merge_sections_remove_hook);
6699   return TRUE;
6700 }
6701
6702 /* Create an entry in an ELF linker hash table.  */
6703
6704 struct bfd_hash_entry *
6705 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
6706                             struct bfd_hash_table *table,
6707                             const char *string)
6708 {
6709   /* Allocate the structure if it has not already been allocated by a
6710      subclass.  */
6711   if (entry == NULL)
6712     {
6713       entry = (struct bfd_hash_entry *)
6714           bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
6715       if (entry == NULL)
6716         return entry;
6717     }
6718
6719   /* Call the allocation method of the superclass.  */
6720   entry = _bfd_link_hash_newfunc (entry, table, string);
6721   if (entry != NULL)
6722     {
6723       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
6724       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
6725
6726       /* Set local fields.  */
6727       ret->indx = -1;
6728       ret->dynindx = -1;
6729       ret->got = htab->init_got_refcount;
6730       ret->plt = htab->init_plt_refcount;
6731       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
6732                               - offsetof (struct elf_link_hash_entry, size)));
6733       /* Assume that we have been called by a non-ELF symbol reader.
6734          This flag is then reset by the code which reads an ELF input
6735          file.  This ensures that a symbol created by a non-ELF symbol
6736          reader will have the flag set correctly.  */
6737       ret->non_elf = 1;
6738     }
6739
6740   return entry;
6741 }
6742
6743 /* Copy data from an indirect symbol to its direct symbol, hiding the
6744    old indirect symbol.  Also used for copying flags to a weakdef.  */
6745
6746 void
6747 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
6748                                   struct elf_link_hash_entry *dir,
6749                                   struct elf_link_hash_entry *ind)
6750 {
6751   struct elf_link_hash_table *htab;
6752
6753   /* Copy down any references that we may have already seen to the
6754      symbol which just became indirect.  */
6755
6756   dir->ref_dynamic |= ind->ref_dynamic;
6757   dir->ref_regular |= ind->ref_regular;
6758   dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
6759   dir->non_got_ref |= ind->non_got_ref;
6760   dir->needs_plt |= ind->needs_plt;
6761   dir->pointer_equality_needed |= ind->pointer_equality_needed;
6762
6763   if (ind->root.type != bfd_link_hash_indirect)
6764     return;
6765
6766   /* Copy over the global and procedure linkage table refcount entries.
6767      These may have been already set up by a check_relocs routine.  */
6768   htab = elf_hash_table (info);
6769   if (ind->got.refcount > htab->init_got_refcount.refcount)
6770     {
6771       if (dir->got.refcount < 0)
6772         dir->got.refcount = 0;
6773       dir->got.refcount += ind->got.refcount;
6774       ind->got.refcount = htab->init_got_refcount.refcount;
6775     }
6776
6777   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
6778     {
6779       if (dir->plt.refcount < 0)
6780         dir->plt.refcount = 0;
6781       dir->plt.refcount += ind->plt.refcount;
6782       ind->plt.refcount = htab->init_plt_refcount.refcount;
6783     }
6784
6785   if (ind->dynindx != -1)
6786     {
6787       if (dir->dynindx != -1)
6788         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
6789       dir->dynindx = ind->dynindx;
6790       dir->dynstr_index = ind->dynstr_index;
6791       ind->dynindx = -1;
6792       ind->dynstr_index = 0;
6793     }
6794 }
6795
6796 void
6797 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
6798                                 struct elf_link_hash_entry *h,
6799                                 bfd_boolean force_local)
6800 {
6801   /* STT_GNU_IFUNC symbol must go through PLT.  */
6802   if (h->type != STT_GNU_IFUNC)
6803     {
6804       h->plt = elf_hash_table (info)->init_plt_offset;
6805       h->needs_plt = 0;
6806     }
6807   if (force_local)
6808     {
6809       h->forced_local = 1;
6810       if (h->dynindx != -1)
6811         {
6812           h->dynindx = -1;
6813           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
6814                                   h->dynstr_index);
6815         }
6816     }
6817 }
6818
6819 /* Initialize an ELF linker hash table.  */
6820
6821 bfd_boolean
6822 _bfd_elf_link_hash_table_init
6823   (struct elf_link_hash_table *table,
6824    bfd *abfd,
6825    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
6826                                       struct bfd_hash_table *,
6827                                       const char *),
6828    unsigned int entsize,
6829    enum elf_target_id target_id)
6830 {
6831   bfd_boolean ret;
6832   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
6833
6834   memset (table, 0, sizeof * table);
6835   table->init_got_refcount.refcount = can_refcount - 1;
6836   table->init_plt_refcount.refcount = can_refcount - 1;
6837   table->init_got_offset.offset = -(bfd_vma) 1;
6838   table->init_plt_offset.offset = -(bfd_vma) 1;
6839   /* The first dynamic symbol is a dummy.  */
6840   table->dynsymcount = 1;
6841
6842   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
6843
6844   table->root.type = bfd_link_elf_hash_table;
6845   table->hash_table_id = target_id;
6846
6847   return ret;
6848 }
6849
6850 /* Create an ELF linker hash table.  */
6851
6852 struct bfd_link_hash_table *
6853 _bfd_elf_link_hash_table_create (bfd *abfd)
6854 {
6855   struct elf_link_hash_table *ret;
6856   bfd_size_type amt = sizeof (struct elf_link_hash_table);
6857
6858   ret = (struct elf_link_hash_table *) bfd_malloc (amt);
6859   if (ret == NULL)
6860     return NULL;
6861
6862   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
6863                                        sizeof (struct elf_link_hash_entry),
6864                                        GENERIC_ELF_DATA))
6865     {
6866       free (ret);
6867       return NULL;
6868     }
6869
6870   return &ret->root;
6871 }
6872
6873 /* This is a hook for the ELF emulation code in the generic linker to
6874    tell the backend linker what file name to use for the DT_NEEDED
6875    entry for a dynamic object.  */
6876
6877 void
6878 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
6879 {
6880   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
6881       && bfd_get_format (abfd) == bfd_object)
6882     elf_dt_name (abfd) = name;
6883 }
6884
6885 int
6886 bfd_elf_get_dyn_lib_class (bfd *abfd)
6887 {
6888   int lib_class;
6889   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
6890       && bfd_get_format (abfd) == bfd_object)
6891     lib_class = elf_dyn_lib_class (abfd);
6892   else
6893     lib_class = 0;
6894   return lib_class;
6895 }
6896
6897 void
6898 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
6899 {
6900   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
6901       && bfd_get_format (abfd) == bfd_object)
6902     elf_dyn_lib_class (abfd) = lib_class;
6903 }
6904
6905 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
6906    the linker ELF emulation code.  */
6907
6908 struct bfd_link_needed_list *
6909 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
6910                          struct bfd_link_info *info)
6911 {
6912   if (! is_elf_hash_table (info->hash))
6913     return NULL;
6914   return elf_hash_table (info)->needed;
6915 }
6916
6917 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
6918    hook for the linker ELF emulation code.  */
6919
6920 struct bfd_link_needed_list *
6921 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
6922                           struct bfd_link_info *info)
6923 {
6924   if (! is_elf_hash_table (info->hash))
6925     return NULL;
6926   return elf_hash_table (info)->runpath;
6927 }
6928
6929 /* Get the name actually used for a dynamic object for a link.  This
6930    is the SONAME entry if there is one.  Otherwise, it is the string
6931    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
6932
6933 const char *
6934 bfd_elf_get_dt_soname (bfd *abfd)
6935 {
6936   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
6937       && bfd_get_format (abfd) == bfd_object)
6938     return elf_dt_name (abfd);
6939   return NULL;
6940 }
6941
6942 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
6943    the ELF linker emulation code.  */
6944
6945 bfd_boolean
6946 bfd_elf_get_bfd_needed_list (bfd *abfd,
6947                              struct bfd_link_needed_list **pneeded)
6948 {
6949   asection *s;
6950   bfd_byte *dynbuf = NULL;
6951   unsigned int elfsec;
6952   unsigned long shlink;
6953   bfd_byte *extdyn, *extdynend;
6954   size_t extdynsize;
6955   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
6956
6957   *pneeded = NULL;
6958
6959   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
6960       || bfd_get_format (abfd) != bfd_object)
6961     return TRUE;
6962
6963   s = bfd_get_section_by_name (abfd, ".dynamic");
6964   if (s == NULL || s->size == 0)
6965     return TRUE;
6966
6967   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
6968     goto error_return;
6969
6970   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
6971   if (elfsec == SHN_BAD)
6972     goto error_return;
6973
6974   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
6975
6976   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
6977   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
6978
6979   extdyn = dynbuf;
6980   extdynend = extdyn + s->size;
6981   for (; extdyn < extdynend; extdyn += extdynsize)
6982     {
6983       Elf_Internal_Dyn dyn;
6984
6985       (*swap_dyn_in) (abfd, extdyn, &dyn);
6986
6987       if (dyn.d_tag == DT_NULL)
6988         break;
6989
6990       if (dyn.d_tag == DT_NEEDED)
6991         {
6992           const char *string;
6993           struct bfd_link_needed_list *l;
6994           unsigned int tagv = dyn.d_un.d_val;
6995           bfd_size_type amt;
6996
6997           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
6998           if (string == NULL)
6999             goto error_return;
7000
7001           amt = sizeof *l;
7002           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7003           if (l == NULL)
7004             goto error_return;
7005
7006           l->by = abfd;
7007           l->name = string;
7008           l->next = *pneeded;
7009           *pneeded = l;
7010         }
7011     }
7012
7013   free (dynbuf);
7014
7015   return TRUE;
7016
7017  error_return:
7018   if (dynbuf != NULL)
7019     free (dynbuf);
7020   return FALSE;
7021 }
7022
7023 struct elf_symbuf_symbol
7024 {
7025   unsigned long st_name;        /* Symbol name, index in string tbl */
7026   unsigned char st_info;        /* Type and binding attributes */
7027   unsigned char st_other;       /* Visibilty, and target specific */
7028 };
7029
7030 struct elf_symbuf_head
7031 {
7032   struct elf_symbuf_symbol *ssym;
7033   bfd_size_type count;
7034   unsigned int st_shndx;
7035 };
7036
7037 struct elf_symbol
7038 {
7039   union
7040     {
7041       Elf_Internal_Sym *isym;
7042       struct elf_symbuf_symbol *ssym;
7043     } u;
7044   const char *name;
7045 };
7046
7047 /* Sort references to symbols by ascending section number.  */
7048
7049 static int
7050 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7051 {
7052   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7053   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7054
7055   return s1->st_shndx - s2->st_shndx;
7056 }
7057
7058 static int
7059 elf_sym_name_compare (const void *arg1, const void *arg2)
7060 {
7061   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7062   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7063   return strcmp (s1->name, s2->name);
7064 }
7065
7066 static struct elf_symbuf_head *
7067 elf_create_symbuf (bfd_size_type symcount, Elf_Internal_Sym *isymbuf)
7068 {
7069   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7070   struct elf_symbuf_symbol *ssym;
7071   struct elf_symbuf_head *ssymbuf, *ssymhead;
7072   bfd_size_type i, shndx_count, total_size;
7073
7074   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7075   if (indbuf == NULL)
7076     return NULL;
7077
7078   for (ind = indbuf, i = 0; i < symcount; i++)
7079     if (isymbuf[i].st_shndx != SHN_UNDEF)
7080       *ind++ = &isymbuf[i];
7081   indbufend = ind;
7082
7083   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7084          elf_sort_elf_symbol);
7085
7086   shndx_count = 0;
7087   if (indbufend > indbuf)
7088     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7089       if (ind[0]->st_shndx != ind[1]->st_shndx)
7090         shndx_count++;
7091
7092   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7093                 + (indbufend - indbuf) * sizeof (*ssym));
7094   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7095   if (ssymbuf == NULL)
7096     {
7097       free (indbuf);
7098       return NULL;
7099     }
7100
7101   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7102   ssymbuf->ssym = NULL;
7103   ssymbuf->count = shndx_count;
7104   ssymbuf->st_shndx = 0;
7105   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7106     {
7107       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7108         {
7109           ssymhead++;
7110           ssymhead->ssym = ssym;
7111           ssymhead->count = 0;
7112           ssymhead->st_shndx = (*ind)->st_shndx;
7113         }
7114       ssym->st_name = (*ind)->st_name;
7115       ssym->st_info = (*ind)->st_info;
7116       ssym->st_other = (*ind)->st_other;
7117       ssymhead->count++;
7118     }
7119   BFD_ASSERT ((bfd_size_type) (ssymhead - ssymbuf) == shndx_count
7120               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7121                   == total_size));
7122
7123   free (indbuf);
7124   return ssymbuf;
7125 }
7126
7127 /* Check if 2 sections define the same set of local and global
7128    symbols.  */
7129
7130 static bfd_boolean
7131 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7132                                    struct bfd_link_info *info)
7133 {
7134   bfd *bfd1, *bfd2;
7135   const struct elf_backend_data *bed1, *bed2;
7136   Elf_Internal_Shdr *hdr1, *hdr2;
7137   bfd_size_type symcount1, symcount2;
7138   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7139   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7140   Elf_Internal_Sym *isym, *isymend;
7141   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7142   bfd_size_type count1, count2, i;
7143   unsigned int shndx1, shndx2;
7144   bfd_boolean result;
7145
7146   bfd1 = sec1->owner;
7147   bfd2 = sec2->owner;
7148
7149   /* Both sections have to be in ELF.  */
7150   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7151       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7152     return FALSE;
7153
7154   if (elf_section_type (sec1) != elf_section_type (sec2))
7155     return FALSE;
7156
7157   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7158   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7159   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7160     return FALSE;
7161
7162   bed1 = get_elf_backend_data (bfd1);
7163   bed2 = get_elf_backend_data (bfd2);
7164   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7165   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7166   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7167   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7168
7169   if (symcount1 == 0 || symcount2 == 0)
7170     return FALSE;
7171
7172   result = FALSE;
7173   isymbuf1 = NULL;
7174   isymbuf2 = NULL;
7175   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7176   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7177
7178   if (ssymbuf1 == NULL)
7179     {
7180       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7181                                        NULL, NULL, NULL);
7182       if (isymbuf1 == NULL)
7183         goto done;
7184
7185       if (!info->reduce_memory_overheads)
7186         elf_tdata (bfd1)->symbuf = ssymbuf1
7187           = elf_create_symbuf (symcount1, isymbuf1);
7188     }
7189
7190   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7191     {
7192       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7193                                        NULL, NULL, NULL);
7194       if (isymbuf2 == NULL)
7195         goto done;
7196
7197       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7198         elf_tdata (bfd2)->symbuf = ssymbuf2
7199           = elf_create_symbuf (symcount2, isymbuf2);
7200     }
7201
7202   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7203     {
7204       /* Optimized faster version.  */
7205       bfd_size_type lo, hi, mid;
7206       struct elf_symbol *symp;
7207       struct elf_symbuf_symbol *ssym, *ssymend;
7208
7209       lo = 0;
7210       hi = ssymbuf1->count;
7211       ssymbuf1++;
7212       count1 = 0;
7213       while (lo < hi)
7214         {
7215           mid = (lo + hi) / 2;
7216           if (shndx1 < ssymbuf1[mid].st_shndx)
7217             hi = mid;
7218           else if (shndx1 > ssymbuf1[mid].st_shndx)
7219             lo = mid + 1;
7220           else
7221             {
7222               count1 = ssymbuf1[mid].count;
7223               ssymbuf1 += mid;
7224               break;
7225             }
7226         }
7227
7228       lo = 0;
7229       hi = ssymbuf2->count;
7230       ssymbuf2++;
7231       count2 = 0;
7232       while (lo < hi)
7233         {
7234           mid = (lo + hi) / 2;
7235           if (shndx2 < ssymbuf2[mid].st_shndx)
7236             hi = mid;
7237           else if (shndx2 > ssymbuf2[mid].st_shndx)
7238             lo = mid + 1;
7239           else
7240             {
7241               count2 = ssymbuf2[mid].count;
7242               ssymbuf2 += mid;
7243               break;
7244             }
7245         }
7246
7247       if (count1 == 0 || count2 == 0 || count1 != count2)
7248         goto done;
7249
7250       symtable1 = (struct elf_symbol *)
7251           bfd_malloc (count1 * sizeof (struct elf_symbol));
7252       symtable2 = (struct elf_symbol *)
7253           bfd_malloc (count2 * sizeof (struct elf_symbol));
7254       if (symtable1 == NULL || symtable2 == NULL)
7255         goto done;
7256
7257       symp = symtable1;
7258       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7259            ssym < ssymend; ssym++, symp++)
7260         {
7261           symp->u.ssym = ssym;
7262           symp->name = bfd_elf_string_from_elf_section (bfd1,
7263                                                         hdr1->sh_link,
7264                                                         ssym->st_name);
7265         }
7266
7267       symp = symtable2;
7268       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7269            ssym < ssymend; ssym++, symp++)
7270         {
7271           symp->u.ssym = ssym;
7272           symp->name = bfd_elf_string_from_elf_section (bfd2,
7273                                                         hdr2->sh_link,
7274                                                         ssym->st_name);
7275         }
7276
7277       /* Sort symbol by name.  */
7278       qsort (symtable1, count1, sizeof (struct elf_symbol),
7279              elf_sym_name_compare);
7280       qsort (symtable2, count1, sizeof (struct elf_symbol),
7281              elf_sym_name_compare);
7282
7283       for (i = 0; i < count1; i++)
7284         /* Two symbols must have the same binding, type and name.  */
7285         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7286             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7287             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7288           goto done;
7289
7290       result = TRUE;
7291       goto done;
7292     }
7293
7294   symtable1 = (struct elf_symbol *)
7295       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7296   symtable2 = (struct elf_symbol *)
7297       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7298   if (symtable1 == NULL || symtable2 == NULL)
7299     goto done;
7300
7301   /* Count definitions in the section.  */
7302   count1 = 0;
7303   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7304     if (isym->st_shndx == shndx1)
7305       symtable1[count1++].u.isym = isym;
7306
7307   count2 = 0;
7308   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7309     if (isym->st_shndx == shndx2)
7310       symtable2[count2++].u.isym = isym;
7311
7312   if (count1 == 0 || count2 == 0 || count1 != count2)
7313     goto done;
7314
7315   for (i = 0; i < count1; i++)
7316     symtable1[i].name
7317       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7318                                          symtable1[i].u.isym->st_name);
7319
7320   for (i = 0; i < count2; i++)
7321     symtable2[i].name
7322       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7323                                          symtable2[i].u.isym->st_name);
7324
7325   /* Sort symbol by name.  */
7326   qsort (symtable1, count1, sizeof (struct elf_symbol),
7327          elf_sym_name_compare);
7328   qsort (symtable2, count1, sizeof (struct elf_symbol),
7329          elf_sym_name_compare);
7330
7331   for (i = 0; i < count1; i++)
7332     /* Two symbols must have the same binding, type and name.  */
7333     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7334         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7335         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7336       goto done;
7337
7338   result = TRUE;
7339
7340 done:
7341   if (symtable1)
7342     free (symtable1);
7343   if (symtable2)
7344     free (symtable2);
7345   if (isymbuf1)
7346     free (isymbuf1);
7347   if (isymbuf2)
7348     free (isymbuf2);
7349
7350   return result;
7351 }
7352
7353 /* Return TRUE if 2 section types are compatible.  */
7354
7355 bfd_boolean
7356 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7357                                  bfd *bbfd, const asection *bsec)
7358 {
7359   if (asec == NULL
7360       || bsec == NULL
7361       || abfd->xvec->flavour != bfd_target_elf_flavour
7362       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7363     return TRUE;
7364
7365   return elf_section_type (asec) == elf_section_type (bsec);
7366 }
7367 \f
7368 /* Final phase of ELF linker.  */
7369
7370 /* A structure we use to avoid passing large numbers of arguments.  */
7371
7372 struct elf_final_link_info
7373 {
7374   /* General link information.  */
7375   struct bfd_link_info *info;
7376   /* Output BFD.  */
7377   bfd *output_bfd;
7378   /* Symbol string table.  */
7379   struct bfd_strtab_hash *symstrtab;
7380   /* .dynsym section.  */
7381   asection *dynsym_sec;
7382   /* .hash section.  */
7383   asection *hash_sec;
7384   /* symbol version section (.gnu.version).  */
7385   asection *symver_sec;
7386   /* Buffer large enough to hold contents of any section.  */
7387   bfd_byte *contents;
7388   /* Buffer large enough to hold external relocs of any section.  */
7389   void *external_relocs;
7390   /* Buffer large enough to hold internal relocs of any section.  */
7391   Elf_Internal_Rela *internal_relocs;
7392   /* Buffer large enough to hold external local symbols of any input
7393      BFD.  */
7394   bfd_byte *external_syms;
7395   /* And a buffer for symbol section indices.  */
7396   Elf_External_Sym_Shndx *locsym_shndx;
7397   /* Buffer large enough to hold internal local symbols of any input
7398      BFD.  */
7399   Elf_Internal_Sym *internal_syms;
7400   /* Array large enough to hold a symbol index for each local symbol
7401      of any input BFD.  */
7402   long *indices;
7403   /* Array large enough to hold a section pointer for each local
7404      symbol of any input BFD.  */
7405   asection **sections;
7406   /* Buffer to hold swapped out symbols.  */
7407   bfd_byte *symbuf;
7408   /* And one for symbol section indices.  */
7409   Elf_External_Sym_Shndx *symshndxbuf;
7410   /* Number of swapped out symbols in buffer.  */
7411   size_t symbuf_count;
7412   /* Number of symbols which fit in symbuf.  */
7413   size_t symbuf_size;
7414   /* And same for symshndxbuf.  */
7415   size_t shndxbuf_size;
7416 };
7417
7418 /* This struct is used to pass information to elf_link_output_extsym.  */
7419
7420 struct elf_outext_info
7421 {
7422   bfd_boolean failed;
7423   bfd_boolean localsyms;
7424   struct elf_final_link_info *finfo;
7425 };
7426
7427
7428 /* Support for evaluating a complex relocation.
7429
7430    Complex relocations are generalized, self-describing relocations.  The
7431    implementation of them consists of two parts: complex symbols, and the
7432    relocations themselves.
7433
7434    The relocations are use a reserved elf-wide relocation type code (R_RELC
7435    external / BFD_RELOC_RELC internal) and an encoding of relocation field
7436    information (start bit, end bit, word width, etc) into the addend.  This
7437    information is extracted from CGEN-generated operand tables within gas.
7438
7439    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
7440    internal) representing prefix-notation expressions, including but not
7441    limited to those sorts of expressions normally encoded as addends in the
7442    addend field.  The symbol mangling format is:
7443
7444    <node> := <literal>
7445           |  <unary-operator> ':' <node>
7446           |  <binary-operator> ':' <node> ':' <node>
7447           ;
7448
7449    <literal> := 's' <digits=N> ':' <N character symbol name>
7450              |  'S' <digits=N> ':' <N character section name>
7451              |  '#' <hexdigits>
7452              ;
7453
7454    <binary-operator> := as in C
7455    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
7456
7457 static void
7458 set_symbol_value (bfd *bfd_with_globals,
7459                   Elf_Internal_Sym *isymbuf,
7460                   size_t locsymcount,
7461                   size_t symidx,
7462                   bfd_vma val)
7463 {
7464   struct elf_link_hash_entry **sym_hashes;
7465   struct elf_link_hash_entry *h;
7466   size_t extsymoff = locsymcount;
7467
7468   if (symidx < locsymcount)
7469     {
7470       Elf_Internal_Sym *sym;
7471
7472       sym = isymbuf + symidx;
7473       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
7474         {
7475           /* It is a local symbol: move it to the
7476              "absolute" section and give it a value.  */
7477           sym->st_shndx = SHN_ABS;
7478           sym->st_value = val;
7479           return;
7480         }
7481       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
7482       extsymoff = 0;
7483     }
7484
7485   /* It is a global symbol: set its link type
7486      to "defined" and give it a value.  */
7487
7488   sym_hashes = elf_sym_hashes (bfd_with_globals);
7489   h = sym_hashes [symidx - extsymoff];
7490   while (h->root.type == bfd_link_hash_indirect
7491          || h->root.type == bfd_link_hash_warning)
7492     h = (struct elf_link_hash_entry *) h->root.u.i.link;
7493   h->root.type = bfd_link_hash_defined;
7494   h->root.u.def.value = val;
7495   h->root.u.def.section = bfd_abs_section_ptr;
7496 }
7497
7498 static bfd_boolean
7499 resolve_symbol (const char *name,
7500                 bfd *input_bfd,
7501                 struct elf_final_link_info *finfo,
7502                 bfd_vma *result,
7503                 Elf_Internal_Sym *isymbuf,
7504                 size_t locsymcount)
7505 {
7506   Elf_Internal_Sym *sym;
7507   struct bfd_link_hash_entry *global_entry;
7508   const char *candidate = NULL;
7509   Elf_Internal_Shdr *symtab_hdr;
7510   size_t i;
7511
7512   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
7513
7514   for (i = 0; i < locsymcount; ++ i)
7515     {
7516       sym = isymbuf + i;
7517
7518       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
7519         continue;
7520
7521       candidate = bfd_elf_string_from_elf_section (input_bfd,
7522                                                    symtab_hdr->sh_link,
7523                                                    sym->st_name);
7524 #ifdef DEBUG
7525       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
7526               name, candidate, (unsigned long) sym->st_value);
7527 #endif
7528       if (candidate && strcmp (candidate, name) == 0)
7529         {
7530           asection *sec = finfo->sections [i];
7531
7532           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
7533           *result += sec->output_offset + sec->output_section->vma;
7534 #ifdef DEBUG
7535           printf ("Found symbol with value %8.8lx\n",
7536                   (unsigned long) *result);
7537 #endif
7538           return TRUE;
7539         }
7540     }
7541
7542   /* Hmm, haven't found it yet. perhaps it is a global.  */
7543   global_entry = bfd_link_hash_lookup (finfo->info->hash, name,
7544                                        FALSE, FALSE, TRUE);
7545   if (!global_entry)
7546     return FALSE;
7547
7548   if (global_entry->type == bfd_link_hash_defined
7549       || global_entry->type == bfd_link_hash_defweak)
7550     {
7551       *result = (global_entry->u.def.value
7552                  + global_entry->u.def.section->output_section->vma
7553                  + global_entry->u.def.section->output_offset);
7554 #ifdef DEBUG
7555       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
7556               global_entry->root.string, (unsigned long) *result);
7557 #endif
7558       return TRUE;
7559     }
7560
7561   return FALSE;
7562 }
7563
7564 static bfd_boolean
7565 resolve_section (const char *name,
7566                  asection *sections,
7567                  bfd_vma *result)
7568 {
7569   asection *curr;
7570   unsigned int len;
7571
7572   for (curr = sections; curr; curr = curr->next)
7573     if (strcmp (curr->name, name) == 0)
7574       {
7575         *result = curr->vma;
7576         return TRUE;
7577       }
7578
7579   /* Hmm. still haven't found it. try pseudo-section names.  */
7580   for (curr = sections; curr; curr = curr->next)
7581     {
7582       len = strlen (curr->name);
7583       if (len > strlen (name))
7584         continue;
7585
7586       if (strncmp (curr->name, name, len) == 0)
7587         {
7588           if (strncmp (".end", name + len, 4) == 0)
7589             {
7590               *result = curr->vma + curr->size;
7591               return TRUE;
7592             }
7593
7594           /* Insert more pseudo-section names here, if you like.  */
7595         }
7596     }
7597
7598   return FALSE;
7599 }
7600
7601 static void
7602 undefined_reference (const char *reftype, const char *name)
7603 {
7604   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
7605                       reftype, name);
7606 }
7607
7608 static bfd_boolean
7609 eval_symbol (bfd_vma *result,
7610              const char **symp,
7611              bfd *input_bfd,
7612              struct elf_final_link_info *finfo,
7613              bfd_vma dot,
7614              Elf_Internal_Sym *isymbuf,
7615              size_t locsymcount,
7616              int signed_p)
7617 {
7618   size_t len;
7619   size_t symlen;
7620   bfd_vma a;
7621   bfd_vma b;
7622   char symbuf[4096];
7623   const char *sym = *symp;
7624   const char *symend;
7625   bfd_boolean symbol_is_section = FALSE;
7626
7627   len = strlen (sym);
7628   symend = sym + len;
7629
7630   if (len < 1 || len > sizeof (symbuf))
7631     {
7632       bfd_set_error (bfd_error_invalid_operation);
7633       return FALSE;
7634     }
7635
7636   switch (* sym)
7637     {
7638     case '.':
7639       *result = dot;
7640       *symp = sym + 1;
7641       return TRUE;
7642
7643     case '#':
7644       ++sym;
7645       *result = strtoul (sym, (char **) symp, 16);
7646       return TRUE;
7647
7648     case 'S':
7649       symbol_is_section = TRUE;
7650     case 's':
7651       ++sym;
7652       symlen = strtol (sym, (char **) symp, 10);
7653       sym = *symp + 1; /* Skip the trailing ':'.  */
7654
7655       if (symend < sym || symlen + 1 > sizeof (symbuf))
7656         {
7657           bfd_set_error (bfd_error_invalid_operation);
7658           return FALSE;
7659         }
7660
7661       memcpy (symbuf, sym, symlen);
7662       symbuf[symlen] = '\0';
7663       *symp = sym + symlen;
7664
7665       /* Is it always possible, with complex symbols, that gas "mis-guessed"
7666          the symbol as a section, or vice-versa. so we're pretty liberal in our
7667          interpretation here; section means "try section first", not "must be a
7668          section", and likewise with symbol.  */
7669
7670       if (symbol_is_section)
7671         {
7672           if (!resolve_section (symbuf, finfo->output_bfd->sections, result)
7673               && !resolve_symbol (symbuf, input_bfd, finfo, result,
7674                                   isymbuf, locsymcount))
7675             {
7676               undefined_reference ("section", symbuf);
7677               return FALSE;
7678             }
7679         }
7680       else
7681         {
7682           if (!resolve_symbol (symbuf, input_bfd, finfo, result,
7683                                isymbuf, locsymcount)
7684               && !resolve_section (symbuf, finfo->output_bfd->sections,
7685                                    result))
7686             {
7687               undefined_reference ("symbol", symbuf);
7688               return FALSE;
7689             }
7690         }
7691
7692       return TRUE;
7693
7694       /* All that remains are operators.  */
7695
7696 #define UNARY_OP(op)                                            \
7697   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7698     {                                                           \
7699       sym += strlen (#op);                                      \
7700       if (*sym == ':')                                          \
7701         ++sym;                                                  \
7702       *symp = sym;                                              \
7703       if (!eval_symbol (&a, symp, input_bfd, finfo, dot,        \
7704                         isymbuf, locsymcount, signed_p))        \
7705         return FALSE;                                           \
7706       if (signed_p)                                             \
7707         *result = op ((bfd_signed_vma) a);                      \
7708       else                                                      \
7709         *result = op a;                                         \
7710       return TRUE;                                              \
7711     }
7712
7713 #define BINARY_OP(op)                                           \
7714   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7715     {                                                           \
7716       sym += strlen (#op);                                      \
7717       if (*sym == ':')                                          \
7718         ++sym;                                                  \
7719       *symp = sym;                                              \
7720       if (!eval_symbol (&a, symp, input_bfd, finfo, dot,        \
7721                         isymbuf, locsymcount, signed_p))        \
7722         return FALSE;                                           \
7723       ++*symp;                                                  \
7724       if (!eval_symbol (&b, symp, input_bfd, finfo, dot,        \
7725                         isymbuf, locsymcount, signed_p))        \
7726         return FALSE;                                           \
7727       if (signed_p)                                             \
7728         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
7729       else                                                      \
7730         *result = a op b;                                       \
7731       return TRUE;                                              \
7732     }
7733
7734     default:
7735       UNARY_OP  (0-);
7736       BINARY_OP (<<);
7737       BINARY_OP (>>);
7738       BINARY_OP (==);
7739       BINARY_OP (!=);
7740       BINARY_OP (<=);
7741       BINARY_OP (>=);
7742       BINARY_OP (&&);
7743       BINARY_OP (||);
7744       UNARY_OP  (~);
7745       UNARY_OP  (!);
7746       BINARY_OP (*);
7747       BINARY_OP (/);
7748       BINARY_OP (%);
7749       BINARY_OP (^);
7750       BINARY_OP (|);
7751       BINARY_OP (&);
7752       BINARY_OP (+);
7753       BINARY_OP (-);
7754       BINARY_OP (<);
7755       BINARY_OP (>);
7756 #undef UNARY_OP
7757 #undef BINARY_OP
7758       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
7759       bfd_set_error (bfd_error_invalid_operation);
7760       return FALSE;
7761     }
7762 }
7763
7764 static void
7765 put_value (bfd_vma size,
7766            unsigned long chunksz,
7767            bfd *input_bfd,
7768            bfd_vma x,
7769            bfd_byte *location)
7770 {
7771   location += (size - chunksz);
7772
7773   for (; size; size -= chunksz, location -= chunksz, x >>= (chunksz * 8))
7774     {
7775       switch (chunksz)
7776         {
7777         default:
7778         case 0:
7779           abort ();
7780         case 1:
7781           bfd_put_8 (input_bfd, x, location);
7782           break;
7783         case 2:
7784           bfd_put_16 (input_bfd, x, location);
7785           break;
7786         case 4:
7787           bfd_put_32 (input_bfd, x, location);
7788           break;
7789         case 8:
7790 #ifdef BFD64
7791           bfd_put_64 (input_bfd, x, location);
7792 #else
7793           abort ();
7794 #endif
7795           break;
7796         }
7797     }
7798 }
7799
7800 static bfd_vma
7801 get_value (bfd_vma size,
7802            unsigned long chunksz,
7803            bfd *input_bfd,
7804            bfd_byte *location)
7805 {
7806   bfd_vma x = 0;
7807
7808   for (; size; size -= chunksz, location += chunksz)
7809     {
7810       switch (chunksz)
7811         {
7812         default:
7813         case 0:
7814           abort ();
7815         case 1:
7816           x = (x << (8 * chunksz)) | bfd_get_8 (input_bfd, location);
7817           break;
7818         case 2:
7819           x = (x << (8 * chunksz)) | bfd_get_16 (input_bfd, location);
7820           break;
7821         case 4:
7822           x = (x << (8 * chunksz)) | bfd_get_32 (input_bfd, location);
7823           break;
7824         case 8:
7825 #ifdef BFD64
7826           x = (x << (8 * chunksz)) | bfd_get_64 (input_bfd, location);
7827 #else
7828           abort ();
7829 #endif
7830           break;
7831         }
7832     }
7833   return x;
7834 }
7835
7836 static void
7837 decode_complex_addend (unsigned long *start,   /* in bits */
7838                        unsigned long *oplen,   /* in bits */
7839                        unsigned long *len,     /* in bits */
7840                        unsigned long *wordsz,  /* in bytes */
7841                        unsigned long *chunksz, /* in bytes */
7842                        unsigned long *lsb0_p,
7843                        unsigned long *signed_p,
7844                        unsigned long *trunc_p,
7845                        unsigned long encoded)
7846 {
7847   * start     =  encoded        & 0x3F;
7848   * len       = (encoded >>  6) & 0x3F;
7849   * oplen     = (encoded >> 12) & 0x3F;
7850   * wordsz    = (encoded >> 18) & 0xF;
7851   * chunksz   = (encoded >> 22) & 0xF;
7852   * lsb0_p    = (encoded >> 27) & 1;
7853   * signed_p  = (encoded >> 28) & 1;
7854   * trunc_p   = (encoded >> 29) & 1;
7855 }
7856
7857 bfd_reloc_status_type
7858 bfd_elf_perform_complex_relocation (bfd *input_bfd,
7859                                     asection *input_section ATTRIBUTE_UNUSED,
7860                                     bfd_byte *contents,
7861                                     Elf_Internal_Rela *rel,
7862                                     bfd_vma relocation)
7863 {
7864   bfd_vma shift, x, mask;
7865   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
7866   bfd_reloc_status_type r;
7867
7868   /*  Perform this reloc, since it is complex.
7869       (this is not to say that it necessarily refers to a complex
7870       symbol; merely that it is a self-describing CGEN based reloc.
7871       i.e. the addend has the complete reloc information (bit start, end,
7872       word size, etc) encoded within it.).  */
7873
7874   decode_complex_addend (&start, &oplen, &len, &wordsz,
7875                          &chunksz, &lsb0_p, &signed_p,
7876                          &trunc_p, rel->r_addend);
7877
7878   mask = (((1L << (len - 1)) - 1) << 1) | 1;
7879
7880   if (lsb0_p)
7881     shift = (start + 1) - len;
7882   else
7883     shift = (8 * wordsz) - (start + len);
7884
7885   /* FIXME: octets_per_byte.  */
7886   x = get_value (wordsz, chunksz, input_bfd, contents + rel->r_offset);
7887
7888 #ifdef DEBUG
7889   printf ("Doing complex reloc: "
7890           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
7891           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
7892           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
7893           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
7894           oplen, (unsigned long) x, (unsigned long) mask,
7895           (unsigned long) relocation);
7896 #endif
7897
7898   r = bfd_reloc_ok;
7899   if (! trunc_p)
7900     /* Now do an overflow check.  */
7901     r = bfd_check_overflow ((signed_p
7902                              ? complain_overflow_signed
7903                              : complain_overflow_unsigned),
7904                             len, 0, (8 * wordsz),
7905                             relocation);
7906
7907   /* Do the deed.  */
7908   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
7909
7910 #ifdef DEBUG
7911   printf ("           relocation: %8.8lx\n"
7912           "         shifted mask: %8.8lx\n"
7913           " shifted/masked reloc: %8.8lx\n"
7914           "               result: %8.8lx\n",
7915           (unsigned long) relocation, (unsigned long) (mask << shift),
7916           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
7917 #endif
7918   /* FIXME: octets_per_byte.  */
7919   put_value (wordsz, chunksz, input_bfd, x, contents + rel->r_offset);
7920   return r;
7921 }
7922
7923 /* When performing a relocatable link, the input relocations are
7924    preserved.  But, if they reference global symbols, the indices
7925    referenced must be updated.  Update all the relocations found in
7926    RELDATA.  */
7927
7928 static void
7929 elf_link_adjust_relocs (bfd *abfd,
7930                         struct bfd_elf_section_reloc_data *reldata)
7931 {
7932   unsigned int i;
7933   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
7934   bfd_byte *erela;
7935   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
7936   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
7937   bfd_vma r_type_mask;
7938   int r_sym_shift;
7939   unsigned int count = reldata->count;
7940   struct elf_link_hash_entry **rel_hash = reldata->hashes;
7941
7942   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
7943     {
7944       swap_in = bed->s->swap_reloc_in;
7945       swap_out = bed->s->swap_reloc_out;
7946     }
7947   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
7948     {
7949       swap_in = bed->s->swap_reloca_in;
7950       swap_out = bed->s->swap_reloca_out;
7951     }
7952   else
7953     abort ();
7954
7955   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
7956     abort ();
7957
7958   if (bed->s->arch_size == 32)
7959     {
7960       r_type_mask = 0xff;
7961       r_sym_shift = 8;
7962     }
7963   else
7964     {
7965       r_type_mask = 0xffffffff;
7966       r_sym_shift = 32;
7967     }
7968
7969   erela = reldata->hdr->contents;
7970   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
7971     {
7972       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
7973       unsigned int j;
7974
7975       if (*rel_hash == NULL)
7976         continue;
7977
7978       BFD_ASSERT ((*rel_hash)->indx >= 0);
7979
7980       (*swap_in) (abfd, erela, irela);
7981       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
7982         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
7983                            | (irela[j].r_info & r_type_mask));
7984       (*swap_out) (abfd, irela, erela);
7985     }
7986 }
7987
7988 struct elf_link_sort_rela
7989 {
7990   union {
7991     bfd_vma offset;
7992     bfd_vma sym_mask;
7993   } u;
7994   enum elf_reloc_type_class type;
7995   /* We use this as an array of size int_rels_per_ext_rel.  */
7996   Elf_Internal_Rela rela[1];
7997 };
7998
7999 static int
8000 elf_link_sort_cmp1 (const void *A, const void *B)
8001 {
8002   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8003   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8004   int relativea, relativeb;
8005
8006   relativea = a->type == reloc_class_relative;
8007   relativeb = b->type == reloc_class_relative;
8008
8009   if (relativea < relativeb)
8010     return 1;
8011   if (relativea > relativeb)
8012     return -1;
8013   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8014     return -1;
8015   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8016     return 1;
8017   if (a->rela->r_offset < b->rela->r_offset)
8018     return -1;
8019   if (a->rela->r_offset > b->rela->r_offset)
8020     return 1;
8021   return 0;
8022 }
8023
8024 static int
8025 elf_link_sort_cmp2 (const void *A, const void *B)
8026 {
8027   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8028   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8029   int copya, copyb;
8030
8031   if (a->u.offset < b->u.offset)
8032     return -1;
8033   if (a->u.offset > b->u.offset)
8034     return 1;
8035   copya = (a->type == reloc_class_copy) * 2 + (a->type == reloc_class_plt);
8036   copyb = (b->type == reloc_class_copy) * 2 + (b->type == reloc_class_plt);
8037   if (copya < copyb)
8038     return -1;
8039   if (copya > copyb)
8040     return 1;
8041   if (a->rela->r_offset < b->rela->r_offset)
8042     return -1;
8043   if (a->rela->r_offset > b->rela->r_offset)
8044     return 1;
8045   return 0;
8046 }
8047
8048 static size_t
8049 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8050 {
8051   asection *dynamic_relocs;
8052   asection *rela_dyn;
8053   asection *rel_dyn;
8054   bfd_size_type count, size;
8055   size_t i, ret, sort_elt, ext_size;
8056   bfd_byte *sort, *s_non_relative, *p;
8057   struct elf_link_sort_rela *sq;
8058   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8059   int i2e = bed->s->int_rels_per_ext_rel;
8060   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8061   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8062   struct bfd_link_order *lo;
8063   bfd_vma r_sym_mask;
8064   bfd_boolean use_rela;
8065
8066   /* Find a dynamic reloc section.  */
8067   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8068   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8069   if (rela_dyn != NULL && rela_dyn->size > 0
8070       && rel_dyn != NULL && rel_dyn->size > 0)
8071     {
8072       bfd_boolean use_rela_initialised = FALSE;
8073
8074       /* This is just here to stop gcc from complaining.
8075          It's initialization checking code is not perfect.  */
8076       use_rela = TRUE;
8077
8078       /* Both sections are present.  Examine the sizes
8079          of the indirect sections to help us choose.  */
8080       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8081         if (lo->type == bfd_indirect_link_order)
8082           {
8083             asection *o = lo->u.indirect.section;
8084
8085             if ((o->size % bed->s->sizeof_rela) == 0)
8086               {
8087                 if ((o->size % bed->s->sizeof_rel) == 0)
8088                   /* Section size is divisible by both rel and rela sizes.
8089                      It is of no help to us.  */
8090                   ;
8091                 else
8092                   {
8093                     /* Section size is only divisible by rela.  */
8094                     if (use_rela_initialised && (use_rela == FALSE))
8095                       {
8096                         _bfd_error_handler
8097                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8098                         bfd_set_error (bfd_error_invalid_operation);
8099                         return 0;
8100                       }
8101                     else
8102                       {
8103                         use_rela = TRUE;
8104                         use_rela_initialised = TRUE;
8105                       }
8106                   }
8107               }
8108             else if ((o->size % bed->s->sizeof_rel) == 0)
8109               {
8110                 /* Section size is only divisible by rel.  */
8111                 if (use_rela_initialised && (use_rela == TRUE))
8112                   {
8113                     _bfd_error_handler
8114                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8115                     bfd_set_error (bfd_error_invalid_operation);
8116                     return 0;
8117                   }
8118                 else
8119                   {
8120                     use_rela = FALSE;
8121                     use_rela_initialised = TRUE;
8122                   }
8123               }
8124             else
8125               {
8126                 /* The section size is not divisible by either - something is wrong.  */
8127                 _bfd_error_handler
8128                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8129                 bfd_set_error (bfd_error_invalid_operation);
8130                 return 0;
8131               }
8132           }
8133
8134       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8135         if (lo->type == bfd_indirect_link_order)
8136           {
8137             asection *o = lo->u.indirect.section;
8138
8139             if ((o->size % bed->s->sizeof_rela) == 0)
8140               {
8141                 if ((o->size % bed->s->sizeof_rel) == 0)
8142                   /* Section size is divisible by both rel and rela sizes.
8143                      It is of no help to us.  */
8144                   ;
8145                 else
8146                   {
8147                     /* Section size is only divisible by rela.  */
8148                     if (use_rela_initialised && (use_rela == FALSE))
8149                       {
8150                         _bfd_error_handler
8151                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8152                         bfd_set_error (bfd_error_invalid_operation);
8153                         return 0;
8154                       }
8155                     else
8156                       {
8157                         use_rela = TRUE;
8158                         use_rela_initialised = TRUE;
8159                       }
8160                   }
8161               }
8162             else if ((o->size % bed->s->sizeof_rel) == 0)
8163               {
8164                 /* Section size is only divisible by rel.  */
8165                 if (use_rela_initialised && (use_rela == TRUE))
8166                   {
8167                     _bfd_error_handler
8168                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8169                     bfd_set_error (bfd_error_invalid_operation);
8170                     return 0;
8171                   }
8172                 else
8173                   {
8174                     use_rela = FALSE;
8175                     use_rela_initialised = TRUE;
8176                   }
8177               }
8178             else
8179               {
8180                 /* The section size is not divisible by either - something is wrong.  */
8181                 _bfd_error_handler
8182                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8183                 bfd_set_error (bfd_error_invalid_operation);
8184                 return 0;
8185               }
8186           }
8187
8188       if (! use_rela_initialised)
8189         /* Make a guess.  */
8190         use_rela = TRUE;
8191     }
8192   else if (rela_dyn != NULL && rela_dyn->size > 0)
8193     use_rela = TRUE;
8194   else if (rel_dyn != NULL && rel_dyn->size > 0)
8195     use_rela = FALSE;
8196   else
8197     return 0;
8198
8199   if (use_rela)
8200     {
8201       dynamic_relocs = rela_dyn;
8202       ext_size = bed->s->sizeof_rela;
8203       swap_in = bed->s->swap_reloca_in;
8204       swap_out = bed->s->swap_reloca_out;
8205     }
8206   else
8207     {
8208       dynamic_relocs = rel_dyn;
8209       ext_size = bed->s->sizeof_rel;
8210       swap_in = bed->s->swap_reloc_in;
8211       swap_out = bed->s->swap_reloc_out;
8212     }
8213
8214   size = 0;
8215   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8216     if (lo->type == bfd_indirect_link_order)
8217       size += lo->u.indirect.section->size;
8218
8219   if (size != dynamic_relocs->size)
8220     return 0;
8221
8222   sort_elt = (sizeof (struct elf_link_sort_rela)
8223               + (i2e - 1) * sizeof (Elf_Internal_Rela));
8224
8225   count = dynamic_relocs->size / ext_size;
8226   if (count == 0)
8227     return 0;
8228   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
8229
8230   if (sort == NULL)
8231     {
8232       (*info->callbacks->warning)
8233         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
8234       return 0;
8235     }
8236
8237   if (bed->s->arch_size == 32)
8238     r_sym_mask = ~(bfd_vma) 0xff;
8239   else
8240     r_sym_mask = ~(bfd_vma) 0xffffffff;
8241
8242   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8243     if (lo->type == bfd_indirect_link_order)
8244       {
8245         bfd_byte *erel, *erelend;
8246         asection *o = lo->u.indirect.section;
8247
8248         if (o->contents == NULL && o->size != 0)
8249           {
8250             /* This is a reloc section that is being handled as a normal
8251                section.  See bfd_section_from_shdr.  We can't combine
8252                relocs in this case.  */
8253             free (sort);
8254             return 0;
8255           }
8256         erel = o->contents;
8257         erelend = o->contents + o->size;
8258         /* FIXME: octets_per_byte.  */
8259         p = sort + o->output_offset / ext_size * sort_elt;
8260
8261         while (erel < erelend)
8262           {
8263             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8264
8265             (*swap_in) (abfd, erel, s->rela);
8266             s->type = (*bed->elf_backend_reloc_type_class) (s->rela);
8267             s->u.sym_mask = r_sym_mask;
8268             p += sort_elt;
8269             erel += ext_size;
8270           }
8271       }
8272
8273   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
8274
8275   for (i = 0, p = sort; i < count; i++, p += sort_elt)
8276     {
8277       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8278       if (s->type != reloc_class_relative)
8279         break;
8280     }
8281   ret = i;
8282   s_non_relative = p;
8283
8284   sq = (struct elf_link_sort_rela *) s_non_relative;
8285   for (; i < count; i++, p += sort_elt)
8286     {
8287       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
8288       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
8289         sq = sp;
8290       sp->u.offset = sq->rela->r_offset;
8291     }
8292
8293   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
8294
8295   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8296     if (lo->type == bfd_indirect_link_order)
8297       {
8298         bfd_byte *erel, *erelend;
8299         asection *o = lo->u.indirect.section;
8300
8301         erel = o->contents;
8302         erelend = o->contents + o->size;
8303         /* FIXME: octets_per_byte.  */
8304         p = sort + o->output_offset / ext_size * sort_elt;
8305         while (erel < erelend)
8306           {
8307             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8308             (*swap_out) (abfd, s->rela, erel);
8309             p += sort_elt;
8310             erel += ext_size;
8311           }
8312       }
8313
8314   free (sort);
8315   *psec = dynamic_relocs;
8316   return ret;
8317 }
8318
8319 /* Flush the output symbols to the file.  */
8320
8321 static bfd_boolean
8322 elf_link_flush_output_syms (struct elf_final_link_info *finfo,
8323                             const struct elf_backend_data *bed)
8324 {
8325   if (finfo->symbuf_count > 0)
8326     {
8327       Elf_Internal_Shdr *hdr;
8328       file_ptr pos;
8329       bfd_size_type amt;
8330
8331       hdr = &elf_tdata (finfo->output_bfd)->symtab_hdr;
8332       pos = hdr->sh_offset + hdr->sh_size;
8333       amt = finfo->symbuf_count * bed->s->sizeof_sym;
8334       if (bfd_seek (finfo->output_bfd, pos, SEEK_SET) != 0
8335           || bfd_bwrite (finfo->symbuf, amt, finfo->output_bfd) != amt)
8336         return FALSE;
8337
8338       hdr->sh_size += amt;
8339       finfo->symbuf_count = 0;
8340     }
8341
8342   return TRUE;
8343 }
8344
8345 /* Add a symbol to the output symbol table.  */
8346
8347 static int
8348 elf_link_output_sym (struct elf_final_link_info *finfo,
8349                      const char *name,
8350                      Elf_Internal_Sym *elfsym,
8351                      asection *input_sec,
8352                      struct elf_link_hash_entry *h)
8353 {
8354   bfd_byte *dest;
8355   Elf_External_Sym_Shndx *destshndx;
8356   int (*output_symbol_hook)
8357     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
8358      struct elf_link_hash_entry *);
8359   const struct elf_backend_data *bed;
8360
8361   bed = get_elf_backend_data (finfo->output_bfd);
8362   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
8363   if (output_symbol_hook != NULL)
8364     {
8365       int ret = (*output_symbol_hook) (finfo->info, name, elfsym, input_sec, h);
8366       if (ret != 1)
8367         return ret;
8368     }
8369
8370   if (name == NULL || *name == '\0')
8371     elfsym->st_name = 0;
8372   else if (input_sec->flags & SEC_EXCLUDE)
8373     elfsym->st_name = 0;
8374   else
8375     {
8376       elfsym->st_name = (unsigned long) _bfd_stringtab_add (finfo->symstrtab,
8377                                                             name, TRUE, FALSE);
8378       if (elfsym->st_name == (unsigned long) -1)
8379         return 0;
8380     }
8381
8382   if (finfo->symbuf_count >= finfo->symbuf_size)
8383     {
8384       if (! elf_link_flush_output_syms (finfo, bed))
8385         return 0;
8386     }
8387
8388   dest = finfo->symbuf + finfo->symbuf_count * bed->s->sizeof_sym;
8389   destshndx = finfo->symshndxbuf;
8390   if (destshndx != NULL)
8391     {
8392       if (bfd_get_symcount (finfo->output_bfd) >= finfo->shndxbuf_size)
8393         {
8394           bfd_size_type amt;
8395
8396           amt = finfo->shndxbuf_size * sizeof (Elf_External_Sym_Shndx);
8397           destshndx = (Elf_External_Sym_Shndx *) bfd_realloc (destshndx,
8398                                                               amt * 2);
8399           if (destshndx == NULL)
8400             return 0;
8401           finfo->symshndxbuf = destshndx;
8402           memset ((char *) destshndx + amt, 0, amt);
8403           finfo->shndxbuf_size *= 2;
8404         }
8405       destshndx += bfd_get_symcount (finfo->output_bfd);
8406     }
8407
8408   bed->s->swap_symbol_out (finfo->output_bfd, elfsym, dest, destshndx);
8409   finfo->symbuf_count += 1;
8410   bfd_get_symcount (finfo->output_bfd) += 1;
8411
8412   return 1;
8413 }
8414
8415 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
8416
8417 static bfd_boolean
8418 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
8419 {
8420   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
8421       && sym->st_shndx < SHN_LORESERVE)
8422     {
8423       /* The gABI doesn't support dynamic symbols in output sections
8424          beyond 64k.  */
8425       (*_bfd_error_handler)
8426         (_("%B: Too many sections: %d (>= %d)"),
8427          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
8428       bfd_set_error (bfd_error_nonrepresentable_section);
8429       return FALSE;
8430     }
8431   return TRUE;
8432 }
8433
8434 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
8435    allowing an unsatisfied unversioned symbol in the DSO to match a
8436    versioned symbol that would normally require an explicit version.
8437    We also handle the case that a DSO references a hidden symbol
8438    which may be satisfied by a versioned symbol in another DSO.  */
8439
8440 static bfd_boolean
8441 elf_link_check_versioned_symbol (struct bfd_link_info *info,
8442                                  const struct elf_backend_data *bed,
8443                                  struct elf_link_hash_entry *h)
8444 {
8445   bfd *abfd;
8446   struct elf_link_loaded_list *loaded;
8447
8448   if (!is_elf_hash_table (info->hash))
8449     return FALSE;
8450
8451   switch (h->root.type)
8452     {
8453     default:
8454       abfd = NULL;
8455       break;
8456
8457     case bfd_link_hash_undefined:
8458     case bfd_link_hash_undefweak:
8459       abfd = h->root.u.undef.abfd;
8460       if ((abfd->flags & DYNAMIC) == 0
8461           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
8462         return FALSE;
8463       break;
8464
8465     case bfd_link_hash_defined:
8466     case bfd_link_hash_defweak:
8467       abfd = h->root.u.def.section->owner;
8468       break;
8469
8470     case bfd_link_hash_common:
8471       abfd = h->root.u.c.p->section->owner;
8472       break;
8473     }
8474   BFD_ASSERT (abfd != NULL);
8475
8476   for (loaded = elf_hash_table (info)->loaded;
8477        loaded != NULL;
8478        loaded = loaded->next)
8479     {
8480       bfd *input;
8481       Elf_Internal_Shdr *hdr;
8482       bfd_size_type symcount;
8483       bfd_size_type extsymcount;
8484       bfd_size_type extsymoff;
8485       Elf_Internal_Shdr *versymhdr;
8486       Elf_Internal_Sym *isym;
8487       Elf_Internal_Sym *isymend;
8488       Elf_Internal_Sym *isymbuf;
8489       Elf_External_Versym *ever;
8490       Elf_External_Versym *extversym;
8491
8492       input = loaded->abfd;
8493
8494       /* We check each DSO for a possible hidden versioned definition.  */
8495       if (input == abfd
8496           || (input->flags & DYNAMIC) == 0
8497           || elf_dynversym (input) == 0)
8498         continue;
8499
8500       hdr = &elf_tdata (input)->dynsymtab_hdr;
8501
8502       symcount = hdr->sh_size / bed->s->sizeof_sym;
8503       if (elf_bad_symtab (input))
8504         {
8505           extsymcount = symcount;
8506           extsymoff = 0;
8507         }
8508       else
8509         {
8510           extsymcount = symcount - hdr->sh_info;
8511           extsymoff = hdr->sh_info;
8512         }
8513
8514       if (extsymcount == 0)
8515         continue;
8516
8517       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
8518                                       NULL, NULL, NULL);
8519       if (isymbuf == NULL)
8520         return FALSE;
8521
8522       /* Read in any version definitions.  */
8523       versymhdr = &elf_tdata (input)->dynversym_hdr;
8524       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
8525       if (extversym == NULL)
8526         goto error_ret;
8527
8528       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
8529           || (bfd_bread (extversym, versymhdr->sh_size, input)
8530               != versymhdr->sh_size))
8531         {
8532           free (extversym);
8533         error_ret:
8534           free (isymbuf);
8535           return FALSE;
8536         }
8537
8538       ever = extversym + extsymoff;
8539       isymend = isymbuf + extsymcount;
8540       for (isym = isymbuf; isym < isymend; isym++, ever++)
8541         {
8542           const char *name;
8543           Elf_Internal_Versym iver;
8544           unsigned short version_index;
8545
8546           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
8547               || isym->st_shndx == SHN_UNDEF)
8548             continue;
8549
8550           name = bfd_elf_string_from_elf_section (input,
8551                                                   hdr->sh_link,
8552                                                   isym->st_name);
8553           if (strcmp (name, h->root.root.string) != 0)
8554             continue;
8555
8556           _bfd_elf_swap_versym_in (input, ever, &iver);
8557
8558           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
8559               && !(h->def_regular
8560                    && h->forced_local))
8561             {
8562               /* If we have a non-hidden versioned sym, then it should
8563                  have provided a definition for the undefined sym unless
8564                  it is defined in a non-shared object and forced local.
8565                */
8566               abort ();
8567             }
8568
8569           version_index = iver.vs_vers & VERSYM_VERSION;
8570           if (version_index == 1 || version_index == 2)
8571             {
8572               /* This is the base or first version.  We can use it.  */
8573               free (extversym);
8574               free (isymbuf);
8575               return TRUE;
8576             }
8577         }
8578
8579       free (extversym);
8580       free (isymbuf);
8581     }
8582
8583   return FALSE;
8584 }
8585
8586 /* Add an external symbol to the symbol table.  This is called from
8587    the hash table traversal routine.  When generating a shared object,
8588    we go through the symbol table twice.  The first time we output
8589    anything that might have been forced to local scope in a version
8590    script.  The second time we output the symbols that are still
8591    global symbols.  */
8592
8593 static bfd_boolean
8594 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
8595 {
8596   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
8597   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
8598   struct elf_final_link_info *finfo = eoinfo->finfo;
8599   bfd_boolean strip;
8600   Elf_Internal_Sym sym;
8601   asection *input_sec;
8602   const struct elf_backend_data *bed;
8603   long indx;
8604   int ret;
8605
8606   if (h->root.type == bfd_link_hash_warning)
8607     {
8608       h = (struct elf_link_hash_entry *) h->root.u.i.link;
8609       if (h->root.type == bfd_link_hash_new)
8610         return TRUE;
8611     }
8612
8613   /* Decide whether to output this symbol in this pass.  */
8614   if (eoinfo->localsyms)
8615     {
8616       if (!h->forced_local)
8617         return TRUE;
8618     }
8619   else
8620     {
8621       if (h->forced_local)
8622         return TRUE;
8623     }
8624
8625   bed = get_elf_backend_data (finfo->output_bfd);
8626
8627   if (h->root.type == bfd_link_hash_undefined)
8628     {
8629       /* If we have an undefined symbol reference here then it must have
8630          come from a shared library that is being linked in.  (Undefined
8631          references in regular files have already been handled unless
8632          they are in unreferenced sections which are removed by garbage
8633          collection).  */
8634       bfd_boolean ignore_undef = FALSE;
8635
8636       /* Some symbols may be special in that the fact that they're
8637          undefined can be safely ignored - let backend determine that.  */
8638       if (bed->elf_backend_ignore_undef_symbol)
8639         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
8640
8641       /* If we are reporting errors for this situation then do so now.  */
8642       if (!ignore_undef
8643           && h->ref_dynamic
8644           && (!h->ref_regular || finfo->info->gc_sections)
8645           && ! elf_link_check_versioned_symbol (finfo->info, bed, h)
8646           && finfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
8647         {
8648           if (! (finfo->info->callbacks->undefined_symbol
8649                  (finfo->info, h->root.root.string,
8650                   h->ref_regular ? NULL : h->root.u.undef.abfd,
8651                   NULL, 0, finfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR)))
8652             {
8653               bfd_set_error (bfd_error_bad_value);
8654               eoinfo->failed = TRUE;
8655               return FALSE;
8656             }
8657         }
8658     }
8659
8660   /* We should also warn if a forced local symbol is referenced from
8661      shared libraries.  */
8662   if (!finfo->info->relocatable
8663       && finfo->info->executable
8664       && h->forced_local
8665       && h->ref_dynamic
8666       && h->def_regular
8667       && !h->dynamic_def
8668       && !h->dynamic_weak
8669       && ! elf_link_check_versioned_symbol (finfo->info, bed, h))
8670     {
8671       bfd *def_bfd;
8672       const char *msg;
8673
8674       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
8675         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
8676       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
8677         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
8678       else
8679         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
8680       def_bfd = finfo->output_bfd;
8681       if (h->root.u.def.section != bfd_abs_section_ptr)
8682         def_bfd = h->root.u.def.section->owner;
8683       (*_bfd_error_handler) (msg, finfo->output_bfd, def_bfd,
8684                              h->root.root.string);
8685       bfd_set_error (bfd_error_bad_value);
8686       eoinfo->failed = TRUE;
8687       return FALSE;
8688     }
8689
8690   /* We don't want to output symbols that have never been mentioned by
8691      a regular file, or that we have been told to strip.  However, if
8692      h->indx is set to -2, the symbol is used by a reloc and we must
8693      output it.  */
8694   if (h->indx == -2)
8695     strip = FALSE;
8696   else if ((h->def_dynamic
8697             || h->ref_dynamic
8698             || h->root.type == bfd_link_hash_new)
8699            && !h->def_regular
8700            && !h->ref_regular)
8701     strip = TRUE;
8702   else if (finfo->info->strip == strip_all)
8703     strip = TRUE;
8704   else if (finfo->info->strip == strip_some
8705            && bfd_hash_lookup (finfo->info->keep_hash,
8706                                h->root.root.string, FALSE, FALSE) == NULL)
8707     strip = TRUE;
8708   else if ((h->root.type == bfd_link_hash_defined
8709             || h->root.type == bfd_link_hash_defweak)
8710            && ((finfo->info->strip_discarded
8711                 && elf_discarded_section (h->root.u.def.section))
8712                || (h->root.u.def.section->owner != NULL
8713                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
8714     strip = TRUE;
8715   else if ((h->root.type == bfd_link_hash_undefined
8716             || h->root.type == bfd_link_hash_undefweak)
8717            && h->root.u.undef.abfd != NULL
8718            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
8719     strip = TRUE;
8720   else
8721     strip = FALSE;
8722
8723   /* If we're stripping it, and it's not a dynamic symbol, there's
8724      nothing else to do unless it is a forced local symbol or a
8725      STT_GNU_IFUNC symbol.  */
8726   if (strip
8727       && h->dynindx == -1
8728       && h->type != STT_GNU_IFUNC
8729       && !h->forced_local)
8730     return TRUE;
8731
8732   sym.st_value = 0;
8733   sym.st_size = h->size;
8734   sym.st_other = h->other;
8735   if (h->forced_local)
8736     {
8737       sym.st_info = ELF_ST_INFO (STB_LOCAL, h->type);
8738       /* Turn off visibility on local symbol.  */
8739       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
8740     }
8741   else if (h->unique_global)
8742     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, h->type);
8743   else if (h->root.type == bfd_link_hash_undefweak
8744            || h->root.type == bfd_link_hash_defweak)
8745     sym.st_info = ELF_ST_INFO (STB_WEAK, h->type);
8746   else
8747     sym.st_info = ELF_ST_INFO (STB_GLOBAL, h->type);
8748   sym.st_target_internal = h->target_internal;
8749
8750   switch (h->root.type)
8751     {
8752     default:
8753     case bfd_link_hash_new:
8754     case bfd_link_hash_warning:
8755       abort ();
8756       return FALSE;
8757
8758     case bfd_link_hash_undefined:
8759     case bfd_link_hash_undefweak:
8760       input_sec = bfd_und_section_ptr;
8761       sym.st_shndx = SHN_UNDEF;
8762       break;
8763
8764     case bfd_link_hash_defined:
8765     case bfd_link_hash_defweak:
8766       {
8767         input_sec = h->root.u.def.section;
8768         if (input_sec->output_section != NULL)
8769           {
8770             sym.st_shndx =
8771               _bfd_elf_section_from_bfd_section (finfo->output_bfd,
8772                                                  input_sec->output_section);
8773             if (sym.st_shndx == SHN_BAD)
8774               {
8775                 (*_bfd_error_handler)
8776                   (_("%B: could not find output section %A for input section %A"),
8777                    finfo->output_bfd, input_sec->output_section, input_sec);
8778                 bfd_set_error (bfd_error_nonrepresentable_section);
8779                 eoinfo->failed = TRUE;
8780                 return FALSE;
8781               }
8782
8783             /* ELF symbols in relocatable files are section relative,
8784                but in nonrelocatable files they are virtual
8785                addresses.  */
8786             sym.st_value = h->root.u.def.value + input_sec->output_offset;
8787             if (! finfo->info->relocatable)
8788               {
8789                 sym.st_value += input_sec->output_section->vma;
8790                 if (h->type == STT_TLS)
8791                   {
8792                     asection *tls_sec = elf_hash_table (finfo->info)->tls_sec;
8793                     if (tls_sec != NULL)
8794                       sym.st_value -= tls_sec->vma;
8795                     else
8796                       {
8797                         /* The TLS section may have been garbage collected.  */
8798                         BFD_ASSERT (finfo->info->gc_sections
8799                                     && !input_sec->gc_mark);
8800                       }
8801                   }
8802               }
8803           }
8804         else
8805           {
8806             BFD_ASSERT (input_sec->owner == NULL
8807                         || (input_sec->owner->flags & DYNAMIC) != 0);
8808             sym.st_shndx = SHN_UNDEF;
8809             input_sec = bfd_und_section_ptr;
8810           }
8811       }
8812       break;
8813
8814     case bfd_link_hash_common:
8815       input_sec = h->root.u.c.p->section;
8816       sym.st_shndx = bed->common_section_index (input_sec);
8817       sym.st_value = 1 << h->root.u.c.p->alignment_power;
8818       break;
8819
8820     case bfd_link_hash_indirect:
8821       /* These symbols are created by symbol versioning.  They point
8822          to the decorated version of the name.  For example, if the
8823          symbol foo@@GNU_1.2 is the default, which should be used when
8824          foo is used with no version, then we add an indirect symbol
8825          foo which points to foo@@GNU_1.2.  We ignore these symbols,
8826          since the indirected symbol is already in the hash table.  */
8827       return TRUE;
8828     }
8829
8830   /* Give the processor backend a chance to tweak the symbol value,
8831      and also to finish up anything that needs to be done for this
8832      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
8833      forced local syms when non-shared is due to a historical quirk.
8834      STT_GNU_IFUNC symbol must go through PLT.  */
8835   if ((h->type == STT_GNU_IFUNC
8836        && h->def_regular
8837        && !finfo->info->relocatable)
8838       || ((h->dynindx != -1
8839            || h->forced_local)
8840           && ((finfo->info->shared
8841                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
8842                    || h->root.type != bfd_link_hash_undefweak))
8843               || !h->forced_local)
8844           && elf_hash_table (finfo->info)->dynamic_sections_created))
8845     {
8846       if (! ((*bed->elf_backend_finish_dynamic_symbol)
8847              (finfo->output_bfd, finfo->info, h, &sym)))
8848         {
8849           eoinfo->failed = TRUE;
8850           return FALSE;
8851         }
8852     }
8853
8854   /* If we are marking the symbol as undefined, and there are no
8855      non-weak references to this symbol from a regular object, then
8856      mark the symbol as weak undefined; if there are non-weak
8857      references, mark the symbol as strong.  We can't do this earlier,
8858      because it might not be marked as undefined until the
8859      finish_dynamic_symbol routine gets through with it.  */
8860   if (sym.st_shndx == SHN_UNDEF
8861       && h->ref_regular
8862       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
8863           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
8864     {
8865       int bindtype;
8866       unsigned int type = ELF_ST_TYPE (sym.st_info);
8867
8868       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
8869       if (type == STT_GNU_IFUNC)
8870         type = STT_FUNC;
8871
8872       if (h->ref_regular_nonweak)
8873         bindtype = STB_GLOBAL;
8874       else
8875         bindtype = STB_WEAK;
8876       sym.st_info = ELF_ST_INFO (bindtype, type);
8877     }
8878
8879   /* If this is a symbol defined in a dynamic library, don't use the
8880      symbol size from the dynamic library.  Relinking an executable
8881      against a new library may introduce gratuitous changes in the
8882      executable's symbols if we keep the size.  */
8883   if (sym.st_shndx == SHN_UNDEF
8884       && !h->def_regular
8885       && h->def_dynamic)
8886     sym.st_size = 0;
8887
8888   /* If a non-weak symbol with non-default visibility is not defined
8889      locally, it is a fatal error.  */
8890   if (! finfo->info->relocatable
8891       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
8892       && ELF_ST_BIND (sym.st_info) != STB_WEAK
8893       && h->root.type == bfd_link_hash_undefined
8894       && !h->def_regular)
8895     {
8896       const char *msg;
8897
8898       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
8899         msg = _("%B: protected symbol `%s' isn't defined");
8900       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
8901         msg = _("%B: internal symbol `%s' isn't defined");
8902       else
8903         msg = _("%B: hidden symbol `%s' isn't defined");
8904       (*_bfd_error_handler) (msg, finfo->output_bfd, h->root.root.string);
8905       bfd_set_error (bfd_error_bad_value);
8906       eoinfo->failed = TRUE;
8907       return FALSE;
8908     }
8909
8910   /* If this symbol should be put in the .dynsym section, then put it
8911      there now.  We already know the symbol index.  We also fill in
8912      the entry in the .hash section.  */
8913   if (h->dynindx != -1
8914       && elf_hash_table (finfo->info)->dynamic_sections_created)
8915     {
8916       bfd_byte *esym;
8917
8918       sym.st_name = h->dynstr_index;
8919       esym = finfo->dynsym_sec->contents + h->dynindx * bed->s->sizeof_sym;
8920       if (! check_dynsym (finfo->output_bfd, &sym))
8921         {
8922           eoinfo->failed = TRUE;
8923           return FALSE;
8924         }
8925       bed->s->swap_symbol_out (finfo->output_bfd, &sym, esym, 0);
8926
8927       if (finfo->hash_sec != NULL)
8928         {
8929           size_t hash_entry_size;
8930           bfd_byte *bucketpos;
8931           bfd_vma chain;
8932           size_t bucketcount;
8933           size_t bucket;
8934
8935           bucketcount = elf_hash_table (finfo->info)->bucketcount;
8936           bucket = h->u.elf_hash_value % bucketcount;
8937
8938           hash_entry_size
8939             = elf_section_data (finfo->hash_sec)->this_hdr.sh_entsize;
8940           bucketpos = ((bfd_byte *) finfo->hash_sec->contents
8941                        + (bucket + 2) * hash_entry_size);
8942           chain = bfd_get (8 * hash_entry_size, finfo->output_bfd, bucketpos);
8943           bfd_put (8 * hash_entry_size, finfo->output_bfd, h->dynindx, bucketpos);
8944           bfd_put (8 * hash_entry_size, finfo->output_bfd, chain,
8945                    ((bfd_byte *) finfo->hash_sec->contents
8946                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
8947         }
8948
8949       if (finfo->symver_sec != NULL && finfo->symver_sec->contents != NULL)
8950         {
8951           Elf_Internal_Versym iversym;
8952           Elf_External_Versym *eversym;
8953
8954           if (!h->def_regular)
8955             {
8956               if (h->verinfo.verdef == NULL)
8957                 iversym.vs_vers = 0;
8958               else
8959                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
8960             }
8961           else
8962             {
8963               if (h->verinfo.vertree == NULL)
8964                 iversym.vs_vers = 1;
8965               else
8966                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
8967               if (finfo->info->create_default_symver)
8968                 iversym.vs_vers++;
8969             }
8970
8971           if (h->hidden)
8972             iversym.vs_vers |= VERSYM_HIDDEN;
8973
8974           eversym = (Elf_External_Versym *) finfo->symver_sec->contents;
8975           eversym += h->dynindx;
8976           _bfd_elf_swap_versym_out (finfo->output_bfd, &iversym, eversym);
8977         }
8978     }
8979
8980   /* If we're stripping it, then it was just a dynamic symbol, and
8981      there's nothing else to do.  */
8982   if (strip || (input_sec->flags & SEC_EXCLUDE) != 0)
8983     return TRUE;
8984
8985   indx = bfd_get_symcount (finfo->output_bfd);
8986   ret = elf_link_output_sym (finfo, h->root.root.string, &sym, input_sec, h);
8987   if (ret == 0)
8988     {
8989       eoinfo->failed = TRUE;
8990       return FALSE;
8991     }
8992   else if (ret == 1)
8993     h->indx = indx;
8994   else if (h->indx == -2)
8995     abort();
8996
8997   return TRUE;
8998 }
8999
9000 /* Return TRUE if special handling is done for relocs in SEC against
9001    symbols defined in discarded sections.  */
9002
9003 static bfd_boolean
9004 elf_section_ignore_discarded_relocs (asection *sec)
9005 {
9006   const struct elf_backend_data *bed;
9007
9008   switch (sec->sec_info_type)
9009     {
9010     case ELF_INFO_TYPE_STABS:
9011     case ELF_INFO_TYPE_EH_FRAME:
9012       return TRUE;
9013     default:
9014       break;
9015     }
9016
9017   bed = get_elf_backend_data (sec->owner);
9018   if (bed->elf_backend_ignore_discarded_relocs != NULL
9019       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
9020     return TRUE;
9021
9022   return FALSE;
9023 }
9024
9025 /* Return a mask saying how ld should treat relocations in SEC against
9026    symbols defined in discarded sections.  If this function returns
9027    COMPLAIN set, ld will issue a warning message.  If this function
9028    returns PRETEND set, and the discarded section was link-once and the
9029    same size as the kept link-once section, ld will pretend that the
9030    symbol was actually defined in the kept section.  Otherwise ld will
9031    zero the reloc (at least that is the intent, but some cooperation by
9032    the target dependent code is needed, particularly for REL targets).  */
9033
9034 unsigned int
9035 _bfd_elf_default_action_discarded (asection *sec)
9036 {
9037   if (sec->flags & SEC_DEBUGGING)
9038     return PRETEND;
9039
9040   if (strcmp (".eh_frame", sec->name) == 0)
9041     return 0;
9042
9043   if (strcmp (".gcc_except_table", sec->name) == 0)
9044     return 0;
9045
9046   return COMPLAIN | PRETEND;
9047 }
9048
9049 /* Find a match between a section and a member of a section group.  */
9050
9051 static asection *
9052 match_group_member (asection *sec, asection *group,
9053                     struct bfd_link_info *info)
9054 {
9055   asection *first = elf_next_in_group (group);
9056   asection *s = first;
9057
9058   while (s != NULL)
9059     {
9060       if (bfd_elf_match_symbols_in_sections (s, sec, info))
9061         return s;
9062
9063       s = elf_next_in_group (s);
9064       if (s == first)
9065         break;
9066     }
9067
9068   return NULL;
9069 }
9070
9071 /* Check if the kept section of a discarded section SEC can be used
9072    to replace it.  Return the replacement if it is OK.  Otherwise return
9073    NULL.  */
9074
9075 asection *
9076 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
9077 {
9078   asection *kept;
9079
9080   kept = sec->kept_section;
9081   if (kept != NULL)
9082     {
9083       if ((kept->flags & SEC_GROUP) != 0)
9084         kept = match_group_member (sec, kept, info);
9085       if (kept != NULL
9086           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
9087               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
9088         kept = NULL;
9089       sec->kept_section = kept;
9090     }
9091   return kept;
9092 }
9093
9094 /* Link an input file into the linker output file.  This function
9095    handles all the sections and relocations of the input file at once.
9096    This is so that we only have to read the local symbols once, and
9097    don't have to keep them in memory.  */
9098
9099 static bfd_boolean
9100 elf_link_input_bfd (struct elf_final_link_info *finfo, bfd *input_bfd)
9101 {
9102   int (*relocate_section)
9103     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
9104      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
9105   bfd *output_bfd;
9106   Elf_Internal_Shdr *symtab_hdr;
9107   size_t locsymcount;
9108   size_t extsymoff;
9109   Elf_Internal_Sym *isymbuf;
9110   Elf_Internal_Sym *isym;
9111   Elf_Internal_Sym *isymend;
9112   long *pindex;
9113   asection **ppsection;
9114   asection *o;
9115   const struct elf_backend_data *bed;
9116   struct elf_link_hash_entry **sym_hashes;
9117   bfd_size_type address_size;
9118   bfd_vma r_type_mask;
9119   int r_sym_shift;
9120
9121   output_bfd = finfo->output_bfd;
9122   bed = get_elf_backend_data (output_bfd);
9123   relocate_section = bed->elf_backend_relocate_section;
9124
9125   /* If this is a dynamic object, we don't want to do anything here:
9126      we don't want the local symbols, and we don't want the section
9127      contents.  */
9128   if ((input_bfd->flags & DYNAMIC) != 0)
9129     return TRUE;
9130
9131   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9132   if (elf_bad_symtab (input_bfd))
9133     {
9134       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
9135       extsymoff = 0;
9136     }
9137   else
9138     {
9139       locsymcount = symtab_hdr->sh_info;
9140       extsymoff = symtab_hdr->sh_info;
9141     }
9142
9143   /* Read the local symbols.  */
9144   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
9145   if (isymbuf == NULL && locsymcount != 0)
9146     {
9147       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
9148                                       finfo->internal_syms,
9149                                       finfo->external_syms,
9150                                       finfo->locsym_shndx);
9151       if (isymbuf == NULL)
9152         return FALSE;
9153     }
9154
9155   /* Find local symbol sections and adjust values of symbols in
9156      SEC_MERGE sections.  Write out those local symbols we know are
9157      going into the output file.  */
9158   isymend = isymbuf + locsymcount;
9159   for (isym = isymbuf, pindex = finfo->indices, ppsection = finfo->sections;
9160        isym < isymend;
9161        isym++, pindex++, ppsection++)
9162     {
9163       asection *isec;
9164       const char *name;
9165       Elf_Internal_Sym osym;
9166       long indx;
9167       int ret;
9168
9169       *pindex = -1;
9170
9171       if (elf_bad_symtab (input_bfd))
9172         {
9173           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
9174             {
9175               *ppsection = NULL;
9176               continue;
9177             }
9178         }
9179
9180       if (isym->st_shndx == SHN_UNDEF)
9181         isec = bfd_und_section_ptr;
9182       else if (isym->st_shndx == SHN_ABS)
9183         isec = bfd_abs_section_ptr;
9184       else if (isym->st_shndx == SHN_COMMON)
9185         isec = bfd_com_section_ptr;
9186       else
9187         {
9188           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
9189           if (isec == NULL)
9190             {
9191               /* Don't attempt to output symbols with st_shnx in the
9192                  reserved range other than SHN_ABS and SHN_COMMON.  */
9193               *ppsection = NULL;
9194               continue;
9195             }
9196           else if (isec->sec_info_type == ELF_INFO_TYPE_MERGE
9197                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
9198             isym->st_value =
9199               _bfd_merged_section_offset (output_bfd, &isec,
9200                                           elf_section_data (isec)->sec_info,
9201                                           isym->st_value);
9202         }
9203
9204       *ppsection = isec;
9205
9206       /* Don't output the first, undefined, symbol.  */
9207       if (ppsection == finfo->sections)
9208         continue;
9209
9210       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
9211         {
9212           /* We never output section symbols.  Instead, we use the
9213              section symbol of the corresponding section in the output
9214              file.  */
9215           continue;
9216         }
9217
9218       /* If we are stripping all symbols, we don't want to output this
9219          one.  */
9220       if (finfo->info->strip == strip_all)
9221         continue;
9222
9223       /* If we are discarding all local symbols, we don't want to
9224          output this one.  If we are generating a relocatable output
9225          file, then some of the local symbols may be required by
9226          relocs; we output them below as we discover that they are
9227          needed.  */
9228       if (finfo->info->discard == discard_all)
9229         continue;
9230
9231       /* If this symbol is defined in a section which we are
9232          discarding, we don't need to keep it.  */
9233       if (isym->st_shndx != SHN_UNDEF
9234           && isym->st_shndx < SHN_LORESERVE
9235           && bfd_section_removed_from_list (output_bfd,
9236                                             isec->output_section))
9237         continue;
9238
9239       /* Get the name of the symbol.  */
9240       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
9241                                               isym->st_name);
9242       if (name == NULL)
9243         return FALSE;
9244
9245       /* See if we are discarding symbols with this name.  */
9246       if ((finfo->info->strip == strip_some
9247            && (bfd_hash_lookup (finfo->info->keep_hash, name, FALSE, FALSE)
9248                == NULL))
9249           || (((finfo->info->discard == discard_sec_merge
9250                 && (isec->flags & SEC_MERGE) && ! finfo->info->relocatable)
9251                || finfo->info->discard == discard_l)
9252               && bfd_is_local_label_name (input_bfd, name)))
9253         continue;
9254
9255       osym = *isym;
9256
9257       /* Adjust the section index for the output file.  */
9258       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
9259                                                          isec->output_section);
9260       if (osym.st_shndx == SHN_BAD)
9261         return FALSE;
9262
9263       /* ELF symbols in relocatable files are section relative, but
9264          in executable files they are virtual addresses.  Note that
9265          this code assumes that all ELF sections have an associated
9266          BFD section with a reasonable value for output_offset; below
9267          we assume that they also have a reasonable value for
9268          output_section.  Any special sections must be set up to meet
9269          these requirements.  */
9270       osym.st_value += isec->output_offset;
9271       if (! finfo->info->relocatable)
9272         {
9273           osym.st_value += isec->output_section->vma;
9274           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
9275             {
9276               /* STT_TLS symbols are relative to PT_TLS segment base.  */
9277               BFD_ASSERT (elf_hash_table (finfo->info)->tls_sec != NULL);
9278               osym.st_value -= elf_hash_table (finfo->info)->tls_sec->vma;
9279             }
9280         }
9281
9282       indx = bfd_get_symcount (output_bfd);
9283       ret = elf_link_output_sym (finfo, name, &osym, isec, NULL);
9284       if (ret == 0)
9285         return FALSE;
9286       else if (ret == 1)
9287         *pindex = indx;
9288     }
9289
9290   if (bed->s->arch_size == 32)
9291     {
9292       r_type_mask = 0xff;
9293       r_sym_shift = 8;
9294       address_size = 4;
9295     }
9296   else
9297     {
9298       r_type_mask = 0xffffffff;
9299       r_sym_shift = 32;
9300       address_size = 8;
9301     }
9302
9303   /* Relocate the contents of each section.  */
9304   sym_hashes = elf_sym_hashes (input_bfd);
9305   for (o = input_bfd->sections; o != NULL; o = o->next)
9306     {
9307       bfd_byte *contents;
9308
9309       if (! o->linker_mark)
9310         {
9311           /* This section was omitted from the link.  */
9312           continue;
9313         }
9314
9315       if (finfo->info->relocatable
9316           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
9317         {
9318           /* Deal with the group signature symbol.  */
9319           struct bfd_elf_section_data *sec_data = elf_section_data (o);
9320           unsigned long symndx = sec_data->this_hdr.sh_info;
9321           asection *osec = o->output_section;
9322
9323           if (symndx >= locsymcount
9324               || (elf_bad_symtab (input_bfd)
9325                   && finfo->sections[symndx] == NULL))
9326             {
9327               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
9328               while (h->root.type == bfd_link_hash_indirect
9329                      || h->root.type == bfd_link_hash_warning)
9330                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
9331               /* Arrange for symbol to be output.  */
9332               h->indx = -2;
9333               elf_section_data (osec)->this_hdr.sh_info = -2;
9334             }
9335           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
9336             {
9337               /* We'll use the output section target_index.  */
9338               asection *sec = finfo->sections[symndx]->output_section;
9339               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
9340             }
9341           else
9342             {
9343               if (finfo->indices[symndx] == -1)
9344                 {
9345                   /* Otherwise output the local symbol now.  */
9346                   Elf_Internal_Sym sym = isymbuf[symndx];
9347                   asection *sec = finfo->sections[symndx]->output_section;
9348                   const char *name;
9349                   long indx;
9350                   int ret;
9351
9352                   name = bfd_elf_string_from_elf_section (input_bfd,
9353                                                           symtab_hdr->sh_link,
9354                                                           sym.st_name);
9355                   if (name == NULL)
9356                     return FALSE;
9357
9358                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
9359                                                                     sec);
9360                   if (sym.st_shndx == SHN_BAD)
9361                     return FALSE;
9362
9363                   sym.st_value += o->output_offset;
9364
9365                   indx = bfd_get_symcount (output_bfd);
9366                   ret = elf_link_output_sym (finfo, name, &sym, o, NULL);
9367                   if (ret == 0)
9368                     return FALSE;
9369                   else if (ret == 1)
9370                     finfo->indices[symndx] = indx;
9371                   else
9372                     abort ();
9373                 }
9374               elf_section_data (osec)->this_hdr.sh_info
9375                 = finfo->indices[symndx];
9376             }
9377         }
9378
9379       if ((o->flags & SEC_HAS_CONTENTS) == 0
9380           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
9381         continue;
9382
9383       if ((o->flags & SEC_LINKER_CREATED) != 0)
9384         {
9385           /* Section was created by _bfd_elf_link_create_dynamic_sections
9386              or somesuch.  */
9387           continue;
9388         }
9389
9390       /* Get the contents of the section.  They have been cached by a
9391          relaxation routine.  Note that o is a section in an input
9392          file, so the contents field will not have been set by any of
9393          the routines which work on output files.  */
9394       if (elf_section_data (o)->this_hdr.contents != NULL)
9395         contents = elf_section_data (o)->this_hdr.contents;
9396       else
9397         {
9398           contents = finfo->contents;
9399           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
9400             return FALSE;
9401         }
9402
9403       if ((o->flags & SEC_RELOC) != 0)
9404         {
9405           Elf_Internal_Rela *internal_relocs;
9406           Elf_Internal_Rela *rel, *relend;
9407           int action_discarded;
9408           int ret;
9409
9410           /* Get the swapped relocs.  */
9411           internal_relocs
9412             = _bfd_elf_link_read_relocs (input_bfd, o, finfo->external_relocs,
9413                                          finfo->internal_relocs, FALSE);
9414           if (internal_relocs == NULL
9415               && o->reloc_count > 0)
9416             return FALSE;
9417
9418           /* We need to reverse-copy input .ctors/.dtors sections if
9419              they are placed in .init_array/.finit_array for output.  */
9420           if (o->size > address_size
9421               && ((strncmp (o->name, ".ctors", 6) == 0
9422                    && strcmp (o->output_section->name,
9423                               ".init_array") == 0)
9424                   || (strncmp (o->name, ".dtors", 6) == 0
9425                       && strcmp (o->output_section->name,
9426                                  ".fini_array") == 0))
9427               && (o->name[6] == 0 || o->name[6] == '.'))
9428             {
9429               if (o->size != o->reloc_count * address_size)
9430                 {
9431                   (*_bfd_error_handler)
9432                     (_("error: %B: size of section %A is not "
9433                        "multiple of address size"),
9434                      input_bfd, o);
9435                   bfd_set_error (bfd_error_on_input);
9436                   return FALSE;
9437                 }
9438               o->flags |= SEC_ELF_REVERSE_COPY;
9439             }
9440
9441           action_discarded = -1;
9442           if (!elf_section_ignore_discarded_relocs (o))
9443             action_discarded = (*bed->action_discarded) (o);
9444
9445           /* Run through the relocs evaluating complex reloc symbols and
9446              looking for relocs against symbols from discarded sections
9447              or section symbols from removed link-once sections.
9448              Complain about relocs against discarded sections.  Zero
9449              relocs against removed link-once sections.  */
9450
9451           rel = internal_relocs;
9452           relend = rel + o->reloc_count * bed->s->int_rels_per_ext_rel;
9453           for ( ; rel < relend; rel++)
9454             {
9455               unsigned long r_symndx = rel->r_info >> r_sym_shift;
9456               unsigned int s_type;
9457               asection **ps, *sec;
9458               struct elf_link_hash_entry *h = NULL;
9459               const char *sym_name;
9460
9461               if (r_symndx == STN_UNDEF)
9462                 continue;
9463
9464               if (r_symndx >= locsymcount
9465                   || (elf_bad_symtab (input_bfd)
9466                       && finfo->sections[r_symndx] == NULL))
9467                 {
9468                   h = sym_hashes[r_symndx - extsymoff];
9469
9470                   /* Badly formatted input files can contain relocs that
9471                      reference non-existant symbols.  Check here so that
9472                      we do not seg fault.  */
9473                   if (h == NULL)
9474                     {
9475                       char buffer [32];
9476
9477                       sprintf_vma (buffer, rel->r_info);
9478                       (*_bfd_error_handler)
9479                         (_("error: %B contains a reloc (0x%s) for section %A "
9480                            "that references a non-existent global symbol"),
9481                          input_bfd, o, buffer);
9482                       bfd_set_error (bfd_error_bad_value);
9483                       return FALSE;
9484                     }
9485
9486                   while (h->root.type == bfd_link_hash_indirect
9487                          || h->root.type == bfd_link_hash_warning)
9488                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9489
9490                   s_type = h->type;
9491
9492                   ps = NULL;
9493                   if (h->root.type == bfd_link_hash_defined
9494                       || h->root.type == bfd_link_hash_defweak)
9495                     ps = &h->root.u.def.section;
9496
9497                   sym_name = h->root.root.string;
9498                 }
9499               else
9500                 {
9501                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
9502
9503                   s_type = ELF_ST_TYPE (sym->st_info);
9504                   ps = &finfo->sections[r_symndx];
9505                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
9506                                                sym, *ps);
9507                 }
9508
9509               if ((s_type == STT_RELC || s_type == STT_SRELC)
9510                   && !finfo->info->relocatable)
9511                 {
9512                   bfd_vma val;
9513                   bfd_vma dot = (rel->r_offset
9514                                  + o->output_offset + o->output_section->vma);
9515 #ifdef DEBUG
9516                   printf ("Encountered a complex symbol!");
9517                   printf (" (input_bfd %s, section %s, reloc %ld\n",
9518                           input_bfd->filename, o->name,
9519                           (long) (rel - internal_relocs));
9520                   printf (" symbol: idx  %8.8lx, name %s\n",
9521                           r_symndx, sym_name);
9522                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
9523                           (unsigned long) rel->r_info,
9524                           (unsigned long) rel->r_offset);
9525 #endif
9526                   if (!eval_symbol (&val, &sym_name, input_bfd, finfo, dot,
9527                                     isymbuf, locsymcount, s_type == STT_SRELC))
9528                     return FALSE;
9529
9530                   /* Symbol evaluated OK.  Update to absolute value.  */
9531                   set_symbol_value (input_bfd, isymbuf, locsymcount,
9532                                     r_symndx, val);
9533                   continue;
9534                 }
9535
9536               if (action_discarded != -1 && ps != NULL)
9537                 {
9538                   /* Complain if the definition comes from a
9539                      discarded section.  */
9540                   if ((sec = *ps) != NULL && elf_discarded_section (sec))
9541                     {
9542                       BFD_ASSERT (r_symndx != STN_UNDEF);
9543                       if (action_discarded & COMPLAIN)
9544                         (*finfo->info->callbacks->einfo)
9545                           (_("%X`%s' referenced in section `%A' of %B: "
9546                              "defined in discarded section `%A' of %B\n"),
9547                            sym_name, o, input_bfd, sec, sec->owner);
9548
9549                       /* Try to do the best we can to support buggy old
9550                          versions of gcc.  Pretend that the symbol is
9551                          really defined in the kept linkonce section.
9552                          FIXME: This is quite broken.  Modifying the
9553                          symbol here means we will be changing all later
9554                          uses of the symbol, not just in this section.  */
9555                       if (action_discarded & PRETEND)
9556                         {
9557                           asection *kept;
9558
9559                           kept = _bfd_elf_check_kept_section (sec,
9560                                                               finfo->info);
9561                           if (kept != NULL)
9562                             {
9563                               *ps = kept;
9564                               continue;
9565                             }
9566                         }
9567                     }
9568                 }
9569             }
9570
9571           /* Relocate the section by invoking a back end routine.
9572
9573              The back end routine is responsible for adjusting the
9574              section contents as necessary, and (if using Rela relocs
9575              and generating a relocatable output file) adjusting the
9576              reloc addend as necessary.
9577
9578              The back end routine does not have to worry about setting
9579              the reloc address or the reloc symbol index.
9580
9581              The back end routine is given a pointer to the swapped in
9582              internal symbols, and can access the hash table entries
9583              for the external symbols via elf_sym_hashes (input_bfd).
9584
9585              When generating relocatable output, the back end routine
9586              must handle STB_LOCAL/STT_SECTION symbols specially.  The
9587              output symbol is going to be a section symbol
9588              corresponding to the output section, which will require
9589              the addend to be adjusted.  */
9590
9591           ret = (*relocate_section) (output_bfd, finfo->info,
9592                                      input_bfd, o, contents,
9593                                      internal_relocs,
9594                                      isymbuf,
9595                                      finfo->sections);
9596           if (!ret)
9597             return FALSE;
9598
9599           if (ret == 2
9600               || finfo->info->relocatable
9601               || finfo->info->emitrelocations)
9602             {
9603               Elf_Internal_Rela *irela;
9604               Elf_Internal_Rela *irelaend, *irelamid;
9605               bfd_vma last_offset;
9606               struct elf_link_hash_entry **rel_hash;
9607               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
9608               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
9609               unsigned int next_erel;
9610               bfd_boolean rela_normal;
9611               struct bfd_elf_section_data *esdi, *esdo;
9612
9613               esdi = elf_section_data (o);
9614               esdo = elf_section_data (o->output_section);
9615               rela_normal = FALSE;
9616
9617               /* Adjust the reloc addresses and symbol indices.  */
9618
9619               irela = internal_relocs;
9620               irelaend = irela + o->reloc_count * bed->s->int_rels_per_ext_rel;
9621               rel_hash = esdo->rel.hashes + esdo->rel.count;
9622               /* We start processing the REL relocs, if any.  When we reach
9623                  IRELAMID in the loop, we switch to the RELA relocs.  */
9624               irelamid = irela;
9625               if (esdi->rel.hdr != NULL)
9626                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
9627                              * bed->s->int_rels_per_ext_rel);
9628               rel_hash_list = rel_hash;
9629               rela_hash_list = NULL;
9630               last_offset = o->output_offset;
9631               if (!finfo->info->relocatable)
9632                 last_offset += o->output_section->vma;
9633               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
9634                 {
9635                   unsigned long r_symndx;
9636                   asection *sec;
9637                   Elf_Internal_Sym sym;
9638
9639                   if (next_erel == bed->s->int_rels_per_ext_rel)
9640                     {
9641                       rel_hash++;
9642                       next_erel = 0;
9643                     }
9644
9645                   if (irela == irelamid)
9646                     {
9647                       rel_hash = esdo->rela.hashes + esdo->rela.count;
9648                       rela_hash_list = rel_hash;
9649                       rela_normal = bed->rela_normal;
9650                     }
9651
9652                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
9653                                                              finfo->info, o,
9654                                                              irela->r_offset);
9655                   if (irela->r_offset >= (bfd_vma) -2)
9656                     {
9657                       /* This is a reloc for a deleted entry or somesuch.
9658                          Turn it into an R_*_NONE reloc, at the same
9659                          offset as the last reloc.  elf_eh_frame.c and
9660                          bfd_elf_discard_info rely on reloc offsets
9661                          being ordered.  */
9662                       irela->r_offset = last_offset;
9663                       irela->r_info = 0;
9664                       irela->r_addend = 0;
9665                       continue;
9666                     }
9667
9668                   irela->r_offset += o->output_offset;
9669
9670                   /* Relocs in an executable have to be virtual addresses.  */
9671                   if (!finfo->info->relocatable)
9672                     irela->r_offset += o->output_section->vma;
9673
9674                   last_offset = irela->r_offset;
9675
9676                   r_symndx = irela->r_info >> r_sym_shift;
9677                   if (r_symndx == STN_UNDEF)
9678                     continue;
9679
9680                   if (r_symndx >= locsymcount
9681                       || (elf_bad_symtab (input_bfd)
9682                           && finfo->sections[r_symndx] == NULL))
9683                     {
9684                       struct elf_link_hash_entry *rh;
9685                       unsigned long indx;
9686
9687                       /* This is a reloc against a global symbol.  We
9688                          have not yet output all the local symbols, so
9689                          we do not know the symbol index of any global
9690                          symbol.  We set the rel_hash entry for this
9691                          reloc to point to the global hash table entry
9692                          for this symbol.  The symbol index is then
9693                          set at the end of bfd_elf_final_link.  */
9694                       indx = r_symndx - extsymoff;
9695                       rh = elf_sym_hashes (input_bfd)[indx];
9696                       while (rh->root.type == bfd_link_hash_indirect
9697                              || rh->root.type == bfd_link_hash_warning)
9698                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
9699
9700                       /* Setting the index to -2 tells
9701                          elf_link_output_extsym that this symbol is
9702                          used by a reloc.  */
9703                       BFD_ASSERT (rh->indx < 0);
9704                       rh->indx = -2;
9705
9706                       *rel_hash = rh;
9707
9708                       continue;
9709                     }
9710
9711                   /* This is a reloc against a local symbol.  */
9712
9713                   *rel_hash = NULL;
9714                   sym = isymbuf[r_symndx];
9715                   sec = finfo->sections[r_symndx];
9716                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
9717                     {
9718                       /* I suppose the backend ought to fill in the
9719                          section of any STT_SECTION symbol against a
9720                          processor specific section.  */
9721                       r_symndx = STN_UNDEF;
9722                       if (bfd_is_abs_section (sec))
9723                         ;
9724                       else if (sec == NULL || sec->owner == NULL)
9725                         {
9726                           bfd_set_error (bfd_error_bad_value);
9727                           return FALSE;
9728                         }
9729                       else
9730                         {
9731                           asection *osec = sec->output_section;
9732
9733                           /* If we have discarded a section, the output
9734                              section will be the absolute section.  In
9735                              case of discarded SEC_MERGE sections, use
9736                              the kept section.  relocate_section should
9737                              have already handled discarded linkonce
9738                              sections.  */
9739                           if (bfd_is_abs_section (osec)
9740                               && sec->kept_section != NULL
9741                               && sec->kept_section->output_section != NULL)
9742                             {
9743                               osec = sec->kept_section->output_section;
9744                               irela->r_addend -= osec->vma;
9745                             }
9746
9747                           if (!bfd_is_abs_section (osec))
9748                             {
9749                               r_symndx = osec->target_index;
9750                               if (r_symndx == STN_UNDEF)
9751                                 {
9752                                   struct elf_link_hash_table *htab;
9753                                   asection *oi;
9754
9755                                   htab = elf_hash_table (finfo->info);
9756                                   oi = htab->text_index_section;
9757                                   if ((osec->flags & SEC_READONLY) == 0
9758                                       && htab->data_index_section != NULL)
9759                                     oi = htab->data_index_section;
9760
9761                                   if (oi != NULL)
9762                                     {
9763                                       irela->r_addend += osec->vma - oi->vma;
9764                                       r_symndx = oi->target_index;
9765                                     }
9766                                 }
9767
9768                               BFD_ASSERT (r_symndx != STN_UNDEF);
9769                             }
9770                         }
9771
9772                       /* Adjust the addend according to where the
9773                          section winds up in the output section.  */
9774                       if (rela_normal)
9775                         irela->r_addend += sec->output_offset;
9776                     }
9777                   else
9778                     {
9779                       if (finfo->indices[r_symndx] == -1)
9780                         {
9781                           unsigned long shlink;
9782                           const char *name;
9783                           asection *osec;
9784                           long indx;
9785
9786                           if (finfo->info->strip == strip_all)
9787                             {
9788                               /* You can't do ld -r -s.  */
9789                               bfd_set_error (bfd_error_invalid_operation);
9790                               return FALSE;
9791                             }
9792
9793                           /* This symbol was skipped earlier, but
9794                              since it is needed by a reloc, we
9795                              must output it now.  */
9796                           shlink = symtab_hdr->sh_link;
9797                           name = (bfd_elf_string_from_elf_section
9798                                   (input_bfd, shlink, sym.st_name));
9799                           if (name == NULL)
9800                             return FALSE;
9801
9802                           osec = sec->output_section;
9803                           sym.st_shndx =
9804                             _bfd_elf_section_from_bfd_section (output_bfd,
9805                                                                osec);
9806                           if (sym.st_shndx == SHN_BAD)
9807                             return FALSE;
9808
9809                           sym.st_value += sec->output_offset;
9810                           if (! finfo->info->relocatable)
9811                             {
9812                               sym.st_value += osec->vma;
9813                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
9814                                 {
9815                                   /* STT_TLS symbols are relative to PT_TLS
9816                                      segment base.  */
9817                                   BFD_ASSERT (elf_hash_table (finfo->info)
9818                                               ->tls_sec != NULL);
9819                                   sym.st_value -= (elf_hash_table (finfo->info)
9820                                                    ->tls_sec->vma);
9821                                 }
9822                             }
9823
9824                           indx = bfd_get_symcount (output_bfd);
9825                           ret = elf_link_output_sym (finfo, name, &sym, sec,
9826                                                      NULL);
9827                           if (ret == 0)
9828                             return FALSE;
9829                           else if (ret == 1)
9830                             finfo->indices[r_symndx] = indx;
9831                           else
9832                             abort ();
9833                         }
9834
9835                       r_symndx = finfo->indices[r_symndx];
9836                     }
9837
9838                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
9839                                    | (irela->r_info & r_type_mask));
9840                 }
9841
9842               /* Swap out the relocs.  */
9843               input_rel_hdr = esdi->rel.hdr;
9844               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
9845                 {
9846                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
9847                                                      input_rel_hdr,
9848                                                      internal_relocs,
9849                                                      rel_hash_list))
9850                     return FALSE;
9851                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
9852                                       * bed->s->int_rels_per_ext_rel);
9853                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
9854                 }
9855
9856               input_rela_hdr = esdi->rela.hdr;
9857               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
9858                 {
9859                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
9860                                                      input_rela_hdr,
9861                                                      internal_relocs,
9862                                                      rela_hash_list))
9863                     return FALSE;
9864                 }
9865             }
9866         }
9867
9868       /* Write out the modified section contents.  */
9869       if (bed->elf_backend_write_section
9870           && (*bed->elf_backend_write_section) (output_bfd, finfo->info, o,
9871                                                 contents))
9872         {
9873           /* Section written out.  */
9874         }
9875       else switch (o->sec_info_type)
9876         {
9877         case ELF_INFO_TYPE_STABS:
9878           if (! (_bfd_write_section_stabs
9879                  (output_bfd,
9880                   &elf_hash_table (finfo->info)->stab_info,
9881                   o, &elf_section_data (o)->sec_info, contents)))
9882             return FALSE;
9883           break;
9884         case ELF_INFO_TYPE_MERGE:
9885           if (! _bfd_write_merged_section (output_bfd, o,
9886                                            elf_section_data (o)->sec_info))
9887             return FALSE;
9888           break;
9889         case ELF_INFO_TYPE_EH_FRAME:
9890           {
9891             if (! _bfd_elf_write_section_eh_frame (output_bfd, finfo->info,
9892                                                    o, contents))
9893               return FALSE;
9894           }
9895           break;
9896         default:
9897           {
9898             /* FIXME: octets_per_byte.  */
9899             if (! (o->flags & SEC_EXCLUDE))
9900               {
9901                 file_ptr offset = (file_ptr) o->output_offset;
9902                 bfd_size_type todo = o->size;
9903                 if ((o->flags & SEC_ELF_REVERSE_COPY))
9904                   {
9905                     /* Reverse-copy input section to output.  */
9906                     do
9907                       {
9908                         todo -= address_size;
9909                         if (! bfd_set_section_contents (output_bfd,
9910                                                         o->output_section,
9911                                                         contents + todo,
9912                                                         offset,
9913                                                         address_size))
9914                           return FALSE;
9915                         if (todo == 0)
9916                           break;
9917                         offset += address_size;
9918                       }
9919                     while (1);
9920                   }
9921                 else if (! bfd_set_section_contents (output_bfd,
9922                                                      o->output_section,
9923                                                      contents,
9924                                                      offset, todo))
9925                   return FALSE;
9926               }
9927           }
9928           break;
9929         }
9930     }
9931
9932   return TRUE;
9933 }
9934
9935 /* Generate a reloc when linking an ELF file.  This is a reloc
9936    requested by the linker, and does not come from any input file.  This
9937    is used to build constructor and destructor tables when linking
9938    with -Ur.  */
9939
9940 static bfd_boolean
9941 elf_reloc_link_order (bfd *output_bfd,
9942                       struct bfd_link_info *info,
9943                       asection *output_section,
9944                       struct bfd_link_order *link_order)
9945 {
9946   reloc_howto_type *howto;
9947   long indx;
9948   bfd_vma offset;
9949   bfd_vma addend;
9950   struct bfd_elf_section_reloc_data *reldata;
9951   struct elf_link_hash_entry **rel_hash_ptr;
9952   Elf_Internal_Shdr *rel_hdr;
9953   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
9954   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
9955   bfd_byte *erel;
9956   unsigned int i;
9957   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
9958
9959   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
9960   if (howto == NULL)
9961     {
9962       bfd_set_error (bfd_error_bad_value);
9963       return FALSE;
9964     }
9965
9966   addend = link_order->u.reloc.p->addend;
9967
9968   if (esdo->rel.hdr)
9969     reldata = &esdo->rel;
9970   else if (esdo->rela.hdr)
9971     reldata = &esdo->rela;
9972   else
9973     {
9974       reldata = NULL;
9975       BFD_ASSERT (0);
9976     }
9977
9978   /* Figure out the symbol index.  */
9979   rel_hash_ptr = reldata->hashes + reldata->count;
9980   if (link_order->type == bfd_section_reloc_link_order)
9981     {
9982       indx = link_order->u.reloc.p->u.section->target_index;
9983       BFD_ASSERT (indx != 0);
9984       *rel_hash_ptr = NULL;
9985     }
9986   else
9987     {
9988       struct elf_link_hash_entry *h;
9989
9990       /* Treat a reloc against a defined symbol as though it were
9991          actually against the section.  */
9992       h = ((struct elf_link_hash_entry *)
9993            bfd_wrapped_link_hash_lookup (output_bfd, info,
9994                                          link_order->u.reloc.p->u.name,
9995                                          FALSE, FALSE, TRUE));
9996       if (h != NULL
9997           && (h->root.type == bfd_link_hash_defined
9998               || h->root.type == bfd_link_hash_defweak))
9999         {
10000           asection *section;
10001
10002           section = h->root.u.def.section;
10003           indx = section->output_section->target_index;
10004           *rel_hash_ptr = NULL;
10005           /* It seems that we ought to add the symbol value to the
10006              addend here, but in practice it has already been added
10007              because it was passed to constructor_callback.  */
10008           addend += section->output_section->vma + section->output_offset;
10009         }
10010       else if (h != NULL)
10011         {
10012           /* Setting the index to -2 tells elf_link_output_extsym that
10013              this symbol is used by a reloc.  */
10014           h->indx = -2;
10015           *rel_hash_ptr = h;
10016           indx = 0;
10017         }
10018       else
10019         {
10020           if (! ((*info->callbacks->unattached_reloc)
10021                  (info, link_order->u.reloc.p->u.name, NULL, NULL, 0)))
10022             return FALSE;
10023           indx = 0;
10024         }
10025     }
10026
10027   /* If this is an inplace reloc, we must write the addend into the
10028      object file.  */
10029   if (howto->partial_inplace && addend != 0)
10030     {
10031       bfd_size_type size;
10032       bfd_reloc_status_type rstat;
10033       bfd_byte *buf;
10034       bfd_boolean ok;
10035       const char *sym_name;
10036
10037       size = (bfd_size_type) bfd_get_reloc_size (howto);
10038       buf = (bfd_byte *) bfd_zmalloc (size);
10039       if (buf == NULL)
10040         return FALSE;
10041       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
10042       switch (rstat)
10043         {
10044         case bfd_reloc_ok:
10045           break;
10046
10047         default:
10048         case bfd_reloc_outofrange:
10049           abort ();
10050
10051         case bfd_reloc_overflow:
10052           if (link_order->type == bfd_section_reloc_link_order)
10053             sym_name = bfd_section_name (output_bfd,
10054                                          link_order->u.reloc.p->u.section);
10055           else
10056             sym_name = link_order->u.reloc.p->u.name;
10057           if (! ((*info->callbacks->reloc_overflow)
10058                  (info, NULL, sym_name, howto->name, addend, NULL,
10059                   NULL, (bfd_vma) 0)))
10060             {
10061               free (buf);
10062               return FALSE;
10063             }
10064           break;
10065         }
10066       ok = bfd_set_section_contents (output_bfd, output_section, buf,
10067                                      link_order->offset, size);
10068       free (buf);
10069       if (! ok)
10070         return FALSE;
10071     }
10072
10073   /* The address of a reloc is relative to the section in a
10074      relocatable file, and is a virtual address in an executable
10075      file.  */
10076   offset = link_order->offset;
10077   if (! info->relocatable)
10078     offset += output_section->vma;
10079
10080   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
10081     {
10082       irel[i].r_offset = offset;
10083       irel[i].r_info = 0;
10084       irel[i].r_addend = 0;
10085     }
10086   if (bed->s->arch_size == 32)
10087     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
10088   else
10089     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
10090
10091   rel_hdr = reldata->hdr;
10092   erel = rel_hdr->contents;
10093   if (rel_hdr->sh_type == SHT_REL)
10094     {
10095       erel += reldata->count * bed->s->sizeof_rel;
10096       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
10097     }
10098   else
10099     {
10100       irel[0].r_addend = addend;
10101       erel += reldata->count * bed->s->sizeof_rela;
10102       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
10103     }
10104
10105   ++reldata->count;
10106
10107   return TRUE;
10108 }
10109
10110
10111 /* Get the output vma of the section pointed to by the sh_link field.  */
10112
10113 static bfd_vma
10114 elf_get_linked_section_vma (struct bfd_link_order *p)
10115 {
10116   Elf_Internal_Shdr **elf_shdrp;
10117   asection *s;
10118   int elfsec;
10119
10120   s = p->u.indirect.section;
10121   elf_shdrp = elf_elfsections (s->owner);
10122   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
10123   elfsec = elf_shdrp[elfsec]->sh_link;
10124   /* PR 290:
10125      The Intel C compiler generates SHT_IA_64_UNWIND with
10126      SHF_LINK_ORDER.  But it doesn't set the sh_link or
10127      sh_info fields.  Hence we could get the situation
10128      where elfsec is 0.  */
10129   if (elfsec == 0)
10130     {
10131       const struct elf_backend_data *bed
10132         = get_elf_backend_data (s->owner);
10133       if (bed->link_order_error_handler)
10134         bed->link_order_error_handler
10135           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
10136       return 0;
10137     }
10138   else
10139     {
10140       s = elf_shdrp[elfsec]->bfd_section;
10141       return s->output_section->vma + s->output_offset;
10142     }
10143 }
10144
10145
10146 /* Compare two sections based on the locations of the sections they are
10147    linked to.  Used by elf_fixup_link_order.  */
10148
10149 static int
10150 compare_link_order (const void * a, const void * b)
10151 {
10152   bfd_vma apos;
10153   bfd_vma bpos;
10154
10155   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
10156   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
10157   if (apos < bpos)
10158     return -1;
10159   return apos > bpos;
10160 }
10161
10162
10163 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
10164    order as their linked sections.  Returns false if this could not be done
10165    because an output section includes both ordered and unordered
10166    sections.  Ideally we'd do this in the linker proper.  */
10167
10168 static bfd_boolean
10169 elf_fixup_link_order (bfd *abfd, asection *o)
10170 {
10171   int seen_linkorder;
10172   int seen_other;
10173   int n;
10174   struct bfd_link_order *p;
10175   bfd *sub;
10176   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10177   unsigned elfsec;
10178   struct bfd_link_order **sections;
10179   asection *s, *other_sec, *linkorder_sec;
10180   bfd_vma offset;
10181
10182   other_sec = NULL;
10183   linkorder_sec = NULL;
10184   seen_other = 0;
10185   seen_linkorder = 0;
10186   for (p = o->map_head.link_order; p != NULL; p = p->next)
10187     {
10188       if (p->type == bfd_indirect_link_order)
10189         {
10190           s = p->u.indirect.section;
10191           sub = s->owner;
10192           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
10193               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
10194               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
10195               && elfsec < elf_numsections (sub)
10196               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
10197               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
10198             {
10199               seen_linkorder++;
10200               linkorder_sec = s;
10201             }
10202           else
10203             {
10204               seen_other++;
10205               other_sec = s;
10206             }
10207         }
10208       else
10209         seen_other++;
10210
10211       if (seen_other && seen_linkorder)
10212         {
10213           if (other_sec && linkorder_sec)
10214             (*_bfd_error_handler) (_("%A has both ordered [`%A' in %B] and unordered [`%A' in %B] sections"),
10215                                    o, linkorder_sec,
10216                                    linkorder_sec->owner, other_sec,
10217                                    other_sec->owner);
10218           else
10219             (*_bfd_error_handler) (_("%A has both ordered and unordered sections"),
10220                                    o);
10221           bfd_set_error (bfd_error_bad_value);
10222           return FALSE;
10223         }
10224     }
10225
10226   if (!seen_linkorder)
10227     return TRUE;
10228
10229   sections = (struct bfd_link_order **)
10230     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
10231   if (sections == NULL)
10232     return FALSE;
10233   seen_linkorder = 0;
10234
10235   for (p = o->map_head.link_order; p != NULL; p = p->next)
10236     {
10237       sections[seen_linkorder++] = p;
10238     }
10239   /* Sort the input sections in the order of their linked section.  */
10240   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
10241          compare_link_order);
10242
10243   /* Change the offsets of the sections.  */
10244   offset = 0;
10245   for (n = 0; n < seen_linkorder; n++)
10246     {
10247       s = sections[n]->u.indirect.section;
10248       offset &= ~(bfd_vma) 0 << s->alignment_power;
10249       s->output_offset = offset;
10250       sections[n]->offset = offset;
10251       /* FIXME: octets_per_byte.  */
10252       offset += sections[n]->size;
10253     }
10254
10255   free (sections);
10256   return TRUE;
10257 }
10258
10259
10260 /* Do the final step of an ELF link.  */
10261
10262 bfd_boolean
10263 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
10264 {
10265   bfd_boolean dynamic;
10266   bfd_boolean emit_relocs;
10267   bfd *dynobj;
10268   struct elf_final_link_info finfo;
10269   asection *o;
10270   struct bfd_link_order *p;
10271   bfd *sub;
10272   bfd_size_type max_contents_size;
10273   bfd_size_type max_external_reloc_size;
10274   bfd_size_type max_internal_reloc_count;
10275   bfd_size_type max_sym_count;
10276   bfd_size_type max_sym_shndx_count;
10277   file_ptr off;
10278   Elf_Internal_Sym elfsym;
10279   unsigned int i;
10280   Elf_Internal_Shdr *symtab_hdr;
10281   Elf_Internal_Shdr *symtab_shndx_hdr;
10282   Elf_Internal_Shdr *symstrtab_hdr;
10283   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10284   struct elf_outext_info eoinfo;
10285   bfd_boolean merged;
10286   size_t relativecount = 0;
10287   asection *reldyn = 0;
10288   bfd_size_type amt;
10289   asection *attr_section = NULL;
10290   bfd_vma attr_size = 0;
10291   const char *std_attrs_section;
10292
10293   if (! is_elf_hash_table (info->hash))
10294     return FALSE;
10295
10296   if (info->shared)
10297     abfd->flags |= DYNAMIC;
10298
10299   dynamic = elf_hash_table (info)->dynamic_sections_created;
10300   dynobj = elf_hash_table (info)->dynobj;
10301
10302   emit_relocs = (info->relocatable
10303                  || info->emitrelocations);
10304
10305   finfo.info = info;
10306   finfo.output_bfd = abfd;
10307   finfo.symstrtab = _bfd_elf_stringtab_init ();
10308   if (finfo.symstrtab == NULL)
10309     return FALSE;
10310
10311   if (! dynamic)
10312     {
10313       finfo.dynsym_sec = NULL;
10314       finfo.hash_sec = NULL;
10315       finfo.symver_sec = NULL;
10316     }
10317   else
10318     {
10319       finfo.dynsym_sec = bfd_get_section_by_name (dynobj, ".dynsym");
10320       finfo.hash_sec = bfd_get_section_by_name (dynobj, ".hash");
10321       BFD_ASSERT (finfo.dynsym_sec != NULL);
10322       finfo.symver_sec = bfd_get_section_by_name (dynobj, ".gnu.version");
10323       /* Note that it is OK if symver_sec is NULL.  */
10324     }
10325
10326   finfo.contents = NULL;
10327   finfo.external_relocs = NULL;
10328   finfo.internal_relocs = NULL;
10329   finfo.external_syms = NULL;
10330   finfo.locsym_shndx = NULL;
10331   finfo.internal_syms = NULL;
10332   finfo.indices = NULL;
10333   finfo.sections = NULL;
10334   finfo.symbuf = NULL;
10335   finfo.symshndxbuf = NULL;
10336   finfo.symbuf_count = 0;
10337   finfo.shndxbuf_size = 0;
10338
10339   /* The object attributes have been merged.  Remove the input
10340      sections from the link, and set the contents of the output
10341      secton.  */
10342   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
10343   for (o = abfd->sections; o != NULL; o = o->next)
10344     {
10345       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
10346           || strcmp (o->name, ".gnu.attributes") == 0)
10347         {
10348           for (p = o->map_head.link_order; p != NULL; p = p->next)
10349             {
10350               asection *input_section;
10351
10352               if (p->type != bfd_indirect_link_order)
10353                 continue;
10354               input_section = p->u.indirect.section;
10355               /* Hack: reset the SEC_HAS_CONTENTS flag so that
10356                  elf_link_input_bfd ignores this section.  */
10357               input_section->flags &= ~SEC_HAS_CONTENTS;
10358             }
10359
10360           attr_size = bfd_elf_obj_attr_size (abfd);
10361           if (attr_size)
10362             {
10363               bfd_set_section_size (abfd, o, attr_size);
10364               attr_section = o;
10365               /* Skip this section later on.  */
10366               o->map_head.link_order = NULL;
10367             }
10368           else
10369             o->flags |= SEC_EXCLUDE;
10370         }
10371     }
10372
10373   /* Count up the number of relocations we will output for each output
10374      section, so that we know the sizes of the reloc sections.  We
10375      also figure out some maximum sizes.  */
10376   max_contents_size = 0;
10377   max_external_reloc_size = 0;
10378   max_internal_reloc_count = 0;
10379   max_sym_count = 0;
10380   max_sym_shndx_count = 0;
10381   merged = FALSE;
10382   for (o = abfd->sections; o != NULL; o = o->next)
10383     {
10384       struct bfd_elf_section_data *esdo = elf_section_data (o);
10385       o->reloc_count = 0;
10386
10387       for (p = o->map_head.link_order; p != NULL; p = p->next)
10388         {
10389           unsigned int reloc_count = 0;
10390           struct bfd_elf_section_data *esdi = NULL;
10391
10392           if (p->type == bfd_section_reloc_link_order
10393               || p->type == bfd_symbol_reloc_link_order)
10394             reloc_count = 1;
10395           else if (p->type == bfd_indirect_link_order)
10396             {
10397               asection *sec;
10398
10399               sec = p->u.indirect.section;
10400               esdi = elf_section_data (sec);
10401
10402               /* Mark all sections which are to be included in the
10403                  link.  This will normally be every section.  We need
10404                  to do this so that we can identify any sections which
10405                  the linker has decided to not include.  */
10406               sec->linker_mark = TRUE;
10407
10408               if (sec->flags & SEC_MERGE)
10409                 merged = TRUE;
10410
10411               if (info->relocatable || info->emitrelocations)
10412                 reloc_count = sec->reloc_count;
10413               else if (bed->elf_backend_count_relocs)
10414                 reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
10415
10416               if (sec->rawsize > max_contents_size)
10417                 max_contents_size = sec->rawsize;
10418               if (sec->size > max_contents_size)
10419                 max_contents_size = sec->size;
10420
10421               /* We are interested in just local symbols, not all
10422                  symbols.  */
10423               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
10424                   && (sec->owner->flags & DYNAMIC) == 0)
10425                 {
10426                   size_t sym_count;
10427
10428                   if (elf_bad_symtab (sec->owner))
10429                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
10430                                  / bed->s->sizeof_sym);
10431                   else
10432                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
10433
10434                   if (sym_count > max_sym_count)
10435                     max_sym_count = sym_count;
10436
10437                   if (sym_count > max_sym_shndx_count
10438                       && elf_symtab_shndx (sec->owner) != 0)
10439                     max_sym_shndx_count = sym_count;
10440
10441                   if ((sec->flags & SEC_RELOC) != 0)
10442                     {
10443                       size_t ext_size = 0;
10444
10445                       if (esdi->rel.hdr != NULL)
10446                         ext_size = esdi->rel.hdr->sh_size;
10447                       if (esdi->rela.hdr != NULL)
10448                         ext_size += esdi->rela.hdr->sh_size;
10449
10450                       if (ext_size > max_external_reloc_size)
10451                         max_external_reloc_size = ext_size;
10452                       if (sec->reloc_count > max_internal_reloc_count)
10453                         max_internal_reloc_count = sec->reloc_count;
10454                     }
10455                 }
10456             }
10457
10458           if (reloc_count == 0)
10459             continue;
10460
10461           o->reloc_count += reloc_count;
10462
10463           if (p->type == bfd_indirect_link_order
10464               && (info->relocatable || info->emitrelocations))
10465             {
10466               if (esdi->rel.hdr)
10467                 esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
10468               if (esdi->rela.hdr)
10469                 esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
10470             }
10471           else
10472             {
10473               if (o->use_rela_p)
10474                 esdo->rela.count += reloc_count;
10475               else
10476                 esdo->rel.count += reloc_count;
10477             }
10478         }
10479
10480       if (o->reloc_count > 0)
10481         o->flags |= SEC_RELOC;
10482       else
10483         {
10484           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
10485              set it (this is probably a bug) and if it is set
10486              assign_section_numbers will create a reloc section.  */
10487           o->flags &=~ SEC_RELOC;
10488         }
10489
10490       /* If the SEC_ALLOC flag is not set, force the section VMA to
10491          zero.  This is done in elf_fake_sections as well, but forcing
10492          the VMA to 0 here will ensure that relocs against these
10493          sections are handled correctly.  */
10494       if ((o->flags & SEC_ALLOC) == 0
10495           && ! o->user_set_vma)
10496         o->vma = 0;
10497     }
10498
10499   if (! info->relocatable && merged)
10500     elf_link_hash_traverse (elf_hash_table (info),
10501                             _bfd_elf_link_sec_merge_syms, abfd);
10502
10503   /* Figure out the file positions for everything but the symbol table
10504      and the relocs.  We set symcount to force assign_section_numbers
10505      to create a symbol table.  */
10506   bfd_get_symcount (abfd) = info->strip == strip_all ? 0 : 1;
10507   BFD_ASSERT (! abfd->output_has_begun);
10508   if (! _bfd_elf_compute_section_file_positions (abfd, info))
10509     goto error_return;
10510
10511   /* Set sizes, and assign file positions for reloc sections.  */
10512   for (o = abfd->sections; o != NULL; o = o->next)
10513     {
10514       struct bfd_elf_section_data *esdo = elf_section_data (o);
10515       if ((o->flags & SEC_RELOC) != 0)
10516         {
10517           if (esdo->rel.hdr
10518               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
10519             goto error_return;
10520
10521           if (esdo->rela.hdr
10522               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
10523             goto error_return;
10524         }
10525
10526       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
10527          to count upwards while actually outputting the relocations.  */
10528       esdo->rel.count = 0;
10529       esdo->rela.count = 0;
10530     }
10531
10532   _bfd_elf_assign_file_positions_for_relocs (abfd);
10533
10534   /* We have now assigned file positions for all the sections except
10535      .symtab and .strtab.  We start the .symtab section at the current
10536      file position, and write directly to it.  We build the .strtab
10537      section in memory.  */
10538   bfd_get_symcount (abfd) = 0;
10539   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
10540   /* sh_name is set in prep_headers.  */
10541   symtab_hdr->sh_type = SHT_SYMTAB;
10542   /* sh_flags, sh_addr and sh_size all start off zero.  */
10543   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
10544   /* sh_link is set in assign_section_numbers.  */
10545   /* sh_info is set below.  */
10546   /* sh_offset is set just below.  */
10547   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
10548
10549   off = elf_tdata (abfd)->next_file_pos;
10550   off = _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
10551
10552   /* Note that at this point elf_tdata (abfd)->next_file_pos is
10553      incorrect.  We do not yet know the size of the .symtab section.
10554      We correct next_file_pos below, after we do know the size.  */
10555
10556   /* Allocate a buffer to hold swapped out symbols.  This is to avoid
10557      continuously seeking to the right position in the file.  */
10558   if (! info->keep_memory || max_sym_count < 20)
10559     finfo.symbuf_size = 20;
10560   else
10561     finfo.symbuf_size = max_sym_count;
10562   amt = finfo.symbuf_size;
10563   amt *= bed->s->sizeof_sym;
10564   finfo.symbuf = (bfd_byte *) bfd_malloc (amt);
10565   if (finfo.symbuf == NULL)
10566     goto error_return;
10567   if (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF))
10568     {
10569       /* Wild guess at number of output symbols.  realloc'd as needed.  */
10570       amt = 2 * max_sym_count + elf_numsections (abfd) + 1000;
10571       finfo.shndxbuf_size = amt;
10572       amt *= sizeof (Elf_External_Sym_Shndx);
10573       finfo.symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
10574       if (finfo.symshndxbuf == NULL)
10575         goto error_return;
10576     }
10577
10578   /* Start writing out the symbol table.  The first symbol is always a
10579      dummy symbol.  */
10580   if (info->strip != strip_all
10581       || emit_relocs)
10582     {
10583       elfsym.st_value = 0;
10584       elfsym.st_size = 0;
10585       elfsym.st_info = 0;
10586       elfsym.st_other = 0;
10587       elfsym.st_shndx = SHN_UNDEF;
10588       elfsym.st_target_internal = 0;
10589       if (elf_link_output_sym (&finfo, NULL, &elfsym, bfd_und_section_ptr,
10590                                NULL) != 1)
10591         goto error_return;
10592     }
10593
10594   /* Output a symbol for each section.  We output these even if we are
10595      discarding local symbols, since they are used for relocs.  These
10596      symbols have no names.  We store the index of each one in the
10597      index field of the section, so that we can find it again when
10598      outputting relocs.  */
10599   if (info->strip != strip_all
10600       || emit_relocs)
10601     {
10602       elfsym.st_size = 0;
10603       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
10604       elfsym.st_other = 0;
10605       elfsym.st_value = 0;
10606       elfsym.st_target_internal = 0;
10607       for (i = 1; i < elf_numsections (abfd); i++)
10608         {
10609           o = bfd_section_from_elf_index (abfd, i);
10610           if (o != NULL)
10611             {
10612               o->target_index = bfd_get_symcount (abfd);
10613               elfsym.st_shndx = i;
10614               if (!info->relocatable)
10615                 elfsym.st_value = o->vma;
10616               if (elf_link_output_sym (&finfo, NULL, &elfsym, o, NULL) != 1)
10617                 goto error_return;
10618             }
10619         }
10620     }
10621
10622   /* Allocate some memory to hold information read in from the input
10623      files.  */
10624   if (max_contents_size != 0)
10625     {
10626       finfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
10627       if (finfo.contents == NULL)
10628         goto error_return;
10629     }
10630
10631   if (max_external_reloc_size != 0)
10632     {
10633       finfo.external_relocs = bfd_malloc (max_external_reloc_size);
10634       if (finfo.external_relocs == NULL)
10635         goto error_return;
10636     }
10637
10638   if (max_internal_reloc_count != 0)
10639     {
10640       amt = max_internal_reloc_count * bed->s->int_rels_per_ext_rel;
10641       amt *= sizeof (Elf_Internal_Rela);
10642       finfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
10643       if (finfo.internal_relocs == NULL)
10644         goto error_return;
10645     }
10646
10647   if (max_sym_count != 0)
10648     {
10649       amt = max_sym_count * bed->s->sizeof_sym;
10650       finfo.external_syms = (bfd_byte *) bfd_malloc (amt);
10651       if (finfo.external_syms == NULL)
10652         goto error_return;
10653
10654       amt = max_sym_count * sizeof (Elf_Internal_Sym);
10655       finfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
10656       if (finfo.internal_syms == NULL)
10657         goto error_return;
10658
10659       amt = max_sym_count * sizeof (long);
10660       finfo.indices = (long int *) bfd_malloc (amt);
10661       if (finfo.indices == NULL)
10662         goto error_return;
10663
10664       amt = max_sym_count * sizeof (asection *);
10665       finfo.sections = (asection **) bfd_malloc (amt);
10666       if (finfo.sections == NULL)
10667         goto error_return;
10668     }
10669
10670   if (max_sym_shndx_count != 0)
10671     {
10672       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
10673       finfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
10674       if (finfo.locsym_shndx == NULL)
10675         goto error_return;
10676     }
10677
10678   if (elf_hash_table (info)->tls_sec)
10679     {
10680       bfd_vma base, end = 0;
10681       asection *sec;
10682
10683       for (sec = elf_hash_table (info)->tls_sec;
10684            sec && (sec->flags & SEC_THREAD_LOCAL);
10685            sec = sec->next)
10686         {
10687           bfd_size_type size = sec->size;
10688
10689           if (size == 0
10690               && (sec->flags & SEC_HAS_CONTENTS) == 0)
10691             {
10692               struct bfd_link_order *ord = sec->map_tail.link_order;
10693
10694               if (ord != NULL)
10695                 size = ord->offset + ord->size;
10696             }
10697           end = sec->vma + size;
10698         }
10699       base = elf_hash_table (info)->tls_sec->vma;
10700       /* Only align end of TLS section if static TLS doesn't have special
10701          alignment requirements.  */
10702       if (bed->static_tls_alignment == 1)
10703         end = align_power (end,
10704                            elf_hash_table (info)->tls_sec->alignment_power);
10705       elf_hash_table (info)->tls_size = end - base;
10706     }
10707
10708   /* Reorder SHF_LINK_ORDER sections.  */
10709   for (o = abfd->sections; o != NULL; o = o->next)
10710     {
10711       if (!elf_fixup_link_order (abfd, o))
10712         return FALSE;
10713     }
10714
10715   /* Since ELF permits relocations to be against local symbols, we
10716      must have the local symbols available when we do the relocations.
10717      Since we would rather only read the local symbols once, and we
10718      would rather not keep them in memory, we handle all the
10719      relocations for a single input file at the same time.
10720
10721      Unfortunately, there is no way to know the total number of local
10722      symbols until we have seen all of them, and the local symbol
10723      indices precede the global symbol indices.  This means that when
10724      we are generating relocatable output, and we see a reloc against
10725      a global symbol, we can not know the symbol index until we have
10726      finished examining all the local symbols to see which ones we are
10727      going to output.  To deal with this, we keep the relocations in
10728      memory, and don't output them until the end of the link.  This is
10729      an unfortunate waste of memory, but I don't see a good way around
10730      it.  Fortunately, it only happens when performing a relocatable
10731      link, which is not the common case.  FIXME: If keep_memory is set
10732      we could write the relocs out and then read them again; I don't
10733      know how bad the memory loss will be.  */
10734
10735   for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
10736     sub->output_has_begun = FALSE;
10737   for (o = abfd->sections; o != NULL; o = o->next)
10738     {
10739       for (p = o->map_head.link_order; p != NULL; p = p->next)
10740         {
10741           if (p->type == bfd_indirect_link_order
10742               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
10743                   == bfd_target_elf_flavour)
10744               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
10745             {
10746               if (! sub->output_has_begun)
10747                 {
10748                   if (! elf_link_input_bfd (&finfo, sub))
10749                     goto error_return;
10750                   sub->output_has_begun = TRUE;
10751                 }
10752             }
10753           else if (p->type == bfd_section_reloc_link_order
10754                    || p->type == bfd_symbol_reloc_link_order)
10755             {
10756               if (! elf_reloc_link_order (abfd, info, o, p))
10757                 goto error_return;
10758             }
10759           else
10760             {
10761               if (! _bfd_default_link_order (abfd, info, o, p))
10762                 {
10763                   if (p->type == bfd_indirect_link_order
10764                       && (bfd_get_flavour (sub)
10765                           == bfd_target_elf_flavour)
10766                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
10767                           != bed->s->elfclass))
10768                     {
10769                       const char *iclass, *oclass;
10770
10771                       if (bed->s->elfclass == ELFCLASS64)
10772                         {
10773                           iclass = "ELFCLASS32";
10774                           oclass = "ELFCLASS64";
10775                         }
10776                       else
10777                         {
10778                           iclass = "ELFCLASS64";
10779                           oclass = "ELFCLASS32";
10780                         }
10781
10782                       bfd_set_error (bfd_error_wrong_format);
10783                       (*_bfd_error_handler)
10784                         (_("%B: file class %s incompatible with %s"),
10785                          sub, iclass, oclass);
10786                     }
10787
10788                   goto error_return;
10789                 }
10790             }
10791         }
10792     }
10793
10794   /* Free symbol buffer if needed.  */
10795   if (!info->reduce_memory_overheads)
10796     {
10797       for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
10798         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
10799             && elf_tdata (sub)->symbuf)
10800           {
10801             free (elf_tdata (sub)->symbuf);
10802             elf_tdata (sub)->symbuf = NULL;
10803           }
10804     }
10805
10806   /* Output any global symbols that got converted to local in a
10807      version script or due to symbol visibility.  We do this in a
10808      separate step since ELF requires all local symbols to appear
10809      prior to any global symbols.  FIXME: We should only do this if
10810      some global symbols were, in fact, converted to become local.
10811      FIXME: Will this work correctly with the Irix 5 linker?  */
10812   eoinfo.failed = FALSE;
10813   eoinfo.finfo = &finfo;
10814   eoinfo.localsyms = TRUE;
10815   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
10816   if (eoinfo.failed)
10817     return FALSE;
10818
10819   /* If backend needs to output some local symbols not present in the hash
10820      table, do it now.  */
10821   if (bed->elf_backend_output_arch_local_syms)
10822     {
10823       typedef int (*out_sym_func)
10824         (void *, const char *, Elf_Internal_Sym *, asection *,
10825          struct elf_link_hash_entry *);
10826
10827       if (! ((*bed->elf_backend_output_arch_local_syms)
10828              (abfd, info, &finfo, (out_sym_func) elf_link_output_sym)))
10829         return FALSE;
10830     }
10831
10832   /* That wrote out all the local symbols.  Finish up the symbol table
10833      with the global symbols. Even if we want to strip everything we
10834      can, we still need to deal with those global symbols that got
10835      converted to local in a version script.  */
10836
10837   /* The sh_info field records the index of the first non local symbol.  */
10838   symtab_hdr->sh_info = bfd_get_symcount (abfd);
10839
10840   if (dynamic
10841       && finfo.dynsym_sec->output_section != bfd_abs_section_ptr)
10842     {
10843       Elf_Internal_Sym sym;
10844       bfd_byte *dynsym = finfo.dynsym_sec->contents;
10845       long last_local = 0;
10846
10847       /* Write out the section symbols for the output sections.  */
10848       if (info->shared || elf_hash_table (info)->is_relocatable_executable)
10849         {
10850           asection *s;
10851
10852           sym.st_size = 0;
10853           sym.st_name = 0;
10854           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
10855           sym.st_other = 0;
10856           sym.st_target_internal = 0;
10857
10858           for (s = abfd->sections; s != NULL; s = s->next)
10859             {
10860               int indx;
10861               bfd_byte *dest;
10862               long dynindx;
10863
10864               dynindx = elf_section_data (s)->dynindx;
10865               if (dynindx <= 0)
10866                 continue;
10867               indx = elf_section_data (s)->this_idx;
10868               BFD_ASSERT (indx > 0);
10869               sym.st_shndx = indx;
10870               if (! check_dynsym (abfd, &sym))
10871                 return FALSE;
10872               sym.st_value = s->vma;
10873               dest = dynsym + dynindx * bed->s->sizeof_sym;
10874               if (last_local < dynindx)
10875                 last_local = dynindx;
10876               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
10877             }
10878         }
10879
10880       /* Write out the local dynsyms.  */
10881       if (elf_hash_table (info)->dynlocal)
10882         {
10883           struct elf_link_local_dynamic_entry *e;
10884           for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
10885             {
10886               asection *s;
10887               bfd_byte *dest;
10888
10889               /* Copy the internal symbol and turn off visibility.
10890                  Note that we saved a word of storage and overwrote
10891                  the original st_name with the dynstr_index.  */
10892               sym = e->isym;
10893               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
10894
10895               s = bfd_section_from_elf_index (e->input_bfd,
10896                                               e->isym.st_shndx);
10897               if (s != NULL)
10898                 {
10899                   sym.st_shndx =
10900                     elf_section_data (s->output_section)->this_idx;
10901                   if (! check_dynsym (abfd, &sym))
10902                     return FALSE;
10903                   sym.st_value = (s->output_section->vma
10904                                   + s->output_offset
10905                                   + e->isym.st_value);
10906                 }
10907
10908               if (last_local < e->dynindx)
10909                 last_local = e->dynindx;
10910
10911               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
10912               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
10913             }
10914         }
10915
10916       elf_section_data (finfo.dynsym_sec->output_section)->this_hdr.sh_info =
10917         last_local + 1;
10918     }
10919
10920   /* We get the global symbols from the hash table.  */
10921   eoinfo.failed = FALSE;
10922   eoinfo.localsyms = FALSE;
10923   eoinfo.finfo = &finfo;
10924   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
10925   if (eoinfo.failed)
10926     return FALSE;
10927
10928   /* If backend needs to output some symbols not present in the hash
10929      table, do it now.  */
10930   if (bed->elf_backend_output_arch_syms)
10931     {
10932       typedef int (*out_sym_func)
10933         (void *, const char *, Elf_Internal_Sym *, asection *,
10934          struct elf_link_hash_entry *);
10935
10936       if (! ((*bed->elf_backend_output_arch_syms)
10937              (abfd, info, &finfo, (out_sym_func) elf_link_output_sym)))
10938         return FALSE;
10939     }
10940
10941   /* Flush all symbols to the file.  */
10942   if (! elf_link_flush_output_syms (&finfo, bed))
10943     return FALSE;
10944
10945   /* Now we know the size of the symtab section.  */
10946   off += symtab_hdr->sh_size;
10947
10948   symtab_shndx_hdr = &elf_tdata (abfd)->symtab_shndx_hdr;
10949   if (symtab_shndx_hdr->sh_name != 0)
10950     {
10951       symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
10952       symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
10953       symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
10954       amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
10955       symtab_shndx_hdr->sh_size = amt;
10956
10957       off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
10958                                                        off, TRUE);
10959
10960       if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
10961           || (bfd_bwrite (finfo.symshndxbuf, amt, abfd) != amt))
10962         return FALSE;
10963     }
10964
10965
10966   /* Finish up and write out the symbol string table (.strtab)
10967      section.  */
10968   symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
10969   /* sh_name was set in prep_headers.  */
10970   symstrtab_hdr->sh_type = SHT_STRTAB;
10971   symstrtab_hdr->sh_flags = 0;
10972   symstrtab_hdr->sh_addr = 0;
10973   symstrtab_hdr->sh_size = _bfd_stringtab_size (finfo.symstrtab);
10974   symstrtab_hdr->sh_entsize = 0;
10975   symstrtab_hdr->sh_link = 0;
10976   symstrtab_hdr->sh_info = 0;
10977   /* sh_offset is set just below.  */
10978   symstrtab_hdr->sh_addralign = 1;
10979
10980   off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr, off, TRUE);
10981   elf_tdata (abfd)->next_file_pos = off;
10982
10983   if (bfd_get_symcount (abfd) > 0)
10984     {
10985       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
10986           || ! _bfd_stringtab_emit (abfd, finfo.symstrtab))
10987         return FALSE;
10988     }
10989
10990   /* Adjust the relocs to have the correct symbol indices.  */
10991   for (o = abfd->sections; o != NULL; o = o->next)
10992     {
10993       struct bfd_elf_section_data *esdo = elf_section_data (o);
10994       if ((o->flags & SEC_RELOC) == 0)
10995         continue;
10996
10997       if (esdo->rel.hdr != NULL)
10998         elf_link_adjust_relocs (abfd, &esdo->rel);
10999       if (esdo->rela.hdr != NULL)
11000         elf_link_adjust_relocs (abfd, &esdo->rela);
11001
11002       /* Set the reloc_count field to 0 to prevent write_relocs from
11003          trying to swap the relocs out itself.  */
11004       o->reloc_count = 0;
11005     }
11006
11007   if (dynamic && info->combreloc && dynobj != NULL)
11008     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
11009
11010   /* If we are linking against a dynamic object, or generating a
11011      shared library, finish up the dynamic linking information.  */
11012   if (dynamic)
11013     {
11014       bfd_byte *dyncon, *dynconend;
11015
11016       /* Fix up .dynamic entries.  */
11017       o = bfd_get_section_by_name (dynobj, ".dynamic");
11018       BFD_ASSERT (o != NULL);
11019
11020       dyncon = o->contents;
11021       dynconend = o->contents + o->size;
11022       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11023         {
11024           Elf_Internal_Dyn dyn;
11025           const char *name;
11026           unsigned int type;
11027
11028           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11029
11030           switch (dyn.d_tag)
11031             {
11032             default:
11033               continue;
11034             case DT_NULL:
11035               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
11036                 {
11037                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
11038                     {
11039                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
11040                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
11041                     default: continue;
11042                     }
11043                   dyn.d_un.d_val = relativecount;
11044                   relativecount = 0;
11045                   break;
11046                 }
11047               continue;
11048
11049             case DT_INIT:
11050               name = info->init_function;
11051               goto get_sym;
11052             case DT_FINI:
11053               name = info->fini_function;
11054             get_sym:
11055               {
11056                 struct elf_link_hash_entry *h;
11057
11058                 h = elf_link_hash_lookup (elf_hash_table (info), name,
11059                                           FALSE, FALSE, TRUE);
11060                 if (h != NULL
11061                     && (h->root.type == bfd_link_hash_defined
11062                         || h->root.type == bfd_link_hash_defweak))
11063                   {
11064                     dyn.d_un.d_ptr = h->root.u.def.value;
11065                     o = h->root.u.def.section;
11066                     if (o->output_section != NULL)
11067                       dyn.d_un.d_ptr += (o->output_section->vma
11068                                          + o->output_offset);
11069                     else
11070                       {
11071                         /* The symbol is imported from another shared
11072                            library and does not apply to this one.  */
11073                         dyn.d_un.d_ptr = 0;
11074                       }
11075                     break;
11076                   }
11077               }
11078               continue;
11079
11080             case DT_PREINIT_ARRAYSZ:
11081               name = ".preinit_array";
11082               goto get_size;
11083             case DT_INIT_ARRAYSZ:
11084               name = ".init_array";
11085               goto get_size;
11086             case DT_FINI_ARRAYSZ:
11087               name = ".fini_array";
11088             get_size:
11089               o = bfd_get_section_by_name (abfd, name);
11090               if (o == NULL)
11091                 {
11092                   (*_bfd_error_handler)
11093                     (_("%B: could not find output section %s"), abfd, name);
11094                   goto error_return;
11095                 }
11096               if (o->size == 0)
11097                 (*_bfd_error_handler)
11098                   (_("warning: %s section has zero size"), name);
11099               dyn.d_un.d_val = o->size;
11100               break;
11101
11102             case DT_PREINIT_ARRAY:
11103               name = ".preinit_array";
11104               goto get_vma;
11105             case DT_INIT_ARRAY:
11106               name = ".init_array";
11107               goto get_vma;
11108             case DT_FINI_ARRAY:
11109               name = ".fini_array";
11110               goto get_vma;
11111
11112             case DT_HASH:
11113               name = ".hash";
11114               goto get_vma;
11115             case DT_GNU_HASH:
11116               name = ".gnu.hash";
11117               goto get_vma;
11118             case DT_STRTAB:
11119               name = ".dynstr";
11120               goto get_vma;
11121             case DT_SYMTAB:
11122               name = ".dynsym";
11123               goto get_vma;
11124             case DT_VERDEF:
11125               name = ".gnu.version_d";
11126               goto get_vma;
11127             case DT_VERNEED:
11128               name = ".gnu.version_r";
11129               goto get_vma;
11130             case DT_VERSYM:
11131               name = ".gnu.version";
11132             get_vma:
11133               o = bfd_get_section_by_name (abfd, name);
11134               if (o == NULL)
11135                 {
11136                   (*_bfd_error_handler)
11137                     (_("%B: could not find output section %s"), abfd, name);
11138                   goto error_return;
11139                 }
11140               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
11141                 {
11142                   (*_bfd_error_handler)
11143                     (_("warning: section '%s' is being made into a note"), name);
11144                   bfd_set_error (bfd_error_nonrepresentable_section);
11145                   goto error_return;
11146                 }
11147               dyn.d_un.d_ptr = o->vma;
11148               break;
11149
11150             case DT_REL:
11151             case DT_RELA:
11152             case DT_RELSZ:
11153             case DT_RELASZ:
11154               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
11155                 type = SHT_REL;
11156               else
11157                 type = SHT_RELA;
11158               dyn.d_un.d_val = 0;
11159               dyn.d_un.d_ptr = 0;
11160               for (i = 1; i < elf_numsections (abfd); i++)
11161                 {
11162                   Elf_Internal_Shdr *hdr;
11163
11164                   hdr = elf_elfsections (abfd)[i];
11165                   if (hdr->sh_type == type
11166                       && (hdr->sh_flags & SHF_ALLOC) != 0)
11167                     {
11168                       if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
11169                         dyn.d_un.d_val += hdr->sh_size;
11170                       else
11171                         {
11172                           if (dyn.d_un.d_ptr == 0
11173                               || hdr->sh_addr < dyn.d_un.d_ptr)
11174                             dyn.d_un.d_ptr = hdr->sh_addr;
11175                         }
11176                     }
11177                 }
11178               break;
11179             }
11180           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
11181         }
11182     }
11183
11184   /* If we have created any dynamic sections, then output them.  */
11185   if (dynobj != NULL)
11186     {
11187       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
11188         goto error_return;
11189
11190       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
11191       if ((info->warn_shared_textrel && info->shared)
11192           || info->error_textrel)
11193         {
11194           bfd_byte *dyncon, *dynconend;
11195
11196           /* Fix up .dynamic entries.  */
11197           o = bfd_get_section_by_name (dynobj, ".dynamic");
11198           BFD_ASSERT (o != NULL);
11199
11200           dyncon = o->contents;
11201           dynconend = o->contents + o->size;
11202           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11203             {
11204               Elf_Internal_Dyn dyn;
11205
11206               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11207
11208               if (dyn.d_tag == DT_TEXTREL)
11209                 {
11210                   if (info->error_textrel)
11211                     info->callbacks->einfo
11212                       (_("%P%X: read-only segment has dynamic relocations.\n"));
11213                   else
11214                     info->callbacks->einfo
11215                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
11216                   break;
11217                 }
11218             }
11219         }
11220
11221       for (o = dynobj->sections; o != NULL; o = o->next)
11222         {
11223           if ((o->flags & SEC_HAS_CONTENTS) == 0
11224               || o->size == 0
11225               || o->output_section == bfd_abs_section_ptr)
11226             continue;
11227           if ((o->flags & SEC_LINKER_CREATED) == 0)
11228             {
11229               /* At this point, we are only interested in sections
11230                  created by _bfd_elf_link_create_dynamic_sections.  */
11231               continue;
11232             }
11233           if (elf_hash_table (info)->stab_info.stabstr == o)
11234             continue;
11235           if (elf_hash_table (info)->eh_info.hdr_sec == o)
11236             continue;
11237           if ((elf_section_data (o->output_section)->this_hdr.sh_type
11238                != SHT_STRTAB)
11239               && (strcmp (bfd_get_section_name (abfd, o), ".dynstr") != 0))
11240             {
11241               /* FIXME: octets_per_byte.  */
11242               if (! bfd_set_section_contents (abfd, o->output_section,
11243                                               o->contents,
11244                                               (file_ptr) o->output_offset,
11245                                               o->size))
11246                 goto error_return;
11247             }
11248           else
11249             {
11250               /* The contents of the .dynstr section are actually in a
11251                  stringtab.  */
11252               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
11253               if (bfd_seek (abfd, off, SEEK_SET) != 0
11254                   || ! _bfd_elf_strtab_emit (abfd,
11255                                              elf_hash_table (info)->dynstr))
11256                 goto error_return;
11257             }
11258         }
11259     }
11260
11261   if (info->relocatable)
11262     {
11263       bfd_boolean failed = FALSE;
11264
11265       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
11266       if (failed)
11267         goto error_return;
11268     }
11269
11270   /* If we have optimized stabs strings, output them.  */
11271   if (elf_hash_table (info)->stab_info.stabstr != NULL)
11272     {
11273       if (! _bfd_write_stab_strings (abfd, &elf_hash_table (info)->stab_info))
11274         goto error_return;
11275     }
11276
11277   if (info->eh_frame_hdr)
11278     {
11279       if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
11280         goto error_return;
11281     }
11282
11283   if (finfo.symstrtab != NULL)
11284     _bfd_stringtab_free (finfo.symstrtab);
11285   if (finfo.contents != NULL)
11286     free (finfo.contents);
11287   if (finfo.external_relocs != NULL)
11288     free (finfo.external_relocs);
11289   if (finfo.internal_relocs != NULL)
11290     free (finfo.internal_relocs);
11291   if (finfo.external_syms != NULL)
11292     free (finfo.external_syms);
11293   if (finfo.locsym_shndx != NULL)
11294     free (finfo.locsym_shndx);
11295   if (finfo.internal_syms != NULL)
11296     free (finfo.internal_syms);
11297   if (finfo.indices != NULL)
11298     free (finfo.indices);
11299   if (finfo.sections != NULL)
11300     free (finfo.sections);
11301   if (finfo.symbuf != NULL)
11302     free (finfo.symbuf);
11303   if (finfo.symshndxbuf != NULL)
11304     free (finfo.symshndxbuf);
11305   for (o = abfd->sections; o != NULL; o = o->next)
11306     {
11307       struct bfd_elf_section_data *esdo = elf_section_data (o);
11308       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11309         free (esdo->rel.hashes);
11310       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11311         free (esdo->rela.hashes);
11312     }
11313
11314   elf_tdata (abfd)->linker = TRUE;
11315
11316   if (attr_section)
11317     {
11318       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
11319       if (contents == NULL)
11320         return FALSE;   /* Bail out and fail.  */
11321       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
11322       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
11323       free (contents);
11324     }
11325
11326   return TRUE;
11327
11328  error_return:
11329   if (finfo.symstrtab != NULL)
11330     _bfd_stringtab_free (finfo.symstrtab);
11331   if (finfo.contents != NULL)
11332     free (finfo.contents);
11333   if (finfo.external_relocs != NULL)
11334     free (finfo.external_relocs);
11335   if (finfo.internal_relocs != NULL)
11336     free (finfo.internal_relocs);
11337   if (finfo.external_syms != NULL)
11338     free (finfo.external_syms);
11339   if (finfo.locsym_shndx != NULL)
11340     free (finfo.locsym_shndx);
11341   if (finfo.internal_syms != NULL)
11342     free (finfo.internal_syms);
11343   if (finfo.indices != NULL)
11344     free (finfo.indices);
11345   if (finfo.sections != NULL)
11346     free (finfo.sections);
11347   if (finfo.symbuf != NULL)
11348     free (finfo.symbuf);
11349   if (finfo.symshndxbuf != NULL)
11350     free (finfo.symshndxbuf);
11351   for (o = abfd->sections; o != NULL; o = o->next)
11352     {
11353       struct bfd_elf_section_data *esdo = elf_section_data (o);
11354       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11355         free (esdo->rel.hashes);
11356       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11357         free (esdo->rela.hashes);
11358     }
11359
11360   return FALSE;
11361 }
11362 \f
11363 /* Initialize COOKIE for input bfd ABFD.  */
11364
11365 static bfd_boolean
11366 init_reloc_cookie (struct elf_reloc_cookie *cookie,
11367                    struct bfd_link_info *info, bfd *abfd)
11368 {
11369   Elf_Internal_Shdr *symtab_hdr;
11370   const struct elf_backend_data *bed;
11371
11372   bed = get_elf_backend_data (abfd);
11373   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11374
11375   cookie->abfd = abfd;
11376   cookie->sym_hashes = elf_sym_hashes (abfd);
11377   cookie->bad_symtab = elf_bad_symtab (abfd);
11378   if (cookie->bad_symtab)
11379     {
11380       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
11381       cookie->extsymoff = 0;
11382     }
11383   else
11384     {
11385       cookie->locsymcount = symtab_hdr->sh_info;
11386       cookie->extsymoff = symtab_hdr->sh_info;
11387     }
11388
11389   if (bed->s->arch_size == 32)
11390     cookie->r_sym_shift = 8;
11391   else
11392     cookie->r_sym_shift = 32;
11393
11394   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
11395   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
11396     {
11397       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
11398                                               cookie->locsymcount, 0,
11399                                               NULL, NULL, NULL);
11400       if (cookie->locsyms == NULL)
11401         {
11402           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
11403           return FALSE;
11404         }
11405       if (info->keep_memory)
11406         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
11407     }
11408   return TRUE;
11409 }
11410
11411 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
11412
11413 static void
11414 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
11415 {
11416   Elf_Internal_Shdr *symtab_hdr;
11417
11418   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11419   if (cookie->locsyms != NULL
11420       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
11421     free (cookie->locsyms);
11422 }
11423
11424 /* Initialize the relocation information in COOKIE for input section SEC
11425    of input bfd ABFD.  */
11426
11427 static bfd_boolean
11428 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
11429                         struct bfd_link_info *info, bfd *abfd,
11430                         asection *sec)
11431 {
11432   const struct elf_backend_data *bed;
11433
11434   if (sec->reloc_count == 0)
11435     {
11436       cookie->rels = NULL;
11437       cookie->relend = NULL;
11438     }
11439   else
11440     {
11441       bed = get_elf_backend_data (abfd);
11442
11443       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
11444                                                 info->keep_memory);
11445       if (cookie->rels == NULL)
11446         return FALSE;
11447       cookie->rel = cookie->rels;
11448       cookie->relend = (cookie->rels
11449                         + sec->reloc_count * bed->s->int_rels_per_ext_rel);
11450     }
11451   cookie->rel = cookie->rels;
11452   return TRUE;
11453 }
11454
11455 /* Free the memory allocated by init_reloc_cookie_rels,
11456    if appropriate.  */
11457
11458 static void
11459 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
11460                         asection *sec)
11461 {
11462   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
11463     free (cookie->rels);
11464 }
11465
11466 /* Initialize the whole of COOKIE for input section SEC.  */
11467
11468 static bfd_boolean
11469 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
11470                                struct bfd_link_info *info,
11471                                asection *sec)
11472 {
11473   if (!init_reloc_cookie (cookie, info, sec->owner))
11474     goto error1;
11475   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
11476     goto error2;
11477   return TRUE;
11478
11479  error2:
11480   fini_reloc_cookie (cookie, sec->owner);
11481  error1:
11482   return FALSE;
11483 }
11484
11485 /* Free the memory allocated by init_reloc_cookie_for_section,
11486    if appropriate.  */
11487
11488 static void
11489 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
11490                                asection *sec)
11491 {
11492   fini_reloc_cookie_rels (cookie, sec);
11493   fini_reloc_cookie (cookie, sec->owner);
11494 }
11495 \f
11496 /* Garbage collect unused sections.  */
11497
11498 /* Default gc_mark_hook.  */
11499
11500 asection *
11501 _bfd_elf_gc_mark_hook (asection *sec,
11502                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
11503                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
11504                        struct elf_link_hash_entry *h,
11505                        Elf_Internal_Sym *sym)
11506 {
11507   const char *sec_name;
11508
11509   if (h != NULL)
11510     {
11511       switch (h->root.type)
11512         {
11513         case bfd_link_hash_defined:
11514         case bfd_link_hash_defweak:
11515           return h->root.u.def.section;
11516
11517         case bfd_link_hash_common:
11518           return h->root.u.c.p->section;
11519
11520         case bfd_link_hash_undefined:
11521         case bfd_link_hash_undefweak:
11522           /* To work around a glibc bug, keep all XXX input sections
11523              when there is an as yet undefined reference to __start_XXX
11524              or __stop_XXX symbols.  The linker will later define such
11525              symbols for orphan input sections that have a name
11526              representable as a C identifier.  */
11527           if (strncmp (h->root.root.string, "__start_", 8) == 0)
11528             sec_name = h->root.root.string + 8;
11529           else if (strncmp (h->root.root.string, "__stop_", 7) == 0)
11530             sec_name = h->root.root.string + 7;
11531           else
11532             sec_name = NULL;
11533
11534           if (sec_name && *sec_name != '\0')
11535             {
11536               bfd *i;
11537               
11538               for (i = info->input_bfds; i; i = i->link_next)
11539                 {
11540                   sec = bfd_get_section_by_name (i, sec_name);
11541                   if (sec)
11542                     sec->flags |= SEC_KEEP;
11543                 }
11544             }
11545           break;
11546
11547         default:
11548           break;
11549         }
11550     }
11551   else
11552     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
11553
11554   return NULL;
11555 }
11556
11557 /* COOKIE->rel describes a relocation against section SEC, which is
11558    a section we've decided to keep.  Return the section that contains
11559    the relocation symbol, or NULL if no section contains it.  */
11560
11561 asection *
11562 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
11563                        elf_gc_mark_hook_fn gc_mark_hook,
11564                        struct elf_reloc_cookie *cookie)
11565 {
11566   unsigned long r_symndx;
11567   struct elf_link_hash_entry *h;
11568
11569   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
11570   if (r_symndx == STN_UNDEF)
11571     return NULL;
11572
11573   if (r_symndx >= cookie->locsymcount
11574       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
11575     {
11576       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
11577       while (h->root.type == bfd_link_hash_indirect
11578              || h->root.type == bfd_link_hash_warning)
11579         h = (struct elf_link_hash_entry *) h->root.u.i.link;
11580       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
11581     }
11582
11583   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
11584                           &cookie->locsyms[r_symndx]);
11585 }
11586
11587 /* COOKIE->rel describes a relocation against section SEC, which is
11588    a section we've decided to keep.  Mark the section that contains
11589    the relocation symbol.  */
11590
11591 bfd_boolean
11592 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
11593                         asection *sec,
11594                         elf_gc_mark_hook_fn gc_mark_hook,
11595                         struct elf_reloc_cookie *cookie)
11596 {
11597   asection *rsec;
11598
11599   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie);
11600   if (rsec && !rsec->gc_mark)
11601     {
11602       if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour)
11603         rsec->gc_mark = 1;
11604       else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
11605         return FALSE;
11606     }
11607   return TRUE;
11608 }
11609
11610 /* The mark phase of garbage collection.  For a given section, mark
11611    it and any sections in this section's group, and all the sections
11612    which define symbols to which it refers.  */
11613
11614 bfd_boolean
11615 _bfd_elf_gc_mark (struct bfd_link_info *info,
11616                   asection *sec,
11617                   elf_gc_mark_hook_fn gc_mark_hook)
11618 {
11619   bfd_boolean ret;
11620   asection *group_sec, *eh_frame;
11621
11622   sec->gc_mark = 1;
11623
11624   /* Mark all the sections in the group.  */
11625   group_sec = elf_section_data (sec)->next_in_group;
11626   if (group_sec && !group_sec->gc_mark)
11627     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
11628       return FALSE;
11629
11630   /* Look through the section relocs.  */
11631   ret = TRUE;
11632   eh_frame = elf_eh_frame_section (sec->owner);
11633   if ((sec->flags & SEC_RELOC) != 0
11634       && sec->reloc_count > 0
11635       && sec != eh_frame)
11636     {
11637       struct elf_reloc_cookie cookie;
11638
11639       if (!init_reloc_cookie_for_section (&cookie, info, sec))
11640         ret = FALSE;
11641       else
11642         {
11643           for (; cookie.rel < cookie.relend; cookie.rel++)
11644             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
11645               {
11646                 ret = FALSE;
11647                 break;
11648               }
11649           fini_reloc_cookie_for_section (&cookie, sec);
11650         }
11651     }
11652
11653   if (ret && eh_frame && elf_fde_list (sec))
11654     {
11655       struct elf_reloc_cookie cookie;
11656
11657       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
11658         ret = FALSE;
11659       else
11660         {
11661           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
11662                                       gc_mark_hook, &cookie))
11663             ret = FALSE;
11664           fini_reloc_cookie_for_section (&cookie, eh_frame);
11665         }
11666     }
11667
11668   return ret;
11669 }
11670
11671 /* Keep debug and special sections.  */
11672
11673 bfd_boolean
11674 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
11675                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
11676 {
11677   bfd *ibfd;
11678
11679   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link_next)
11680     {
11681       asection *isec;
11682       bfd_boolean some_kept;
11683
11684       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
11685         continue;
11686
11687       /* Ensure all linker created sections are kept, and see whether
11688          any other section is already marked.  */
11689       some_kept = FALSE;
11690       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
11691         {
11692           if ((isec->flags & SEC_LINKER_CREATED) != 0)
11693             isec->gc_mark = 1;
11694           else if (isec->gc_mark)
11695             some_kept = TRUE;
11696         }
11697
11698       /* If no section in this file will be kept, then we can
11699          toss out debug sections.  */
11700       if (!some_kept)
11701         continue;
11702
11703       /* Keep debug and special sections like .comment when they are
11704          not part of a group, or when we have single-member groups.  */
11705       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
11706         if ((elf_next_in_group (isec) == NULL
11707              || elf_next_in_group (isec) == isec)
11708             && ((isec->flags & SEC_DEBUGGING) != 0
11709                 || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0))
11710           isec->gc_mark = 1;
11711     }
11712   return TRUE;
11713 }
11714
11715 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
11716
11717 struct elf_gc_sweep_symbol_info
11718 {
11719   struct bfd_link_info *info;
11720   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
11721                        bfd_boolean);
11722 };
11723
11724 static bfd_boolean
11725 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
11726 {
11727   if ((h->root.type == bfd_link_hash_defined
11728        || h->root.type == bfd_link_hash_defweak)
11729       && !h->root.u.def.section->gc_mark
11730       && !(h->root.u.def.section->owner->flags & DYNAMIC))
11731     {
11732       struct elf_gc_sweep_symbol_info *inf =
11733           (struct elf_gc_sweep_symbol_info *) data;
11734       (*inf->hide_symbol) (inf->info, h, TRUE);
11735     }
11736
11737   return TRUE;
11738 }
11739
11740 /* The sweep phase of garbage collection.  Remove all garbage sections.  */
11741
11742 typedef bfd_boolean (*gc_sweep_hook_fn)
11743   (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
11744
11745 static bfd_boolean
11746 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
11747 {
11748   bfd *sub;
11749   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11750   gc_sweep_hook_fn gc_sweep_hook = bed->gc_sweep_hook;
11751   unsigned long section_sym_count;
11752   struct elf_gc_sweep_symbol_info sweep_info;
11753
11754   for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
11755     {
11756       asection *o;
11757
11758       if (bfd_get_flavour (sub) != bfd_target_elf_flavour)
11759         continue;
11760
11761       for (o = sub->sections; o != NULL; o = o->next)
11762         {
11763           /* When any section in a section group is kept, we keep all
11764              sections in the section group.  If the first member of
11765              the section group is excluded, we will also exclude the
11766              group section.  */
11767           if (o->flags & SEC_GROUP)
11768             {
11769               asection *first = elf_next_in_group (o);
11770               o->gc_mark = first->gc_mark;
11771             }
11772
11773           if (o->gc_mark)
11774             continue;
11775
11776           /* Skip sweeping sections already excluded.  */
11777           if (o->flags & SEC_EXCLUDE)
11778             continue;
11779
11780           /* Since this is early in the link process, it is simple
11781              to remove a section from the output.  */
11782           o->flags |= SEC_EXCLUDE;
11783
11784           if (info->print_gc_sections && o->size != 0)
11785             _bfd_error_handler (_("Removing unused section '%s' in file '%B'"), sub, o->name);
11786
11787           /* But we also have to update some of the relocation
11788              info we collected before.  */
11789           if (gc_sweep_hook
11790               && (o->flags & SEC_RELOC) != 0
11791               && o->reloc_count > 0
11792               && !bfd_is_abs_section (o->output_section))
11793             {
11794               Elf_Internal_Rela *internal_relocs;
11795               bfd_boolean r;
11796
11797               internal_relocs
11798                 = _bfd_elf_link_read_relocs (o->owner, o, NULL, NULL,
11799                                              info->keep_memory);
11800               if (internal_relocs == NULL)
11801                 return FALSE;
11802
11803               r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
11804
11805               if (elf_section_data (o)->relocs != internal_relocs)
11806                 free (internal_relocs);
11807
11808               if (!r)
11809                 return FALSE;
11810             }
11811         }
11812     }
11813
11814   /* Remove the symbols that were in the swept sections from the dynamic
11815      symbol table.  GCFIXME: Anyone know how to get them out of the
11816      static symbol table as well?  */
11817   sweep_info.info = info;
11818   sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
11819   elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
11820                           &sweep_info);
11821
11822   _bfd_elf_link_renumber_dynsyms (abfd, info, &section_sym_count);
11823   return TRUE;
11824 }
11825
11826 /* Propagate collected vtable information.  This is called through
11827    elf_link_hash_traverse.  */
11828
11829 static bfd_boolean
11830 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
11831 {
11832   /* Those that are not vtables.  */
11833   if (h->vtable == NULL || h->vtable->parent == NULL)
11834     return TRUE;
11835
11836   /* Those vtables that do not have parents, we cannot merge.  */
11837   if (h->vtable->parent == (struct elf_link_hash_entry *) -1)
11838     return TRUE;
11839
11840   /* If we've already been done, exit.  */
11841   if (h->vtable->used && h->vtable->used[-1])
11842     return TRUE;
11843
11844   /* Make sure the parent's table is up to date.  */
11845   elf_gc_propagate_vtable_entries_used (h->vtable->parent, okp);
11846
11847   if (h->vtable->used == NULL)
11848     {
11849       /* None of this table's entries were referenced.  Re-use the
11850          parent's table.  */
11851       h->vtable->used = h->vtable->parent->vtable->used;
11852       h->vtable->size = h->vtable->parent->vtable->size;
11853     }
11854   else
11855     {
11856       size_t n;
11857       bfd_boolean *cu, *pu;
11858
11859       /* Or the parent's entries into ours.  */
11860       cu = h->vtable->used;
11861       cu[-1] = TRUE;
11862       pu = h->vtable->parent->vtable->used;
11863       if (pu != NULL)
11864         {
11865           const struct elf_backend_data *bed;
11866           unsigned int log_file_align;
11867
11868           bed = get_elf_backend_data (h->root.u.def.section->owner);
11869           log_file_align = bed->s->log_file_align;
11870           n = h->vtable->parent->vtable->size >> log_file_align;
11871           while (n--)
11872             {
11873               if (*pu)
11874                 *cu = TRUE;
11875               pu++;
11876               cu++;
11877             }
11878         }
11879     }
11880
11881   return TRUE;
11882 }
11883
11884 static bfd_boolean
11885 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
11886 {
11887   asection *sec;
11888   bfd_vma hstart, hend;
11889   Elf_Internal_Rela *relstart, *relend, *rel;
11890   const struct elf_backend_data *bed;
11891   unsigned int log_file_align;
11892
11893   /* Take care of both those symbols that do not describe vtables as
11894      well as those that are not loaded.  */
11895   if (h->vtable == NULL || h->vtable->parent == NULL)
11896     return TRUE;
11897
11898   BFD_ASSERT (h->root.type == bfd_link_hash_defined
11899               || h->root.type == bfd_link_hash_defweak);
11900
11901   sec = h->root.u.def.section;
11902   hstart = h->root.u.def.value;
11903   hend = hstart + h->size;
11904
11905   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
11906   if (!relstart)
11907     return *(bfd_boolean *) okp = FALSE;
11908   bed = get_elf_backend_data (sec->owner);
11909   log_file_align = bed->s->log_file_align;
11910
11911   relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
11912
11913   for (rel = relstart; rel < relend; ++rel)
11914     if (rel->r_offset >= hstart && rel->r_offset < hend)
11915       {
11916         /* If the entry is in use, do nothing.  */
11917         if (h->vtable->used
11918             && (rel->r_offset - hstart) < h->vtable->size)
11919           {
11920             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
11921             if (h->vtable->used[entry])
11922               continue;
11923           }
11924         /* Otherwise, kill it.  */
11925         rel->r_offset = rel->r_info = rel->r_addend = 0;
11926       }
11927
11928   return TRUE;
11929 }
11930
11931 /* Mark sections containing dynamically referenced symbols.  When
11932    building shared libraries, we must assume that any visible symbol is
11933    referenced.  */
11934
11935 bfd_boolean
11936 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
11937 {
11938   struct bfd_link_info *info = (struct bfd_link_info *) inf;
11939
11940   if ((h->root.type == bfd_link_hash_defined
11941        || h->root.type == bfd_link_hash_defweak)
11942       && (h->ref_dynamic
11943           || ((!info->executable || info->export_dynamic)
11944               && h->def_regular
11945               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
11946               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
11947               && (strchr (h->root.root.string, ELF_VER_CHR) != NULL
11948                   || !bfd_hide_sym_by_version (info->version_info,
11949                                                h->root.root.string)))))
11950     h->root.u.def.section->flags |= SEC_KEEP;
11951
11952   return TRUE;
11953 }
11954
11955 /* Keep all sections containing symbols undefined on the command-line,
11956    and the section containing the entry symbol.  */
11957
11958 void
11959 _bfd_elf_gc_keep (struct bfd_link_info *info)
11960 {
11961   struct bfd_sym_chain *sym;
11962
11963   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
11964     {
11965       struct elf_link_hash_entry *h;
11966
11967       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
11968                                 FALSE, FALSE, FALSE);
11969
11970       if (h != NULL
11971           && (h->root.type == bfd_link_hash_defined
11972               || h->root.type == bfd_link_hash_defweak)
11973           && !bfd_is_abs_section (h->root.u.def.section))
11974         h->root.u.def.section->flags |= SEC_KEEP;
11975     }
11976 }
11977
11978 /* Do mark and sweep of unused sections.  */
11979
11980 bfd_boolean
11981 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
11982 {
11983   bfd_boolean ok = TRUE;
11984   bfd *sub;
11985   elf_gc_mark_hook_fn gc_mark_hook;
11986   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11987
11988   if (!bed->can_gc_sections
11989       || !is_elf_hash_table (info->hash))
11990     {
11991       (*_bfd_error_handler)(_("Warning: gc-sections option ignored"));
11992       return TRUE;
11993     }
11994
11995   bed->gc_keep (info);
11996
11997   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
11998      at the .eh_frame section if we can mark the FDEs individually.  */
11999   _bfd_elf_begin_eh_frame_parsing (info);
12000   for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
12001     {
12002       asection *sec;
12003       struct elf_reloc_cookie cookie;
12004
12005       sec = bfd_get_section_by_name (sub, ".eh_frame");
12006       if (sec && init_reloc_cookie_for_section (&cookie, info, sec))
12007         {
12008           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
12009           if (elf_section_data (sec)->sec_info)
12010             elf_eh_frame_section (sub) = sec;
12011           fini_reloc_cookie_for_section (&cookie, sec);
12012         }
12013     }
12014   _bfd_elf_end_eh_frame_parsing (info);
12015
12016   /* Apply transitive closure to the vtable entry usage info.  */
12017   elf_link_hash_traverse (elf_hash_table (info),
12018                           elf_gc_propagate_vtable_entries_used,
12019                           &ok);
12020   if (!ok)
12021     return FALSE;
12022
12023   /* Kill the vtable relocations that were not used.  */
12024   elf_link_hash_traverse (elf_hash_table (info),
12025                           elf_gc_smash_unused_vtentry_relocs,
12026                           &ok);
12027   if (!ok)
12028     return FALSE;
12029
12030   /* Mark dynamically referenced symbols.  */
12031   if (elf_hash_table (info)->dynamic_sections_created)
12032     elf_link_hash_traverse (elf_hash_table (info),
12033                             bed->gc_mark_dynamic_ref,
12034                             info);
12035
12036   /* Grovel through relocs to find out who stays ...  */
12037   gc_mark_hook = bed->gc_mark_hook;
12038   for (sub = info->input_bfds; sub != NULL; sub = sub->link_next)
12039     {
12040       asection *o;
12041
12042       if (bfd_get_flavour (sub) != bfd_target_elf_flavour)
12043         continue;
12044
12045       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
12046          Also treat note sections as a root, if the section is not part
12047          of a group.  */
12048       for (o = sub->sections; o != NULL; o = o->next)
12049         if (!o->gc_mark
12050             && (o->flags & SEC_EXCLUDE) == 0
12051             && ((o->flags & SEC_KEEP) != 0
12052                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
12053                     && elf_next_in_group (o) == NULL )))
12054           {
12055             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
12056               return FALSE;
12057           }
12058     }
12059
12060   /* Allow the backend to mark additional target specific sections.  */
12061   bed->gc_mark_extra_sections (info, gc_mark_hook);
12062
12063   /* ... and mark SEC_EXCLUDE for those that go.  */
12064   return elf_gc_sweep (abfd, info);
12065 }
12066 \f
12067 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
12068
12069 bfd_boolean
12070 bfd_elf_gc_record_vtinherit (bfd *abfd,
12071                              asection *sec,
12072                              struct elf_link_hash_entry *h,
12073                              bfd_vma offset)
12074 {
12075   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
12076   struct elf_link_hash_entry **search, *child;
12077   bfd_size_type extsymcount;
12078   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12079
12080   /* The sh_info field of the symtab header tells us where the
12081      external symbols start.  We don't care about the local symbols at
12082      this point.  */
12083   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
12084   if (!elf_bad_symtab (abfd))
12085     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
12086
12087   sym_hashes = elf_sym_hashes (abfd);
12088   sym_hashes_end = sym_hashes + extsymcount;
12089
12090   /* Hunt down the child symbol, which is in this section at the same
12091      offset as the relocation.  */
12092   for (search = sym_hashes; search != sym_hashes_end; ++search)
12093     {
12094       if ((child = *search) != NULL
12095           && (child->root.type == bfd_link_hash_defined
12096               || child->root.type == bfd_link_hash_defweak)
12097           && child->root.u.def.section == sec
12098           && child->root.u.def.value == offset)
12099         goto win;
12100     }
12101
12102   (*_bfd_error_handler) ("%B: %A+%lu: No symbol found for INHERIT",
12103                          abfd, sec, (unsigned long) offset);
12104   bfd_set_error (bfd_error_invalid_operation);
12105   return FALSE;
12106
12107  win:
12108   if (!child->vtable)
12109     {
12110       child->vtable = (struct elf_link_virtual_table_entry *)
12111           bfd_zalloc (abfd, sizeof (*child->vtable));
12112       if (!child->vtable)
12113         return FALSE;
12114     }
12115   if (!h)
12116     {
12117       /* This *should* only be the absolute section.  It could potentially
12118          be that someone has defined a non-global vtable though, which
12119          would be bad.  It isn't worth paging in the local symbols to be
12120          sure though; that case should simply be handled by the assembler.  */
12121
12122       child->vtable->parent = (struct elf_link_hash_entry *) -1;
12123     }
12124   else
12125     child->vtable->parent = h;
12126
12127   return TRUE;
12128 }
12129
12130 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
12131
12132 bfd_boolean
12133 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
12134                            asection *sec ATTRIBUTE_UNUSED,
12135                            struct elf_link_hash_entry *h,
12136                            bfd_vma addend)
12137 {
12138   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12139   unsigned int log_file_align = bed->s->log_file_align;
12140
12141   if (!h->vtable)
12142     {
12143       h->vtable = (struct elf_link_virtual_table_entry *)
12144           bfd_zalloc (abfd, sizeof (*h->vtable));
12145       if (!h->vtable)
12146         return FALSE;
12147     }
12148
12149   if (addend >= h->vtable->size)
12150     {
12151       size_t size, bytes, file_align;
12152       bfd_boolean *ptr = h->vtable->used;
12153
12154       /* While the symbol is undefined, we have to be prepared to handle
12155          a zero size.  */
12156       file_align = 1 << log_file_align;
12157       if (h->root.type == bfd_link_hash_undefined)
12158         size = addend + file_align;
12159       else
12160         {
12161           size = h->size;
12162           if (addend >= size)
12163             {
12164               /* Oops!  We've got a reference past the defined end of
12165                  the table.  This is probably a bug -- shall we warn?  */
12166               size = addend + file_align;
12167             }
12168         }
12169       size = (size + file_align - 1) & -file_align;
12170
12171       /* Allocate one extra entry for use as a "done" flag for the
12172          consolidation pass.  */
12173       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
12174
12175       if (ptr)
12176         {
12177           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
12178
12179           if (ptr != NULL)
12180             {
12181               size_t oldbytes;
12182
12183               oldbytes = (((h->vtable->size >> log_file_align) + 1)
12184                           * sizeof (bfd_boolean));
12185               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
12186             }
12187         }
12188       else
12189         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
12190
12191       if (ptr == NULL)
12192         return FALSE;
12193
12194       /* And arrange for that done flag to be at index -1.  */
12195       h->vtable->used = ptr + 1;
12196       h->vtable->size = size;
12197     }
12198
12199   h->vtable->used[addend >> log_file_align] = TRUE;
12200
12201   return TRUE;
12202 }
12203
12204 /* Map an ELF section header flag to its corresponding string.  */
12205 typedef struct
12206 {
12207   char *flag_name;
12208   flagword flag_value;
12209 } elf_flags_to_name_table;
12210
12211 static elf_flags_to_name_table elf_flags_to_names [] =
12212 {
12213   { "SHF_WRITE", SHF_WRITE },
12214   { "SHF_ALLOC", SHF_ALLOC },
12215   { "SHF_EXECINSTR", SHF_EXECINSTR },
12216   { "SHF_MERGE", SHF_MERGE },
12217   { "SHF_STRINGS", SHF_STRINGS },
12218   { "SHF_INFO_LINK", SHF_INFO_LINK},
12219   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
12220   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
12221   { "SHF_GROUP", SHF_GROUP },
12222   { "SHF_TLS", SHF_TLS },
12223   { "SHF_MASKOS", SHF_MASKOS },
12224   { "SHF_EXCLUDE", SHF_EXCLUDE },
12225 };
12226
12227 void
12228 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
12229                               struct flag_info *finfo)
12230 {
12231   bfd *output_bfd = info->output_bfd;
12232   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
12233   struct flag_info_list *tf = finfo->flag_list;
12234   int with_hex = 0;
12235   int without_hex = 0;
12236
12237   for (tf = finfo->flag_list; tf != NULL; tf = tf->next)
12238     {
12239       int i;
12240       if (bed->elf_backend_lookup_section_flags_hook)
12241         {
12242           flagword hexval =
12243              (*bed->elf_backend_lookup_section_flags_hook) ((char *) tf->name);
12244
12245           if (hexval != 0)
12246             {
12247               if (tf->with == with_flags)
12248                 with_hex |= hexval;
12249               else if (tf->with == without_flags)
12250                 without_hex |= hexval;
12251               tf->valid = TRUE;
12252               continue;
12253             }
12254         }
12255       for (i = 0; i < 12; i++)
12256         {
12257           if (!strcmp (tf->name, elf_flags_to_names[i].flag_name))
12258             {
12259               if (tf->with == with_flags)
12260                 with_hex |= elf_flags_to_names[i].flag_value;
12261               else if (tf->with == without_flags)
12262                 without_hex |= elf_flags_to_names[i].flag_value;
12263               tf->valid = TRUE;
12264               continue;
12265             }
12266         }
12267       if (tf->valid == FALSE)
12268         {
12269           info->callbacks->einfo 
12270                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
12271           return;
12272         }
12273     }
12274  finfo->flags_initialized = TRUE;
12275  finfo->only_with_flags |= with_hex;
12276  finfo->not_with_flags |= without_hex;
12277
12278  return;
12279 }
12280
12281 struct alloc_got_off_arg {
12282   bfd_vma gotoff;
12283   struct bfd_link_info *info;
12284 };
12285
12286 /* We need a special top-level link routine to convert got reference counts
12287    to real got offsets.  */
12288
12289 static bfd_boolean
12290 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
12291 {
12292   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
12293   bfd *obfd = gofarg->info->output_bfd;
12294   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
12295
12296   if (h->got.refcount > 0)
12297     {
12298       h->got.offset = gofarg->gotoff;
12299       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
12300     }
12301   else
12302     h->got.offset = (bfd_vma) -1;
12303
12304   return TRUE;
12305 }
12306
12307 /* And an accompanying bit to work out final got entry offsets once
12308    we're done.  Should be called from final_link.  */
12309
12310 bfd_boolean
12311 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
12312                                         struct bfd_link_info *info)
12313 {
12314   bfd *i;
12315   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12316   bfd_vma gotoff;
12317   struct alloc_got_off_arg gofarg;
12318
12319   BFD_ASSERT (abfd == info->output_bfd);
12320
12321   if (! is_elf_hash_table (info->hash))
12322     return FALSE;
12323
12324   /* The GOT offset is relative to the .got section, but the GOT header is
12325      put into the .got.plt section, if the backend uses it.  */
12326   if (bed->want_got_plt)
12327     gotoff = 0;
12328   else
12329     gotoff = bed->got_header_size;
12330
12331   /* Do the local .got entries first.  */
12332   for (i = info->input_bfds; i; i = i->link_next)
12333     {
12334       bfd_signed_vma *local_got;
12335       bfd_size_type j, locsymcount;
12336       Elf_Internal_Shdr *symtab_hdr;
12337
12338       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
12339         continue;
12340
12341       local_got = elf_local_got_refcounts (i);
12342       if (!local_got)
12343         continue;
12344
12345       symtab_hdr = &elf_tdata (i)->symtab_hdr;
12346       if (elf_bad_symtab (i))
12347         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12348       else
12349         locsymcount = symtab_hdr->sh_info;
12350
12351       for (j = 0; j < locsymcount; ++j)
12352         {
12353           if (local_got[j] > 0)
12354             {
12355               local_got[j] = gotoff;
12356               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
12357             }
12358           else
12359             local_got[j] = (bfd_vma) -1;
12360         }
12361     }
12362
12363   /* Then the global .got entries.  .plt refcounts are handled by
12364      adjust_dynamic_symbol  */
12365   gofarg.gotoff = gotoff;
12366   gofarg.info = info;
12367   elf_link_hash_traverse (elf_hash_table (info),
12368                           elf_gc_allocate_got_offsets,
12369                           &gofarg);
12370   return TRUE;
12371 }
12372
12373 /* Many folk need no more in the way of final link than this, once
12374    got entry reference counting is enabled.  */
12375
12376 bfd_boolean
12377 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
12378 {
12379   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
12380     return FALSE;
12381
12382   /* Invoke the regular ELF backend linker to do all the work.  */
12383   return bfd_elf_final_link (abfd, info);
12384 }
12385
12386 bfd_boolean
12387 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
12388 {
12389   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
12390
12391   if (rcookie->bad_symtab)
12392     rcookie->rel = rcookie->rels;
12393
12394   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
12395     {
12396       unsigned long r_symndx;
12397
12398       if (! rcookie->bad_symtab)
12399         if (rcookie->rel->r_offset > offset)
12400           return FALSE;
12401       if (rcookie->rel->r_offset != offset)
12402         continue;
12403
12404       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
12405       if (r_symndx == STN_UNDEF)
12406         return TRUE;
12407
12408       if (r_symndx >= rcookie->locsymcount
12409           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12410         {
12411           struct elf_link_hash_entry *h;
12412
12413           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
12414
12415           while (h->root.type == bfd_link_hash_indirect
12416                  || h->root.type == bfd_link_hash_warning)
12417             h = (struct elf_link_hash_entry *) h->root.u.i.link;
12418
12419           if ((h->root.type == bfd_link_hash_defined
12420                || h->root.type == bfd_link_hash_defweak)
12421               && elf_discarded_section (h->root.u.def.section))
12422             return TRUE;
12423           else
12424             return FALSE;
12425         }
12426       else
12427         {
12428           /* It's not a relocation against a global symbol,
12429              but it could be a relocation against a local
12430              symbol for a discarded section.  */
12431           asection *isec;
12432           Elf_Internal_Sym *isym;
12433
12434           /* Need to: get the symbol; get the section.  */
12435           isym = &rcookie->locsyms[r_symndx];
12436           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
12437           if (isec != NULL && elf_discarded_section (isec))
12438             return TRUE;
12439         }
12440       return FALSE;
12441     }
12442   return FALSE;
12443 }
12444
12445 /* Discard unneeded references to discarded sections.
12446    Returns TRUE if any section's size was changed.  */
12447 /* This function assumes that the relocations are in sorted order,
12448    which is true for all known assemblers.  */
12449
12450 bfd_boolean
12451 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
12452 {
12453   struct elf_reloc_cookie cookie;
12454   asection *stab, *eh;
12455   const struct elf_backend_data *bed;
12456   bfd *abfd;
12457   bfd_boolean ret = FALSE;
12458
12459   if (info->traditional_format
12460       || !is_elf_hash_table (info->hash))
12461     return FALSE;
12462
12463   _bfd_elf_begin_eh_frame_parsing (info);
12464   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link_next)
12465     {
12466       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
12467         continue;
12468
12469       bed = get_elf_backend_data (abfd);
12470
12471       if ((abfd->flags & DYNAMIC) != 0)
12472         continue;
12473
12474       eh = NULL;
12475       if (!info->relocatable)
12476         {
12477           eh = bfd_get_section_by_name (abfd, ".eh_frame");
12478           if (eh != NULL
12479               && (eh->size == 0
12480                   || bfd_is_abs_section (eh->output_section)))
12481             eh = NULL;
12482         }
12483
12484       stab = bfd_get_section_by_name (abfd, ".stab");
12485       if (stab != NULL
12486           && (stab->size == 0
12487               || bfd_is_abs_section (stab->output_section)
12488               || stab->sec_info_type != ELF_INFO_TYPE_STABS))
12489         stab = NULL;
12490
12491       if (stab == NULL
12492           && eh == NULL
12493           && bed->elf_backend_discard_info == NULL)
12494         continue;
12495
12496       if (!init_reloc_cookie (&cookie, info, abfd))
12497         return FALSE;
12498
12499       if (stab != NULL
12500           && stab->reloc_count > 0
12501           && init_reloc_cookie_rels (&cookie, info, abfd, stab))
12502         {
12503           if (_bfd_discard_section_stabs (abfd, stab,
12504                                           elf_section_data (stab)->sec_info,
12505                                           bfd_elf_reloc_symbol_deleted_p,
12506                                           &cookie))
12507             ret = TRUE;
12508           fini_reloc_cookie_rels (&cookie, stab);
12509         }
12510
12511       if (eh != NULL
12512           && init_reloc_cookie_rels (&cookie, info, abfd, eh))
12513         {
12514           _bfd_elf_parse_eh_frame (abfd, info, eh, &cookie);
12515           if (_bfd_elf_discard_section_eh_frame (abfd, info, eh,
12516                                                  bfd_elf_reloc_symbol_deleted_p,
12517                                                  &cookie))
12518             ret = TRUE;
12519           fini_reloc_cookie_rels (&cookie, eh);
12520         }
12521
12522       if (bed->elf_backend_discard_info != NULL
12523           && (*bed->elf_backend_discard_info) (abfd, &cookie, info))
12524         ret = TRUE;
12525
12526       fini_reloc_cookie (&cookie, abfd);
12527     }
12528   _bfd_elf_end_eh_frame_parsing (info);
12529
12530   if (info->eh_frame_hdr
12531       && !info->relocatable
12532       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
12533     ret = TRUE;
12534
12535   return ret;
12536 }
12537
12538 bfd_boolean
12539 _bfd_elf_section_already_linked (bfd *abfd,
12540                                  asection *sec,
12541                                  struct bfd_link_info *info)
12542 {
12543   flagword flags;
12544   const char *name, *key;
12545   struct bfd_section_already_linked *l;
12546   struct bfd_section_already_linked_hash_entry *already_linked_list;
12547
12548   if (sec->output_section == bfd_abs_section_ptr)
12549     return FALSE;
12550
12551   flags = sec->flags;
12552
12553   /* Return if it isn't a linkonce section.  A comdat group section
12554      also has SEC_LINK_ONCE set.  */
12555   if ((flags & SEC_LINK_ONCE) == 0)
12556     return FALSE;
12557
12558   /* Don't put group member sections on our list of already linked
12559      sections.  They are handled as a group via their group section.  */
12560   if (elf_sec_group (sec) != NULL)
12561     return FALSE;
12562
12563   /* For a SHT_GROUP section, use the group signature as the key.  */
12564   name = sec->name;
12565   if ((flags & SEC_GROUP) != 0
12566       && elf_next_in_group (sec) != NULL
12567       && elf_group_name (elf_next_in_group (sec)) != NULL)
12568     key = elf_group_name (elf_next_in_group (sec));
12569   else
12570     {
12571       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
12572       if (CONST_STRNEQ (name, ".gnu.linkonce.")
12573           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
12574         key++;
12575       else
12576         /* Must be a user linkonce section that doesn't follow gcc's
12577            naming convention.  In this case we won't be matching
12578            single member groups.  */
12579         key = name;
12580     }
12581
12582   already_linked_list = bfd_section_already_linked_table_lookup (key);
12583
12584   for (l = already_linked_list->entry; l != NULL; l = l->next)
12585     {
12586       /* We may have 2 different types of sections on the list: group
12587          sections with a signature of <key> (<key> is some string),
12588          and linkonce sections named .gnu.linkonce.<type>.<key>.
12589          Match like sections.  LTO plugin sections are an exception.
12590          They are always named .gnu.linkonce.t.<key> and match either
12591          type of section.  */
12592       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
12593            && ((flags & SEC_GROUP) != 0
12594                || strcmp (name, l->sec->name) == 0))
12595           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
12596         {
12597           /* The section has already been linked.  See if we should
12598              issue a warning.  */
12599           if (!_bfd_handle_already_linked (sec, l, info))
12600             return FALSE;
12601
12602           if (flags & SEC_GROUP)
12603             {
12604               asection *first = elf_next_in_group (sec);
12605               asection *s = first;
12606
12607               while (s != NULL)
12608                 {
12609                   s->output_section = bfd_abs_section_ptr;
12610                   /* Record which group discards it.  */
12611                   s->kept_section = l->sec;
12612                   s = elf_next_in_group (s);
12613                   /* These lists are circular.  */
12614                   if (s == first)
12615                     break;
12616                 }
12617             }
12618
12619           return TRUE;
12620         }
12621     }
12622
12623   /* A single member comdat group section may be discarded by a
12624      linkonce section and vice versa.  */
12625   if ((flags & SEC_GROUP) != 0)
12626     {
12627       asection *first = elf_next_in_group (sec);
12628
12629       if (first != NULL && elf_next_in_group (first) == first)
12630         /* Check this single member group against linkonce sections.  */
12631         for (l = already_linked_list->entry; l != NULL; l = l->next)
12632           if ((l->sec->flags & SEC_GROUP) == 0
12633               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
12634             {
12635               first->output_section = bfd_abs_section_ptr;
12636               first->kept_section = l->sec;
12637               sec->output_section = bfd_abs_section_ptr;
12638               break;
12639             }
12640     }
12641   else
12642     /* Check this linkonce section against single member groups.  */
12643     for (l = already_linked_list->entry; l != NULL; l = l->next)
12644       if (l->sec->flags & SEC_GROUP)
12645         {
12646           asection *first = elf_next_in_group (l->sec);
12647
12648           if (first != NULL
12649               && elf_next_in_group (first) == first
12650               && bfd_elf_match_symbols_in_sections (first, sec, info))
12651             {
12652               sec->output_section = bfd_abs_section_ptr;
12653               sec->kept_section = first;
12654               break;
12655             }
12656         }
12657
12658   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
12659      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
12660      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
12661      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
12662      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
12663      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
12664      `.gnu.linkonce.t.F' section from a different bfd not requiring any
12665      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
12666      The reverse order cannot happen as there is never a bfd with only the
12667      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
12668      matter as here were are looking only for cross-bfd sections.  */
12669
12670   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
12671     for (l = already_linked_list->entry; l != NULL; l = l->next)
12672       if ((l->sec->flags & SEC_GROUP) == 0
12673           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
12674         {
12675           if (abfd != l->sec->owner)
12676             sec->output_section = bfd_abs_section_ptr;
12677           break;
12678         }
12679
12680   /* This is the first section with this name.  Record it.  */
12681   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
12682     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
12683   return sec->output_section == bfd_abs_section_ptr;
12684 }
12685
12686 bfd_boolean
12687 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
12688 {
12689   return sym->st_shndx == SHN_COMMON;
12690 }
12691
12692 unsigned int
12693 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
12694 {
12695   return SHN_COMMON;
12696 }
12697
12698 asection *
12699 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
12700 {
12701   return bfd_com_section_ptr;
12702 }
12703
12704 bfd_vma
12705 _bfd_elf_default_got_elt_size (bfd *abfd,
12706                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
12707                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
12708                                bfd *ibfd ATTRIBUTE_UNUSED,
12709                                unsigned long symndx ATTRIBUTE_UNUSED)
12710 {
12711   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12712   return bed->s->arch_size / 8;
12713 }
12714
12715 /* Routines to support the creation of dynamic relocs.  */
12716
12717 /* Returns the name of the dynamic reloc section associated with SEC.  */
12718
12719 static const char *
12720 get_dynamic_reloc_section_name (bfd *       abfd,
12721                                 asection *  sec,
12722                                 bfd_boolean is_rela)
12723 {
12724   char *name;
12725   const char *old_name = bfd_get_section_name (NULL, sec);
12726   const char *prefix = is_rela ? ".rela" : ".rel";
12727
12728   if (old_name == NULL)
12729     return NULL;
12730
12731   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
12732   sprintf (name, "%s%s", prefix, old_name); 
12733
12734   return name;
12735 }
12736
12737 /* Returns the dynamic reloc section associated with SEC.
12738    If necessary compute the name of the dynamic reloc section based
12739    on SEC's name (looked up in ABFD's string table) and the setting
12740    of IS_RELA.  */
12741
12742 asection *
12743 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
12744                                     asection *  sec,
12745                                     bfd_boolean is_rela)
12746 {
12747   asection * reloc_sec = elf_section_data (sec)->sreloc;
12748
12749   if (reloc_sec == NULL)
12750     {
12751       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
12752
12753       if (name != NULL)
12754         {
12755           reloc_sec = bfd_get_section_by_name (abfd, name);
12756
12757           if (reloc_sec != NULL)
12758             elf_section_data (sec)->sreloc = reloc_sec;
12759         }
12760     }
12761
12762   return reloc_sec;
12763 }
12764
12765 /* Returns the dynamic reloc section associated with SEC.  If the
12766    section does not exist it is created and attached to the DYNOBJ
12767    bfd and stored in the SRELOC field of SEC's elf_section_data
12768    structure.
12769
12770    ALIGNMENT is the alignment for the newly created section and
12771    IS_RELA defines whether the name should be .rela.<SEC's name>
12772    or .rel.<SEC's name>.  The section name is looked up in the
12773    string table associated with ABFD.  */
12774
12775 asection *
12776 _bfd_elf_make_dynamic_reloc_section (asection *         sec,
12777                                      bfd *              dynobj,
12778                                      unsigned int       alignment,
12779                                      bfd *              abfd,
12780                                      bfd_boolean        is_rela)
12781 {
12782   asection * reloc_sec = elf_section_data (sec)->sreloc;
12783
12784   if (reloc_sec == NULL)
12785     {
12786       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
12787
12788       if (name == NULL)
12789         return NULL;
12790
12791       reloc_sec = bfd_get_section_by_name (dynobj, name);
12792
12793       if (reloc_sec == NULL)
12794         {
12795           flagword flags;
12796
12797           flags = (SEC_HAS_CONTENTS | SEC_READONLY | SEC_IN_MEMORY | SEC_LINKER_CREATED);
12798           if ((sec->flags & SEC_ALLOC) != 0)
12799             flags |= SEC_ALLOC | SEC_LOAD;
12800
12801           reloc_sec = bfd_make_section_with_flags (dynobj, name, flags);
12802           if (reloc_sec != NULL)
12803             {
12804               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
12805                 reloc_sec = NULL;
12806             }
12807         }
12808
12809       elf_section_data (sec)->sreloc = reloc_sec;
12810     }
12811
12812   return reloc_sec;
12813 }
12814
12815 /* Copy the ELF symbol type associated with a linker hash entry.  */
12816 void
12817 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd ATTRIBUTE_UNUSED,
12818     struct bfd_link_hash_entry * hdest,
12819     struct bfd_link_hash_entry * hsrc)
12820 {
12821   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *)hdest;
12822   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *)hsrc;
12823
12824   ehdest->type = ehsrc->type;
12825   ehdest->target_internal = ehsrc->target_internal;
12826 }
12827
12828 /* Append a RELA relocation REL to section S in BFD.  */
12829
12830 void
12831 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
12832 {
12833   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12834   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
12835   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
12836   bed->s->swap_reloca_out (abfd, rel, loc);
12837 }
12838
12839 /* Append a REL relocation REL to section S in BFD.  */
12840
12841 void
12842 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
12843 {
12844   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12845   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
12846   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
12847   bed->s->swap_reloca_out (abfd, rel, loc);
12848 }