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