a6b3c944080339c300badc18ace995a218a2572c
[external/binutils.git] / bfd / elflink.c
1 /* ELF linking support for BFD.
2    Copyright (C) 1995-2016 Free Software Foundation, Inc.
3
4    This file is part of BFD, the Binary File Descriptor library.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
19    MA 02110-1301, USA.  */
20
21 #include "sysdep.h"
22 #include "bfd.h"
23 #include "bfd_stdint.h"
24 #include "bfdlink.h"
25 #include "libbfd.h"
26 #define ARCH_SIZE 0
27 #include "elf-bfd.h"
28 #include "safe-ctype.h"
29 #include "libiberty.h"
30 #include "objalloc.h"
31
32 /* This struct is used to pass information to routines called via
33    elf_link_hash_traverse which must return failure.  */
34
35 struct elf_info_failed
36 {
37   struct bfd_link_info *info;
38   bfd_boolean failed;
39 };
40
41 /* This structure is used to pass information to
42    _bfd_elf_link_find_version_dependencies.  */
43
44 struct elf_find_verdep_info
45 {
46   /* General link information.  */
47   struct bfd_link_info *info;
48   /* The number of dependencies.  */
49   unsigned int vers;
50   /* Whether we had a failure.  */
51   bfd_boolean failed;
52 };
53
54 static bfd_boolean _bfd_elf_fix_symbol_flags
55   (struct elf_link_hash_entry *, struct elf_info_failed *);
56
57 asection *
58 _bfd_elf_section_for_symbol (struct elf_reloc_cookie *cookie,
59                              unsigned long r_symndx,
60                              bfd_boolean discard)
61 {
62   if (r_symndx >= cookie->locsymcount
63       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
64     {
65       struct elf_link_hash_entry *h;
66
67       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
68
69       while (h->root.type == bfd_link_hash_indirect
70              || h->root.type == bfd_link_hash_warning)
71         h = (struct elf_link_hash_entry *) h->root.u.i.link;
72
73       if ((h->root.type == bfd_link_hash_defined
74            || h->root.type == bfd_link_hash_defweak)
75            && discarded_section (h->root.u.def.section))
76         return h->root.u.def.section;
77       else
78         return NULL;
79     }
80   else
81     {
82       /* It's not a relocation against a global symbol,
83          but it could be a relocation against a local
84          symbol for a discarded section.  */
85       asection *isec;
86       Elf_Internal_Sym *isym;
87
88       /* Need to: get the symbol; get the section.  */
89       isym = &cookie->locsyms[r_symndx];
90       isec = bfd_section_from_elf_index (cookie->abfd, isym->st_shndx);
91       if (isec != NULL
92           && discard ? discarded_section (isec) : 1)
93         return isec;
94      }
95   return NULL;
96 }
97
98 /* Define a symbol in a dynamic linkage section.  */
99
100 struct elf_link_hash_entry *
101 _bfd_elf_define_linkage_sym (bfd *abfd,
102                              struct bfd_link_info *info,
103                              asection *sec,
104                              const char *name)
105 {
106   struct elf_link_hash_entry *h;
107   struct bfd_link_hash_entry *bh;
108   const struct elf_backend_data *bed;
109
110   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
111   if (h != NULL)
112     {
113       /* Zap symbol defined in an as-needed lib that wasn't linked.
114          This is a symptom of a larger problem:  Absolute symbols
115          defined in shared libraries can't be overridden, because we
116          lose the link to the bfd which is via the symbol section.  */
117       h->root.type = bfd_link_hash_new;
118     }
119
120   bh = &h->root;
121   bed = get_elf_backend_data (abfd);
122   if (!_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL,
123                                          sec, 0, NULL, FALSE, bed->collect,
124                                          &bh))
125     return NULL;
126   h = (struct elf_link_hash_entry *) bh;
127   h->def_regular = 1;
128   h->non_elf = 0;
129   h->root.linker_def = 1;
130   h->type = STT_OBJECT;
131   if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
132     h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
133
134   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
135   return h;
136 }
137
138 bfd_boolean
139 _bfd_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
140 {
141   flagword flags;
142   asection *s;
143   struct elf_link_hash_entry *h;
144   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
145   struct elf_link_hash_table *htab = elf_hash_table (info);
146
147   /* This function may be called more than once.  */
148   s = bfd_get_linker_section (abfd, ".got");
149   if (s != NULL)
150     return TRUE;
151
152   flags = bed->dynamic_sec_flags;
153
154   s = bfd_make_section_anyway_with_flags (abfd,
155                                           (bed->rela_plts_and_copies_p
156                                            ? ".rela.got" : ".rel.got"),
157                                           (bed->dynamic_sec_flags
158                                            | SEC_READONLY));
159   if (s == NULL
160       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
161     return FALSE;
162   htab->srelgot = s;
163
164   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
165   if (s == NULL
166       || !bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
167     return FALSE;
168   htab->sgot = s;
169
170   if (bed->want_got_plt)
171     {
172       s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
173       if (s == NULL
174           || !bfd_set_section_alignment (abfd, s,
175                                          bed->s->log_file_align))
176         return FALSE;
177       htab->sgotplt = s;
178     }
179
180   /* The first bit of the global offset table is the header.  */
181   s->size += bed->got_header_size;
182
183   if (bed->want_got_sym)
184     {
185       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
186          (or .got.plt) section.  We don't do this in the linker script
187          because we don't want to define the symbol if we are not creating
188          a global offset table.  */
189       h = _bfd_elf_define_linkage_sym (abfd, info, s,
190                                        "_GLOBAL_OFFSET_TABLE_");
191       elf_hash_table (info)->hgot = h;
192       if (h == NULL)
193         return FALSE;
194     }
195
196   return TRUE;
197 }
198 \f
199 /* Create a strtab to hold the dynamic symbol names.  */
200 static bfd_boolean
201 _bfd_elf_link_create_dynstrtab (bfd *abfd, struct bfd_link_info *info)
202 {
203   struct elf_link_hash_table *hash_table;
204
205   hash_table = elf_hash_table (info);
206   if (hash_table->dynobj == NULL)
207     {
208       /* We may not set dynobj, an input file holding linker created
209          dynamic sections to abfd, which may be a dynamic object with
210          its own dynamic sections.  We need to find a normal input file
211          to hold linker created sections if possible.  */
212       if ((abfd->flags & (DYNAMIC | BFD_PLUGIN)) != 0)
213         {
214           bfd *ibfd;
215           for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link.next)
216             if ((ibfd->flags
217                  & (DYNAMIC | BFD_LINKER_CREATED | BFD_PLUGIN)) == 0)
218               {
219                 abfd = ibfd;
220                 break;
221               }
222         }
223       hash_table->dynobj = abfd;
224     }
225
226   if (hash_table->dynstr == NULL)
227     {
228       hash_table->dynstr = _bfd_elf_strtab_init ();
229       if (hash_table->dynstr == NULL)
230         return FALSE;
231     }
232   return TRUE;
233 }
234
235 /* Create some sections which will be filled in with dynamic linking
236    information.  ABFD is an input file which requires dynamic sections
237    to be created.  The dynamic sections take up virtual memory space
238    when the final executable is run, so we need to create them before
239    addresses are assigned to the output sections.  We work out the
240    actual contents and size of these sections later.  */
241
242 bfd_boolean
243 _bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
244 {
245   flagword flags;
246   asection *s;
247   const struct elf_backend_data *bed;
248   struct elf_link_hash_entry *h;
249
250   if (! is_elf_hash_table (info->hash))
251     return FALSE;
252
253   if (elf_hash_table (info)->dynamic_sections_created)
254     return TRUE;
255
256   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
257     return FALSE;
258
259   abfd = elf_hash_table (info)->dynobj;
260   bed = get_elf_backend_data (abfd);
261
262   flags = bed->dynamic_sec_flags;
263
264   /* A dynamically linked executable has a .interp section, but a
265      shared library does not.  */
266   if (bfd_link_executable (info) && !info->nointerp)
267     {
268       s = bfd_make_section_anyway_with_flags (abfd, ".interp",
269                                               flags | SEC_READONLY);
270       if (s == NULL)
271         return FALSE;
272     }
273
274   /* Create sections to hold version informations.  These are removed
275      if they are not needed.  */
276   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_d",
277                                           flags | SEC_READONLY);
278   if (s == NULL
279       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
280     return FALSE;
281
282   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version",
283                                           flags | SEC_READONLY);
284   if (s == NULL
285       || ! bfd_set_section_alignment (abfd, s, 1))
286     return FALSE;
287
288   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_r",
289                                           flags | SEC_READONLY);
290   if (s == NULL
291       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
292     return FALSE;
293
294   s = bfd_make_section_anyway_with_flags (abfd, ".dynsym",
295                                           flags | SEC_READONLY);
296   if (s == NULL
297       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
298     return FALSE;
299   elf_hash_table (info)->dynsym = s;
300
301   s = bfd_make_section_anyway_with_flags (abfd, ".dynstr",
302                                           flags | SEC_READONLY);
303   if (s == NULL)
304     return FALSE;
305
306   s = bfd_make_section_anyway_with_flags (abfd, ".dynamic", flags);
307   if (s == NULL
308       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
309     return FALSE;
310
311   /* The special symbol _DYNAMIC is always set to the start of the
312      .dynamic section.  We could set _DYNAMIC in a linker script, but we
313      only want to define it if we are, in fact, creating a .dynamic
314      section.  We don't want to define it if there is no .dynamic
315      section, since on some ELF platforms the start up code examines it
316      to decide how to initialize the process.  */
317   h = _bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC");
318   elf_hash_table (info)->hdynamic = h;
319   if (h == NULL)
320     return FALSE;
321
322   if (info->emit_hash)
323     {
324       s = bfd_make_section_anyway_with_flags (abfd, ".hash",
325                                               flags | SEC_READONLY);
326       if (s == NULL
327           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
328         return FALSE;
329       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
330     }
331
332   if (info->emit_gnu_hash)
333     {
334       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
335                                               flags | SEC_READONLY);
336       if (s == NULL
337           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
338         return FALSE;
339       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
340          4 32-bit words followed by variable count of 64-bit words, then
341          variable count of 32-bit words.  */
342       if (bed->s->arch_size == 64)
343         elf_section_data (s)->this_hdr.sh_entsize = 0;
344       else
345         elf_section_data (s)->this_hdr.sh_entsize = 4;
346     }
347
348   /* Let the backend create the rest of the sections.  This lets the
349      backend set the right flags.  The backend will normally create
350      the .got and .plt sections.  */
351   if (bed->elf_backend_create_dynamic_sections == NULL
352       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
353     return FALSE;
354
355   elf_hash_table (info)->dynamic_sections_created = TRUE;
356
357   return TRUE;
358 }
359
360 /* Create dynamic sections when linking against a dynamic object.  */
361
362 bfd_boolean
363 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
364 {
365   flagword flags, pltflags;
366   struct elf_link_hash_entry *h;
367   asection *s;
368   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
369   struct elf_link_hash_table *htab = elf_hash_table (info);
370
371   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
372      .rel[a].bss sections.  */
373   flags = bed->dynamic_sec_flags;
374
375   pltflags = flags;
376   if (bed->plt_not_loaded)
377     /* We do not clear SEC_ALLOC here because we still want the OS to
378        allocate space for the section; it's just that there's nothing
379        to read in from the object file.  */
380     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
381   else
382     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
383   if (bed->plt_readonly)
384     pltflags |= SEC_READONLY;
385
386   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
387   if (s == NULL
388       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
389     return FALSE;
390   htab->splt = s;
391
392   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
393      .plt section.  */
394   if (bed->want_plt_sym)
395     {
396       h = _bfd_elf_define_linkage_sym (abfd, info, s,
397                                        "_PROCEDURE_LINKAGE_TABLE_");
398       elf_hash_table (info)->hplt = h;
399       if (h == NULL)
400         return FALSE;
401     }
402
403   s = bfd_make_section_anyway_with_flags (abfd,
404                                           (bed->rela_plts_and_copies_p
405                                            ? ".rela.plt" : ".rel.plt"),
406                                           flags | SEC_READONLY);
407   if (s == NULL
408       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
409     return FALSE;
410   htab->srelplt = s;
411
412   if (! _bfd_elf_create_got_section (abfd, info))
413     return FALSE;
414
415   if (bed->want_dynbss)
416     {
417       /* The .dynbss section is a place to put symbols which are defined
418          by dynamic objects, are referenced by regular objects, and are
419          not functions.  We must allocate space for them in the process
420          image and use a R_*_COPY reloc to tell the dynamic linker to
421          initialize them at run time.  The linker script puts the .dynbss
422          section into the .bss section of the final image.  */
423       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
424                                               (SEC_ALLOC | SEC_LINKER_CREATED));
425       if (s == NULL)
426         return FALSE;
427
428       /* The .rel[a].bss section holds copy relocs.  This section is not
429          normally needed.  We need to create it here, though, so that the
430          linker will map it to an output section.  We can't just create it
431          only if we need it, because we will not know whether we need it
432          until we have seen all the input files, and the first time the
433          main linker code calls BFD after examining all the input files
434          (size_dynamic_sections) the input sections have already been
435          mapped to the output sections.  If the section turns out not to
436          be needed, we can discard it later.  We will never need this
437          section when generating a shared object, since they do not use
438          copy relocs.  */
439       if (! bfd_link_pic (info))
440         {
441           s = bfd_make_section_anyway_with_flags (abfd,
442                                                   (bed->rela_plts_and_copies_p
443                                                    ? ".rela.bss" : ".rel.bss"),
444                                                   flags | SEC_READONLY);
445           if (s == NULL
446               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
447             return FALSE;
448         }
449     }
450
451   return TRUE;
452 }
453 \f
454 /* Record a new dynamic symbol.  We record the dynamic symbols as we
455    read the input files, since we need to have a list of all of them
456    before we can determine the final sizes of the output sections.
457    Note that we may actually call this function even though we are not
458    going to output any dynamic symbols; in some cases we know that a
459    symbol should be in the dynamic symbol table, but only if there is
460    one.  */
461
462 bfd_boolean
463 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
464                                     struct elf_link_hash_entry *h)
465 {
466   if (h->dynindx == -1)
467     {
468       struct elf_strtab_hash *dynstr;
469       char *p;
470       const char *name;
471       bfd_size_type indx;
472
473       /* XXX: The ABI draft says the linker must turn hidden and
474          internal symbols into STB_LOCAL symbols when producing the
475          DSO. However, if ld.so honors st_other in the dynamic table,
476          this would not be necessary.  */
477       switch (ELF_ST_VISIBILITY (h->other))
478         {
479         case STV_INTERNAL:
480         case STV_HIDDEN:
481           if (h->root.type != bfd_link_hash_undefined
482               && h->root.type != bfd_link_hash_undefweak)
483             {
484               h->forced_local = 1;
485               if (!elf_hash_table (info)->is_relocatable_executable)
486                 return TRUE;
487             }
488
489         default:
490           break;
491         }
492
493       h->dynindx = elf_hash_table (info)->dynsymcount;
494       ++elf_hash_table (info)->dynsymcount;
495
496       dynstr = elf_hash_table (info)->dynstr;
497       if (dynstr == NULL)
498         {
499           /* Create a strtab to hold the dynamic symbol names.  */
500           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
501           if (dynstr == NULL)
502             return FALSE;
503         }
504
505       /* We don't put any version information in the dynamic string
506          table.  */
507       name = h->root.root.string;
508       p = strchr (name, ELF_VER_CHR);
509       if (p != NULL)
510         /* We know that the p points into writable memory.  In fact,
511            there are only a few symbols that have read-only names, being
512            those like _GLOBAL_OFFSET_TABLE_ that are created specially
513            by the backends.  Most symbols will have names pointing into
514            an ELF string table read from a file, or to objalloc memory.  */
515         *p = 0;
516
517       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
518
519       if (p != NULL)
520         *p = ELF_VER_CHR;
521
522       if (indx == (bfd_size_type) -1)
523         return FALSE;
524       h->dynstr_index = indx;
525     }
526
527   return TRUE;
528 }
529 \f
530 /* Mark a symbol dynamic.  */
531
532 static void
533 bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
534                                   struct elf_link_hash_entry *h,
535                                   Elf_Internal_Sym *sym)
536 {
537   struct bfd_elf_dynamic_list *d = info->dynamic_list;
538
539   /* It may be called more than once on the same H.  */
540   if(h->dynamic || bfd_link_relocatable (info))
541     return;
542
543   if ((info->dynamic_data
544        && (h->type == STT_OBJECT
545            || h->type == STT_COMMON
546            || (sym != NULL
547                && (ELF_ST_TYPE (sym->st_info) == STT_OBJECT
548                    || ELF_ST_TYPE (sym->st_info) == STT_COMMON))))
549       || (d != NULL
550           && h->root.type == bfd_link_hash_new
551           && (*d->match) (&d->head, NULL, h->root.root.string)))
552     h->dynamic = 1;
553 }
554
555 /* Record an assignment to a symbol made by a linker script.  We need
556    this in case some dynamic object refers to this symbol.  */
557
558 bfd_boolean
559 bfd_elf_record_link_assignment (bfd *output_bfd,
560                                 struct bfd_link_info *info,
561                                 const char *name,
562                                 bfd_boolean provide,
563                                 bfd_boolean hidden)
564 {
565   struct elf_link_hash_entry *h, *hv;
566   struct elf_link_hash_table *htab;
567   const struct elf_backend_data *bed;
568
569   if (!is_elf_hash_table (info->hash))
570     return TRUE;
571
572   htab = elf_hash_table (info);
573   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
574   if (h == NULL)
575     return provide;
576
577   if (h->versioned == unknown)
578     {
579       /* Set versioned if symbol version is unknown.  */
580       char *version = strrchr (name, ELF_VER_CHR);
581       if (version)
582         {
583           if (version > name && version[-1] != ELF_VER_CHR)
584             h->versioned = versioned_hidden;
585           else
586             h->versioned = versioned;
587         }
588     }
589
590   switch (h->root.type)
591     {
592     case bfd_link_hash_defined:
593     case bfd_link_hash_defweak:
594     case bfd_link_hash_common:
595       break;
596     case bfd_link_hash_undefweak:
597     case bfd_link_hash_undefined:
598       /* Since we're defining the symbol, don't let it seem to have not
599          been defined.  record_dynamic_symbol and size_dynamic_sections
600          may depend on this.  */
601       h->root.type = bfd_link_hash_new;
602       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
603         bfd_link_repair_undef_list (&htab->root);
604       break;
605     case bfd_link_hash_new:
606       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
607       h->non_elf = 0;
608       break;
609     case bfd_link_hash_indirect:
610       /* We had a versioned symbol in a dynamic library.  We make the
611          the versioned symbol point to this one.  */
612       bed = get_elf_backend_data (output_bfd);
613       hv = h;
614       while (hv->root.type == bfd_link_hash_indirect
615              || hv->root.type == bfd_link_hash_warning)
616         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
617       /* We don't need to update h->root.u since linker will set them
618          later.  */
619       h->root.type = bfd_link_hash_undefined;
620       hv->root.type = bfd_link_hash_indirect;
621       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
622       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
623       break;
624     case bfd_link_hash_warning:
625       abort ();
626       break;
627     }
628
629   /* If this symbol is being provided by the linker script, and it is
630      currently defined by a dynamic object, but not by a regular
631      object, then mark it as undefined so that the generic linker will
632      force the correct value.  */
633   if (provide
634       && h->def_dynamic
635       && !h->def_regular)
636     h->root.type = bfd_link_hash_undefined;
637
638   /* If this symbol is not being provided by the linker script, and it is
639      currently defined by a dynamic object, but not by a regular object,
640      then clear out any version information because the symbol will not be
641      associated with the dynamic object any more.  */
642   if (!provide
643       && h->def_dynamic
644       && !h->def_regular)
645     h->verinfo.verdef = NULL;
646
647   h->def_regular = 1;
648
649   if (hidden)
650     {
651       bed = get_elf_backend_data (output_bfd);
652       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
653         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
654       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
655     }
656
657   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
658      and executables.  */
659   if (!bfd_link_relocatable (info)
660       && h->dynindx != -1
661       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
662           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
663     h->forced_local = 1;
664
665   if ((h->def_dynamic
666        || h->ref_dynamic
667        || bfd_link_dll (info)
668        || elf_hash_table (info)->is_relocatable_executable)
669       && h->dynindx == -1)
670     {
671       if (! bfd_elf_link_record_dynamic_symbol (info, h))
672         return FALSE;
673
674       /* If this is a weak defined symbol, and we know a corresponding
675          real symbol from the same dynamic object, make sure the real
676          symbol is also made into a dynamic symbol.  */
677       if (h->u.weakdef != NULL
678           && h->u.weakdef->dynindx == -1)
679         {
680           if (! bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
681             return FALSE;
682         }
683     }
684
685   return TRUE;
686 }
687
688 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
689    success, and 2 on a failure caused by attempting to record a symbol
690    in a discarded section, eg. a discarded link-once section symbol.  */
691
692 int
693 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
694                                           bfd *input_bfd,
695                                           long input_indx)
696 {
697   bfd_size_type amt;
698   struct elf_link_local_dynamic_entry *entry;
699   struct elf_link_hash_table *eht;
700   struct elf_strtab_hash *dynstr;
701   unsigned long dynstr_index;
702   char *name;
703   Elf_External_Sym_Shndx eshndx;
704   char esym[sizeof (Elf64_External_Sym)];
705
706   if (! is_elf_hash_table (info->hash))
707     return 0;
708
709   /* See if the entry exists already.  */
710   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
711     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
712       return 1;
713
714   amt = sizeof (*entry);
715   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
716   if (entry == NULL)
717     return 0;
718
719   /* Go find the symbol, so that we can find it's name.  */
720   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
721                              1, input_indx, &entry->isym, esym, &eshndx))
722     {
723       bfd_release (input_bfd, entry);
724       return 0;
725     }
726
727   if (entry->isym.st_shndx != SHN_UNDEF
728       && entry->isym.st_shndx < SHN_LORESERVE)
729     {
730       asection *s;
731
732       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
733       if (s == NULL || bfd_is_abs_section (s->output_section))
734         {
735           /* We can still bfd_release here as nothing has done another
736              bfd_alloc.  We can't do this later in this function.  */
737           bfd_release (input_bfd, entry);
738           return 2;
739         }
740     }
741
742   name = (bfd_elf_string_from_elf_section
743           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
744            entry->isym.st_name));
745
746   dynstr = elf_hash_table (info)->dynstr;
747   if (dynstr == NULL)
748     {
749       /* Create a strtab to hold the dynamic symbol names.  */
750       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
751       if (dynstr == NULL)
752         return 0;
753     }
754
755   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
756   if (dynstr_index == (unsigned long) -1)
757     return 0;
758   entry->isym.st_name = dynstr_index;
759
760   eht = elf_hash_table (info);
761
762   entry->next = eht->dynlocal;
763   eht->dynlocal = entry;
764   entry->input_bfd = input_bfd;
765   entry->input_indx = input_indx;
766   eht->dynsymcount++;
767
768   /* Whatever binding the symbol had before, it's now local.  */
769   entry->isym.st_info
770     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
771
772   /* The dynindx will be set at the end of size_dynamic_sections.  */
773
774   return 1;
775 }
776
777 /* Return the dynindex of a local dynamic symbol.  */
778
779 long
780 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
781                                     bfd *input_bfd,
782                                     long input_indx)
783 {
784   struct elf_link_local_dynamic_entry *e;
785
786   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
787     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
788       return e->dynindx;
789   return -1;
790 }
791
792 /* This function is used to renumber the dynamic symbols, if some of
793    them are removed because they are marked as local.  This is called
794    via elf_link_hash_traverse.  */
795
796 static bfd_boolean
797 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
798                                       void *data)
799 {
800   size_t *count = (size_t *) data;
801
802   if (h->forced_local)
803     return TRUE;
804
805   if (h->dynindx != -1)
806     h->dynindx = ++(*count);
807
808   return TRUE;
809 }
810
811
812 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
813    STB_LOCAL binding.  */
814
815 static bfd_boolean
816 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
817                                             void *data)
818 {
819   size_t *count = (size_t *) data;
820
821   if (!h->forced_local)
822     return TRUE;
823
824   if (h->dynindx != -1)
825     h->dynindx = ++(*count);
826
827   return TRUE;
828 }
829
830 /* Return true if the dynamic symbol for a given section should be
831    omitted when creating a shared library.  */
832 bfd_boolean
833 _bfd_elf_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED,
834                                    struct bfd_link_info *info,
835                                    asection *p)
836 {
837   struct elf_link_hash_table *htab;
838   asection *ip;
839
840   switch (elf_section_data (p)->this_hdr.sh_type)
841     {
842     case SHT_PROGBITS:
843     case SHT_NOBITS:
844       /* If sh_type is yet undecided, assume it could be
845          SHT_PROGBITS/SHT_NOBITS.  */
846     case SHT_NULL:
847       htab = elf_hash_table (info);
848       if (p == htab->tls_sec)
849         return FALSE;
850
851       if (htab->text_index_section != NULL)
852         return p != htab->text_index_section && p != htab->data_index_section;
853
854       return (htab->dynobj != NULL
855               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
856               && ip->output_section == p);
857
858       /* There shouldn't be section relative relocations
859          against any other section.  */
860     default:
861       return TRUE;
862     }
863 }
864
865 /* Assign dynsym indices.  In a shared library we generate a section
866    symbol for each output section, which come first.  Next come symbols
867    which have been forced to local binding.  Then all of the back-end
868    allocated local dynamic syms, followed by the rest of the global
869    symbols.  */
870
871 static unsigned long
872 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
873                                 struct bfd_link_info *info,
874                                 unsigned long *section_sym_count)
875 {
876   unsigned long dynsymcount = 0;
877
878   if (bfd_link_pic (info)
879       || elf_hash_table (info)->is_relocatable_executable)
880     {
881       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
882       asection *p;
883       for (p = output_bfd->sections; p ; p = p->next)
884         if ((p->flags & SEC_EXCLUDE) == 0
885             && (p->flags & SEC_ALLOC) != 0
886             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
887           elf_section_data (p)->dynindx = ++dynsymcount;
888         else
889           elf_section_data (p)->dynindx = 0;
890     }
891   *section_sym_count = dynsymcount;
892
893   elf_link_hash_traverse (elf_hash_table (info),
894                           elf_link_renumber_local_hash_table_dynsyms,
895                           &dynsymcount);
896
897   if (elf_hash_table (info)->dynlocal)
898     {
899       struct elf_link_local_dynamic_entry *p;
900       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
901         p->dynindx = ++dynsymcount;
902     }
903
904   elf_link_hash_traverse (elf_hash_table (info),
905                           elf_link_renumber_hash_table_dynsyms,
906                           &dynsymcount);
907
908   /* There is an unused NULL entry at the head of the table which we
909      must account for in our count even if the table is empty since it
910      is intended for the mandatory DT_SYMTAB tag (.dynsym section) in
911      .dynamic section.  */
912   dynsymcount++;
913
914   elf_hash_table (info)->dynsymcount = dynsymcount;
915   return dynsymcount;
916 }
917
918 /* Merge st_other field.  */
919
920 static void
921 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
922                     const Elf_Internal_Sym *isym, asection *sec,
923                     bfd_boolean definition, bfd_boolean dynamic)
924 {
925   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
926
927   /* If st_other has a processor-specific meaning, specific
928      code might be needed here.  */
929   if (bed->elf_backend_merge_symbol_attribute)
930     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
931                                                 dynamic);
932
933   if (!dynamic)
934     {
935       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
936       unsigned hvis = ELF_ST_VISIBILITY (h->other);
937
938       /* Keep the most constraining visibility.  Leave the remainder
939          of the st_other field to elf_backend_merge_symbol_attribute.  */
940       if (symvis - 1 < hvis - 1)
941         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
942     }
943   else if (definition
944            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
945            && (sec->flags & SEC_READONLY) == 0)
946     h->protected_def = 1;
947 }
948
949 /* This function is called when we want to merge a new symbol with an
950    existing symbol.  It handles the various cases which arise when we
951    find a definition in a dynamic object, or when there is already a
952    definition in a dynamic object.  The new symbol is described by
953    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
954    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
955    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
956    of an old common symbol.  We set OVERRIDE if the old symbol is
957    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
958    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
959    to change.  By OK to change, we mean that we shouldn't warn if the
960    type or size does change.  */
961
962 static bfd_boolean
963 _bfd_elf_merge_symbol (bfd *abfd,
964                        struct bfd_link_info *info,
965                        const char *name,
966                        Elf_Internal_Sym *sym,
967                        asection **psec,
968                        bfd_vma *pvalue,
969                        struct elf_link_hash_entry **sym_hash,
970                        bfd **poldbfd,
971                        bfd_boolean *pold_weak,
972                        unsigned int *pold_alignment,
973                        bfd_boolean *skip,
974                        bfd_boolean *override,
975                        bfd_boolean *type_change_ok,
976                        bfd_boolean *size_change_ok,
977                        bfd_boolean *matched)
978 {
979   asection *sec, *oldsec;
980   struct elf_link_hash_entry *h;
981   struct elf_link_hash_entry *hi;
982   struct elf_link_hash_entry *flip;
983   int bind;
984   bfd *oldbfd;
985   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
986   bfd_boolean newweak, oldweak, newfunc, oldfunc;
987   const struct elf_backend_data *bed;
988   char *new_version;
989
990   *skip = FALSE;
991   *override = FALSE;
992
993   sec = *psec;
994   bind = ELF_ST_BIND (sym->st_info);
995
996   if (! bfd_is_und_section (sec))
997     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
998   else
999     h = ((struct elf_link_hash_entry *)
1000          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
1001   if (h == NULL)
1002     return FALSE;
1003   *sym_hash = h;
1004
1005   bed = get_elf_backend_data (abfd);
1006
1007   /* NEW_VERSION is the symbol version of the new symbol.  */
1008   if (h->versioned != unversioned)
1009     {
1010       /* Symbol version is unknown or versioned.  */
1011       new_version = strrchr (name, ELF_VER_CHR);
1012       if (new_version)
1013         {
1014           if (h->versioned == unknown)
1015             {
1016               if (new_version > name && new_version[-1] != ELF_VER_CHR)
1017                 h->versioned = versioned_hidden;
1018               else
1019                 h->versioned = versioned;
1020             }
1021           new_version += 1;
1022           if (new_version[0] == '\0')
1023             new_version = NULL;
1024         }
1025       else
1026         h->versioned = unversioned;
1027     }
1028   else
1029     new_version = NULL;
1030
1031   /* For merging, we only care about real symbols.  But we need to make
1032      sure that indirect symbol dynamic flags are updated.  */
1033   hi = h;
1034   while (h->root.type == bfd_link_hash_indirect
1035          || h->root.type == bfd_link_hash_warning)
1036     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1037
1038   if (!*matched)
1039     {
1040       if (hi == h || h->root.type == bfd_link_hash_new)
1041         *matched = TRUE;
1042       else
1043         {
1044           /* OLD_HIDDEN is true if the existing symbol is only visible
1045              to the symbol with the same symbol version.  NEW_HIDDEN is
1046              true if the new symbol is only visible to the symbol with
1047              the same symbol version.  */
1048           bfd_boolean old_hidden = h->versioned == versioned_hidden;
1049           bfd_boolean new_hidden = hi->versioned == versioned_hidden;
1050           if (!old_hidden && !new_hidden)
1051             /* The new symbol matches the existing symbol if both
1052                aren't hidden.  */
1053             *matched = TRUE;
1054           else
1055             {
1056               /* OLD_VERSION is the symbol version of the existing
1057                  symbol. */
1058               char *old_version;
1059
1060               if (h->versioned >= versioned)
1061                 old_version = strrchr (h->root.root.string,
1062                                        ELF_VER_CHR) + 1;
1063               else
1064                  old_version = NULL;
1065
1066               /* The new symbol matches the existing symbol if they
1067                  have the same symbol version.  */
1068               *matched = (old_version == new_version
1069                           || (old_version != NULL
1070                               && new_version != NULL
1071                               && strcmp (old_version, new_version) == 0));
1072             }
1073         }
1074     }
1075
1076   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
1077      existing symbol.  */
1078
1079   oldbfd = NULL;
1080   oldsec = NULL;
1081   switch (h->root.type)
1082     {
1083     default:
1084       break;
1085
1086     case bfd_link_hash_undefined:
1087     case bfd_link_hash_undefweak:
1088       oldbfd = h->root.u.undef.abfd;
1089       break;
1090
1091     case bfd_link_hash_defined:
1092     case bfd_link_hash_defweak:
1093       oldbfd = h->root.u.def.section->owner;
1094       oldsec = h->root.u.def.section;
1095       break;
1096
1097     case bfd_link_hash_common:
1098       oldbfd = h->root.u.c.p->section->owner;
1099       oldsec = h->root.u.c.p->section;
1100       if (pold_alignment)
1101         *pold_alignment = h->root.u.c.p->alignment_power;
1102       break;
1103     }
1104   if (poldbfd && *poldbfd == NULL)
1105     *poldbfd = oldbfd;
1106
1107   /* Differentiate strong and weak symbols.  */
1108   newweak = bind == STB_WEAK;
1109   oldweak = (h->root.type == bfd_link_hash_defweak
1110              || h->root.type == bfd_link_hash_undefweak);
1111   if (pold_weak)
1112     *pold_weak = oldweak;
1113
1114   /* This code is for coping with dynamic objects, and is only useful
1115      if we are doing an ELF link.  */
1116   if (!(*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
1117     return TRUE;
1118
1119   /* We have to check it for every instance since the first few may be
1120      references and not all compilers emit symbol type for undefined
1121      symbols.  */
1122   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
1123
1124   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1125      respectively, is from a dynamic object.  */
1126
1127   newdyn = (abfd->flags & DYNAMIC) != 0;
1128
1129   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
1130      syms and defined syms in dynamic libraries respectively.
1131      ref_dynamic on the other hand can be set for a symbol defined in
1132      a dynamic library, and def_dynamic may not be set;  When the
1133      definition in a dynamic lib is overridden by a definition in the
1134      executable use of the symbol in the dynamic lib becomes a
1135      reference to the executable symbol.  */
1136   if (newdyn)
1137     {
1138       if (bfd_is_und_section (sec))
1139         {
1140           if (bind != STB_WEAK)
1141             {
1142               h->ref_dynamic_nonweak = 1;
1143               hi->ref_dynamic_nonweak = 1;
1144             }
1145         }
1146       else
1147         {
1148           /* Update the existing symbol only if they match. */
1149           if (*matched)
1150             h->dynamic_def = 1;
1151           hi->dynamic_def = 1;
1152         }
1153     }
1154
1155   /* If we just created the symbol, mark it as being an ELF symbol.
1156      Other than that, there is nothing to do--there is no merge issue
1157      with a newly defined symbol--so we just return.  */
1158
1159   if (h->root.type == bfd_link_hash_new)
1160     {
1161       h->non_elf = 0;
1162       return TRUE;
1163     }
1164
1165   /* In cases involving weak versioned symbols, we may wind up trying
1166      to merge a symbol with itself.  Catch that here, to avoid the
1167      confusion that results if we try to override a symbol with
1168      itself.  The additional tests catch cases like
1169      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1170      dynamic object, which we do want to handle here.  */
1171   if (abfd == oldbfd
1172       && (newweak || oldweak)
1173       && ((abfd->flags & DYNAMIC) == 0
1174           || !h->def_regular))
1175     return TRUE;
1176
1177   olddyn = FALSE;
1178   if (oldbfd != NULL)
1179     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1180   else if (oldsec != NULL)
1181     {
1182       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1183          indices used by MIPS ELF.  */
1184       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1185     }
1186
1187   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1188      respectively, appear to be a definition rather than reference.  */
1189
1190   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1191
1192   olddef = (h->root.type != bfd_link_hash_undefined
1193             && h->root.type != bfd_link_hash_undefweak
1194             && h->root.type != bfd_link_hash_common);
1195
1196   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1197      respectively, appear to be a function.  */
1198
1199   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1200              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1201
1202   oldfunc = (h->type != STT_NOTYPE
1203              && bed->is_function_type (h->type));
1204
1205   /* When we try to create a default indirect symbol from the dynamic
1206      definition with the default version, we skip it if its type and
1207      the type of existing regular definition mismatch.  */
1208   if (pold_alignment == NULL
1209       && newdyn
1210       && newdef
1211       && !olddyn
1212       && (((olddef || h->root.type == bfd_link_hash_common)
1213            && ELF_ST_TYPE (sym->st_info) != h->type
1214            && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1215            && h->type != STT_NOTYPE
1216            && !(newfunc && oldfunc))
1217           || (olddef
1218               && ((h->type == STT_GNU_IFUNC)
1219                   != (ELF_ST_TYPE (sym->st_info) == STT_GNU_IFUNC)))))
1220     {
1221       *skip = TRUE;
1222       return TRUE;
1223     }
1224
1225   /* Check TLS symbols.  We don't check undefined symbols introduced
1226      by "ld -u" which have no type (and oldbfd NULL), and we don't
1227      check symbols from plugins because they also have no type.  */
1228   if (oldbfd != NULL
1229       && (oldbfd->flags & BFD_PLUGIN) == 0
1230       && (abfd->flags & BFD_PLUGIN) == 0
1231       && ELF_ST_TYPE (sym->st_info) != h->type
1232       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1233     {
1234       bfd *ntbfd, *tbfd;
1235       bfd_boolean ntdef, tdef;
1236       asection *ntsec, *tsec;
1237
1238       if (h->type == STT_TLS)
1239         {
1240           ntbfd = abfd;
1241           ntsec = sec;
1242           ntdef = newdef;
1243           tbfd = oldbfd;
1244           tsec = oldsec;
1245           tdef = olddef;
1246         }
1247       else
1248         {
1249           ntbfd = oldbfd;
1250           ntsec = oldsec;
1251           ntdef = olddef;
1252           tbfd = abfd;
1253           tsec = sec;
1254           tdef = newdef;
1255         }
1256
1257       if (tdef && ntdef)
1258         (*_bfd_error_handler)
1259           (_("%s: TLS definition in %B section %A "
1260              "mismatches non-TLS definition in %B section %A"),
1261            tbfd, tsec, ntbfd, ntsec, h->root.root.string);
1262       else if (!tdef && !ntdef)
1263         (*_bfd_error_handler)
1264           (_("%s: TLS reference in %B "
1265              "mismatches non-TLS reference in %B"),
1266            tbfd, ntbfd, h->root.root.string);
1267       else if (tdef)
1268         (*_bfd_error_handler)
1269           (_("%s: TLS definition in %B section %A "
1270              "mismatches non-TLS reference in %B"),
1271            tbfd, tsec, ntbfd, h->root.root.string);
1272       else
1273         (*_bfd_error_handler)
1274           (_("%s: TLS reference in %B "
1275              "mismatches non-TLS definition in %B section %A"),
1276            tbfd, ntbfd, ntsec, h->root.root.string);
1277
1278       bfd_set_error (bfd_error_bad_value);
1279       return FALSE;
1280     }
1281
1282   /* If the old symbol has non-default visibility, we ignore the new
1283      definition from a dynamic object.  */
1284   if (newdyn
1285       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1286       && !bfd_is_und_section (sec))
1287     {
1288       *skip = TRUE;
1289       /* Make sure this symbol is dynamic.  */
1290       h->ref_dynamic = 1;
1291       hi->ref_dynamic = 1;
1292       /* A protected symbol has external availability. Make sure it is
1293          recorded as dynamic.
1294
1295          FIXME: Should we check type and size for protected symbol?  */
1296       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1297         return bfd_elf_link_record_dynamic_symbol (info, h);
1298       else
1299         return TRUE;
1300     }
1301   else if (!newdyn
1302            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1303            && h->def_dynamic)
1304     {
1305       /* If the new symbol with non-default visibility comes from a
1306          relocatable file and the old definition comes from a dynamic
1307          object, we remove the old definition.  */
1308       if (hi->root.type == bfd_link_hash_indirect)
1309         {
1310           /* Handle the case where the old dynamic definition is
1311              default versioned.  We need to copy the symbol info from
1312              the symbol with default version to the normal one if it
1313              was referenced before.  */
1314           if (h->ref_regular)
1315             {
1316               hi->root.type = h->root.type;
1317               h->root.type = bfd_link_hash_indirect;
1318               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1319
1320               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1321               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1322                 {
1323                   /* If the new symbol is hidden or internal, completely undo
1324                      any dynamic link state.  */
1325                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1326                   h->forced_local = 0;
1327                   h->ref_dynamic = 0;
1328                 }
1329               else
1330                 h->ref_dynamic = 1;
1331
1332               h->def_dynamic = 0;
1333               /* FIXME: Should we check type and size for protected symbol?  */
1334               h->size = 0;
1335               h->type = 0;
1336
1337               h = hi;
1338             }
1339           else
1340             h = hi;
1341         }
1342
1343       /* If the old symbol was undefined before, then it will still be
1344          on the undefs list.  If the new symbol is undefined or
1345          common, we can't make it bfd_link_hash_new here, because new
1346          undefined or common symbols will be added to the undefs list
1347          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1348          added twice to the undefs list.  Also, if the new symbol is
1349          undefweak then we don't want to lose the strong undef.  */
1350       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1351         {
1352           h->root.type = bfd_link_hash_undefined;
1353           h->root.u.undef.abfd = abfd;
1354         }
1355       else
1356         {
1357           h->root.type = bfd_link_hash_new;
1358           h->root.u.undef.abfd = NULL;
1359         }
1360
1361       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1362         {
1363           /* If the new symbol is hidden or internal, completely undo
1364              any dynamic link state.  */
1365           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1366           h->forced_local = 0;
1367           h->ref_dynamic = 0;
1368         }
1369       else
1370         h->ref_dynamic = 1;
1371       h->def_dynamic = 0;
1372       /* FIXME: Should we check type and size for protected symbol?  */
1373       h->size = 0;
1374       h->type = 0;
1375       return TRUE;
1376     }
1377
1378   /* If a new weak symbol definition comes from a regular file and the
1379      old symbol comes from a dynamic library, we treat the new one as
1380      strong.  Similarly, an old weak symbol definition from a regular
1381      file is treated as strong when the new symbol comes from a dynamic
1382      library.  Further, an old weak symbol from a dynamic library is
1383      treated as strong if the new symbol is from a dynamic library.
1384      This reflects the way glibc's ld.so works.
1385
1386      Do this before setting *type_change_ok or *size_change_ok so that
1387      we warn properly when dynamic library symbols are overridden.  */
1388
1389   if (newdef && !newdyn && olddyn)
1390     newweak = FALSE;
1391   if (olddef && newdyn)
1392     oldweak = FALSE;
1393
1394   /* Allow changes between different types of function symbol.  */
1395   if (newfunc && oldfunc)
1396     *type_change_ok = TRUE;
1397
1398   /* It's OK to change the type if either the existing symbol or the
1399      new symbol is weak.  A type change is also OK if the old symbol
1400      is undefined and the new symbol is defined.  */
1401
1402   if (oldweak
1403       || newweak
1404       || (newdef
1405           && h->root.type == bfd_link_hash_undefined))
1406     *type_change_ok = TRUE;
1407
1408   /* It's OK to change the size if either the existing symbol or the
1409      new symbol is weak, or if the old symbol is undefined.  */
1410
1411   if (*type_change_ok
1412       || h->root.type == bfd_link_hash_undefined)
1413     *size_change_ok = TRUE;
1414
1415   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1416      symbol, respectively, appears to be a common symbol in a dynamic
1417      object.  If a symbol appears in an uninitialized section, and is
1418      not weak, and is not a function, then it may be a common symbol
1419      which was resolved when the dynamic object was created.  We want
1420      to treat such symbols specially, because they raise special
1421      considerations when setting the symbol size: if the symbol
1422      appears as a common symbol in a regular object, and the size in
1423      the regular object is larger, we must make sure that we use the
1424      larger size.  This problematic case can always be avoided in C,
1425      but it must be handled correctly when using Fortran shared
1426      libraries.
1427
1428      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1429      likewise for OLDDYNCOMMON and OLDDEF.
1430
1431      Note that this test is just a heuristic, and that it is quite
1432      possible to have an uninitialized symbol in a shared object which
1433      is really a definition, rather than a common symbol.  This could
1434      lead to some minor confusion when the symbol really is a common
1435      symbol in some regular object.  However, I think it will be
1436      harmless.  */
1437
1438   if (newdyn
1439       && newdef
1440       && !newweak
1441       && (sec->flags & SEC_ALLOC) != 0
1442       && (sec->flags & SEC_LOAD) == 0
1443       && sym->st_size > 0
1444       && !newfunc)
1445     newdyncommon = TRUE;
1446   else
1447     newdyncommon = FALSE;
1448
1449   if (olddyn
1450       && olddef
1451       && h->root.type == bfd_link_hash_defined
1452       && h->def_dynamic
1453       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1454       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1455       && h->size > 0
1456       && !oldfunc)
1457     olddyncommon = TRUE;
1458   else
1459     olddyncommon = FALSE;
1460
1461   /* We now know everything about the old and new symbols.  We ask the
1462      backend to check if we can merge them.  */
1463   if (bed->merge_symbol != NULL)
1464     {
1465       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1466         return FALSE;
1467       sec = *psec;
1468     }
1469
1470   /* If both the old and the new symbols look like common symbols in a
1471      dynamic object, set the size of the symbol to the larger of the
1472      two.  */
1473
1474   if (olddyncommon
1475       && newdyncommon
1476       && sym->st_size != h->size)
1477     {
1478       /* Since we think we have two common symbols, issue a multiple
1479          common warning if desired.  Note that we only warn if the
1480          size is different.  If the size is the same, we simply let
1481          the old symbol override the new one as normally happens with
1482          symbols defined in dynamic objects.  */
1483
1484       if (! ((*info->callbacks->multiple_common)
1485              (info, &h->root, abfd, bfd_link_hash_common, sym->st_size)))
1486         return FALSE;
1487
1488       if (sym->st_size > h->size)
1489         h->size = sym->st_size;
1490
1491       *size_change_ok = TRUE;
1492     }
1493
1494   /* If we are looking at a dynamic object, and we have found a
1495      definition, we need to see if the symbol was already defined by
1496      some other object.  If so, we want to use the existing
1497      definition, and we do not want to report a multiple symbol
1498      definition error; we do this by clobbering *PSEC to be
1499      bfd_und_section_ptr.
1500
1501      We treat a common symbol as a definition if the symbol in the
1502      shared library is a function, since common symbols always
1503      represent variables; this can cause confusion in principle, but
1504      any such confusion would seem to indicate an erroneous program or
1505      shared library.  We also permit a common symbol in a regular
1506      object to override a weak symbol in a shared object.  A common
1507      symbol in executable also overrides a symbol in a shared object.  */
1508
1509   if (newdyn
1510       && newdef
1511       && (olddef
1512           || (h->root.type == bfd_link_hash_common
1513               && (newweak
1514                   || newfunc
1515                   || (!olddyn && bfd_link_executable (info))))))
1516     {
1517       *override = TRUE;
1518       newdef = FALSE;
1519       newdyncommon = FALSE;
1520
1521       *psec = sec = bfd_und_section_ptr;
1522       *size_change_ok = TRUE;
1523
1524       /* If we get here when the old symbol is a common symbol, then
1525          we are explicitly letting it override a weak symbol or
1526          function in a dynamic object, and we don't want to warn about
1527          a type change.  If the old symbol is a defined symbol, a type
1528          change warning may still be appropriate.  */
1529
1530       if (h->root.type == bfd_link_hash_common)
1531         *type_change_ok = TRUE;
1532     }
1533
1534   /* Handle the special case of an old common symbol merging with a
1535      new symbol which looks like a common symbol in a shared object.
1536      We change *PSEC and *PVALUE to make the new symbol look like a
1537      common symbol, and let _bfd_generic_link_add_one_symbol do the
1538      right thing.  */
1539
1540   if (newdyncommon
1541       && h->root.type == bfd_link_hash_common)
1542     {
1543       *override = TRUE;
1544       newdef = FALSE;
1545       newdyncommon = FALSE;
1546       *pvalue = sym->st_size;
1547       *psec = sec = bed->common_section (oldsec);
1548       *size_change_ok = TRUE;
1549     }
1550
1551   /* Skip weak definitions of symbols that are already defined.  */
1552   if (newdef && olddef && newweak)
1553     {
1554       /* Don't skip new non-IR weak syms.  */
1555       if (!(oldbfd != NULL
1556             && (oldbfd->flags & BFD_PLUGIN) != 0
1557             && (abfd->flags & BFD_PLUGIN) == 0))
1558         {
1559           newdef = FALSE;
1560           *skip = TRUE;
1561         }
1562
1563       /* Merge st_other.  If the symbol already has a dynamic index,
1564          but visibility says it should not be visible, turn it into a
1565          local symbol.  */
1566       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1567       if (h->dynindx != -1)
1568         switch (ELF_ST_VISIBILITY (h->other))
1569           {
1570           case STV_INTERNAL:
1571           case STV_HIDDEN:
1572             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1573             break;
1574           }
1575     }
1576
1577   /* If the old symbol is from a dynamic object, and the new symbol is
1578      a definition which is not from a dynamic object, then the new
1579      symbol overrides the old symbol.  Symbols from regular files
1580      always take precedence over symbols from dynamic objects, even if
1581      they are defined after the dynamic object in the link.
1582
1583      As above, we again permit a common symbol in a regular object to
1584      override a definition in a shared object if the shared object
1585      symbol is a function or is weak.  */
1586
1587   flip = NULL;
1588   if (!newdyn
1589       && (newdef
1590           || (bfd_is_com_section (sec)
1591               && (oldweak || oldfunc)))
1592       && olddyn
1593       && olddef
1594       && h->def_dynamic)
1595     {
1596       /* Change the hash table entry to undefined, and let
1597          _bfd_generic_link_add_one_symbol do the right thing with the
1598          new definition.  */
1599
1600       h->root.type = bfd_link_hash_undefined;
1601       h->root.u.undef.abfd = h->root.u.def.section->owner;
1602       *size_change_ok = TRUE;
1603
1604       olddef = FALSE;
1605       olddyncommon = FALSE;
1606
1607       /* We again permit a type change when a common symbol may be
1608          overriding a function.  */
1609
1610       if (bfd_is_com_section (sec))
1611         {
1612           if (oldfunc)
1613             {
1614               /* If a common symbol overrides a function, make sure
1615                  that it isn't defined dynamically nor has type
1616                  function.  */
1617               h->def_dynamic = 0;
1618               h->type = STT_NOTYPE;
1619             }
1620           *type_change_ok = TRUE;
1621         }
1622
1623       if (hi->root.type == bfd_link_hash_indirect)
1624         flip = hi;
1625       else
1626         /* This union may have been set to be non-NULL when this symbol
1627            was seen in a dynamic object.  We must force the union to be
1628            NULL, so that it is correct for a regular symbol.  */
1629         h->verinfo.vertree = NULL;
1630     }
1631
1632   /* Handle the special case of a new common symbol merging with an
1633      old symbol that looks like it might be a common symbol defined in
1634      a shared object.  Note that we have already handled the case in
1635      which a new common symbol should simply override the definition
1636      in the shared library.  */
1637
1638   if (! newdyn
1639       && bfd_is_com_section (sec)
1640       && olddyncommon)
1641     {
1642       /* It would be best if we could set the hash table entry to a
1643          common symbol, but we don't know what to use for the section
1644          or the alignment.  */
1645       if (! ((*info->callbacks->multiple_common)
1646              (info, &h->root, abfd, bfd_link_hash_common, sym->st_size)))
1647         return FALSE;
1648
1649       /* If the presumed common symbol in the dynamic object is
1650          larger, pretend that the new symbol has its size.  */
1651
1652       if (h->size > *pvalue)
1653         *pvalue = h->size;
1654
1655       /* We need to remember the alignment required by the symbol
1656          in the dynamic object.  */
1657       BFD_ASSERT (pold_alignment);
1658       *pold_alignment = h->root.u.def.section->alignment_power;
1659
1660       olddef = FALSE;
1661       olddyncommon = FALSE;
1662
1663       h->root.type = bfd_link_hash_undefined;
1664       h->root.u.undef.abfd = h->root.u.def.section->owner;
1665
1666       *size_change_ok = TRUE;
1667       *type_change_ok = TRUE;
1668
1669       if (hi->root.type == bfd_link_hash_indirect)
1670         flip = hi;
1671       else
1672         h->verinfo.vertree = NULL;
1673     }
1674
1675   if (flip != NULL)
1676     {
1677       /* Handle the case where we had a versioned symbol in a dynamic
1678          library and now find a definition in a normal object.  In this
1679          case, we make the versioned symbol point to the normal one.  */
1680       flip->root.type = h->root.type;
1681       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1682       h->root.type = bfd_link_hash_indirect;
1683       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1684       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1685       if (h->def_dynamic)
1686         {
1687           h->def_dynamic = 0;
1688           flip->ref_dynamic = 1;
1689         }
1690     }
1691
1692   return TRUE;
1693 }
1694
1695 /* This function is called to create an indirect symbol from the
1696    default for the symbol with the default version if needed. The
1697    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1698    set DYNSYM if the new indirect symbol is dynamic.  */
1699
1700 static bfd_boolean
1701 _bfd_elf_add_default_symbol (bfd *abfd,
1702                              struct bfd_link_info *info,
1703                              struct elf_link_hash_entry *h,
1704                              const char *name,
1705                              Elf_Internal_Sym *sym,
1706                              asection *sec,
1707                              bfd_vma value,
1708                              bfd **poldbfd,
1709                              bfd_boolean *dynsym)
1710 {
1711   bfd_boolean type_change_ok;
1712   bfd_boolean size_change_ok;
1713   bfd_boolean skip;
1714   char *shortname;
1715   struct elf_link_hash_entry *hi;
1716   struct bfd_link_hash_entry *bh;
1717   const struct elf_backend_data *bed;
1718   bfd_boolean collect;
1719   bfd_boolean dynamic;
1720   bfd_boolean override;
1721   char *p;
1722   size_t len, shortlen;
1723   asection *tmp_sec;
1724   bfd_boolean matched;
1725
1726   if (h->versioned == unversioned || h->versioned == versioned_hidden)
1727     return TRUE;
1728
1729   /* If this symbol has a version, and it is the default version, we
1730      create an indirect symbol from the default name to the fully
1731      decorated name.  This will cause external references which do not
1732      specify a version to be bound to this version of the symbol.  */
1733   p = strchr (name, ELF_VER_CHR);
1734   if (h->versioned == unknown)
1735     {
1736       if (p == NULL)
1737         {
1738           h->versioned = unversioned;
1739           return TRUE;
1740         }
1741       else
1742         {
1743           if (p[1] != ELF_VER_CHR)
1744             {
1745               h->versioned = versioned_hidden;
1746               return TRUE;
1747             }
1748           else
1749             h->versioned = versioned;
1750         }
1751     }
1752   else
1753     {
1754       /* PR ld/19073: We may see an unversioned definition after the
1755          default version.  */
1756       if (p == NULL)
1757         return TRUE;
1758     }
1759
1760   bed = get_elf_backend_data (abfd);
1761   collect = bed->collect;
1762   dynamic = (abfd->flags & DYNAMIC) != 0;
1763
1764   shortlen = p - name;
1765   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1766   if (shortname == NULL)
1767     return FALSE;
1768   memcpy (shortname, name, shortlen);
1769   shortname[shortlen] = '\0';
1770
1771   /* We are going to create a new symbol.  Merge it with any existing
1772      symbol with this name.  For the purposes of the merge, act as
1773      though we were defining the symbol we just defined, although we
1774      actually going to define an indirect symbol.  */
1775   type_change_ok = FALSE;
1776   size_change_ok = FALSE;
1777   matched = TRUE;
1778   tmp_sec = sec;
1779   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1780                               &hi, poldbfd, NULL, NULL, &skip, &override,
1781                               &type_change_ok, &size_change_ok, &matched))
1782     return FALSE;
1783
1784   if (skip)
1785     goto nondefault;
1786
1787   if (! override)
1788     {
1789       /* Add the default symbol if not performing a relocatable link.  */
1790       if (! bfd_link_relocatable (info))
1791         {
1792           bh = &hi->root;
1793           if (! (_bfd_generic_link_add_one_symbol
1794                  (info, abfd, shortname, BSF_INDIRECT,
1795                   bfd_ind_section_ptr,
1796                   0, name, FALSE, collect, &bh)))
1797             return FALSE;
1798           hi = (struct elf_link_hash_entry *) bh;
1799         }
1800     }
1801   else
1802     {
1803       /* In this case the symbol named SHORTNAME is overriding the
1804          indirect symbol we want to add.  We were planning on making
1805          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1806          is the name without a version.  NAME is the fully versioned
1807          name, and it is the default version.
1808
1809          Overriding means that we already saw a definition for the
1810          symbol SHORTNAME in a regular object, and it is overriding
1811          the symbol defined in the dynamic object.
1812
1813          When this happens, we actually want to change NAME, the
1814          symbol we just added, to refer to SHORTNAME.  This will cause
1815          references to NAME in the shared object to become references
1816          to SHORTNAME in the regular object.  This is what we expect
1817          when we override a function in a shared object: that the
1818          references in the shared object will be mapped to the
1819          definition in the regular object.  */
1820
1821       while (hi->root.type == bfd_link_hash_indirect
1822              || hi->root.type == bfd_link_hash_warning)
1823         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1824
1825       h->root.type = bfd_link_hash_indirect;
1826       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1827       if (h->def_dynamic)
1828         {
1829           h->def_dynamic = 0;
1830           hi->ref_dynamic = 1;
1831           if (hi->ref_regular
1832               || hi->def_regular)
1833             {
1834               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1835                 return FALSE;
1836             }
1837         }
1838
1839       /* Now set HI to H, so that the following code will set the
1840          other fields correctly.  */
1841       hi = h;
1842     }
1843
1844   /* Check if HI is a warning symbol.  */
1845   if (hi->root.type == bfd_link_hash_warning)
1846     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1847
1848   /* If there is a duplicate definition somewhere, then HI may not
1849      point to an indirect symbol.  We will have reported an error to
1850      the user in that case.  */
1851
1852   if (hi->root.type == bfd_link_hash_indirect)
1853     {
1854       struct elf_link_hash_entry *ht;
1855
1856       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1857       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
1858
1859       /* A reference to the SHORTNAME symbol from a dynamic library
1860          will be satisfied by the versioned symbol at runtime.  In
1861          effect, we have a reference to the versioned symbol.  */
1862       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1863       hi->dynamic_def |= ht->dynamic_def;
1864
1865       /* See if the new flags lead us to realize that the symbol must
1866          be dynamic.  */
1867       if (! *dynsym)
1868         {
1869           if (! dynamic)
1870             {
1871               if (! bfd_link_executable (info)
1872                   || hi->def_dynamic
1873                   || hi->ref_dynamic)
1874                 *dynsym = TRUE;
1875             }
1876           else
1877             {
1878               if (hi->ref_regular)
1879                 *dynsym = TRUE;
1880             }
1881         }
1882     }
1883
1884   /* We also need to define an indirection from the nondefault version
1885      of the symbol.  */
1886
1887 nondefault:
1888   len = strlen (name);
1889   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
1890   if (shortname == NULL)
1891     return FALSE;
1892   memcpy (shortname, name, shortlen);
1893   memcpy (shortname + shortlen, p + 1, len - shortlen);
1894
1895   /* Once again, merge with any existing symbol.  */
1896   type_change_ok = FALSE;
1897   size_change_ok = FALSE;
1898   tmp_sec = sec;
1899   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1900                               &hi, poldbfd, NULL, NULL, &skip, &override,
1901                               &type_change_ok, &size_change_ok, &matched))
1902     return FALSE;
1903
1904   if (skip)
1905     return TRUE;
1906
1907   if (override)
1908     {
1909       /* Here SHORTNAME is a versioned name, so we don't expect to see
1910          the type of override we do in the case above unless it is
1911          overridden by a versioned definition.  */
1912       if (hi->root.type != bfd_link_hash_defined
1913           && hi->root.type != bfd_link_hash_defweak)
1914         (*_bfd_error_handler)
1915           (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
1916            abfd, shortname);
1917     }
1918   else
1919     {
1920       bh = &hi->root;
1921       if (! (_bfd_generic_link_add_one_symbol
1922              (info, abfd, shortname, BSF_INDIRECT,
1923               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
1924         return FALSE;
1925       hi = (struct elf_link_hash_entry *) bh;
1926
1927       /* If there is a duplicate definition somewhere, then HI may not
1928          point to an indirect symbol.  We will have reported an error
1929          to the user in that case.  */
1930
1931       if (hi->root.type == bfd_link_hash_indirect)
1932         {
1933           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
1934           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1935           hi->dynamic_def |= h->dynamic_def;
1936
1937           /* See if the new flags lead us to realize that the symbol
1938              must be dynamic.  */
1939           if (! *dynsym)
1940             {
1941               if (! dynamic)
1942                 {
1943                   if (! bfd_link_executable (info)
1944                       || hi->ref_dynamic)
1945                     *dynsym = TRUE;
1946                 }
1947               else
1948                 {
1949                   if (hi->ref_regular)
1950                     *dynsym = TRUE;
1951                 }
1952             }
1953         }
1954     }
1955
1956   return TRUE;
1957 }
1958 \f
1959 /* This routine is used to export all defined symbols into the dynamic
1960    symbol table.  It is called via elf_link_hash_traverse.  */
1961
1962 static bfd_boolean
1963 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
1964 {
1965   struct elf_info_failed *eif = (struct elf_info_failed *) data;
1966
1967   /* Ignore indirect symbols.  These are added by the versioning code.  */
1968   if (h->root.type == bfd_link_hash_indirect)
1969     return TRUE;
1970
1971   /* Ignore this if we won't export it.  */
1972   if (!eif->info->export_dynamic && !h->dynamic)
1973     return TRUE;
1974
1975   if (h->dynindx == -1
1976       && (h->def_regular || h->ref_regular)
1977       && ! bfd_hide_sym_by_version (eif->info->version_info,
1978                                     h->root.root.string))
1979     {
1980       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
1981         {
1982           eif->failed = TRUE;
1983           return FALSE;
1984         }
1985     }
1986
1987   return TRUE;
1988 }
1989 \f
1990 /* Look through the symbols which are defined in other shared
1991    libraries and referenced here.  Update the list of version
1992    dependencies.  This will be put into the .gnu.version_r section.
1993    This function is called via elf_link_hash_traverse.  */
1994
1995 static bfd_boolean
1996 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
1997                                          void *data)
1998 {
1999   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
2000   Elf_Internal_Verneed *t;
2001   Elf_Internal_Vernaux *a;
2002   bfd_size_type amt;
2003
2004   /* We only care about symbols defined in shared objects with version
2005      information.  */
2006   if (!h->def_dynamic
2007       || h->def_regular
2008       || h->dynindx == -1
2009       || h->verinfo.verdef == NULL
2010       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
2011           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
2012     return TRUE;
2013
2014   /* See if we already know about this version.  */
2015   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
2016        t != NULL;
2017        t = t->vn_nextref)
2018     {
2019       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
2020         continue;
2021
2022       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
2023         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
2024           return TRUE;
2025
2026       break;
2027     }
2028
2029   /* This is a new version.  Add it to tree we are building.  */
2030
2031   if (t == NULL)
2032     {
2033       amt = sizeof *t;
2034       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
2035       if (t == NULL)
2036         {
2037           rinfo->failed = TRUE;
2038           return FALSE;
2039         }
2040
2041       t->vn_bfd = h->verinfo.verdef->vd_bfd;
2042       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
2043       elf_tdata (rinfo->info->output_bfd)->verref = t;
2044     }
2045
2046   amt = sizeof *a;
2047   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
2048   if (a == NULL)
2049     {
2050       rinfo->failed = TRUE;
2051       return FALSE;
2052     }
2053
2054   /* Note that we are copying a string pointer here, and testing it
2055      above.  If bfd_elf_string_from_elf_section is ever changed to
2056      discard the string data when low in memory, this will have to be
2057      fixed.  */
2058   a->vna_nodename = h->verinfo.verdef->vd_nodename;
2059
2060   a->vna_flags = h->verinfo.verdef->vd_flags;
2061   a->vna_nextptr = t->vn_auxptr;
2062
2063   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
2064   ++rinfo->vers;
2065
2066   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
2067
2068   t->vn_auxptr = a;
2069
2070   return TRUE;
2071 }
2072
2073 /* Figure out appropriate versions for all the symbols.  We may not
2074    have the version number script until we have read all of the input
2075    files, so until that point we don't know which symbols should be
2076    local.  This function is called via elf_link_hash_traverse.  */
2077
2078 static bfd_boolean
2079 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2080 {
2081   struct elf_info_failed *sinfo;
2082   struct bfd_link_info *info;
2083   const struct elf_backend_data *bed;
2084   struct elf_info_failed eif;
2085   char *p;
2086   bfd_size_type amt;
2087
2088   sinfo = (struct elf_info_failed *) data;
2089   info = sinfo->info;
2090
2091   /* Fix the symbol flags.  */
2092   eif.failed = FALSE;
2093   eif.info = info;
2094   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2095     {
2096       if (eif.failed)
2097         sinfo->failed = TRUE;
2098       return FALSE;
2099     }
2100
2101   /* We only need version numbers for symbols defined in regular
2102      objects.  */
2103   if (!h->def_regular)
2104     return TRUE;
2105
2106   bed = get_elf_backend_data (info->output_bfd);
2107   p = strchr (h->root.root.string, ELF_VER_CHR);
2108   if (p != NULL && h->verinfo.vertree == NULL)
2109     {
2110       struct bfd_elf_version_tree *t;
2111
2112       ++p;
2113       if (*p == ELF_VER_CHR)
2114         ++p;
2115
2116       /* If there is no version string, we can just return out.  */
2117       if (*p == '\0')
2118         return TRUE;
2119
2120       /* Look for the version.  If we find it, it is no longer weak.  */
2121       for (t = sinfo->info->version_info; t != NULL; t = t->next)
2122         {
2123           if (strcmp (t->name, p) == 0)
2124             {
2125               size_t len;
2126               char *alc;
2127               struct bfd_elf_version_expr *d;
2128
2129               len = p - h->root.root.string;
2130               alc = (char *) bfd_malloc (len);
2131               if (alc == NULL)
2132                 {
2133                   sinfo->failed = TRUE;
2134                   return FALSE;
2135                 }
2136               memcpy (alc, h->root.root.string, len - 1);
2137               alc[len - 1] = '\0';
2138               if (alc[len - 2] == ELF_VER_CHR)
2139                 alc[len - 2] = '\0';
2140
2141               h->verinfo.vertree = t;
2142               t->used = TRUE;
2143               d = NULL;
2144
2145               if (t->globals.list != NULL)
2146                 d = (*t->match) (&t->globals, NULL, alc);
2147
2148               /* See if there is anything to force this symbol to
2149                  local scope.  */
2150               if (d == NULL && t->locals.list != NULL)
2151                 {
2152                   d = (*t->match) (&t->locals, NULL, alc);
2153                   if (d != NULL
2154                       && h->dynindx != -1
2155                       && ! info->export_dynamic)
2156                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2157                 }
2158
2159               free (alc);
2160               break;
2161             }
2162         }
2163
2164       /* If we are building an application, we need to create a
2165          version node for this version.  */
2166       if (t == NULL && bfd_link_executable (info))
2167         {
2168           struct bfd_elf_version_tree **pp;
2169           int version_index;
2170
2171           /* If we aren't going to export this symbol, we don't need
2172              to worry about it.  */
2173           if (h->dynindx == -1)
2174             return TRUE;
2175
2176           amt = sizeof *t;
2177           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd, amt);
2178           if (t == NULL)
2179             {
2180               sinfo->failed = TRUE;
2181               return FALSE;
2182             }
2183
2184           t->name = p;
2185           t->name_indx = (unsigned int) -1;
2186           t->used = TRUE;
2187
2188           version_index = 1;
2189           /* Don't count anonymous version tag.  */
2190           if (sinfo->info->version_info != NULL
2191               && sinfo->info->version_info->vernum == 0)
2192             version_index = 0;
2193           for (pp = &sinfo->info->version_info;
2194                *pp != NULL;
2195                pp = &(*pp)->next)
2196             ++version_index;
2197           t->vernum = version_index;
2198
2199           *pp = t;
2200
2201           h->verinfo.vertree = t;
2202         }
2203       else if (t == NULL)
2204         {
2205           /* We could not find the version for a symbol when
2206              generating a shared archive.  Return an error.  */
2207           (*_bfd_error_handler)
2208             (_("%B: version node not found for symbol %s"),
2209              info->output_bfd, h->root.root.string);
2210           bfd_set_error (bfd_error_bad_value);
2211           sinfo->failed = TRUE;
2212           return FALSE;
2213         }
2214     }
2215
2216   /* If we don't have a version for this symbol, see if we can find
2217      something.  */
2218   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2219     {
2220       bfd_boolean hide;
2221
2222       h->verinfo.vertree
2223         = bfd_find_version_for_sym (sinfo->info->version_info,
2224                                     h->root.root.string, &hide);
2225       if (h->verinfo.vertree != NULL && hide)
2226         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2227     }
2228
2229   return TRUE;
2230 }
2231 \f
2232 /* Read and swap the relocs from the section indicated by SHDR.  This
2233    may be either a REL or a RELA section.  The relocations are
2234    translated into RELA relocations and stored in INTERNAL_RELOCS,
2235    which should have already been allocated to contain enough space.
2236    The EXTERNAL_RELOCS are a buffer where the external form of the
2237    relocations should be stored.
2238
2239    Returns FALSE if something goes wrong.  */
2240
2241 static bfd_boolean
2242 elf_link_read_relocs_from_section (bfd *abfd,
2243                                    asection *sec,
2244                                    Elf_Internal_Shdr *shdr,
2245                                    void *external_relocs,
2246                                    Elf_Internal_Rela *internal_relocs)
2247 {
2248   const struct elf_backend_data *bed;
2249   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2250   const bfd_byte *erela;
2251   const bfd_byte *erelaend;
2252   Elf_Internal_Rela *irela;
2253   Elf_Internal_Shdr *symtab_hdr;
2254   size_t nsyms;
2255
2256   /* Position ourselves at the start of the section.  */
2257   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2258     return FALSE;
2259
2260   /* Read the relocations.  */
2261   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2262     return FALSE;
2263
2264   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2265   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2266
2267   bed = get_elf_backend_data (abfd);
2268
2269   /* Convert the external relocations to the internal format.  */
2270   if (shdr->sh_entsize == bed->s->sizeof_rel)
2271     swap_in = bed->s->swap_reloc_in;
2272   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2273     swap_in = bed->s->swap_reloca_in;
2274   else
2275     {
2276       bfd_set_error (bfd_error_wrong_format);
2277       return FALSE;
2278     }
2279
2280   erela = (const bfd_byte *) external_relocs;
2281   erelaend = erela + shdr->sh_size;
2282   irela = internal_relocs;
2283   while (erela < erelaend)
2284     {
2285       bfd_vma r_symndx;
2286
2287       (*swap_in) (abfd, erela, irela);
2288       r_symndx = ELF32_R_SYM (irela->r_info);
2289       if (bed->s->arch_size == 64)
2290         r_symndx >>= 24;
2291       if (nsyms > 0)
2292         {
2293           if ((size_t) r_symndx >= nsyms)
2294             {
2295               (*_bfd_error_handler)
2296                 (_("%B: bad reloc symbol index (0x%lx >= 0x%lx)"
2297                    " for offset 0x%lx in section `%A'"),
2298                  abfd, sec,
2299                  (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2300               bfd_set_error (bfd_error_bad_value);
2301               return FALSE;
2302             }
2303         }
2304       else if (r_symndx != STN_UNDEF)
2305         {
2306           (*_bfd_error_handler)
2307             (_("%B: non-zero symbol index (0x%lx) for offset 0x%lx in section `%A'"
2308                " when the object file has no symbol table"),
2309              abfd, sec,
2310              (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2311           bfd_set_error (bfd_error_bad_value);
2312           return FALSE;
2313         }
2314       irela += bed->s->int_rels_per_ext_rel;
2315       erela += shdr->sh_entsize;
2316     }
2317
2318   return TRUE;
2319 }
2320
2321 /* Read and swap the relocs for a section O.  They may have been
2322    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2323    not NULL, they are used as buffers to read into.  They are known to
2324    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2325    the return value is allocated using either malloc or bfd_alloc,
2326    according to the KEEP_MEMORY argument.  If O has two relocation
2327    sections (both REL and RELA relocations), then the REL_HDR
2328    relocations will appear first in INTERNAL_RELOCS, followed by the
2329    RELA_HDR relocations.  */
2330
2331 Elf_Internal_Rela *
2332 _bfd_elf_link_read_relocs (bfd *abfd,
2333                            asection *o,
2334                            void *external_relocs,
2335                            Elf_Internal_Rela *internal_relocs,
2336                            bfd_boolean keep_memory)
2337 {
2338   void *alloc1 = NULL;
2339   Elf_Internal_Rela *alloc2 = NULL;
2340   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2341   struct bfd_elf_section_data *esdo = elf_section_data (o);
2342   Elf_Internal_Rela *internal_rela_relocs;
2343
2344   if (esdo->relocs != NULL)
2345     return esdo->relocs;
2346
2347   if (o->reloc_count == 0)
2348     return NULL;
2349
2350   if (internal_relocs == NULL)
2351     {
2352       bfd_size_type size;
2353
2354       size = o->reloc_count;
2355       size *= bed->s->int_rels_per_ext_rel * sizeof (Elf_Internal_Rela);
2356       if (keep_memory)
2357         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2358       else
2359         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2360       if (internal_relocs == NULL)
2361         goto error_return;
2362     }
2363
2364   if (external_relocs == NULL)
2365     {
2366       bfd_size_type size = 0;
2367
2368       if (esdo->rel.hdr)
2369         size += esdo->rel.hdr->sh_size;
2370       if (esdo->rela.hdr)
2371         size += esdo->rela.hdr->sh_size;
2372
2373       alloc1 = bfd_malloc (size);
2374       if (alloc1 == NULL)
2375         goto error_return;
2376       external_relocs = alloc1;
2377     }
2378
2379   internal_rela_relocs = internal_relocs;
2380   if (esdo->rel.hdr)
2381     {
2382       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2383                                               external_relocs,
2384                                               internal_relocs))
2385         goto error_return;
2386       external_relocs = (((bfd_byte *) external_relocs)
2387                          + esdo->rel.hdr->sh_size);
2388       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2389                                * bed->s->int_rels_per_ext_rel);
2390     }
2391
2392   if (esdo->rela.hdr
2393       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2394                                               external_relocs,
2395                                               internal_rela_relocs)))
2396     goto error_return;
2397
2398   /* Cache the results for next time, if we can.  */
2399   if (keep_memory)
2400     esdo->relocs = internal_relocs;
2401
2402   if (alloc1 != NULL)
2403     free (alloc1);
2404
2405   /* Don't free alloc2, since if it was allocated we are passing it
2406      back (under the name of internal_relocs).  */
2407
2408   return internal_relocs;
2409
2410  error_return:
2411   if (alloc1 != NULL)
2412     free (alloc1);
2413   if (alloc2 != NULL)
2414     {
2415       if (keep_memory)
2416         bfd_release (abfd, alloc2);
2417       else
2418         free (alloc2);
2419     }
2420   return NULL;
2421 }
2422
2423 /* Compute the size of, and allocate space for, REL_HDR which is the
2424    section header for a section containing relocations for O.  */
2425
2426 static bfd_boolean
2427 _bfd_elf_link_size_reloc_section (bfd *abfd,
2428                                   struct bfd_elf_section_reloc_data *reldata)
2429 {
2430   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2431
2432   /* That allows us to calculate the size of the section.  */
2433   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2434
2435   /* The contents field must last into write_object_contents, so we
2436      allocate it with bfd_alloc rather than malloc.  Also since we
2437      cannot be sure that the contents will actually be filled in,
2438      we zero the allocated space.  */
2439   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2440   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2441     return FALSE;
2442
2443   if (reldata->hashes == NULL && reldata->count)
2444     {
2445       struct elf_link_hash_entry **p;
2446
2447       p = ((struct elf_link_hash_entry **)
2448            bfd_zmalloc (reldata->count * sizeof (*p)));
2449       if (p == NULL)
2450         return FALSE;
2451
2452       reldata->hashes = p;
2453     }
2454
2455   return TRUE;
2456 }
2457
2458 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2459    originated from the section given by INPUT_REL_HDR) to the
2460    OUTPUT_BFD.  */
2461
2462 bfd_boolean
2463 _bfd_elf_link_output_relocs (bfd *output_bfd,
2464                              asection *input_section,
2465                              Elf_Internal_Shdr *input_rel_hdr,
2466                              Elf_Internal_Rela *internal_relocs,
2467                              struct elf_link_hash_entry **rel_hash
2468                                ATTRIBUTE_UNUSED)
2469 {
2470   Elf_Internal_Rela *irela;
2471   Elf_Internal_Rela *irelaend;
2472   bfd_byte *erel;
2473   struct bfd_elf_section_reloc_data *output_reldata;
2474   asection *output_section;
2475   const struct elf_backend_data *bed;
2476   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2477   struct bfd_elf_section_data *esdo;
2478
2479   output_section = input_section->output_section;
2480
2481   bed = get_elf_backend_data (output_bfd);
2482   esdo = elf_section_data (output_section);
2483   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2484     {
2485       output_reldata = &esdo->rel;
2486       swap_out = bed->s->swap_reloc_out;
2487     }
2488   else if (esdo->rela.hdr
2489            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2490     {
2491       output_reldata = &esdo->rela;
2492       swap_out = bed->s->swap_reloca_out;
2493     }
2494   else
2495     {
2496       (*_bfd_error_handler)
2497         (_("%B: relocation size mismatch in %B section %A"),
2498          output_bfd, input_section->owner, input_section);
2499       bfd_set_error (bfd_error_wrong_format);
2500       return FALSE;
2501     }
2502
2503   erel = output_reldata->hdr->contents;
2504   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2505   irela = internal_relocs;
2506   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2507                       * bed->s->int_rels_per_ext_rel);
2508   while (irela < irelaend)
2509     {
2510       (*swap_out) (output_bfd, irela, erel);
2511       irela += bed->s->int_rels_per_ext_rel;
2512       erel += input_rel_hdr->sh_entsize;
2513     }
2514
2515   /* Bump the counter, so that we know where to add the next set of
2516      relocations.  */
2517   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2518
2519   return TRUE;
2520 }
2521 \f
2522 /* Make weak undefined symbols in PIE dynamic.  */
2523
2524 bfd_boolean
2525 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2526                                  struct elf_link_hash_entry *h)
2527 {
2528   if (bfd_link_pie (info)
2529       && h->dynindx == -1
2530       && h->root.type == bfd_link_hash_undefweak)
2531     return bfd_elf_link_record_dynamic_symbol (info, h);
2532
2533   return TRUE;
2534 }
2535
2536 /* Fix up the flags for a symbol.  This handles various cases which
2537    can only be fixed after all the input files are seen.  This is
2538    currently called by both adjust_dynamic_symbol and
2539    assign_sym_version, which is unnecessary but perhaps more robust in
2540    the face of future changes.  */
2541
2542 static bfd_boolean
2543 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2544                            struct elf_info_failed *eif)
2545 {
2546   const struct elf_backend_data *bed;
2547
2548   /* If this symbol was mentioned in a non-ELF file, try to set
2549      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2550      permit a non-ELF file to correctly refer to a symbol defined in
2551      an ELF dynamic object.  */
2552   if (h->non_elf)
2553     {
2554       while (h->root.type == bfd_link_hash_indirect)
2555         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2556
2557       if (h->root.type != bfd_link_hash_defined
2558           && h->root.type != bfd_link_hash_defweak)
2559         {
2560           h->ref_regular = 1;
2561           h->ref_regular_nonweak = 1;
2562         }
2563       else
2564         {
2565           if (h->root.u.def.section->owner != NULL
2566               && (bfd_get_flavour (h->root.u.def.section->owner)
2567                   == bfd_target_elf_flavour))
2568             {
2569               h->ref_regular = 1;
2570               h->ref_regular_nonweak = 1;
2571             }
2572           else
2573             h->def_regular = 1;
2574         }
2575
2576       if (h->dynindx == -1
2577           && (h->def_dynamic
2578               || h->ref_dynamic))
2579         {
2580           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2581             {
2582               eif->failed = TRUE;
2583               return FALSE;
2584             }
2585         }
2586     }
2587   else
2588     {
2589       /* Unfortunately, NON_ELF is only correct if the symbol
2590          was first seen in a non-ELF file.  Fortunately, if the symbol
2591          was first seen in an ELF file, we're probably OK unless the
2592          symbol was defined in a non-ELF file.  Catch that case here.
2593          FIXME: We're still in trouble if the symbol was first seen in
2594          a dynamic object, and then later in a non-ELF regular object.  */
2595       if ((h->root.type == bfd_link_hash_defined
2596            || h->root.type == bfd_link_hash_defweak)
2597           && !h->def_regular
2598           && (h->root.u.def.section->owner != NULL
2599               ? (bfd_get_flavour (h->root.u.def.section->owner)
2600                  != bfd_target_elf_flavour)
2601               : (bfd_is_abs_section (h->root.u.def.section)
2602                  && !h->def_dynamic)))
2603         h->def_regular = 1;
2604     }
2605
2606   /* Backend specific symbol fixup.  */
2607   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2608   if (bed->elf_backend_fixup_symbol
2609       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2610     return FALSE;
2611
2612   /* If this is a final link, and the symbol was defined as a common
2613      symbol in a regular object file, and there was no definition in
2614      any dynamic object, then the linker will have allocated space for
2615      the symbol in a common section but the DEF_REGULAR
2616      flag will not have been set.  */
2617   if (h->root.type == bfd_link_hash_defined
2618       && !h->def_regular
2619       && h->ref_regular
2620       && !h->def_dynamic
2621       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2622     h->def_regular = 1;
2623
2624   /* If -Bsymbolic was used (which means to bind references to global
2625      symbols to the definition within the shared object), and this
2626      symbol was defined in a regular object, then it actually doesn't
2627      need a PLT entry.  Likewise, if the symbol has non-default
2628      visibility.  If the symbol has hidden or internal visibility, we
2629      will force it local.  */
2630   if (h->needs_plt
2631       && bfd_link_pic (eif->info)
2632       && is_elf_hash_table (eif->info->hash)
2633       && (SYMBOLIC_BIND (eif->info, h)
2634           || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2635       && h->def_regular)
2636     {
2637       bfd_boolean force_local;
2638
2639       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2640                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2641       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2642     }
2643
2644   /* If a weak undefined symbol has non-default visibility, we also
2645      hide it from the dynamic linker.  */
2646   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2647       && h->root.type == bfd_link_hash_undefweak)
2648     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2649
2650   /* If this is a weak defined symbol in a dynamic object, and we know
2651      the real definition in the dynamic object, copy interesting flags
2652      over to the real definition.  */
2653   if (h->u.weakdef != NULL)
2654     {
2655       /* If the real definition is defined by a regular object file,
2656          don't do anything special.  See the longer description in
2657          _bfd_elf_adjust_dynamic_symbol, below.  */
2658       if (h->u.weakdef->def_regular)
2659         h->u.weakdef = NULL;
2660       else
2661         {
2662           struct elf_link_hash_entry *weakdef = h->u.weakdef;
2663
2664           while (h->root.type == bfd_link_hash_indirect)
2665             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2666
2667           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2668                       || h->root.type == bfd_link_hash_defweak);
2669           BFD_ASSERT (weakdef->def_dynamic);
2670           BFD_ASSERT (weakdef->root.type == bfd_link_hash_defined
2671                       || weakdef->root.type == bfd_link_hash_defweak);
2672           (*bed->elf_backend_copy_indirect_symbol) (eif->info, weakdef, h);
2673         }
2674     }
2675
2676   return TRUE;
2677 }
2678
2679 /* Make the backend pick a good value for a dynamic symbol.  This is
2680    called via elf_link_hash_traverse, and also calls itself
2681    recursively.  */
2682
2683 static bfd_boolean
2684 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2685 {
2686   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2687   bfd *dynobj;
2688   const struct elf_backend_data *bed;
2689
2690   if (! is_elf_hash_table (eif->info->hash))
2691     return FALSE;
2692
2693   /* Ignore indirect symbols.  These are added by the versioning code.  */
2694   if (h->root.type == bfd_link_hash_indirect)
2695     return TRUE;
2696
2697   /* Fix the symbol flags.  */
2698   if (! _bfd_elf_fix_symbol_flags (h, eif))
2699     return FALSE;
2700
2701   /* If this symbol does not require a PLT entry, and it is not
2702      defined by a dynamic object, or is not referenced by a regular
2703      object, ignore it.  We do have to handle a weak defined symbol,
2704      even if no regular object refers to it, if we decided to add it
2705      to the dynamic symbol table.  FIXME: Do we normally need to worry
2706      about symbols which are defined by one dynamic object and
2707      referenced by another one?  */
2708   if (!h->needs_plt
2709       && h->type != STT_GNU_IFUNC
2710       && (h->def_regular
2711           || !h->def_dynamic
2712           || (!h->ref_regular
2713               && (h->u.weakdef == NULL || h->u.weakdef->dynindx == -1))))
2714     {
2715       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2716       return TRUE;
2717     }
2718
2719   /* If we've already adjusted this symbol, don't do it again.  This
2720      can happen via a recursive call.  */
2721   if (h->dynamic_adjusted)
2722     return TRUE;
2723
2724   /* Don't look at this symbol again.  Note that we must set this
2725      after checking the above conditions, because we may look at a
2726      symbol once, decide not to do anything, and then get called
2727      recursively later after REF_REGULAR is set below.  */
2728   h->dynamic_adjusted = 1;
2729
2730   /* If this is a weak definition, and we know a real definition, and
2731      the real symbol is not itself defined by a regular object file,
2732      then get a good value for the real definition.  We handle the
2733      real symbol first, for the convenience of the backend routine.
2734
2735      Note that there is a confusing case here.  If the real definition
2736      is defined by a regular object file, we don't get the real symbol
2737      from the dynamic object, but we do get the weak symbol.  If the
2738      processor backend uses a COPY reloc, then if some routine in the
2739      dynamic object changes the real symbol, we will not see that
2740      change in the corresponding weak symbol.  This is the way other
2741      ELF linkers work as well, and seems to be a result of the shared
2742      library model.
2743
2744      I will clarify this issue.  Most SVR4 shared libraries define the
2745      variable _timezone and define timezone as a weak synonym.  The
2746      tzset call changes _timezone.  If you write
2747        extern int timezone;
2748        int _timezone = 5;
2749        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2750      you might expect that, since timezone is a synonym for _timezone,
2751      the same number will print both times.  However, if the processor
2752      backend uses a COPY reloc, then actually timezone will be copied
2753      into your process image, and, since you define _timezone
2754      yourself, _timezone will not.  Thus timezone and _timezone will
2755      wind up at different memory locations.  The tzset call will set
2756      _timezone, leaving timezone unchanged.  */
2757
2758   if (h->u.weakdef != NULL)
2759     {
2760       /* If we get to this point, there is an implicit reference to
2761          H->U.WEAKDEF by a regular object file via the weak symbol H.  */
2762       h->u.weakdef->ref_regular = 1;
2763
2764       /* Ensure that the backend adjust_dynamic_symbol function sees
2765          H->U.WEAKDEF before H by recursively calling ourselves.  */
2766       if (! _bfd_elf_adjust_dynamic_symbol (h->u.weakdef, eif))
2767         return FALSE;
2768     }
2769
2770   /* If a symbol has no type and no size and does not require a PLT
2771      entry, then we are probably about to do the wrong thing here: we
2772      are probably going to create a COPY reloc for an empty object.
2773      This case can arise when a shared object is built with assembly
2774      code, and the assembly code fails to set the symbol type.  */
2775   if (h->size == 0
2776       && h->type == STT_NOTYPE
2777       && !h->needs_plt)
2778     (*_bfd_error_handler)
2779       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2780        h->root.root.string);
2781
2782   dynobj = elf_hash_table (eif->info)->dynobj;
2783   bed = get_elf_backend_data (dynobj);
2784
2785   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2786     {
2787       eif->failed = TRUE;
2788       return FALSE;
2789     }
2790
2791   return TRUE;
2792 }
2793
2794 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2795    DYNBSS.  */
2796
2797 bfd_boolean
2798 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
2799                               struct elf_link_hash_entry *h,
2800                               asection *dynbss)
2801 {
2802   unsigned int power_of_two;
2803   bfd_vma mask;
2804   asection *sec = h->root.u.def.section;
2805
2806   /* The section aligment of definition is the maximum alignment
2807      requirement of symbols defined in the section.  Since we don't
2808      know the symbol alignment requirement, we start with the
2809      maximum alignment and check low bits of the symbol address
2810      for the minimum alignment.  */
2811   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2812   mask = ((bfd_vma) 1 << power_of_two) - 1;
2813   while ((h->root.u.def.value & mask) != 0)
2814     {
2815        mask >>= 1;
2816        --power_of_two;
2817     }
2818
2819   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
2820                                                 dynbss))
2821     {
2822       /* Adjust the section alignment if needed.  */
2823       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
2824                                        power_of_two))
2825         return FALSE;
2826     }
2827
2828   /* We make sure that the symbol will be aligned properly.  */
2829   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
2830
2831   /* Define the symbol as being at this point in DYNBSS.  */
2832   h->root.u.def.section = dynbss;
2833   h->root.u.def.value = dynbss->size;
2834
2835   /* Increment the size of DYNBSS to make room for the symbol.  */
2836   dynbss->size += h->size;
2837
2838   /* No error if extern_protected_data is true.  */
2839   if (h->protected_def
2840       && (!info->extern_protected_data
2841           || (info->extern_protected_data < 0
2842               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
2843     info->callbacks->einfo
2844       (_("%P: copy reloc against protected `%T' is dangerous\n"),
2845        h->root.root.string);
2846
2847   return TRUE;
2848 }
2849
2850 /* Adjust all external symbols pointing into SEC_MERGE sections
2851    to reflect the object merging within the sections.  */
2852
2853 static bfd_boolean
2854 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
2855 {
2856   asection *sec;
2857
2858   if ((h->root.type == bfd_link_hash_defined
2859        || h->root.type == bfd_link_hash_defweak)
2860       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
2861       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
2862     {
2863       bfd *output_bfd = (bfd *) data;
2864
2865       h->root.u.def.value =
2866         _bfd_merged_section_offset (output_bfd,
2867                                     &h->root.u.def.section,
2868                                     elf_section_data (sec)->sec_info,
2869                                     h->root.u.def.value);
2870     }
2871
2872   return TRUE;
2873 }
2874
2875 /* Returns false if the symbol referred to by H should be considered
2876    to resolve local to the current module, and true if it should be
2877    considered to bind dynamically.  */
2878
2879 bfd_boolean
2880 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
2881                            struct bfd_link_info *info,
2882                            bfd_boolean not_local_protected)
2883 {
2884   bfd_boolean binding_stays_local_p;
2885   const struct elf_backend_data *bed;
2886   struct elf_link_hash_table *hash_table;
2887
2888   if (h == NULL)
2889     return FALSE;
2890
2891   while (h->root.type == bfd_link_hash_indirect
2892          || h->root.type == bfd_link_hash_warning)
2893     h = (struct elf_link_hash_entry *) h->root.u.i.link;
2894
2895   /* If it was forced local, then clearly it's not dynamic.  */
2896   if (h->dynindx == -1)
2897     return FALSE;
2898   if (h->forced_local)
2899     return FALSE;
2900
2901   /* Identify the cases where name binding rules say that a
2902      visible symbol resolves locally.  */
2903   binding_stays_local_p = (bfd_link_executable (info)
2904                            || SYMBOLIC_BIND (info, h));
2905
2906   switch (ELF_ST_VISIBILITY (h->other))
2907     {
2908     case STV_INTERNAL:
2909     case STV_HIDDEN:
2910       return FALSE;
2911
2912     case STV_PROTECTED:
2913       hash_table = elf_hash_table (info);
2914       if (!is_elf_hash_table (hash_table))
2915         return FALSE;
2916
2917       bed = get_elf_backend_data (hash_table->dynobj);
2918
2919       /* Proper resolution for function pointer equality may require
2920          that these symbols perhaps be resolved dynamically, even though
2921          we should be resolving them to the current module.  */
2922       if (!not_local_protected || !bed->is_function_type (h->type))
2923         binding_stays_local_p = TRUE;
2924       break;
2925
2926     default:
2927       break;
2928     }
2929
2930   /* If it isn't defined locally, then clearly it's dynamic.  */
2931   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
2932     return TRUE;
2933
2934   /* Otherwise, the symbol is dynamic if binding rules don't tell
2935      us that it remains local.  */
2936   return !binding_stays_local_p;
2937 }
2938
2939 /* Return true if the symbol referred to by H should be considered
2940    to resolve local to the current module, and false otherwise.  Differs
2941    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
2942    undefined symbols.  The two functions are virtually identical except
2943    for the place where forced_local and dynindx == -1 are tested.  If
2944    either of those tests are true, _bfd_elf_dynamic_symbol_p will say
2945    the symbol is local, while _bfd_elf_symbol_refs_local_p will say
2946    the symbol is local only for defined symbols.
2947    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
2948    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
2949    treatment of undefined weak symbols.  For those that do not make
2950    undefined weak symbols dynamic, both functions may return false.  */
2951
2952 bfd_boolean
2953 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
2954                               struct bfd_link_info *info,
2955                               bfd_boolean local_protected)
2956 {
2957   const struct elf_backend_data *bed;
2958   struct elf_link_hash_table *hash_table;
2959
2960   /* If it's a local sym, of course we resolve locally.  */
2961   if (h == NULL)
2962     return TRUE;
2963
2964   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
2965   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
2966       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
2967     return TRUE;
2968
2969   /* Common symbols that become definitions don't get the DEF_REGULAR
2970      flag set, so test it first, and don't bail out.  */
2971   if (ELF_COMMON_DEF_P (h))
2972     /* Do nothing.  */;
2973   /* If we don't have a definition in a regular file, then we can't
2974      resolve locally.  The sym is either undefined or dynamic.  */
2975   else if (!h->def_regular)
2976     return FALSE;
2977
2978   /* Forced local symbols resolve locally.  */
2979   if (h->forced_local)
2980     return TRUE;
2981
2982   /* As do non-dynamic symbols.  */
2983   if (h->dynindx == -1)
2984     return TRUE;
2985
2986   /* At this point, we know the symbol is defined and dynamic.  In an
2987      executable it must resolve locally, likewise when building symbolic
2988      shared libraries.  */
2989   if (bfd_link_executable (info) || SYMBOLIC_BIND (info, h))
2990     return TRUE;
2991
2992   /* Now deal with defined dynamic symbols in shared libraries.  Ones
2993      with default visibility might not resolve locally.  */
2994   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
2995     return FALSE;
2996
2997   hash_table = elf_hash_table (info);
2998   if (!is_elf_hash_table (hash_table))
2999     return TRUE;
3000
3001   bed = get_elf_backend_data (hash_table->dynobj);
3002
3003   /* If extern_protected_data is false, STV_PROTECTED non-function
3004      symbols are local.  */
3005   if ((!info->extern_protected_data
3006        || (info->extern_protected_data < 0
3007            && !bed->extern_protected_data))
3008       && !bed->is_function_type (h->type))
3009     return TRUE;
3010
3011   /* Function pointer equality tests may require that STV_PROTECTED
3012      symbols be treated as dynamic symbols.  If the address of a
3013      function not defined in an executable is set to that function's
3014      plt entry in the executable, then the address of the function in
3015      a shared library must also be the plt entry in the executable.  */
3016   return local_protected;
3017 }
3018
3019 /* Caches some TLS segment info, and ensures that the TLS segment vma is
3020    aligned.  Returns the first TLS output section.  */
3021
3022 struct bfd_section *
3023 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
3024 {
3025   struct bfd_section *sec, *tls;
3026   unsigned int align = 0;
3027
3028   for (sec = obfd->sections; sec != NULL; sec = sec->next)
3029     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
3030       break;
3031   tls = sec;
3032
3033   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
3034     if (sec->alignment_power > align)
3035       align = sec->alignment_power;
3036
3037   elf_hash_table (info)->tls_sec = tls;
3038
3039   /* Ensure the alignment of the first section is the largest alignment,
3040      so that the tls segment starts aligned.  */
3041   if (tls != NULL)
3042     tls->alignment_power = align;
3043
3044   return tls;
3045 }
3046
3047 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
3048 static bfd_boolean
3049 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
3050                                   Elf_Internal_Sym *sym)
3051 {
3052   const struct elf_backend_data *bed;
3053
3054   /* Local symbols do not count, but target specific ones might.  */
3055   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
3056       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
3057     return FALSE;
3058
3059   bed = get_elf_backend_data (abfd);
3060   /* Function symbols do not count.  */
3061   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
3062     return FALSE;
3063
3064   /* If the section is undefined, then so is the symbol.  */
3065   if (sym->st_shndx == SHN_UNDEF)
3066     return FALSE;
3067
3068   /* If the symbol is defined in the common section, then
3069      it is a common definition and so does not count.  */
3070   if (bed->common_definition (sym))
3071     return FALSE;
3072
3073   /* If the symbol is in a target specific section then we
3074      must rely upon the backend to tell us what it is.  */
3075   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3076     /* FIXME - this function is not coded yet:
3077
3078        return _bfd_is_global_symbol_definition (abfd, sym);
3079
3080        Instead for now assume that the definition is not global,
3081        Even if this is wrong, at least the linker will behave
3082        in the same way that it used to do.  */
3083     return FALSE;
3084
3085   return TRUE;
3086 }
3087
3088 /* Search the symbol table of the archive element of the archive ABFD
3089    whose archive map contains a mention of SYMDEF, and determine if
3090    the symbol is defined in this element.  */
3091 static bfd_boolean
3092 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3093 {
3094   Elf_Internal_Shdr * hdr;
3095   bfd_size_type symcount;
3096   bfd_size_type extsymcount;
3097   bfd_size_type extsymoff;
3098   Elf_Internal_Sym *isymbuf;
3099   Elf_Internal_Sym *isym;
3100   Elf_Internal_Sym *isymend;
3101   bfd_boolean result;
3102
3103   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3104   if (abfd == NULL)
3105     return FALSE;
3106
3107   /* Return FALSE if the object has been claimed by plugin.  */
3108   if (abfd->plugin_format == bfd_plugin_yes)
3109     return FALSE;
3110
3111   if (! bfd_check_format (abfd, bfd_object))
3112     return FALSE;
3113
3114   /* Select the appropriate symbol table.  */
3115   if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3116     hdr = &elf_tdata (abfd)->symtab_hdr;
3117   else
3118     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3119
3120   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3121
3122   /* The sh_info field of the symtab header tells us where the
3123      external symbols start.  We don't care about the local symbols.  */
3124   if (elf_bad_symtab (abfd))
3125     {
3126       extsymcount = symcount;
3127       extsymoff = 0;
3128     }
3129   else
3130     {
3131       extsymcount = symcount - hdr->sh_info;
3132       extsymoff = hdr->sh_info;
3133     }
3134
3135   if (extsymcount == 0)
3136     return FALSE;
3137
3138   /* Read in the symbol table.  */
3139   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3140                                   NULL, NULL, NULL);
3141   if (isymbuf == NULL)
3142     return FALSE;
3143
3144   /* Scan the symbol table looking for SYMDEF.  */
3145   result = FALSE;
3146   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3147     {
3148       const char *name;
3149
3150       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3151                                               isym->st_name);
3152       if (name == NULL)
3153         break;
3154
3155       if (strcmp (name, symdef->name) == 0)
3156         {
3157           result = is_global_data_symbol_definition (abfd, isym);
3158           break;
3159         }
3160     }
3161
3162   free (isymbuf);
3163
3164   return result;
3165 }
3166 \f
3167 /* Add an entry to the .dynamic table.  */
3168
3169 bfd_boolean
3170 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3171                             bfd_vma tag,
3172                             bfd_vma val)
3173 {
3174   struct elf_link_hash_table *hash_table;
3175   const struct elf_backend_data *bed;
3176   asection *s;
3177   bfd_size_type newsize;
3178   bfd_byte *newcontents;
3179   Elf_Internal_Dyn dyn;
3180
3181   hash_table = elf_hash_table (info);
3182   if (! is_elf_hash_table (hash_table))
3183     return FALSE;
3184
3185   bed = get_elf_backend_data (hash_table->dynobj);
3186   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3187   BFD_ASSERT (s != NULL);
3188
3189   newsize = s->size + bed->s->sizeof_dyn;
3190   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3191   if (newcontents == NULL)
3192     return FALSE;
3193
3194   dyn.d_tag = tag;
3195   dyn.d_un.d_val = val;
3196   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3197
3198   s->size = newsize;
3199   s->contents = newcontents;
3200
3201   return TRUE;
3202 }
3203
3204 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3205    otherwise just check whether one already exists.  Returns -1 on error,
3206    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3207
3208 static int
3209 elf_add_dt_needed_tag (bfd *abfd,
3210                        struct bfd_link_info *info,
3211                        const char *soname,
3212                        bfd_boolean do_it)
3213 {
3214   struct elf_link_hash_table *hash_table;
3215   bfd_size_type strindex;
3216
3217   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3218     return -1;
3219
3220   hash_table = elf_hash_table (info);
3221   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3222   if (strindex == (bfd_size_type) -1)
3223     return -1;
3224
3225   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3226     {
3227       asection *sdyn;
3228       const struct elf_backend_data *bed;
3229       bfd_byte *extdyn;
3230
3231       bed = get_elf_backend_data (hash_table->dynobj);
3232       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3233       if (sdyn != NULL)
3234         for (extdyn = sdyn->contents;
3235              extdyn < sdyn->contents + sdyn->size;
3236              extdyn += bed->s->sizeof_dyn)
3237           {
3238             Elf_Internal_Dyn dyn;
3239
3240             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3241             if (dyn.d_tag == DT_NEEDED
3242                 && dyn.d_un.d_val == strindex)
3243               {
3244                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3245                 return 1;
3246               }
3247           }
3248     }
3249
3250   if (do_it)
3251     {
3252       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3253         return -1;
3254
3255       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3256         return -1;
3257     }
3258   else
3259     /* We were just checking for existence of the tag.  */
3260     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3261
3262   return 0;
3263 }
3264
3265 /* Return true if SONAME is on the needed list between NEEDED and STOP
3266    (or the end of list if STOP is NULL), and needed by a library that
3267    will be loaded.  */
3268
3269 static bfd_boolean
3270 on_needed_list (const char *soname,
3271                 struct bfd_link_needed_list *needed,
3272                 struct bfd_link_needed_list *stop)
3273 {
3274   struct bfd_link_needed_list *look;
3275   for (look = needed; look != stop; look = look->next)
3276     if (strcmp (soname, look->name) == 0
3277         && ((elf_dyn_lib_class (look->by) & DYN_AS_NEEDED) == 0
3278             /* If needed by a library that itself is not directly
3279                needed, recursively check whether that library is
3280                indirectly needed.  Since we add DT_NEEDED entries to
3281                the end of the list, library dependencies appear after
3282                the library.  Therefore search prior to the current
3283                LOOK, preventing possible infinite recursion.  */
3284             || on_needed_list (elf_dt_name (look->by), needed, look)))
3285       return TRUE;
3286
3287   return FALSE;
3288 }
3289
3290 /* Sort symbol by value, section, and size.  */
3291 static int
3292 elf_sort_symbol (const void *arg1, const void *arg2)
3293 {
3294   const struct elf_link_hash_entry *h1;
3295   const struct elf_link_hash_entry *h2;
3296   bfd_signed_vma vdiff;
3297
3298   h1 = *(const struct elf_link_hash_entry **) arg1;
3299   h2 = *(const struct elf_link_hash_entry **) arg2;
3300   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3301   if (vdiff != 0)
3302     return vdiff > 0 ? 1 : -1;
3303   else
3304     {
3305       int sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3306       if (sdiff != 0)
3307         return sdiff > 0 ? 1 : -1;
3308     }
3309   vdiff = h1->size - h2->size;
3310   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3311 }
3312
3313 /* This function is used to adjust offsets into .dynstr for
3314    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3315
3316 static bfd_boolean
3317 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3318 {
3319   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3320
3321   if (h->dynindx != -1)
3322     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3323   return TRUE;
3324 }
3325
3326 /* Assign string offsets in .dynstr, update all structures referencing
3327    them.  */
3328
3329 static bfd_boolean
3330 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3331 {
3332   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3333   struct elf_link_local_dynamic_entry *entry;
3334   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3335   bfd *dynobj = hash_table->dynobj;
3336   asection *sdyn;
3337   bfd_size_type size;
3338   const struct elf_backend_data *bed;
3339   bfd_byte *extdyn;
3340
3341   _bfd_elf_strtab_finalize (dynstr);
3342   size = _bfd_elf_strtab_size (dynstr);
3343
3344   bed = get_elf_backend_data (dynobj);
3345   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3346   BFD_ASSERT (sdyn != NULL);
3347
3348   /* Update all .dynamic entries referencing .dynstr strings.  */
3349   for (extdyn = sdyn->contents;
3350        extdyn < sdyn->contents + sdyn->size;
3351        extdyn += bed->s->sizeof_dyn)
3352     {
3353       Elf_Internal_Dyn dyn;
3354
3355       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3356       switch (dyn.d_tag)
3357         {
3358         case DT_STRSZ:
3359           dyn.d_un.d_val = size;
3360           break;
3361         case DT_NEEDED:
3362         case DT_SONAME:
3363         case DT_RPATH:
3364         case DT_RUNPATH:
3365         case DT_FILTER:
3366         case DT_AUXILIARY:
3367         case DT_AUDIT:
3368         case DT_DEPAUDIT:
3369           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3370           break;
3371         default:
3372           continue;
3373         }
3374       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3375     }
3376
3377   /* Now update local dynamic symbols.  */
3378   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3379     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3380                                                   entry->isym.st_name);
3381
3382   /* And the rest of dynamic symbols.  */
3383   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3384
3385   /* Adjust version definitions.  */
3386   if (elf_tdata (output_bfd)->cverdefs)
3387     {
3388       asection *s;
3389       bfd_byte *p;
3390       bfd_size_type i;
3391       Elf_Internal_Verdef def;
3392       Elf_Internal_Verdaux defaux;
3393
3394       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3395       p = s->contents;
3396       do
3397         {
3398           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3399                                    &def);
3400           p += sizeof (Elf_External_Verdef);
3401           if (def.vd_aux != sizeof (Elf_External_Verdef))
3402             continue;
3403           for (i = 0; i < def.vd_cnt; ++i)
3404             {
3405               _bfd_elf_swap_verdaux_in (output_bfd,
3406                                         (Elf_External_Verdaux *) p, &defaux);
3407               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3408                                                         defaux.vda_name);
3409               _bfd_elf_swap_verdaux_out (output_bfd,
3410                                          &defaux, (Elf_External_Verdaux *) p);
3411               p += sizeof (Elf_External_Verdaux);
3412             }
3413         }
3414       while (def.vd_next);
3415     }
3416
3417   /* Adjust version references.  */
3418   if (elf_tdata (output_bfd)->verref)
3419     {
3420       asection *s;
3421       bfd_byte *p;
3422       bfd_size_type i;
3423       Elf_Internal_Verneed need;
3424       Elf_Internal_Vernaux needaux;
3425
3426       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3427       p = s->contents;
3428       do
3429         {
3430           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3431                                     &need);
3432           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3433           _bfd_elf_swap_verneed_out (output_bfd, &need,
3434                                      (Elf_External_Verneed *) p);
3435           p += sizeof (Elf_External_Verneed);
3436           for (i = 0; i < need.vn_cnt; ++i)
3437             {
3438               _bfd_elf_swap_vernaux_in (output_bfd,
3439                                         (Elf_External_Vernaux *) p, &needaux);
3440               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3441                                                          needaux.vna_name);
3442               _bfd_elf_swap_vernaux_out (output_bfd,
3443                                          &needaux,
3444                                          (Elf_External_Vernaux *) p);
3445               p += sizeof (Elf_External_Vernaux);
3446             }
3447         }
3448       while (need.vn_next);
3449     }
3450
3451   return TRUE;
3452 }
3453 \f
3454 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3455    The default is to only match when the INPUT and OUTPUT are exactly
3456    the same target.  */
3457
3458 bfd_boolean
3459 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3460                                     const bfd_target *output)
3461 {
3462   return input == output;
3463 }
3464
3465 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3466    This version is used when different targets for the same architecture
3467    are virtually identical.  */
3468
3469 bfd_boolean
3470 _bfd_elf_relocs_compatible (const bfd_target *input,
3471                             const bfd_target *output)
3472 {
3473   const struct elf_backend_data *obed, *ibed;
3474
3475   if (input == output)
3476     return TRUE;
3477
3478   ibed = xvec_get_elf_backend_data (input);
3479   obed = xvec_get_elf_backend_data (output);
3480
3481   if (ibed->arch != obed->arch)
3482     return FALSE;
3483
3484   /* If both backends are using this function, deem them compatible.  */
3485   return ibed->relocs_compatible == obed->relocs_compatible;
3486 }
3487
3488 /* Make a special call to the linker "notice" function to tell it that
3489    we are about to handle an as-needed lib, or have finished
3490    processing the lib.  */
3491
3492 bfd_boolean
3493 _bfd_elf_notice_as_needed (bfd *ibfd,
3494                            struct bfd_link_info *info,
3495                            enum notice_asneeded_action act)
3496 {
3497   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3498 }
3499
3500 /* Check relocations an ELF object file.  */
3501
3502 bfd_boolean
3503 _bfd_elf_link_check_relocs (bfd *abfd, struct bfd_link_info *info)
3504 {
3505   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3506   struct elf_link_hash_table *htab = elf_hash_table (info);
3507
3508   /* If this object is the same format as the output object, and it is
3509      not a shared library, then let the backend look through the
3510      relocs.
3511
3512      This is required to build global offset table entries and to
3513      arrange for dynamic relocs.  It is not required for the
3514      particular common case of linking non PIC code, even when linking
3515      against shared libraries, but unfortunately there is no way of
3516      knowing whether an object file has been compiled PIC or not.
3517      Looking through the relocs is not particularly time consuming.
3518      The problem is that we must either (1) keep the relocs in memory,
3519      which causes the linker to require additional runtime memory or
3520      (2) read the relocs twice from the input file, which wastes time.
3521      This would be a good case for using mmap.
3522
3523      I have no idea how to handle linking PIC code into a file of a
3524      different format.  It probably can't be done.  */
3525   if ((abfd->flags & DYNAMIC) == 0
3526       && is_elf_hash_table (htab)
3527       && bed->check_relocs != NULL
3528       && elf_object_id (abfd) == elf_hash_table_id (htab)
3529       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
3530     {
3531       asection *o;
3532
3533       for (o = abfd->sections; o != NULL; o = o->next)
3534         {
3535           Elf_Internal_Rela *internal_relocs;
3536           bfd_boolean ok;
3537
3538           /* Don't check relocations in excluded sections.  */
3539           if ((o->flags & SEC_RELOC) == 0
3540               || (o->flags & SEC_EXCLUDE) != 0
3541               || o->reloc_count == 0
3542               || ((info->strip == strip_all || info->strip == strip_debugger)
3543                   && (o->flags & SEC_DEBUGGING) != 0)
3544               || bfd_is_abs_section (o->output_section))
3545             continue;
3546
3547           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
3548                                                        info->keep_memory);
3549           if (internal_relocs == NULL)
3550             return FALSE;
3551
3552           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
3553
3554           if (elf_section_data (o)->relocs != internal_relocs)
3555             free (internal_relocs);
3556
3557           if (! ok)
3558             return FALSE;
3559         }
3560     }
3561
3562   return TRUE;
3563 }
3564
3565 /* Add symbols from an ELF object file to the linker hash table.  */
3566
3567 static bfd_boolean
3568 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3569 {
3570   Elf_Internal_Ehdr *ehdr;
3571   Elf_Internal_Shdr *hdr;
3572   bfd_size_type symcount;
3573   bfd_size_type extsymcount;
3574   bfd_size_type extsymoff;
3575   struct elf_link_hash_entry **sym_hash;
3576   bfd_boolean dynamic;
3577   Elf_External_Versym *extversym = NULL;
3578   Elf_External_Versym *ever;
3579   struct elf_link_hash_entry *weaks;
3580   struct elf_link_hash_entry **nondeflt_vers = NULL;
3581   bfd_size_type nondeflt_vers_cnt = 0;
3582   Elf_Internal_Sym *isymbuf = NULL;
3583   Elf_Internal_Sym *isym;
3584   Elf_Internal_Sym *isymend;
3585   const struct elf_backend_data *bed;
3586   bfd_boolean add_needed;
3587   struct elf_link_hash_table *htab;
3588   bfd_size_type amt;
3589   void *alloc_mark = NULL;
3590   struct bfd_hash_entry **old_table = NULL;
3591   unsigned int old_size = 0;
3592   unsigned int old_count = 0;
3593   void *old_tab = NULL;
3594   void *old_ent;
3595   struct bfd_link_hash_entry *old_undefs = NULL;
3596   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3597   long old_dynsymcount = 0;
3598   bfd_size_type old_dynstr_size = 0;
3599   size_t tabsize = 0;
3600   asection *s;
3601   bfd_boolean just_syms;
3602
3603   htab = elf_hash_table (info);
3604   bed = get_elf_backend_data (abfd);
3605
3606   if ((abfd->flags & DYNAMIC) == 0)
3607     dynamic = FALSE;
3608   else
3609     {
3610       dynamic = TRUE;
3611
3612       /* You can't use -r against a dynamic object.  Also, there's no
3613          hope of using a dynamic object which does not exactly match
3614          the format of the output file.  */
3615       if (bfd_link_relocatable (info)
3616           || !is_elf_hash_table (htab)
3617           || info->output_bfd->xvec != abfd->xvec)
3618         {
3619           if (bfd_link_relocatable (info))
3620             bfd_set_error (bfd_error_invalid_operation);
3621           else
3622             bfd_set_error (bfd_error_wrong_format);
3623           goto error_return;
3624         }
3625     }
3626
3627   ehdr = elf_elfheader (abfd);
3628   if (info->warn_alternate_em
3629       && bed->elf_machine_code != ehdr->e_machine
3630       && ((bed->elf_machine_alt1 != 0
3631            && ehdr->e_machine == bed->elf_machine_alt1)
3632           || (bed->elf_machine_alt2 != 0
3633               && ehdr->e_machine == bed->elf_machine_alt2)))
3634     info->callbacks->einfo
3635       (_("%P: alternate ELF machine code found (%d) in %B, expecting %d\n"),
3636        ehdr->e_machine, abfd, bed->elf_machine_code);
3637
3638   /* As a GNU extension, any input sections which are named
3639      .gnu.warning.SYMBOL are treated as warning symbols for the given
3640      symbol.  This differs from .gnu.warning sections, which generate
3641      warnings when they are included in an output file.  */
3642   /* PR 12761: Also generate this warning when building shared libraries.  */
3643   for (s = abfd->sections; s != NULL; s = s->next)
3644     {
3645       const char *name;
3646
3647       name = bfd_get_section_name (abfd, s);
3648       if (CONST_STRNEQ (name, ".gnu.warning."))
3649         {
3650           char *msg;
3651           bfd_size_type sz;
3652
3653           name += sizeof ".gnu.warning." - 1;
3654
3655           /* If this is a shared object, then look up the symbol
3656              in the hash table.  If it is there, and it is already
3657              been defined, then we will not be using the entry
3658              from this shared object, so we don't need to warn.
3659              FIXME: If we see the definition in a regular object
3660              later on, we will warn, but we shouldn't.  The only
3661              fix is to keep track of what warnings we are supposed
3662              to emit, and then handle them all at the end of the
3663              link.  */
3664           if (dynamic)
3665             {
3666               struct elf_link_hash_entry *h;
3667
3668               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3669
3670               /* FIXME: What about bfd_link_hash_common?  */
3671               if (h != NULL
3672                   && (h->root.type == bfd_link_hash_defined
3673                       || h->root.type == bfd_link_hash_defweak))
3674                 continue;
3675             }
3676
3677           sz = s->size;
3678           msg = (char *) bfd_alloc (abfd, sz + 1);
3679           if (msg == NULL)
3680             goto error_return;
3681
3682           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3683             goto error_return;
3684
3685           msg[sz] = '\0';
3686
3687           if (! (_bfd_generic_link_add_one_symbol
3688                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3689                   FALSE, bed->collect, NULL)))
3690             goto error_return;
3691
3692           if (bfd_link_executable (info))
3693             {
3694               /* Clobber the section size so that the warning does
3695                  not get copied into the output file.  */
3696               s->size = 0;
3697
3698               /* Also set SEC_EXCLUDE, so that symbols defined in
3699                  the warning section don't get copied to the output.  */
3700               s->flags |= SEC_EXCLUDE;
3701             }
3702         }
3703     }
3704
3705   just_syms = ((s = abfd->sections) != NULL
3706                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3707
3708   add_needed = TRUE;
3709   if (! dynamic)
3710     {
3711       /* If we are creating a shared library, create all the dynamic
3712          sections immediately.  We need to attach them to something,
3713          so we attach them to this BFD, provided it is the right
3714          format and is not from ld --just-symbols.  Always create the
3715          dynamic sections for -E/--dynamic-list.  FIXME: If there
3716          are no input BFD's of the same format as the output, we can't
3717          make a shared library.  */
3718       if (!just_syms
3719           && (bfd_link_pic (info)
3720               || (!bfd_link_relocatable (info)
3721                   && (info->export_dynamic || info->dynamic)))
3722           && is_elf_hash_table (htab)
3723           && info->output_bfd->xvec == abfd->xvec
3724           && !htab->dynamic_sections_created)
3725         {
3726           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3727             goto error_return;
3728         }
3729     }
3730   else if (!is_elf_hash_table (htab))
3731     goto error_return;
3732   else
3733     {
3734       const char *soname = NULL;
3735       char *audit = NULL;
3736       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3737       int ret;
3738
3739       /* ld --just-symbols and dynamic objects don't mix very well.
3740          ld shouldn't allow it.  */
3741       if (just_syms)
3742         abort ();
3743
3744       /* If this dynamic lib was specified on the command line with
3745          --as-needed in effect, then we don't want to add a DT_NEEDED
3746          tag unless the lib is actually used.  Similary for libs brought
3747          in by another lib's DT_NEEDED.  When --no-add-needed is used
3748          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3749          any dynamic library in DT_NEEDED tags in the dynamic lib at
3750          all.  */
3751       add_needed = (elf_dyn_lib_class (abfd)
3752                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3753                        | DYN_NO_NEEDED)) == 0;
3754
3755       s = bfd_get_section_by_name (abfd, ".dynamic");
3756       if (s != NULL)
3757         {
3758           bfd_byte *dynbuf;
3759           bfd_byte *extdyn;
3760           unsigned int elfsec;
3761           unsigned long shlink;
3762
3763           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3764             {
3765 error_free_dyn:
3766               free (dynbuf);
3767               goto error_return;
3768             }
3769
3770           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3771           if (elfsec == SHN_BAD)
3772             goto error_free_dyn;
3773           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3774
3775           for (extdyn = dynbuf;
3776                extdyn < dynbuf + s->size;
3777                extdyn += bed->s->sizeof_dyn)
3778             {
3779               Elf_Internal_Dyn dyn;
3780
3781               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3782               if (dyn.d_tag == DT_SONAME)
3783                 {
3784                   unsigned int tagv = dyn.d_un.d_val;
3785                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3786                   if (soname == NULL)
3787                     goto error_free_dyn;
3788                 }
3789               if (dyn.d_tag == DT_NEEDED)
3790                 {
3791                   struct bfd_link_needed_list *n, **pn;
3792                   char *fnm, *anm;
3793                   unsigned int tagv = dyn.d_un.d_val;
3794
3795                   amt = sizeof (struct bfd_link_needed_list);
3796                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3797                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3798                   if (n == NULL || fnm == NULL)
3799                     goto error_free_dyn;
3800                   amt = strlen (fnm) + 1;
3801                   anm = (char *) bfd_alloc (abfd, amt);
3802                   if (anm == NULL)
3803                     goto error_free_dyn;
3804                   memcpy (anm, fnm, amt);
3805                   n->name = anm;
3806                   n->by = abfd;
3807                   n->next = NULL;
3808                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
3809                     ;
3810                   *pn = n;
3811                 }
3812               if (dyn.d_tag == DT_RUNPATH)
3813                 {
3814                   struct bfd_link_needed_list *n, **pn;
3815                   char *fnm, *anm;
3816                   unsigned int tagv = dyn.d_un.d_val;
3817
3818                   amt = sizeof (struct bfd_link_needed_list);
3819                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3820                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3821                   if (n == NULL || fnm == NULL)
3822                     goto error_free_dyn;
3823                   amt = strlen (fnm) + 1;
3824                   anm = (char *) bfd_alloc (abfd, amt);
3825                   if (anm == NULL)
3826                     goto error_free_dyn;
3827                   memcpy (anm, fnm, amt);
3828                   n->name = anm;
3829                   n->by = abfd;
3830                   n->next = NULL;
3831                   for (pn = & runpath;
3832                        *pn != NULL;
3833                        pn = &(*pn)->next)
3834                     ;
3835                   *pn = n;
3836                 }
3837               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
3838               if (!runpath && dyn.d_tag == DT_RPATH)
3839                 {
3840                   struct bfd_link_needed_list *n, **pn;
3841                   char *fnm, *anm;
3842                   unsigned int tagv = dyn.d_un.d_val;
3843
3844                   amt = sizeof (struct bfd_link_needed_list);
3845                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3846                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3847                   if (n == NULL || fnm == NULL)
3848                     goto error_free_dyn;
3849                   amt = strlen (fnm) + 1;
3850                   anm = (char *) bfd_alloc (abfd, amt);
3851                   if (anm == NULL)
3852                     goto error_free_dyn;
3853                   memcpy (anm, fnm, amt);
3854                   n->name = anm;
3855                   n->by = abfd;
3856                   n->next = NULL;
3857                   for (pn = & rpath;
3858                        *pn != NULL;
3859                        pn = &(*pn)->next)
3860                     ;
3861                   *pn = n;
3862                 }
3863               if (dyn.d_tag == DT_AUDIT)
3864                 {
3865                   unsigned int tagv = dyn.d_un.d_val;
3866                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3867                 }
3868             }
3869
3870           free (dynbuf);
3871         }
3872
3873       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
3874          frees all more recently bfd_alloc'd blocks as well.  */
3875       if (runpath)
3876         rpath = runpath;
3877
3878       if (rpath)
3879         {
3880           struct bfd_link_needed_list **pn;
3881           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
3882             ;
3883           *pn = rpath;
3884         }
3885
3886       /* We do not want to include any of the sections in a dynamic
3887          object in the output file.  We hack by simply clobbering the
3888          list of sections in the BFD.  This could be handled more
3889          cleanly by, say, a new section flag; the existing
3890          SEC_NEVER_LOAD flag is not the one we want, because that one
3891          still implies that the section takes up space in the output
3892          file.  */
3893       bfd_section_list_clear (abfd);
3894
3895       /* Find the name to use in a DT_NEEDED entry that refers to this
3896          object.  If the object has a DT_SONAME entry, we use it.
3897          Otherwise, if the generic linker stuck something in
3898          elf_dt_name, we use that.  Otherwise, we just use the file
3899          name.  */
3900       if (soname == NULL || *soname == '\0')
3901         {
3902           soname = elf_dt_name (abfd);
3903           if (soname == NULL || *soname == '\0')
3904             soname = bfd_get_filename (abfd);
3905         }
3906
3907       /* Save the SONAME because sometimes the linker emulation code
3908          will need to know it.  */
3909       elf_dt_name (abfd) = soname;
3910
3911       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
3912       if (ret < 0)
3913         goto error_return;
3914
3915       /* If we have already included this dynamic object in the
3916          link, just ignore it.  There is no reason to include a
3917          particular dynamic object more than once.  */
3918       if (ret > 0)
3919         return TRUE;
3920
3921       /* Save the DT_AUDIT entry for the linker emulation code. */
3922       elf_dt_audit (abfd) = audit;
3923     }
3924
3925   /* If this is a dynamic object, we always link against the .dynsym
3926      symbol table, not the .symtab symbol table.  The dynamic linker
3927      will only see the .dynsym symbol table, so there is no reason to
3928      look at .symtab for a dynamic object.  */
3929
3930   if (! dynamic || elf_dynsymtab (abfd) == 0)
3931     hdr = &elf_tdata (abfd)->symtab_hdr;
3932   else
3933     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3934
3935   symcount = hdr->sh_size / bed->s->sizeof_sym;
3936
3937   /* The sh_info field of the symtab header tells us where the
3938      external symbols start.  We don't care about the local symbols at
3939      this point.  */
3940   if (elf_bad_symtab (abfd))
3941     {
3942       extsymcount = symcount;
3943       extsymoff = 0;
3944     }
3945   else
3946     {
3947       extsymcount = symcount - hdr->sh_info;
3948       extsymoff = hdr->sh_info;
3949     }
3950
3951   sym_hash = elf_sym_hashes (abfd);
3952   if (extsymcount != 0)
3953     {
3954       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3955                                       NULL, NULL, NULL);
3956       if (isymbuf == NULL)
3957         goto error_return;
3958
3959       if (sym_hash == NULL)
3960         {
3961           /* We store a pointer to the hash table entry for each
3962              external symbol.  */
3963           amt = extsymcount * sizeof (struct elf_link_hash_entry *);
3964           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
3965           if (sym_hash == NULL)
3966             goto error_free_sym;
3967           elf_sym_hashes (abfd) = sym_hash;
3968         }
3969     }
3970
3971   if (dynamic)
3972     {
3973       /* Read in any version definitions.  */
3974       if (!_bfd_elf_slurp_version_tables (abfd,
3975                                           info->default_imported_symver))
3976         goto error_free_sym;
3977
3978       /* Read in the symbol versions, but don't bother to convert them
3979          to internal format.  */
3980       if (elf_dynversym (abfd) != 0)
3981         {
3982           Elf_Internal_Shdr *versymhdr;
3983
3984           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
3985           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
3986           if (extversym == NULL)
3987             goto error_free_sym;
3988           amt = versymhdr->sh_size;
3989           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
3990               || bfd_bread (extversym, amt, abfd) != amt)
3991             goto error_free_vers;
3992         }
3993     }
3994
3995   /* If we are loading an as-needed shared lib, save the symbol table
3996      state before we start adding symbols.  If the lib turns out
3997      to be unneeded, restore the state.  */
3998   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
3999     {
4000       unsigned int i;
4001       size_t entsize;
4002
4003       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
4004         {
4005           struct bfd_hash_entry *p;
4006           struct elf_link_hash_entry *h;
4007
4008           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4009             {
4010               h = (struct elf_link_hash_entry *) p;
4011               entsize += htab->root.table.entsize;
4012               if (h->root.type == bfd_link_hash_warning)
4013                 entsize += htab->root.table.entsize;
4014             }
4015         }
4016
4017       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
4018       old_tab = bfd_malloc (tabsize + entsize);
4019       if (old_tab == NULL)
4020         goto error_free_vers;
4021
4022       /* Remember the current objalloc pointer, so that all mem for
4023          symbols added can later be reclaimed.  */
4024       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
4025       if (alloc_mark == NULL)
4026         goto error_free_vers;
4027
4028       /* Make a special call to the linker "notice" function to
4029          tell it that we are about to handle an as-needed lib.  */
4030       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
4031         goto error_free_vers;
4032
4033       /* Clone the symbol table.  Remember some pointers into the
4034          symbol table, and dynamic symbol count.  */
4035       old_ent = (char *) old_tab + tabsize;
4036       memcpy (old_tab, htab->root.table.table, tabsize);
4037       old_undefs = htab->root.undefs;
4038       old_undefs_tail = htab->root.undefs_tail;
4039       old_table = htab->root.table.table;
4040       old_size = htab->root.table.size;
4041       old_count = htab->root.table.count;
4042       old_dynsymcount = htab->dynsymcount;
4043       old_dynstr_size = _bfd_elf_strtab_size (htab->dynstr);
4044
4045       for (i = 0; i < htab->root.table.size; i++)
4046         {
4047           struct bfd_hash_entry *p;
4048           struct elf_link_hash_entry *h;
4049
4050           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4051             {
4052               memcpy (old_ent, p, htab->root.table.entsize);
4053               old_ent = (char *) old_ent + htab->root.table.entsize;
4054               h = (struct elf_link_hash_entry *) p;
4055               if (h->root.type == bfd_link_hash_warning)
4056                 {
4057                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
4058                   old_ent = (char *) old_ent + htab->root.table.entsize;
4059                 }
4060             }
4061         }
4062     }
4063
4064   weaks = NULL;
4065   ever = extversym != NULL ? extversym + extsymoff : NULL;
4066   for (isym = isymbuf, isymend = isymbuf + extsymcount;
4067        isym < isymend;
4068        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
4069     {
4070       int bind;
4071       bfd_vma value;
4072       asection *sec, *new_sec;
4073       flagword flags;
4074       const char *name;
4075       struct elf_link_hash_entry *h;
4076       struct elf_link_hash_entry *hi;
4077       bfd_boolean definition;
4078       bfd_boolean size_change_ok;
4079       bfd_boolean type_change_ok;
4080       bfd_boolean new_weakdef;
4081       bfd_boolean new_weak;
4082       bfd_boolean old_weak;
4083       bfd_boolean override;
4084       bfd_boolean common;
4085       unsigned int old_alignment;
4086       bfd *old_bfd;
4087       bfd_boolean matched;
4088
4089       override = FALSE;
4090
4091       flags = BSF_NO_FLAGS;
4092       sec = NULL;
4093       value = isym->st_value;
4094       common = bed->common_definition (isym);
4095
4096       bind = ELF_ST_BIND (isym->st_info);
4097       switch (bind)
4098         {
4099         case STB_LOCAL:
4100           /* This should be impossible, since ELF requires that all
4101              global symbols follow all local symbols, and that sh_info
4102              point to the first global symbol.  Unfortunately, Irix 5
4103              screws this up.  */
4104           continue;
4105
4106         case STB_GLOBAL:
4107           if (isym->st_shndx != SHN_UNDEF && !common)
4108             flags = BSF_GLOBAL;
4109           break;
4110
4111         case STB_WEAK:
4112           flags = BSF_WEAK;
4113           break;
4114
4115         case STB_GNU_UNIQUE:
4116           flags = BSF_GNU_UNIQUE;
4117           break;
4118
4119         default:
4120           /* Leave it up to the processor backend.  */
4121           break;
4122         }
4123
4124       if (isym->st_shndx == SHN_UNDEF)
4125         sec = bfd_und_section_ptr;
4126       else if (isym->st_shndx == SHN_ABS)
4127         sec = bfd_abs_section_ptr;
4128       else if (isym->st_shndx == SHN_COMMON)
4129         {
4130           sec = bfd_com_section_ptr;
4131           /* What ELF calls the size we call the value.  What ELF
4132              calls the value we call the alignment.  */
4133           value = isym->st_size;
4134         }
4135       else
4136         {
4137           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
4138           if (sec == NULL)
4139             sec = bfd_abs_section_ptr;
4140           else if (discarded_section (sec))
4141             {
4142               /* Symbols from discarded section are undefined.  We keep
4143                  its visibility.  */
4144               sec = bfd_und_section_ptr;
4145               isym->st_shndx = SHN_UNDEF;
4146             }
4147           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
4148             value -= sec->vma;
4149         }
4150
4151       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4152                                               isym->st_name);
4153       if (name == NULL)
4154         goto error_free_vers;
4155
4156       if (isym->st_shndx == SHN_COMMON
4157           && (abfd->flags & BFD_PLUGIN) != 0)
4158         {
4159           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4160
4161           if (xc == NULL)
4162             {
4163               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4164                                  | SEC_EXCLUDE);
4165               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4166               if (xc == NULL)
4167                 goto error_free_vers;
4168             }
4169           sec = xc;
4170         }
4171       else if (isym->st_shndx == SHN_COMMON
4172                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4173                && !bfd_link_relocatable (info))
4174         {
4175           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4176
4177           if (tcomm == NULL)
4178             {
4179               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4180                                  | SEC_LINKER_CREATED);
4181               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4182               if (tcomm == NULL)
4183                 goto error_free_vers;
4184             }
4185           sec = tcomm;
4186         }
4187       else if (bed->elf_add_symbol_hook)
4188         {
4189           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4190                                              &sec, &value))
4191             goto error_free_vers;
4192
4193           /* The hook function sets the name to NULL if this symbol
4194              should be skipped for some reason.  */
4195           if (name == NULL)
4196             continue;
4197         }
4198
4199       /* Sanity check that all possibilities were handled.  */
4200       if (sec == NULL)
4201         {
4202           bfd_set_error (bfd_error_bad_value);
4203           goto error_free_vers;
4204         }
4205
4206       /* Silently discard TLS symbols from --just-syms.  There's
4207          no way to combine a static TLS block with a new TLS block
4208          for this executable.  */
4209       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4210           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4211         continue;
4212
4213       if (bfd_is_und_section (sec)
4214           || bfd_is_com_section (sec))
4215         definition = FALSE;
4216       else
4217         definition = TRUE;
4218
4219       size_change_ok = FALSE;
4220       type_change_ok = bed->type_change_ok;
4221       old_weak = FALSE;
4222       matched = FALSE;
4223       old_alignment = 0;
4224       old_bfd = NULL;
4225       new_sec = sec;
4226
4227       if (is_elf_hash_table (htab))
4228         {
4229           Elf_Internal_Versym iver;
4230           unsigned int vernum = 0;
4231           bfd_boolean skip;
4232
4233           if (ever == NULL)
4234             {
4235               if (info->default_imported_symver)
4236                 /* Use the default symbol version created earlier.  */
4237                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4238               else
4239                 iver.vs_vers = 0;
4240             }
4241           else
4242             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4243
4244           vernum = iver.vs_vers & VERSYM_VERSION;
4245
4246           /* If this is a hidden symbol, or if it is not version
4247              1, we append the version name to the symbol name.
4248              However, we do not modify a non-hidden absolute symbol
4249              if it is not a function, because it might be the version
4250              symbol itself.  FIXME: What if it isn't?  */
4251           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4252               || (vernum > 1
4253                   && (!bfd_is_abs_section (sec)
4254                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4255             {
4256               const char *verstr;
4257               size_t namelen, verlen, newlen;
4258               char *newname, *p;
4259
4260               if (isym->st_shndx != SHN_UNDEF)
4261                 {
4262                   if (vernum > elf_tdata (abfd)->cverdefs)
4263                     verstr = NULL;
4264                   else if (vernum > 1)
4265                     verstr =
4266                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4267                   else
4268                     verstr = "";
4269
4270                   if (verstr == NULL)
4271                     {
4272                       (*_bfd_error_handler)
4273                         (_("%B: %s: invalid version %u (max %d)"),
4274                          abfd, name, vernum,
4275                          elf_tdata (abfd)->cverdefs);
4276                       bfd_set_error (bfd_error_bad_value);
4277                       goto error_free_vers;
4278                     }
4279                 }
4280               else
4281                 {
4282                   /* We cannot simply test for the number of
4283                      entries in the VERNEED section since the
4284                      numbers for the needed versions do not start
4285                      at 0.  */
4286                   Elf_Internal_Verneed *t;
4287
4288                   verstr = NULL;
4289                   for (t = elf_tdata (abfd)->verref;
4290                        t != NULL;
4291                        t = t->vn_nextref)
4292                     {
4293                       Elf_Internal_Vernaux *a;
4294
4295                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4296                         {
4297                           if (a->vna_other == vernum)
4298                             {
4299                               verstr = a->vna_nodename;
4300                               break;
4301                             }
4302                         }
4303                       if (a != NULL)
4304                         break;
4305                     }
4306                   if (verstr == NULL)
4307                     {
4308                       (*_bfd_error_handler)
4309                         (_("%B: %s: invalid needed version %d"),
4310                          abfd, name, vernum);
4311                       bfd_set_error (bfd_error_bad_value);
4312                       goto error_free_vers;
4313                     }
4314                 }
4315
4316               namelen = strlen (name);
4317               verlen = strlen (verstr);
4318               newlen = namelen + verlen + 2;
4319               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4320                   && isym->st_shndx != SHN_UNDEF)
4321                 ++newlen;
4322
4323               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4324               if (newname == NULL)
4325                 goto error_free_vers;
4326               memcpy (newname, name, namelen);
4327               p = newname + namelen;
4328               *p++ = ELF_VER_CHR;
4329               /* If this is a defined non-hidden version symbol,
4330                  we add another @ to the name.  This indicates the
4331                  default version of the symbol.  */
4332               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4333                   && isym->st_shndx != SHN_UNDEF)
4334                 *p++ = ELF_VER_CHR;
4335               memcpy (p, verstr, verlen + 1);
4336
4337               name = newname;
4338             }
4339
4340           /* If this symbol has default visibility and the user has
4341              requested we not re-export it, then mark it as hidden.  */
4342           if (!bfd_is_und_section (sec)
4343               && !dynamic
4344               && abfd->no_export
4345               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4346             isym->st_other = (STV_HIDDEN
4347                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4348
4349           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4350                                       sym_hash, &old_bfd, &old_weak,
4351                                       &old_alignment, &skip, &override,
4352                                       &type_change_ok, &size_change_ok,
4353                                       &matched))
4354             goto error_free_vers;
4355
4356           if (skip)
4357             continue;
4358
4359           /* Override a definition only if the new symbol matches the
4360              existing one.  */
4361           if (override && matched)
4362             definition = FALSE;
4363
4364           h = *sym_hash;
4365           while (h->root.type == bfd_link_hash_indirect
4366                  || h->root.type == bfd_link_hash_warning)
4367             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4368
4369           if (elf_tdata (abfd)->verdef != NULL
4370               && vernum > 1
4371               && definition)
4372             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4373         }
4374
4375       if (! (_bfd_generic_link_add_one_symbol
4376              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4377               (struct bfd_link_hash_entry **) sym_hash)))
4378         goto error_free_vers;
4379
4380       h = *sym_hash;
4381       /* We need to make sure that indirect symbol dynamic flags are
4382          updated.  */
4383       hi = h;
4384       while (h->root.type == bfd_link_hash_indirect
4385              || h->root.type == bfd_link_hash_warning)
4386         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4387
4388       *sym_hash = h;
4389
4390       new_weak = (flags & BSF_WEAK) != 0;
4391       new_weakdef = FALSE;
4392       if (dynamic
4393           && definition
4394           && new_weak
4395           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4396           && is_elf_hash_table (htab)
4397           && h->u.weakdef == NULL)
4398         {
4399           /* Keep a list of all weak defined non function symbols from
4400              a dynamic object, using the weakdef field.  Later in this
4401              function we will set the weakdef field to the correct
4402              value.  We only put non-function symbols from dynamic
4403              objects on this list, because that happens to be the only
4404              time we need to know the normal symbol corresponding to a
4405              weak symbol, and the information is time consuming to
4406              figure out.  If the weakdef field is not already NULL,
4407              then this symbol was already defined by some previous
4408              dynamic object, and we will be using that previous
4409              definition anyhow.  */
4410
4411           h->u.weakdef = weaks;
4412           weaks = h;
4413           new_weakdef = TRUE;
4414         }
4415
4416       /* Set the alignment of a common symbol.  */
4417       if ((common || bfd_is_com_section (sec))
4418           && h->root.type == bfd_link_hash_common)
4419         {
4420           unsigned int align;
4421
4422           if (common)
4423             align = bfd_log2 (isym->st_value);
4424           else
4425             {
4426               /* The new symbol is a common symbol in a shared object.
4427                  We need to get the alignment from the section.  */
4428               align = new_sec->alignment_power;
4429             }
4430           if (align > old_alignment)
4431             h->root.u.c.p->alignment_power = align;
4432           else
4433             h->root.u.c.p->alignment_power = old_alignment;
4434         }
4435
4436       if (is_elf_hash_table (htab))
4437         {
4438           /* Set a flag in the hash table entry indicating the type of
4439              reference or definition we just found.  A dynamic symbol
4440              is one which is referenced or defined by both a regular
4441              object and a shared object.  */
4442           bfd_boolean dynsym = FALSE;
4443
4444           /* Plugin symbols aren't normal.  Don't set def_regular or
4445              ref_regular for them, or make them dynamic.  */
4446           if ((abfd->flags & BFD_PLUGIN) != 0)
4447             ;
4448           else if (! dynamic)
4449             {
4450               if (! definition)
4451                 {
4452                   h->ref_regular = 1;
4453                   if (bind != STB_WEAK)
4454                     h->ref_regular_nonweak = 1;
4455                 }
4456               else
4457                 {
4458                   h->def_regular = 1;
4459                   if (h->def_dynamic)
4460                     {
4461                       h->def_dynamic = 0;
4462                       h->ref_dynamic = 1;
4463                     }
4464                 }
4465
4466               /* If the indirect symbol has been forced local, don't
4467                  make the real symbol dynamic.  */
4468               if ((h == hi || !hi->forced_local)
4469                   && (bfd_link_dll (info)
4470                       || h->def_dynamic
4471                       || h->ref_dynamic))
4472                 dynsym = TRUE;
4473             }
4474           else
4475             {
4476               if (! definition)
4477                 {
4478                   h->ref_dynamic = 1;
4479                   hi->ref_dynamic = 1;
4480                 }
4481               else
4482                 {
4483                   h->def_dynamic = 1;
4484                   hi->def_dynamic = 1;
4485                 }
4486
4487               /* If the indirect symbol has been forced local, don't
4488                  make the real symbol dynamic.  */
4489               if ((h == hi || !hi->forced_local)
4490                   && (h->def_regular
4491                       || h->ref_regular
4492                       || (h->u.weakdef != NULL
4493                           && ! new_weakdef
4494                           && h->u.weakdef->dynindx != -1)))
4495                 dynsym = TRUE;
4496             }
4497
4498           /* Check to see if we need to add an indirect symbol for
4499              the default name.  */
4500           if (definition
4501               || (!override && h->root.type == bfd_link_hash_common))
4502             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4503                                               sec, value, &old_bfd, &dynsym))
4504               goto error_free_vers;
4505
4506           /* Check the alignment when a common symbol is involved. This
4507              can change when a common symbol is overridden by a normal
4508              definition or a common symbol is ignored due to the old
4509              normal definition. We need to make sure the maximum
4510              alignment is maintained.  */
4511           if ((old_alignment || common)
4512               && h->root.type != bfd_link_hash_common)
4513             {
4514               unsigned int common_align;
4515               unsigned int normal_align;
4516               unsigned int symbol_align;
4517               bfd *normal_bfd;
4518               bfd *common_bfd;
4519
4520               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4521                           || h->root.type == bfd_link_hash_defweak);
4522
4523               symbol_align = ffs (h->root.u.def.value) - 1;
4524               if (h->root.u.def.section->owner != NULL
4525                   && (h->root.u.def.section->owner->flags & DYNAMIC) == 0)
4526                 {
4527                   normal_align = h->root.u.def.section->alignment_power;
4528                   if (normal_align > symbol_align)
4529                     normal_align = symbol_align;
4530                 }
4531               else
4532                 normal_align = symbol_align;
4533
4534               if (old_alignment)
4535                 {
4536                   common_align = old_alignment;
4537                   common_bfd = old_bfd;
4538                   normal_bfd = abfd;
4539                 }
4540               else
4541                 {
4542                   common_align = bfd_log2 (isym->st_value);
4543                   common_bfd = abfd;
4544                   normal_bfd = old_bfd;
4545                 }
4546
4547               if (normal_align < common_align)
4548                 {
4549                   /* PR binutils/2735 */
4550                   if (normal_bfd == NULL)
4551                     (*_bfd_error_handler)
4552                       (_("Warning: alignment %u of common symbol `%s' in %B is"
4553                          " greater than the alignment (%u) of its section %A"),
4554                        common_bfd, h->root.u.def.section,
4555                        1 << common_align, name, 1 << normal_align);
4556                   else
4557                     (*_bfd_error_handler)
4558                       (_("Warning: alignment %u of symbol `%s' in %B"
4559                          " is smaller than %u in %B"),
4560                        normal_bfd, common_bfd,
4561                        1 << normal_align, name, 1 << common_align);
4562                 }
4563             }
4564
4565           /* Remember the symbol size if it isn't undefined.  */
4566           if (isym->st_size != 0
4567               && isym->st_shndx != SHN_UNDEF
4568               && (definition || h->size == 0))
4569             {
4570               if (h->size != 0
4571                   && h->size != isym->st_size
4572                   && ! size_change_ok)
4573                 (*_bfd_error_handler)
4574                   (_("Warning: size of symbol `%s' changed"
4575                      " from %lu in %B to %lu in %B"),
4576                    old_bfd, abfd,
4577                    name, (unsigned long) h->size,
4578                    (unsigned long) isym->st_size);
4579
4580               h->size = isym->st_size;
4581             }
4582
4583           /* If this is a common symbol, then we always want H->SIZE
4584              to be the size of the common symbol.  The code just above
4585              won't fix the size if a common symbol becomes larger.  We
4586              don't warn about a size change here, because that is
4587              covered by --warn-common.  Allow changes between different
4588              function types.  */
4589           if (h->root.type == bfd_link_hash_common)
4590             h->size = h->root.u.c.size;
4591
4592           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4593               && ((definition && !new_weak)
4594                   || (old_weak && h->root.type == bfd_link_hash_common)
4595                   || h->type == STT_NOTYPE))
4596             {
4597               unsigned int type = ELF_ST_TYPE (isym->st_info);
4598
4599               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4600                  symbol.  */
4601               if (type == STT_GNU_IFUNC
4602                   && (abfd->flags & DYNAMIC) != 0)
4603                 type = STT_FUNC;
4604
4605               if (h->type != type)
4606                 {
4607                   if (h->type != STT_NOTYPE && ! type_change_ok)
4608                     (*_bfd_error_handler)
4609                       (_("Warning: type of symbol `%s' changed"
4610                          " from %d to %d in %B"),
4611                        abfd, name, h->type, type);
4612
4613                   h->type = type;
4614                 }
4615             }
4616
4617           /* Merge st_other field.  */
4618           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4619
4620           /* We don't want to make debug symbol dynamic.  */
4621           if (definition
4622               && (sec->flags & SEC_DEBUGGING)
4623               && !bfd_link_relocatable (info))
4624             dynsym = FALSE;
4625
4626           /* Nor should we make plugin symbols dynamic.  */
4627           if ((abfd->flags & BFD_PLUGIN) != 0)
4628             dynsym = FALSE;
4629
4630           if (definition)
4631             {
4632               h->target_internal = isym->st_target_internal;
4633               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4634             }
4635
4636           if (definition && !dynamic)
4637             {
4638               char *p = strchr (name, ELF_VER_CHR);
4639               if (p != NULL && p[1] != ELF_VER_CHR)
4640                 {
4641                   /* Queue non-default versions so that .symver x, x@FOO
4642                      aliases can be checked.  */
4643                   if (!nondeflt_vers)
4644                     {
4645                       amt = ((isymend - isym + 1)
4646                              * sizeof (struct elf_link_hash_entry *));
4647                       nondeflt_vers
4648                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
4649                       if (!nondeflt_vers)
4650                         goto error_free_vers;
4651                     }
4652                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4653                 }
4654             }
4655
4656           if (dynsym && h->dynindx == -1)
4657             {
4658               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4659                 goto error_free_vers;
4660               if (h->u.weakdef != NULL
4661                   && ! new_weakdef
4662                   && h->u.weakdef->dynindx == -1)
4663                 {
4664                   if (!bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
4665                     goto error_free_vers;
4666                 }
4667             }
4668           else if (h->dynindx != -1)
4669             /* If the symbol already has a dynamic index, but
4670                visibility says it should not be visible, turn it into
4671                a local symbol.  */
4672             switch (ELF_ST_VISIBILITY (h->other))
4673               {
4674               case STV_INTERNAL:
4675               case STV_HIDDEN:
4676                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4677                 dynsym = FALSE;
4678                 break;
4679               }
4680
4681           /* Don't add DT_NEEDED for references from the dummy bfd nor
4682              for unmatched symbol.  */
4683           if (!add_needed
4684               && matched
4685               && definition
4686               && ((dynsym
4687                    && h->ref_regular_nonweak
4688                    && (old_bfd == NULL
4689                        || (old_bfd->flags & BFD_PLUGIN) == 0))
4690                   || (h->ref_dynamic_nonweak
4691                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4692                       && !on_needed_list (elf_dt_name (abfd),
4693                                           htab->needed, NULL))))
4694             {
4695               int ret;
4696               const char *soname = elf_dt_name (abfd);
4697
4698               info->callbacks->minfo ("%!", soname, old_bfd,
4699                                       h->root.root.string);
4700
4701               /* A symbol from a library loaded via DT_NEEDED of some
4702                  other library is referenced by a regular object.
4703                  Add a DT_NEEDED entry for it.  Issue an error if
4704                  --no-add-needed is used and the reference was not
4705                  a weak one.  */
4706               if (old_bfd != NULL
4707                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4708                 {
4709                   (*_bfd_error_handler)
4710                     (_("%B: undefined reference to symbol '%s'"),
4711                      old_bfd, name);
4712                   bfd_set_error (bfd_error_missing_dso);
4713                   goto error_free_vers;
4714                 }
4715
4716               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4717                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4718
4719               add_needed = TRUE;
4720               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4721               if (ret < 0)
4722                 goto error_free_vers;
4723
4724               BFD_ASSERT (ret == 0);
4725             }
4726         }
4727     }
4728
4729   if (extversym != NULL)
4730     {
4731       free (extversym);
4732       extversym = NULL;
4733     }
4734
4735   if (isymbuf != NULL)
4736     {
4737       free (isymbuf);
4738       isymbuf = NULL;
4739     }
4740
4741   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4742     {
4743       unsigned int i;
4744
4745       /* Restore the symbol table.  */
4746       old_ent = (char *) old_tab + tabsize;
4747       memset (elf_sym_hashes (abfd), 0,
4748               extsymcount * sizeof (struct elf_link_hash_entry *));
4749       htab->root.table.table = old_table;
4750       htab->root.table.size = old_size;
4751       htab->root.table.count = old_count;
4752       memcpy (htab->root.table.table, old_tab, tabsize);
4753       htab->root.undefs = old_undefs;
4754       htab->root.undefs_tail = old_undefs_tail;
4755       _bfd_elf_strtab_restore_size (htab->dynstr, old_dynstr_size);
4756       for (i = 0; i < htab->root.table.size; i++)
4757         {
4758           struct bfd_hash_entry *p;
4759           struct elf_link_hash_entry *h;
4760           bfd_size_type size;
4761           unsigned int alignment_power;
4762
4763           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4764             {
4765               h = (struct elf_link_hash_entry *) p;
4766               if (h->root.type == bfd_link_hash_warning)
4767                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
4768               if (h->dynindx >= old_dynsymcount
4769                   && h->dynstr_index < old_dynstr_size)
4770                 _bfd_elf_strtab_delref (htab->dynstr, h->dynstr_index);
4771
4772               /* Preserve the maximum alignment and size for common
4773                  symbols even if this dynamic lib isn't on DT_NEEDED
4774                  since it can still be loaded at run time by another
4775                  dynamic lib.  */
4776               if (h->root.type == bfd_link_hash_common)
4777                 {
4778                   size = h->root.u.c.size;
4779                   alignment_power = h->root.u.c.p->alignment_power;
4780                 }
4781               else
4782                 {
4783                   size = 0;
4784                   alignment_power = 0;
4785                 }
4786               memcpy (p, old_ent, htab->root.table.entsize);
4787               old_ent = (char *) old_ent + htab->root.table.entsize;
4788               h = (struct elf_link_hash_entry *) p;
4789               if (h->root.type == bfd_link_hash_warning)
4790                 {
4791                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
4792                   old_ent = (char *) old_ent + htab->root.table.entsize;
4793                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
4794                 }
4795               if (h->root.type == bfd_link_hash_common)
4796                 {
4797                   if (size > h->root.u.c.size)
4798                     h->root.u.c.size = size;
4799                   if (alignment_power > h->root.u.c.p->alignment_power)
4800                     h->root.u.c.p->alignment_power = alignment_power;
4801                 }
4802             }
4803         }
4804
4805       /* Make a special call to the linker "notice" function to
4806          tell it that symbols added for crefs may need to be removed.  */
4807       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
4808         goto error_free_vers;
4809
4810       free (old_tab);
4811       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
4812                            alloc_mark);
4813       if (nondeflt_vers != NULL)
4814         free (nondeflt_vers);
4815       return TRUE;
4816     }
4817
4818   if (old_tab != NULL)
4819     {
4820       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
4821         goto error_free_vers;
4822       free (old_tab);
4823       old_tab = NULL;
4824     }
4825
4826   /* Now that all the symbols from this input file are created, if
4827      not performing a relocatable link, handle .symver foo, foo@BAR
4828      such that any relocs against foo become foo@BAR.  */
4829   if (!bfd_link_relocatable (info) && nondeflt_vers != NULL)
4830     {
4831       bfd_size_type cnt, symidx;
4832
4833       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
4834         {
4835           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
4836           char *shortname, *p;
4837
4838           p = strchr (h->root.root.string, ELF_VER_CHR);
4839           if (p == NULL
4840               || (h->root.type != bfd_link_hash_defined
4841                   && h->root.type != bfd_link_hash_defweak))
4842             continue;
4843
4844           amt = p - h->root.root.string;
4845           shortname = (char *) bfd_malloc (amt + 1);
4846           if (!shortname)
4847             goto error_free_vers;
4848           memcpy (shortname, h->root.root.string, amt);
4849           shortname[amt] = '\0';
4850
4851           hi = (struct elf_link_hash_entry *)
4852                bfd_link_hash_lookup (&htab->root, shortname,
4853                                      FALSE, FALSE, FALSE);
4854           if (hi != NULL
4855               && hi->root.type == h->root.type
4856               && hi->root.u.def.value == h->root.u.def.value
4857               && hi->root.u.def.section == h->root.u.def.section)
4858             {
4859               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
4860               hi->root.type = bfd_link_hash_indirect;
4861               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
4862               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
4863               sym_hash = elf_sym_hashes (abfd);
4864               if (sym_hash)
4865                 for (symidx = 0; symidx < extsymcount; ++symidx)
4866                   if (sym_hash[symidx] == hi)
4867                     {
4868                       sym_hash[symidx] = h;
4869                       break;
4870                     }
4871             }
4872           free (shortname);
4873         }
4874       free (nondeflt_vers);
4875       nondeflt_vers = NULL;
4876     }
4877
4878   /* Now set the weakdefs field correctly for all the weak defined
4879      symbols we found.  The only way to do this is to search all the
4880      symbols.  Since we only need the information for non functions in
4881      dynamic objects, that's the only time we actually put anything on
4882      the list WEAKS.  We need this information so that if a regular
4883      object refers to a symbol defined weakly in a dynamic object, the
4884      real symbol in the dynamic object is also put in the dynamic
4885      symbols; we also must arrange for both symbols to point to the
4886      same memory location.  We could handle the general case of symbol
4887      aliasing, but a general symbol alias can only be generated in
4888      assembler code, handling it correctly would be very time
4889      consuming, and other ELF linkers don't handle general aliasing
4890      either.  */
4891   if (weaks != NULL)
4892     {
4893       struct elf_link_hash_entry **hpp;
4894       struct elf_link_hash_entry **hppend;
4895       struct elf_link_hash_entry **sorted_sym_hash;
4896       struct elf_link_hash_entry *h;
4897       size_t sym_count;
4898
4899       /* Since we have to search the whole symbol list for each weak
4900          defined symbol, search time for N weak defined symbols will be
4901          O(N^2). Binary search will cut it down to O(NlogN).  */
4902       amt = extsymcount * sizeof (struct elf_link_hash_entry *);
4903       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
4904       if (sorted_sym_hash == NULL)
4905         goto error_return;
4906       sym_hash = sorted_sym_hash;
4907       hpp = elf_sym_hashes (abfd);
4908       hppend = hpp + extsymcount;
4909       sym_count = 0;
4910       for (; hpp < hppend; hpp++)
4911         {
4912           h = *hpp;
4913           if (h != NULL
4914               && h->root.type == bfd_link_hash_defined
4915               && !bed->is_function_type (h->type))
4916             {
4917               *sym_hash = h;
4918               sym_hash++;
4919               sym_count++;
4920             }
4921         }
4922
4923       qsort (sorted_sym_hash, sym_count,
4924              sizeof (struct elf_link_hash_entry *),
4925              elf_sort_symbol);
4926
4927       while (weaks != NULL)
4928         {
4929           struct elf_link_hash_entry *hlook;
4930           asection *slook;
4931           bfd_vma vlook;
4932           size_t i, j, idx = 0;
4933
4934           hlook = weaks;
4935           weaks = hlook->u.weakdef;
4936           hlook->u.weakdef = NULL;
4937
4938           BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
4939                       || hlook->root.type == bfd_link_hash_defweak
4940                       || hlook->root.type == bfd_link_hash_common
4941                       || hlook->root.type == bfd_link_hash_indirect);
4942           slook = hlook->root.u.def.section;
4943           vlook = hlook->root.u.def.value;
4944
4945           i = 0;
4946           j = sym_count;
4947           while (i != j)
4948             {
4949               bfd_signed_vma vdiff;
4950               idx = (i + j) / 2;
4951               h = sorted_sym_hash[idx];
4952               vdiff = vlook - h->root.u.def.value;
4953               if (vdiff < 0)
4954                 j = idx;
4955               else if (vdiff > 0)
4956                 i = idx + 1;
4957               else
4958                 {
4959                   int sdiff = slook->id - h->root.u.def.section->id;
4960                   if (sdiff < 0)
4961                     j = idx;
4962                   else if (sdiff > 0)
4963                     i = idx + 1;
4964                   else
4965                     break;
4966                 }
4967             }
4968
4969           /* We didn't find a value/section match.  */
4970           if (i == j)
4971             continue;
4972
4973           /* With multiple aliases, or when the weak symbol is already
4974              strongly defined, we have multiple matching symbols and
4975              the binary search above may land on any of them.  Step
4976              one past the matching symbol(s).  */
4977           while (++idx != j)
4978             {
4979               h = sorted_sym_hash[idx];
4980               if (h->root.u.def.section != slook
4981                   || h->root.u.def.value != vlook)
4982                 break;
4983             }
4984
4985           /* Now look back over the aliases.  Since we sorted by size
4986              as well as value and section, we'll choose the one with
4987              the largest size.  */
4988           while (idx-- != i)
4989             {
4990               h = sorted_sym_hash[idx];
4991
4992               /* Stop if value or section doesn't match.  */
4993               if (h->root.u.def.section != slook
4994                   || h->root.u.def.value != vlook)
4995                 break;
4996               else if (h != hlook)
4997                 {
4998                   hlook->u.weakdef = h;
4999
5000                   /* If the weak definition is in the list of dynamic
5001                      symbols, make sure the real definition is put
5002                      there as well.  */
5003                   if (hlook->dynindx != -1 && h->dynindx == -1)
5004                     {
5005                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
5006                         {
5007                         err_free_sym_hash:
5008                           free (sorted_sym_hash);
5009                           goto error_return;
5010                         }
5011                     }
5012
5013                   /* If the real definition is in the list of dynamic
5014                      symbols, make sure the weak definition is put
5015                      there as well.  If we don't do this, then the
5016                      dynamic loader might not merge the entries for the
5017                      real definition and the weak definition.  */
5018                   if (h->dynindx != -1 && hlook->dynindx == -1)
5019                     {
5020                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
5021                         goto err_free_sym_hash;
5022                     }
5023                   break;
5024                 }
5025             }
5026         }
5027
5028       free (sorted_sym_hash);
5029     }
5030
5031   if (bed->check_directives
5032       && !(*bed->check_directives) (abfd, info))
5033     return FALSE;
5034
5035   if (!info->check_relocs_after_open_input
5036       && !_bfd_elf_link_check_relocs (abfd, info))
5037     return FALSE;
5038
5039   /* If this is a non-traditional link, try to optimize the handling
5040      of the .stab/.stabstr sections.  */
5041   if (! dynamic
5042       && ! info->traditional_format
5043       && is_elf_hash_table (htab)
5044       && (info->strip != strip_all && info->strip != strip_debugger))
5045     {
5046       asection *stabstr;
5047
5048       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
5049       if (stabstr != NULL)
5050         {
5051           bfd_size_type string_offset = 0;
5052           asection *stab;
5053
5054           for (stab = abfd->sections; stab; stab = stab->next)
5055             if (CONST_STRNEQ (stab->name, ".stab")
5056                 && (!stab->name[5] ||
5057                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
5058                 && (stab->flags & SEC_MERGE) == 0
5059                 && !bfd_is_abs_section (stab->output_section))
5060               {
5061                 struct bfd_elf_section_data *secdata;
5062
5063                 secdata = elf_section_data (stab);
5064                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
5065                                                stabstr, &secdata->sec_info,
5066                                                &string_offset))
5067                   goto error_return;
5068                 if (secdata->sec_info)
5069                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
5070             }
5071         }
5072     }
5073
5074   if (is_elf_hash_table (htab) && add_needed)
5075     {
5076       /* Add this bfd to the loaded list.  */
5077       struct elf_link_loaded_list *n;
5078
5079       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
5080       if (n == NULL)
5081         goto error_return;
5082       n->abfd = abfd;
5083       n->next = htab->loaded;
5084       htab->loaded = n;
5085     }
5086
5087   return TRUE;
5088
5089  error_free_vers:
5090   if (old_tab != NULL)
5091     free (old_tab);
5092   if (nondeflt_vers != NULL)
5093     free (nondeflt_vers);
5094   if (extversym != NULL)
5095     free (extversym);
5096  error_free_sym:
5097   if (isymbuf != NULL)
5098     free (isymbuf);
5099  error_return:
5100   return FALSE;
5101 }
5102
5103 /* Return the linker hash table entry of a symbol that might be
5104    satisfied by an archive symbol.  Return -1 on error.  */
5105
5106 struct elf_link_hash_entry *
5107 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5108                                 struct bfd_link_info *info,
5109                                 const char *name)
5110 {
5111   struct elf_link_hash_entry *h;
5112   char *p, *copy;
5113   size_t len, first;
5114
5115   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5116   if (h != NULL)
5117     return h;
5118
5119   /* If this is a default version (the name contains @@), look up the
5120      symbol again with only one `@' as well as without the version.
5121      The effect is that references to the symbol with and without the
5122      version will be matched by the default symbol in the archive.  */
5123
5124   p = strchr (name, ELF_VER_CHR);
5125   if (p == NULL || p[1] != ELF_VER_CHR)
5126     return h;
5127
5128   /* First check with only one `@'.  */
5129   len = strlen (name);
5130   copy = (char *) bfd_alloc (abfd, len);
5131   if (copy == NULL)
5132     return (struct elf_link_hash_entry *) 0 - 1;
5133
5134   first = p - name + 1;
5135   memcpy (copy, name, first);
5136   memcpy (copy + first, name + first + 1, len - first);
5137
5138   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5139   if (h == NULL)
5140     {
5141       /* We also need to check references to the symbol without the
5142          version.  */
5143       copy[first - 1] = '\0';
5144       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5145                                 FALSE, FALSE, TRUE);
5146     }
5147
5148   bfd_release (abfd, copy);
5149   return h;
5150 }
5151
5152 /* Add symbols from an ELF archive file to the linker hash table.  We
5153    don't use _bfd_generic_link_add_archive_symbols because we need to
5154    handle versioned symbols.
5155
5156    Fortunately, ELF archive handling is simpler than that done by
5157    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5158    oddities.  In ELF, if we find a symbol in the archive map, and the
5159    symbol is currently undefined, we know that we must pull in that
5160    object file.
5161
5162    Unfortunately, we do have to make multiple passes over the symbol
5163    table until nothing further is resolved.  */
5164
5165 static bfd_boolean
5166 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5167 {
5168   symindex c;
5169   unsigned char *included = NULL;
5170   carsym *symdefs;
5171   bfd_boolean loop;
5172   bfd_size_type amt;
5173   const struct elf_backend_data *bed;
5174   struct elf_link_hash_entry * (*archive_symbol_lookup)
5175     (bfd *, struct bfd_link_info *, const char *);
5176
5177   if (! bfd_has_map (abfd))
5178     {
5179       /* An empty archive is a special case.  */
5180       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5181         return TRUE;
5182       bfd_set_error (bfd_error_no_armap);
5183       return FALSE;
5184     }
5185
5186   /* Keep track of all symbols we know to be already defined, and all
5187      files we know to be already included.  This is to speed up the
5188      second and subsequent passes.  */
5189   c = bfd_ardata (abfd)->symdef_count;
5190   if (c == 0)
5191     return TRUE;
5192   amt = c;
5193   amt *= sizeof (*included);
5194   included = (unsigned char *) bfd_zmalloc (amt);
5195   if (included == NULL)
5196     return FALSE;
5197
5198   symdefs = bfd_ardata (abfd)->symdefs;
5199   bed = get_elf_backend_data (abfd);
5200   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5201
5202   do
5203     {
5204       file_ptr last;
5205       symindex i;
5206       carsym *symdef;
5207       carsym *symdefend;
5208
5209       loop = FALSE;
5210       last = -1;
5211
5212       symdef = symdefs;
5213       symdefend = symdef + c;
5214       for (i = 0; symdef < symdefend; symdef++, i++)
5215         {
5216           struct elf_link_hash_entry *h;
5217           bfd *element;
5218           struct bfd_link_hash_entry *undefs_tail;
5219           symindex mark;
5220
5221           if (included[i])
5222             continue;
5223           if (symdef->file_offset == last)
5224             {
5225               included[i] = TRUE;
5226               continue;
5227             }
5228
5229           h = archive_symbol_lookup (abfd, info, symdef->name);
5230           if (h == (struct elf_link_hash_entry *) 0 - 1)
5231             goto error_return;
5232
5233           if (h == NULL)
5234             continue;
5235
5236           if (h->root.type == bfd_link_hash_common)
5237             {
5238               /* We currently have a common symbol.  The archive map contains
5239                  a reference to this symbol, so we may want to include it.  We
5240                  only want to include it however, if this archive element
5241                  contains a definition of the symbol, not just another common
5242                  declaration of it.
5243
5244                  Unfortunately some archivers (including GNU ar) will put
5245                  declarations of common symbols into their archive maps, as
5246                  well as real definitions, so we cannot just go by the archive
5247                  map alone.  Instead we must read in the element's symbol
5248                  table and check that to see what kind of symbol definition
5249                  this is.  */
5250               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5251                 continue;
5252             }
5253           else if (h->root.type != bfd_link_hash_undefined)
5254             {
5255               if (h->root.type != bfd_link_hash_undefweak)
5256                 /* Symbol must be defined.  Don't check it again.  */
5257                 included[i] = TRUE;
5258               continue;
5259             }
5260
5261           /* We need to include this archive member.  */
5262           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5263           if (element == NULL)
5264             goto error_return;
5265
5266           if (! bfd_check_format (element, bfd_object))
5267             goto error_return;
5268
5269           undefs_tail = info->hash->undefs_tail;
5270
5271           if (!(*info->callbacks
5272                 ->add_archive_element) (info, element, symdef->name, &element))
5273             goto error_return;
5274           if (!bfd_link_add_symbols (element, info))
5275             goto error_return;
5276
5277           /* If there are any new undefined symbols, we need to make
5278              another pass through the archive in order to see whether
5279              they can be defined.  FIXME: This isn't perfect, because
5280              common symbols wind up on undefs_tail and because an
5281              undefined symbol which is defined later on in this pass
5282              does not require another pass.  This isn't a bug, but it
5283              does make the code less efficient than it could be.  */
5284           if (undefs_tail != info->hash->undefs_tail)
5285             loop = TRUE;
5286
5287           /* Look backward to mark all symbols from this object file
5288              which we have already seen in this pass.  */
5289           mark = i;
5290           do
5291             {
5292               included[mark] = TRUE;
5293               if (mark == 0)
5294                 break;
5295               --mark;
5296             }
5297           while (symdefs[mark].file_offset == symdef->file_offset);
5298
5299           /* We mark subsequent symbols from this object file as we go
5300              on through the loop.  */
5301           last = symdef->file_offset;
5302         }
5303     }
5304   while (loop);
5305
5306   free (included);
5307
5308   return TRUE;
5309
5310  error_return:
5311   if (included != NULL)
5312     free (included);
5313   return FALSE;
5314 }
5315
5316 /* Given an ELF BFD, add symbols to the global hash table as
5317    appropriate.  */
5318
5319 bfd_boolean
5320 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5321 {
5322   switch (bfd_get_format (abfd))
5323     {
5324     case bfd_object:
5325       return elf_link_add_object_symbols (abfd, info);
5326     case bfd_archive:
5327       return elf_link_add_archive_symbols (abfd, info);
5328     default:
5329       bfd_set_error (bfd_error_wrong_format);
5330       return FALSE;
5331     }
5332 }
5333 \f
5334 struct hash_codes_info
5335 {
5336   unsigned long *hashcodes;
5337   bfd_boolean error;
5338 };
5339
5340 /* This function will be called though elf_link_hash_traverse to store
5341    all hash value of the exported symbols in an array.  */
5342
5343 static bfd_boolean
5344 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5345 {
5346   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5347   const char *name;
5348   unsigned long ha;
5349   char *alc = NULL;
5350
5351   /* Ignore indirect symbols.  These are added by the versioning code.  */
5352   if (h->dynindx == -1)
5353     return TRUE;
5354
5355   name = h->root.root.string;
5356   if (h->versioned >= versioned)
5357     {
5358       char *p = strchr (name, ELF_VER_CHR);
5359       if (p != NULL)
5360         {
5361           alc = (char *) bfd_malloc (p - name + 1);
5362           if (alc == NULL)
5363             {
5364               inf->error = TRUE;
5365               return FALSE;
5366             }
5367           memcpy (alc, name, p - name);
5368           alc[p - name] = '\0';
5369           name = alc;
5370         }
5371     }
5372
5373   /* Compute the hash value.  */
5374   ha = bfd_elf_hash (name);
5375
5376   /* Store the found hash value in the array given as the argument.  */
5377   *(inf->hashcodes)++ = ha;
5378
5379   /* And store it in the struct so that we can put it in the hash table
5380      later.  */
5381   h->u.elf_hash_value = ha;
5382
5383   if (alc != NULL)
5384     free (alc);
5385
5386   return TRUE;
5387 }
5388
5389 struct collect_gnu_hash_codes
5390 {
5391   bfd *output_bfd;
5392   const struct elf_backend_data *bed;
5393   unsigned long int nsyms;
5394   unsigned long int maskbits;
5395   unsigned long int *hashcodes;
5396   unsigned long int *hashval;
5397   unsigned long int *indx;
5398   unsigned long int *counts;
5399   bfd_vma *bitmask;
5400   bfd_byte *contents;
5401   long int min_dynindx;
5402   unsigned long int bucketcount;
5403   unsigned long int symindx;
5404   long int local_indx;
5405   long int shift1, shift2;
5406   unsigned long int mask;
5407   bfd_boolean error;
5408 };
5409
5410 /* This function will be called though elf_link_hash_traverse to store
5411    all hash value of the exported symbols in an array.  */
5412
5413 static bfd_boolean
5414 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5415 {
5416   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5417   const char *name;
5418   unsigned long ha;
5419   char *alc = NULL;
5420
5421   /* Ignore indirect symbols.  These are added by the versioning code.  */
5422   if (h->dynindx == -1)
5423     return TRUE;
5424
5425   /* Ignore also local symbols and undefined symbols.  */
5426   if (! (*s->bed->elf_hash_symbol) (h))
5427     return TRUE;
5428
5429   name = h->root.root.string;
5430   if (h->versioned >= versioned)
5431     {
5432       char *p = strchr (name, ELF_VER_CHR);
5433       if (p != NULL)
5434         {
5435           alc = (char *) bfd_malloc (p - name + 1);
5436           if (alc == NULL)
5437             {
5438               s->error = TRUE;
5439               return FALSE;
5440             }
5441           memcpy (alc, name, p - name);
5442           alc[p - name] = '\0';
5443           name = alc;
5444         }
5445     }
5446
5447   /* Compute the hash value.  */
5448   ha = bfd_elf_gnu_hash (name);
5449
5450   /* Store the found hash value in the array for compute_bucket_count,
5451      and also for .dynsym reordering purposes.  */
5452   s->hashcodes[s->nsyms] = ha;
5453   s->hashval[h->dynindx] = ha;
5454   ++s->nsyms;
5455   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5456     s->min_dynindx = h->dynindx;
5457
5458   if (alc != NULL)
5459     free (alc);
5460
5461   return TRUE;
5462 }
5463
5464 /* This function will be called though elf_link_hash_traverse to do
5465    final dynaminc symbol renumbering.  */
5466
5467 static bfd_boolean
5468 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5469 {
5470   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5471   unsigned long int bucket;
5472   unsigned long int val;
5473
5474   /* Ignore indirect symbols.  */
5475   if (h->dynindx == -1)
5476     return TRUE;
5477
5478   /* Ignore also local symbols and undefined symbols.  */
5479   if (! (*s->bed->elf_hash_symbol) (h))
5480     {
5481       if (h->dynindx >= s->min_dynindx)
5482         h->dynindx = s->local_indx++;
5483       return TRUE;
5484     }
5485
5486   bucket = s->hashval[h->dynindx] % s->bucketcount;
5487   val = (s->hashval[h->dynindx] >> s->shift1)
5488         & ((s->maskbits >> s->shift1) - 1);
5489   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5490   s->bitmask[val]
5491     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5492   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5493   if (s->counts[bucket] == 1)
5494     /* Last element terminates the chain.  */
5495     val |= 1;
5496   bfd_put_32 (s->output_bfd, val,
5497               s->contents + (s->indx[bucket] - s->symindx) * 4);
5498   --s->counts[bucket];
5499   h->dynindx = s->indx[bucket]++;
5500   return TRUE;
5501 }
5502
5503 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5504
5505 bfd_boolean
5506 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5507 {
5508   return !(h->forced_local
5509            || h->root.type == bfd_link_hash_undefined
5510            || h->root.type == bfd_link_hash_undefweak
5511            || ((h->root.type == bfd_link_hash_defined
5512                 || h->root.type == bfd_link_hash_defweak)
5513                && h->root.u.def.section->output_section == NULL));
5514 }
5515
5516 /* Array used to determine the number of hash table buckets to use
5517    based on the number of symbols there are.  If there are fewer than
5518    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5519    fewer than 37 we use 17 buckets, and so forth.  We never use more
5520    than 32771 buckets.  */
5521
5522 static const size_t elf_buckets[] =
5523 {
5524   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5525   16411, 32771, 0
5526 };
5527
5528 /* Compute bucket count for hashing table.  We do not use a static set
5529    of possible tables sizes anymore.  Instead we determine for all
5530    possible reasonable sizes of the table the outcome (i.e., the
5531    number of collisions etc) and choose the best solution.  The
5532    weighting functions are not too simple to allow the table to grow
5533    without bounds.  Instead one of the weighting factors is the size.
5534    Therefore the result is always a good payoff between few collisions
5535    (= short chain lengths) and table size.  */
5536 static size_t
5537 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5538                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5539                       unsigned long int nsyms,
5540                       int gnu_hash)
5541 {
5542   size_t best_size = 0;
5543   unsigned long int i;
5544
5545   /* We have a problem here.  The following code to optimize the table
5546      size requires an integer type with more the 32 bits.  If
5547      BFD_HOST_U_64_BIT is set we know about such a type.  */
5548 #ifdef BFD_HOST_U_64_BIT
5549   if (info->optimize)
5550     {
5551       size_t minsize;
5552       size_t maxsize;
5553       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5554       bfd *dynobj = elf_hash_table (info)->dynobj;
5555       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5556       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5557       unsigned long int *counts;
5558       bfd_size_type amt;
5559       unsigned int no_improvement_count = 0;
5560
5561       /* Possible optimization parameters: if we have NSYMS symbols we say
5562          that the hashing table must at least have NSYMS/4 and at most
5563          2*NSYMS buckets.  */
5564       minsize = nsyms / 4;
5565       if (minsize == 0)
5566         minsize = 1;
5567       best_size = maxsize = nsyms * 2;
5568       if (gnu_hash)
5569         {
5570           if (minsize < 2)
5571             minsize = 2;
5572           if ((best_size & 31) == 0)
5573             ++best_size;
5574         }
5575
5576       /* Create array where we count the collisions in.  We must use bfd_malloc
5577          since the size could be large.  */
5578       amt = maxsize;
5579       amt *= sizeof (unsigned long int);
5580       counts = (unsigned long int *) bfd_malloc (amt);
5581       if (counts == NULL)
5582         return 0;
5583
5584       /* Compute the "optimal" size for the hash table.  The criteria is a
5585          minimal chain length.  The minor criteria is (of course) the size
5586          of the table.  */
5587       for (i = minsize; i < maxsize; ++i)
5588         {
5589           /* Walk through the array of hashcodes and count the collisions.  */
5590           BFD_HOST_U_64_BIT max;
5591           unsigned long int j;
5592           unsigned long int fact;
5593
5594           if (gnu_hash && (i & 31) == 0)
5595             continue;
5596
5597           memset (counts, '\0', i * sizeof (unsigned long int));
5598
5599           /* Determine how often each hash bucket is used.  */
5600           for (j = 0; j < nsyms; ++j)
5601             ++counts[hashcodes[j] % i];
5602
5603           /* For the weight function we need some information about the
5604              pagesize on the target.  This is information need not be 100%
5605              accurate.  Since this information is not available (so far) we
5606              define it here to a reasonable default value.  If it is crucial
5607              to have a better value some day simply define this value.  */
5608 # ifndef BFD_TARGET_PAGESIZE
5609 #  define BFD_TARGET_PAGESIZE   (4096)
5610 # endif
5611
5612           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5613              and the chains.  */
5614           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5615
5616 # if 1
5617           /* Variant 1: optimize for short chains.  We add the squares
5618              of all the chain lengths (which favors many small chain
5619              over a few long chains).  */
5620           for (j = 0; j < i; ++j)
5621             max += counts[j] * counts[j];
5622
5623           /* This adds penalties for the overall size of the table.  */
5624           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5625           max *= fact * fact;
5626 # else
5627           /* Variant 2: Optimize a lot more for small table.  Here we
5628              also add squares of the size but we also add penalties for
5629              empty slots (the +1 term).  */
5630           for (j = 0; j < i; ++j)
5631             max += (1 + counts[j]) * (1 + counts[j]);
5632
5633           /* The overall size of the table is considered, but not as
5634              strong as in variant 1, where it is squared.  */
5635           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5636           max *= fact;
5637 # endif
5638
5639           /* Compare with current best results.  */
5640           if (max < best_chlen)
5641             {
5642               best_chlen = max;
5643               best_size = i;
5644               no_improvement_count = 0;
5645             }
5646           /* PR 11843: Avoid futile long searches for the best bucket size
5647              when there are a large number of symbols.  */
5648           else if (++no_improvement_count == 100)
5649             break;
5650         }
5651
5652       free (counts);
5653     }
5654   else
5655 #endif /* defined (BFD_HOST_U_64_BIT) */
5656     {
5657       /* This is the fallback solution if no 64bit type is available or if we
5658          are not supposed to spend much time on optimizations.  We select the
5659          bucket count using a fixed set of numbers.  */
5660       for (i = 0; elf_buckets[i] != 0; i++)
5661         {
5662           best_size = elf_buckets[i];
5663           if (nsyms < elf_buckets[i + 1])
5664             break;
5665         }
5666       if (gnu_hash && best_size < 2)
5667         best_size = 2;
5668     }
5669
5670   return best_size;
5671 }
5672
5673 /* Size any SHT_GROUP section for ld -r.  */
5674
5675 bfd_boolean
5676 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5677 {
5678   bfd *ibfd;
5679
5680   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5681     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5682         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5683       return FALSE;
5684   return TRUE;
5685 }
5686
5687 /* Set a default stack segment size.  The value in INFO wins.  If it
5688    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
5689    undefined it is initialized.  */
5690
5691 bfd_boolean
5692 bfd_elf_stack_segment_size (bfd *output_bfd,
5693                             struct bfd_link_info *info,
5694                             const char *legacy_symbol,
5695                             bfd_vma default_size)
5696 {
5697   struct elf_link_hash_entry *h = NULL;
5698
5699   /* Look for legacy symbol.  */
5700   if (legacy_symbol)
5701     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
5702                               FALSE, FALSE, FALSE);
5703   if (h && (h->root.type == bfd_link_hash_defined
5704             || h->root.type == bfd_link_hash_defweak)
5705       && h->def_regular
5706       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
5707     {
5708       /* The symbol has no type if specified on the command line.  */
5709       h->type = STT_OBJECT;
5710       if (info->stacksize)
5711         (*_bfd_error_handler) (_("%B: stack size specified and %s set"),
5712                                output_bfd, legacy_symbol);
5713       else if (h->root.u.def.section != bfd_abs_section_ptr)
5714         (*_bfd_error_handler) (_("%B: %s not absolute"),
5715                                output_bfd, legacy_symbol);
5716       else
5717         info->stacksize = h->root.u.def.value;
5718     }
5719
5720   if (!info->stacksize)
5721     /* If the user didn't set a size, or explicitly inhibit the
5722        size, set it now.  */
5723     info->stacksize = default_size;
5724
5725   /* Provide the legacy symbol, if it is referenced.  */
5726   if (h && (h->root.type == bfd_link_hash_undefined
5727             || h->root.type == bfd_link_hash_undefweak))
5728     {
5729       struct bfd_link_hash_entry *bh = NULL;
5730
5731       if (!(_bfd_generic_link_add_one_symbol
5732             (info, output_bfd, legacy_symbol,
5733              BSF_GLOBAL, bfd_abs_section_ptr,
5734              info->stacksize >= 0 ? info->stacksize : 0,
5735              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
5736         return FALSE;
5737
5738       h = (struct elf_link_hash_entry *) bh;
5739       h->def_regular = 1;
5740       h->type = STT_OBJECT;
5741     }
5742
5743   return TRUE;
5744 }
5745
5746 /* Set up the sizes and contents of the ELF dynamic sections.  This is
5747    called by the ELF linker emulation before_allocation routine.  We
5748    must set the sizes of the sections before the linker sets the
5749    addresses of the various sections.  */
5750
5751 bfd_boolean
5752 bfd_elf_size_dynamic_sections (bfd *output_bfd,
5753                                const char *soname,
5754                                const char *rpath,
5755                                const char *filter_shlib,
5756                                const char *audit,
5757                                const char *depaudit,
5758                                const char * const *auxiliary_filters,
5759                                struct bfd_link_info *info,
5760                                asection **sinterpptr)
5761 {
5762   bfd_size_type soname_indx;
5763   bfd *dynobj;
5764   const struct elf_backend_data *bed;
5765   struct elf_info_failed asvinfo;
5766
5767   *sinterpptr = NULL;
5768
5769   soname_indx = (bfd_size_type) -1;
5770
5771   if (!is_elf_hash_table (info->hash))
5772     return TRUE;
5773
5774   bed = get_elf_backend_data (output_bfd);
5775
5776   /* Any syms created from now on start with -1 in
5777      got.refcount/offset and plt.refcount/offset.  */
5778   elf_hash_table (info)->init_got_refcount
5779     = elf_hash_table (info)->init_got_offset;
5780   elf_hash_table (info)->init_plt_refcount
5781     = elf_hash_table (info)->init_plt_offset;
5782
5783   if (bfd_link_relocatable (info)
5784       && !_bfd_elf_size_group_sections (info))
5785     return FALSE;
5786
5787   /* The backend may have to create some sections regardless of whether
5788      we're dynamic or not.  */
5789   if (bed->elf_backend_always_size_sections
5790       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
5791     return FALSE;
5792
5793   /* Determine any GNU_STACK segment requirements, after the backend
5794      has had a chance to set a default segment size.  */
5795   if (info->execstack)
5796     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
5797   else if (info->noexecstack)
5798     elf_stack_flags (output_bfd) = PF_R | PF_W;
5799   else
5800     {
5801       bfd *inputobj;
5802       asection *notesec = NULL;
5803       int exec = 0;
5804
5805       for (inputobj = info->input_bfds;
5806            inputobj;
5807            inputobj = inputobj->link.next)
5808         {
5809           asection *s;
5810
5811           if (inputobj->flags
5812               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
5813             continue;
5814           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
5815           if (s)
5816             {
5817               if (s->flags & SEC_CODE)
5818                 exec = PF_X;
5819               notesec = s;
5820             }
5821           else if (bed->default_execstack)
5822             exec = PF_X;
5823         }
5824       if (notesec || info->stacksize > 0)
5825         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
5826       if (notesec && exec && bfd_link_relocatable (info)
5827           && notesec->output_section != bfd_abs_section_ptr)
5828         notesec->output_section->flags |= SEC_CODE;
5829     }
5830
5831   dynobj = elf_hash_table (info)->dynobj;
5832
5833   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
5834     {
5835       struct elf_info_failed eif;
5836       struct elf_link_hash_entry *h;
5837       asection *dynstr;
5838       struct bfd_elf_version_tree *t;
5839       struct bfd_elf_version_expr *d;
5840       asection *s;
5841       bfd_boolean all_defined;
5842
5843       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
5844       BFD_ASSERT (*sinterpptr != NULL || !bfd_link_executable (info) || info->nointerp);
5845
5846       if (soname != NULL)
5847         {
5848           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5849                                              soname, TRUE);
5850           if (soname_indx == (bfd_size_type) -1
5851               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
5852             return FALSE;
5853         }
5854
5855       if (info->symbolic)
5856         {
5857           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
5858             return FALSE;
5859           info->flags |= DF_SYMBOLIC;
5860         }
5861
5862       if (rpath != NULL)
5863         {
5864           bfd_size_type indx;
5865           bfd_vma tag;
5866
5867           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
5868                                       TRUE);
5869           if (indx == (bfd_size_type) -1)
5870             return FALSE;
5871
5872           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
5873           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
5874             return FALSE;
5875         }
5876
5877       if (filter_shlib != NULL)
5878         {
5879           bfd_size_type indx;
5880
5881           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5882                                       filter_shlib, TRUE);
5883           if (indx == (bfd_size_type) -1
5884               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
5885             return FALSE;
5886         }
5887
5888       if (auxiliary_filters != NULL)
5889         {
5890           const char * const *p;
5891
5892           for (p = auxiliary_filters; *p != NULL; p++)
5893             {
5894               bfd_size_type indx;
5895
5896               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
5897                                           *p, TRUE);
5898               if (indx == (bfd_size_type) -1
5899                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
5900                 return FALSE;
5901             }
5902         }
5903
5904       if (audit != NULL)
5905         {
5906           bfd_size_type indx;
5907
5908           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
5909                                       TRUE);
5910           if (indx == (bfd_size_type) -1
5911               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
5912             return FALSE;
5913         }
5914
5915       if (depaudit != NULL)
5916         {
5917           bfd_size_type indx;
5918
5919           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
5920                                       TRUE);
5921           if (indx == (bfd_size_type) -1
5922               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
5923             return FALSE;
5924         }
5925
5926       eif.info = info;
5927       eif.failed = FALSE;
5928
5929       /* If we are supposed to export all symbols into the dynamic symbol
5930          table (this is not the normal case), then do so.  */
5931       if (info->export_dynamic
5932           || (bfd_link_executable (info) && info->dynamic))
5933         {
5934           elf_link_hash_traverse (elf_hash_table (info),
5935                                   _bfd_elf_export_symbol,
5936                                   &eif);
5937           if (eif.failed)
5938             return FALSE;
5939         }
5940
5941       /* Make all global versions with definition.  */
5942       for (t = info->version_info; t != NULL; t = t->next)
5943         for (d = t->globals.list; d != NULL; d = d->next)
5944           if (!d->symver && d->literal)
5945             {
5946               const char *verstr, *name;
5947               size_t namelen, verlen, newlen;
5948               char *newname, *p, leading_char;
5949               struct elf_link_hash_entry *newh;
5950
5951               leading_char = bfd_get_symbol_leading_char (output_bfd);
5952               name = d->pattern;
5953               namelen = strlen (name) + (leading_char != '\0');
5954               verstr = t->name;
5955               verlen = strlen (verstr);
5956               newlen = namelen + verlen + 3;
5957
5958               newname = (char *) bfd_malloc (newlen);
5959               if (newname == NULL)
5960                 return FALSE;
5961               newname[0] = leading_char;
5962               memcpy (newname + (leading_char != '\0'), name, namelen);
5963
5964               /* Check the hidden versioned definition.  */
5965               p = newname + namelen;
5966               *p++ = ELF_VER_CHR;
5967               memcpy (p, verstr, verlen + 1);
5968               newh = elf_link_hash_lookup (elf_hash_table (info),
5969                                            newname, FALSE, FALSE,
5970                                            FALSE);
5971               if (newh == NULL
5972                   || (newh->root.type != bfd_link_hash_defined
5973                       && newh->root.type != bfd_link_hash_defweak))
5974                 {
5975                   /* Check the default versioned definition.  */
5976                   *p++ = ELF_VER_CHR;
5977                   memcpy (p, verstr, verlen + 1);
5978                   newh = elf_link_hash_lookup (elf_hash_table (info),
5979                                                newname, FALSE, FALSE,
5980                                                FALSE);
5981                 }
5982               free (newname);
5983
5984               /* Mark this version if there is a definition and it is
5985                  not defined in a shared object.  */
5986               if (newh != NULL
5987                   && !newh->def_dynamic
5988                   && (newh->root.type == bfd_link_hash_defined
5989                       || newh->root.type == bfd_link_hash_defweak))
5990                 d->symver = 1;
5991             }
5992
5993       /* Attach all the symbols to their version information.  */
5994       asvinfo.info = info;
5995       asvinfo.failed = FALSE;
5996
5997       elf_link_hash_traverse (elf_hash_table (info),
5998                               _bfd_elf_link_assign_sym_version,
5999                               &asvinfo);
6000       if (asvinfo.failed)
6001         return FALSE;
6002
6003       if (!info->allow_undefined_version)
6004         {
6005           /* Check if all global versions have a definition.  */
6006           all_defined = TRUE;
6007           for (t = info->version_info; t != NULL; t = t->next)
6008             for (d = t->globals.list; d != NULL; d = d->next)
6009               if (d->literal && !d->symver && !d->script)
6010                 {
6011                   (*_bfd_error_handler)
6012                     (_("%s: undefined version: %s"),
6013                      d->pattern, t->name);
6014                   all_defined = FALSE;
6015                 }
6016
6017           if (!all_defined)
6018             {
6019               bfd_set_error (bfd_error_bad_value);
6020               return FALSE;
6021             }
6022         }
6023
6024       /* Find all symbols which were defined in a dynamic object and make
6025          the backend pick a reasonable value for them.  */
6026       elf_link_hash_traverse (elf_hash_table (info),
6027                               _bfd_elf_adjust_dynamic_symbol,
6028                               &eif);
6029       if (eif.failed)
6030         return FALSE;
6031
6032       /* Add some entries to the .dynamic section.  We fill in some of the
6033          values later, in bfd_elf_final_link, but we must add the entries
6034          now so that we know the final size of the .dynamic section.  */
6035
6036       /* If there are initialization and/or finalization functions to
6037          call then add the corresponding DT_INIT/DT_FINI entries.  */
6038       h = (info->init_function
6039            ? elf_link_hash_lookup (elf_hash_table (info),
6040                                    info->init_function, FALSE,
6041                                    FALSE, FALSE)
6042            : NULL);
6043       if (h != NULL
6044           && (h->ref_regular
6045               || h->def_regular))
6046         {
6047           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
6048             return FALSE;
6049         }
6050       h = (info->fini_function
6051            ? elf_link_hash_lookup (elf_hash_table (info),
6052                                    info->fini_function, FALSE,
6053                                    FALSE, FALSE)
6054            : NULL);
6055       if (h != NULL
6056           && (h->ref_regular
6057               || h->def_regular))
6058         {
6059           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
6060             return FALSE;
6061         }
6062
6063       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
6064       if (s != NULL && s->linker_has_input)
6065         {
6066           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
6067           if (! bfd_link_executable (info))
6068             {
6069               bfd *sub;
6070               asection *o;
6071
6072               for (sub = info->input_bfds; sub != NULL;
6073                    sub = sub->link.next)
6074                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour)
6075                   for (o = sub->sections; o != NULL; o = o->next)
6076                     if (elf_section_data (o)->this_hdr.sh_type
6077                         == SHT_PREINIT_ARRAY)
6078                       {
6079                         (*_bfd_error_handler)
6080                           (_("%B: .preinit_array section is not allowed in DSO"),
6081                            sub);
6082                         break;
6083                       }
6084
6085               bfd_set_error (bfd_error_nonrepresentable_section);
6086               return FALSE;
6087             }
6088
6089           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6090               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6091             return FALSE;
6092         }
6093       s = bfd_get_section_by_name (output_bfd, ".init_array");
6094       if (s != NULL && s->linker_has_input)
6095         {
6096           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6097               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6098             return FALSE;
6099         }
6100       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6101       if (s != NULL && s->linker_has_input)
6102         {
6103           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6104               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6105             return FALSE;
6106         }
6107
6108       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6109       /* If .dynstr is excluded from the link, we don't want any of
6110          these tags.  Strictly, we should be checking each section
6111          individually;  This quick check covers for the case where
6112          someone does a /DISCARD/ : { *(*) }.  */
6113       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6114         {
6115           bfd_size_type strsize;
6116
6117           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6118           if ((info->emit_hash
6119                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6120               || (info->emit_gnu_hash
6121                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6122               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6123               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6124               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6125               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6126                                               bed->s->sizeof_sym))
6127             return FALSE;
6128         }
6129     }
6130
6131   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6132     return FALSE;
6133
6134   /* The backend must work out the sizes of all the other dynamic
6135      sections.  */
6136   if (dynobj != NULL
6137       && bed->elf_backend_size_dynamic_sections != NULL
6138       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6139     return FALSE;
6140
6141   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6142     {
6143       unsigned long section_sym_count;
6144       struct bfd_elf_version_tree *verdefs;
6145       asection *s;
6146
6147       /* Set up the version definition section.  */
6148       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6149       BFD_ASSERT (s != NULL);
6150
6151       /* We may have created additional version definitions if we are
6152          just linking a regular application.  */
6153       verdefs = info->version_info;
6154
6155       /* Skip anonymous version tag.  */
6156       if (verdefs != NULL && verdefs->vernum == 0)
6157         verdefs = verdefs->next;
6158
6159       if (verdefs == NULL && !info->create_default_symver)
6160         s->flags |= SEC_EXCLUDE;
6161       else
6162         {
6163           unsigned int cdefs;
6164           bfd_size_type size;
6165           struct bfd_elf_version_tree *t;
6166           bfd_byte *p;
6167           Elf_Internal_Verdef def;
6168           Elf_Internal_Verdaux defaux;
6169           struct bfd_link_hash_entry *bh;
6170           struct elf_link_hash_entry *h;
6171           const char *name;
6172
6173           cdefs = 0;
6174           size = 0;
6175
6176           /* Make space for the base version.  */
6177           size += sizeof (Elf_External_Verdef);
6178           size += sizeof (Elf_External_Verdaux);
6179           ++cdefs;
6180
6181           /* Make space for the default version.  */
6182           if (info->create_default_symver)
6183             {
6184               size += sizeof (Elf_External_Verdef);
6185               ++cdefs;
6186             }
6187
6188           for (t = verdefs; t != NULL; t = t->next)
6189             {
6190               struct bfd_elf_version_deps *n;
6191
6192               /* Don't emit base version twice.  */
6193               if (t->vernum == 0)
6194                 continue;
6195
6196               size += sizeof (Elf_External_Verdef);
6197               size += sizeof (Elf_External_Verdaux);
6198               ++cdefs;
6199
6200               for (n = t->deps; n != NULL; n = n->next)
6201                 size += sizeof (Elf_External_Verdaux);
6202             }
6203
6204           s->size = size;
6205           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6206           if (s->contents == NULL && s->size != 0)
6207             return FALSE;
6208
6209           /* Fill in the version definition section.  */
6210
6211           p = s->contents;
6212
6213           def.vd_version = VER_DEF_CURRENT;
6214           def.vd_flags = VER_FLG_BASE;
6215           def.vd_ndx = 1;
6216           def.vd_cnt = 1;
6217           if (info->create_default_symver)
6218             {
6219               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6220               def.vd_next = sizeof (Elf_External_Verdef);
6221             }
6222           else
6223             {
6224               def.vd_aux = sizeof (Elf_External_Verdef);
6225               def.vd_next = (sizeof (Elf_External_Verdef)
6226                              + sizeof (Elf_External_Verdaux));
6227             }
6228
6229           if (soname_indx != (bfd_size_type) -1)
6230             {
6231               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6232                                       soname_indx);
6233               def.vd_hash = bfd_elf_hash (soname);
6234               defaux.vda_name = soname_indx;
6235               name = soname;
6236             }
6237           else
6238             {
6239               bfd_size_type indx;
6240
6241               name = lbasename (output_bfd->filename);
6242               def.vd_hash = bfd_elf_hash (name);
6243               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6244                                           name, FALSE);
6245               if (indx == (bfd_size_type) -1)
6246                 return FALSE;
6247               defaux.vda_name = indx;
6248             }
6249           defaux.vda_next = 0;
6250
6251           _bfd_elf_swap_verdef_out (output_bfd, &def,
6252                                     (Elf_External_Verdef *) p);
6253           p += sizeof (Elf_External_Verdef);
6254           if (info->create_default_symver)
6255             {
6256               /* Add a symbol representing this version.  */
6257               bh = NULL;
6258               if (! (_bfd_generic_link_add_one_symbol
6259                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6260                       0, NULL, FALSE,
6261                       get_elf_backend_data (dynobj)->collect, &bh)))
6262                 return FALSE;
6263               h = (struct elf_link_hash_entry *) bh;
6264               h->non_elf = 0;
6265               h->def_regular = 1;
6266               h->type = STT_OBJECT;
6267               h->verinfo.vertree = NULL;
6268
6269               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6270                 return FALSE;
6271
6272               /* Create a duplicate of the base version with the same
6273                  aux block, but different flags.  */
6274               def.vd_flags = 0;
6275               def.vd_ndx = 2;
6276               def.vd_aux = sizeof (Elf_External_Verdef);
6277               if (verdefs)
6278                 def.vd_next = (sizeof (Elf_External_Verdef)
6279                                + sizeof (Elf_External_Verdaux));
6280               else
6281                 def.vd_next = 0;
6282               _bfd_elf_swap_verdef_out (output_bfd, &def,
6283                                         (Elf_External_Verdef *) p);
6284               p += sizeof (Elf_External_Verdef);
6285             }
6286           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6287                                      (Elf_External_Verdaux *) p);
6288           p += sizeof (Elf_External_Verdaux);
6289
6290           for (t = verdefs; t != NULL; t = t->next)
6291             {
6292               unsigned int cdeps;
6293               struct bfd_elf_version_deps *n;
6294
6295               /* Don't emit the base version twice.  */
6296               if (t->vernum == 0)
6297                 continue;
6298
6299               cdeps = 0;
6300               for (n = t->deps; n != NULL; n = n->next)
6301                 ++cdeps;
6302
6303               /* Add a symbol representing this version.  */
6304               bh = NULL;
6305               if (! (_bfd_generic_link_add_one_symbol
6306                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6307                       0, NULL, FALSE,
6308                       get_elf_backend_data (dynobj)->collect, &bh)))
6309                 return FALSE;
6310               h = (struct elf_link_hash_entry *) bh;
6311               h->non_elf = 0;
6312               h->def_regular = 1;
6313               h->type = STT_OBJECT;
6314               h->verinfo.vertree = t;
6315
6316               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6317                 return FALSE;
6318
6319               def.vd_version = VER_DEF_CURRENT;
6320               def.vd_flags = 0;
6321               if (t->globals.list == NULL
6322                   && t->locals.list == NULL
6323                   && ! t->used)
6324                 def.vd_flags |= VER_FLG_WEAK;
6325               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6326               def.vd_cnt = cdeps + 1;
6327               def.vd_hash = bfd_elf_hash (t->name);
6328               def.vd_aux = sizeof (Elf_External_Verdef);
6329               def.vd_next = 0;
6330
6331               /* If a basever node is next, it *must* be the last node in
6332                  the chain, otherwise Verdef construction breaks.  */
6333               if (t->next != NULL && t->next->vernum == 0)
6334                 BFD_ASSERT (t->next->next == NULL);
6335
6336               if (t->next != NULL && t->next->vernum != 0)
6337                 def.vd_next = (sizeof (Elf_External_Verdef)
6338                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6339
6340               _bfd_elf_swap_verdef_out (output_bfd, &def,
6341                                         (Elf_External_Verdef *) p);
6342               p += sizeof (Elf_External_Verdef);
6343
6344               defaux.vda_name = h->dynstr_index;
6345               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6346                                       h->dynstr_index);
6347               defaux.vda_next = 0;
6348               if (t->deps != NULL)
6349                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6350               t->name_indx = defaux.vda_name;
6351
6352               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6353                                          (Elf_External_Verdaux *) p);
6354               p += sizeof (Elf_External_Verdaux);
6355
6356               for (n = t->deps; n != NULL; n = n->next)
6357                 {
6358                   if (n->version_needed == NULL)
6359                     {
6360                       /* This can happen if there was an error in the
6361                          version script.  */
6362                       defaux.vda_name = 0;
6363                     }
6364                   else
6365                     {
6366                       defaux.vda_name = n->version_needed->name_indx;
6367                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6368                                               defaux.vda_name);
6369                     }
6370                   if (n->next == NULL)
6371                     defaux.vda_next = 0;
6372                   else
6373                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6374
6375                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6376                                              (Elf_External_Verdaux *) p);
6377                   p += sizeof (Elf_External_Verdaux);
6378                 }
6379             }
6380
6381           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6382               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, cdefs))
6383             return FALSE;
6384
6385           elf_tdata (output_bfd)->cverdefs = cdefs;
6386         }
6387
6388       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6389         {
6390           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6391             return FALSE;
6392         }
6393       else if (info->flags & DF_BIND_NOW)
6394         {
6395           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6396             return FALSE;
6397         }
6398
6399       if (info->flags_1)
6400         {
6401           if (bfd_link_executable (info))
6402             info->flags_1 &= ~ (DF_1_INITFIRST
6403                                 | DF_1_NODELETE
6404                                 | DF_1_NOOPEN);
6405           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6406             return FALSE;
6407         }
6408
6409       /* Work out the size of the version reference section.  */
6410
6411       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6412       BFD_ASSERT (s != NULL);
6413       {
6414         struct elf_find_verdep_info sinfo;
6415
6416         sinfo.info = info;
6417         sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6418         if (sinfo.vers == 0)
6419           sinfo.vers = 1;
6420         sinfo.failed = FALSE;
6421
6422         elf_link_hash_traverse (elf_hash_table (info),
6423                                 _bfd_elf_link_find_version_dependencies,
6424                                 &sinfo);
6425         if (sinfo.failed)
6426           return FALSE;
6427
6428         if (elf_tdata (output_bfd)->verref == NULL)
6429           s->flags |= SEC_EXCLUDE;
6430         else
6431           {
6432             Elf_Internal_Verneed *t;
6433             unsigned int size;
6434             unsigned int crefs;
6435             bfd_byte *p;
6436
6437             /* Build the version dependency section.  */
6438             size = 0;
6439             crefs = 0;
6440             for (t = elf_tdata (output_bfd)->verref;
6441                  t != NULL;
6442                  t = t->vn_nextref)
6443               {
6444                 Elf_Internal_Vernaux *a;
6445
6446                 size += sizeof (Elf_External_Verneed);
6447                 ++crefs;
6448                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6449                   size += sizeof (Elf_External_Vernaux);
6450               }
6451
6452             s->size = size;
6453             s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6454             if (s->contents == NULL)
6455               return FALSE;
6456
6457             p = s->contents;
6458             for (t = elf_tdata (output_bfd)->verref;
6459                  t != NULL;
6460                  t = t->vn_nextref)
6461               {
6462                 unsigned int caux;
6463                 Elf_Internal_Vernaux *a;
6464                 bfd_size_type indx;
6465
6466                 caux = 0;
6467                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6468                   ++caux;
6469
6470                 t->vn_version = VER_NEED_CURRENT;
6471                 t->vn_cnt = caux;
6472                 indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6473                                             elf_dt_name (t->vn_bfd) != NULL
6474                                             ? elf_dt_name (t->vn_bfd)
6475                                             : lbasename (t->vn_bfd->filename),
6476                                             FALSE);
6477                 if (indx == (bfd_size_type) -1)
6478                   return FALSE;
6479                 t->vn_file = indx;
6480                 t->vn_aux = sizeof (Elf_External_Verneed);
6481                 if (t->vn_nextref == NULL)
6482                   t->vn_next = 0;
6483                 else
6484                   t->vn_next = (sizeof (Elf_External_Verneed)
6485                                 + caux * sizeof (Elf_External_Vernaux));
6486
6487                 _bfd_elf_swap_verneed_out (output_bfd, t,
6488                                            (Elf_External_Verneed *) p);
6489                 p += sizeof (Elf_External_Verneed);
6490
6491                 for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
6492                   {
6493                     a->vna_hash = bfd_elf_hash (a->vna_nodename);
6494                     indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6495                                                 a->vna_nodename, FALSE);
6496                     if (indx == (bfd_size_type) -1)
6497                       return FALSE;
6498                     a->vna_name = indx;
6499                     if (a->vna_nextptr == NULL)
6500                       a->vna_next = 0;
6501                     else
6502                       a->vna_next = sizeof (Elf_External_Vernaux);
6503
6504                     _bfd_elf_swap_vernaux_out (output_bfd, a,
6505                                                (Elf_External_Vernaux *) p);
6506                     p += sizeof (Elf_External_Vernaux);
6507                   }
6508               }
6509
6510             if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6511                 || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6512               return FALSE;
6513
6514             elf_tdata (output_bfd)->cverrefs = crefs;
6515           }
6516       }
6517
6518       if ((elf_tdata (output_bfd)->cverrefs == 0
6519            && elf_tdata (output_bfd)->cverdefs == 0)
6520           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6521                                              &section_sym_count) == 0)
6522         {
6523           s = bfd_get_linker_section (dynobj, ".gnu.version");
6524           s->flags |= SEC_EXCLUDE;
6525         }
6526     }
6527   return TRUE;
6528 }
6529
6530 /* Find the first non-excluded output section.  We'll use its
6531    section symbol for some emitted relocs.  */
6532 void
6533 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6534 {
6535   asection *s;
6536
6537   for (s = output_bfd->sections; s != NULL; s = s->next)
6538     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6539         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6540       {
6541         elf_hash_table (info)->text_index_section = s;
6542         break;
6543       }
6544 }
6545
6546 /* Find two non-excluded output sections, one for code, one for data.
6547    We'll use their section symbols for some emitted relocs.  */
6548 void
6549 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6550 {
6551   asection *s;
6552
6553   /* Data first, since setting text_index_section changes
6554      _bfd_elf_link_omit_section_dynsym.  */
6555   for (s = output_bfd->sections; s != NULL; s = s->next)
6556     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6557         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6558       {
6559         elf_hash_table (info)->data_index_section = s;
6560         break;
6561       }
6562
6563   for (s = output_bfd->sections; s != NULL; s = s->next)
6564     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6565          == (SEC_ALLOC | SEC_READONLY))
6566         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6567       {
6568         elf_hash_table (info)->text_index_section = s;
6569         break;
6570       }
6571
6572   if (elf_hash_table (info)->text_index_section == NULL)
6573     elf_hash_table (info)->text_index_section
6574       = elf_hash_table (info)->data_index_section;
6575 }
6576
6577 bfd_boolean
6578 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6579 {
6580   const struct elf_backend_data *bed;
6581
6582   if (!is_elf_hash_table (info->hash))
6583     return TRUE;
6584
6585   bed = get_elf_backend_data (output_bfd);
6586   (*bed->elf_backend_init_index_section) (output_bfd, info);
6587
6588   if (elf_hash_table (info)->dynamic_sections_created)
6589     {
6590       bfd *dynobj;
6591       asection *s;
6592       bfd_size_type dynsymcount;
6593       unsigned long section_sym_count;
6594       unsigned int dtagcount;
6595
6596       dynobj = elf_hash_table (info)->dynobj;
6597
6598       /* Assign dynsym indicies.  In a shared library we generate a
6599          section symbol for each output section, which come first.
6600          Next come all of the back-end allocated local dynamic syms,
6601          followed by the rest of the global symbols.  */
6602
6603       dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6604                                                     &section_sym_count);
6605
6606       /* Work out the size of the symbol version section.  */
6607       s = bfd_get_linker_section (dynobj, ".gnu.version");
6608       BFD_ASSERT (s != NULL);
6609       if ((s->flags & SEC_EXCLUDE) == 0)
6610         {
6611           s->size = dynsymcount * sizeof (Elf_External_Versym);
6612           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6613           if (s->contents == NULL)
6614             return FALSE;
6615
6616           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6617             return FALSE;
6618         }
6619
6620       /* Set the size of the .dynsym and .hash sections.  We counted
6621          the number of dynamic symbols in elf_link_add_object_symbols.
6622          We will build the contents of .dynsym and .hash when we build
6623          the final symbol table, because until then we do not know the
6624          correct value to give the symbols.  We built the .dynstr
6625          section as we went along in elf_link_add_object_symbols.  */
6626       s = elf_hash_table (info)->dynsym;
6627       BFD_ASSERT (s != NULL);
6628       s->size = dynsymcount * bed->s->sizeof_sym;
6629
6630       s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6631       if (s->contents == NULL)
6632         return FALSE;
6633
6634       /* The first entry in .dynsym is a dummy symbol.  Clear all the
6635          section syms, in case we don't output them all.  */
6636       ++section_sym_count;
6637       memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6638
6639       elf_hash_table (info)->bucketcount = 0;
6640
6641       /* Compute the size of the hashing table.  As a side effect this
6642          computes the hash values for all the names we export.  */
6643       if (info->emit_hash)
6644         {
6645           unsigned long int *hashcodes;
6646           struct hash_codes_info hashinf;
6647           bfd_size_type amt;
6648           unsigned long int nsyms;
6649           size_t bucketcount;
6650           size_t hash_entry_size;
6651
6652           /* Compute the hash values for all exported symbols.  At the same
6653              time store the values in an array so that we could use them for
6654              optimizations.  */
6655           amt = dynsymcount * sizeof (unsigned long int);
6656           hashcodes = (unsigned long int *) bfd_malloc (amt);
6657           if (hashcodes == NULL)
6658             return FALSE;
6659           hashinf.hashcodes = hashcodes;
6660           hashinf.error = FALSE;
6661
6662           /* Put all hash values in HASHCODES.  */
6663           elf_link_hash_traverse (elf_hash_table (info),
6664                                   elf_collect_hash_codes, &hashinf);
6665           if (hashinf.error)
6666             {
6667               free (hashcodes);
6668               return FALSE;
6669             }
6670
6671           nsyms = hashinf.hashcodes - hashcodes;
6672           bucketcount
6673             = compute_bucket_count (info, hashcodes, nsyms, 0);
6674           free (hashcodes);
6675
6676           if (bucketcount == 0)
6677             return FALSE;
6678
6679           elf_hash_table (info)->bucketcount = bucketcount;
6680
6681           s = bfd_get_linker_section (dynobj, ".hash");
6682           BFD_ASSERT (s != NULL);
6683           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6684           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6685           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6686           if (s->contents == NULL)
6687             return FALSE;
6688
6689           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6690           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6691                    s->contents + hash_entry_size);
6692         }
6693
6694       if (info->emit_gnu_hash)
6695         {
6696           size_t i, cnt;
6697           unsigned char *contents;
6698           struct collect_gnu_hash_codes cinfo;
6699           bfd_size_type amt;
6700           size_t bucketcount;
6701
6702           memset (&cinfo, 0, sizeof (cinfo));
6703
6704           /* Compute the hash values for all exported symbols.  At the same
6705              time store the values in an array so that we could use them for
6706              optimizations.  */
6707           amt = dynsymcount * 2 * sizeof (unsigned long int);
6708           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
6709           if (cinfo.hashcodes == NULL)
6710             return FALSE;
6711
6712           cinfo.hashval = cinfo.hashcodes + dynsymcount;
6713           cinfo.min_dynindx = -1;
6714           cinfo.output_bfd = output_bfd;
6715           cinfo.bed = bed;
6716
6717           /* Put all hash values in HASHCODES.  */
6718           elf_link_hash_traverse (elf_hash_table (info),
6719                                   elf_collect_gnu_hash_codes, &cinfo);
6720           if (cinfo.error)
6721             {
6722               free (cinfo.hashcodes);
6723               return FALSE;
6724             }
6725
6726           bucketcount
6727             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
6728
6729           if (bucketcount == 0)
6730             {
6731               free (cinfo.hashcodes);
6732               return FALSE;
6733             }
6734
6735           s = bfd_get_linker_section (dynobj, ".gnu.hash");
6736           BFD_ASSERT (s != NULL);
6737
6738           if (cinfo.nsyms == 0)
6739             {
6740               /* Empty .gnu.hash section is special.  */
6741               BFD_ASSERT (cinfo.min_dynindx == -1);
6742               free (cinfo.hashcodes);
6743               s->size = 5 * 4 + bed->s->arch_size / 8;
6744               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6745               if (contents == NULL)
6746                 return FALSE;
6747               s->contents = contents;
6748               /* 1 empty bucket.  */
6749               bfd_put_32 (output_bfd, 1, contents);
6750               /* SYMIDX above the special symbol 0.  */
6751               bfd_put_32 (output_bfd, 1, contents + 4);
6752               /* Just one word for bitmask.  */
6753               bfd_put_32 (output_bfd, 1, contents + 8);
6754               /* Only hash fn bloom filter.  */
6755               bfd_put_32 (output_bfd, 0, contents + 12);
6756               /* No hashes are valid - empty bitmask.  */
6757               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
6758               /* No hashes in the only bucket.  */
6759               bfd_put_32 (output_bfd, 0,
6760                           contents + 16 + bed->s->arch_size / 8);
6761             }
6762           else
6763             {
6764               unsigned long int maskwords, maskbitslog2, x;
6765               BFD_ASSERT (cinfo.min_dynindx != -1);
6766
6767               x = cinfo.nsyms;
6768               maskbitslog2 = 1;
6769               while ((x >>= 1) != 0)
6770                 ++maskbitslog2;
6771               if (maskbitslog2 < 3)
6772                 maskbitslog2 = 5;
6773               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
6774                 maskbitslog2 = maskbitslog2 + 3;
6775               else
6776                 maskbitslog2 = maskbitslog2 + 2;
6777               if (bed->s->arch_size == 64)
6778                 {
6779                   if (maskbitslog2 == 5)
6780                     maskbitslog2 = 6;
6781                   cinfo.shift1 = 6;
6782                 }
6783               else
6784                 cinfo.shift1 = 5;
6785               cinfo.mask = (1 << cinfo.shift1) - 1;
6786               cinfo.shift2 = maskbitslog2;
6787               cinfo.maskbits = 1 << maskbitslog2;
6788               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
6789               amt = bucketcount * sizeof (unsigned long int) * 2;
6790               amt += maskwords * sizeof (bfd_vma);
6791               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
6792               if (cinfo.bitmask == NULL)
6793                 {
6794                   free (cinfo.hashcodes);
6795                   return FALSE;
6796                 }
6797
6798               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
6799               cinfo.indx = cinfo.counts + bucketcount;
6800               cinfo.symindx = dynsymcount - cinfo.nsyms;
6801               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
6802
6803               /* Determine how often each hash bucket is used.  */
6804               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
6805               for (i = 0; i < cinfo.nsyms; ++i)
6806                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
6807
6808               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
6809                 if (cinfo.counts[i] != 0)
6810                   {
6811                     cinfo.indx[i] = cnt;
6812                     cnt += cinfo.counts[i];
6813                   }
6814               BFD_ASSERT (cnt == dynsymcount);
6815               cinfo.bucketcount = bucketcount;
6816               cinfo.local_indx = cinfo.min_dynindx;
6817
6818               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
6819               s->size += cinfo.maskbits / 8;
6820               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6821               if (contents == NULL)
6822                 {
6823                   free (cinfo.bitmask);
6824                   free (cinfo.hashcodes);
6825                   return FALSE;
6826                 }
6827
6828               s->contents = contents;
6829               bfd_put_32 (output_bfd, bucketcount, contents);
6830               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
6831               bfd_put_32 (output_bfd, maskwords, contents + 8);
6832               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
6833               contents += 16 + cinfo.maskbits / 8;
6834
6835               for (i = 0; i < bucketcount; ++i)
6836                 {
6837                   if (cinfo.counts[i] == 0)
6838                     bfd_put_32 (output_bfd, 0, contents);
6839                   else
6840                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
6841                   contents += 4;
6842                 }
6843
6844               cinfo.contents = contents;
6845
6846               /* Renumber dynamic symbols, populate .gnu.hash section.  */
6847               elf_link_hash_traverse (elf_hash_table (info),
6848                                       elf_renumber_gnu_hash_syms, &cinfo);
6849
6850               contents = s->contents + 16;
6851               for (i = 0; i < maskwords; ++i)
6852                 {
6853                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
6854                            contents);
6855                   contents += bed->s->arch_size / 8;
6856                 }
6857
6858               free (cinfo.bitmask);
6859               free (cinfo.hashcodes);
6860             }
6861         }
6862
6863       s = bfd_get_linker_section (dynobj, ".dynstr");
6864       BFD_ASSERT (s != NULL);
6865
6866       elf_finalize_dynstr (output_bfd, info);
6867
6868       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6869
6870       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
6871         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
6872           return FALSE;
6873     }
6874
6875   return TRUE;
6876 }
6877 \f
6878 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
6879
6880 static void
6881 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
6882                             asection *sec)
6883 {
6884   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
6885   sec->sec_info_type = SEC_INFO_TYPE_NONE;
6886 }
6887
6888 /* Finish SHF_MERGE section merging.  */
6889
6890 bfd_boolean
6891 _bfd_elf_merge_sections (bfd *obfd, struct bfd_link_info *info)
6892 {
6893   bfd *ibfd;
6894   asection *sec;
6895
6896   if (!is_elf_hash_table (info->hash))
6897     return FALSE;
6898
6899   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
6900     if ((ibfd->flags & DYNAMIC) == 0
6901         && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
6902         && (elf_elfheader (ibfd)->e_ident[EI_CLASS]
6903             == get_elf_backend_data (obfd)->s->elfclass))
6904       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
6905         if ((sec->flags & SEC_MERGE) != 0
6906             && !bfd_is_abs_section (sec->output_section))
6907           {
6908             struct bfd_elf_section_data *secdata;
6909
6910             secdata = elf_section_data (sec);
6911             if (! _bfd_add_merge_section (obfd,
6912                                           &elf_hash_table (info)->merge_info,
6913                                           sec, &secdata->sec_info))
6914               return FALSE;
6915             else if (secdata->sec_info)
6916               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
6917           }
6918
6919   if (elf_hash_table (info)->merge_info != NULL)
6920     _bfd_merge_sections (obfd, info, elf_hash_table (info)->merge_info,
6921                          merge_sections_remove_hook);
6922   return TRUE;
6923 }
6924
6925 /* Create an entry in an ELF linker hash table.  */
6926
6927 struct bfd_hash_entry *
6928 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
6929                             struct bfd_hash_table *table,
6930                             const char *string)
6931 {
6932   /* Allocate the structure if it has not already been allocated by a
6933      subclass.  */
6934   if (entry == NULL)
6935     {
6936       entry = (struct bfd_hash_entry *)
6937         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
6938       if (entry == NULL)
6939         return entry;
6940     }
6941
6942   /* Call the allocation method of the superclass.  */
6943   entry = _bfd_link_hash_newfunc (entry, table, string);
6944   if (entry != NULL)
6945     {
6946       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
6947       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
6948
6949       /* Set local fields.  */
6950       ret->indx = -1;
6951       ret->dynindx = -1;
6952       ret->got = htab->init_got_refcount;
6953       ret->plt = htab->init_plt_refcount;
6954       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
6955                               - offsetof (struct elf_link_hash_entry, size)));
6956       /* Assume that we have been called by a non-ELF symbol reader.
6957          This flag is then reset by the code which reads an ELF input
6958          file.  This ensures that a symbol created by a non-ELF symbol
6959          reader will have the flag set correctly.  */
6960       ret->non_elf = 1;
6961     }
6962
6963   return entry;
6964 }
6965
6966 /* Copy data from an indirect symbol to its direct symbol, hiding the
6967    old indirect symbol.  Also used for copying flags to a weakdef.  */
6968
6969 void
6970 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
6971                                   struct elf_link_hash_entry *dir,
6972                                   struct elf_link_hash_entry *ind)
6973 {
6974   struct elf_link_hash_table *htab;
6975
6976   /* Copy down any references that we may have already seen to the
6977      symbol which just became indirect if DIR isn't a hidden versioned
6978      symbol.  */
6979
6980   if (dir->versioned != versioned_hidden)
6981     {
6982       dir->ref_dynamic |= ind->ref_dynamic;
6983       dir->ref_regular |= ind->ref_regular;
6984       dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
6985       dir->non_got_ref |= ind->non_got_ref;
6986       dir->needs_plt |= ind->needs_plt;
6987       dir->pointer_equality_needed |= ind->pointer_equality_needed;
6988     }
6989
6990   if (ind->root.type != bfd_link_hash_indirect)
6991     return;
6992
6993   /* Copy over the global and procedure linkage table refcount entries.
6994      These may have been already set up by a check_relocs routine.  */
6995   htab = elf_hash_table (info);
6996   if (ind->got.refcount > htab->init_got_refcount.refcount)
6997     {
6998       if (dir->got.refcount < 0)
6999         dir->got.refcount = 0;
7000       dir->got.refcount += ind->got.refcount;
7001       ind->got.refcount = htab->init_got_refcount.refcount;
7002     }
7003
7004   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
7005     {
7006       if (dir->plt.refcount < 0)
7007         dir->plt.refcount = 0;
7008       dir->plt.refcount += ind->plt.refcount;
7009       ind->plt.refcount = htab->init_plt_refcount.refcount;
7010     }
7011
7012   if (ind->dynindx != -1)
7013     {
7014       if (dir->dynindx != -1)
7015         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
7016       dir->dynindx = ind->dynindx;
7017       dir->dynstr_index = ind->dynstr_index;
7018       ind->dynindx = -1;
7019       ind->dynstr_index = 0;
7020     }
7021 }
7022
7023 void
7024 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
7025                                 struct elf_link_hash_entry *h,
7026                                 bfd_boolean force_local)
7027 {
7028   /* STT_GNU_IFUNC symbol must go through PLT.  */
7029   if (h->type != STT_GNU_IFUNC)
7030     {
7031       h->plt = elf_hash_table (info)->init_plt_offset;
7032       h->needs_plt = 0;
7033     }
7034   if (force_local)
7035     {
7036       h->forced_local = 1;
7037       if (h->dynindx != -1)
7038         {
7039           h->dynindx = -1;
7040           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
7041                                   h->dynstr_index);
7042         }
7043     }
7044 }
7045
7046 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
7047    caller.  */
7048
7049 bfd_boolean
7050 _bfd_elf_link_hash_table_init
7051   (struct elf_link_hash_table *table,
7052    bfd *abfd,
7053    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
7054                                       struct bfd_hash_table *,
7055                                       const char *),
7056    unsigned int entsize,
7057    enum elf_target_id target_id)
7058 {
7059   bfd_boolean ret;
7060   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
7061
7062   table->init_got_refcount.refcount = can_refcount - 1;
7063   table->init_plt_refcount.refcount = can_refcount - 1;
7064   table->init_got_offset.offset = -(bfd_vma) 1;
7065   table->init_plt_offset.offset = -(bfd_vma) 1;
7066   /* The first dynamic symbol is a dummy.  */
7067   table->dynsymcount = 1;
7068
7069   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
7070
7071   table->root.type = bfd_link_elf_hash_table;
7072   table->hash_table_id = target_id;
7073
7074   return ret;
7075 }
7076
7077 /* Create an ELF linker hash table.  */
7078
7079 struct bfd_link_hash_table *
7080 _bfd_elf_link_hash_table_create (bfd *abfd)
7081 {
7082   struct elf_link_hash_table *ret;
7083   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7084
7085   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7086   if (ret == NULL)
7087     return NULL;
7088
7089   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7090                                        sizeof (struct elf_link_hash_entry),
7091                                        GENERIC_ELF_DATA))
7092     {
7093       free (ret);
7094       return NULL;
7095     }
7096   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7097
7098   return &ret->root;
7099 }
7100
7101 /* Destroy an ELF linker hash table.  */
7102
7103 void
7104 _bfd_elf_link_hash_table_free (bfd *obfd)
7105 {
7106   struct elf_link_hash_table *htab;
7107
7108   htab = (struct elf_link_hash_table *) obfd->link.hash;
7109   if (htab->dynstr != NULL)
7110     _bfd_elf_strtab_free (htab->dynstr);
7111   _bfd_merge_sections_free (htab->merge_info);
7112   _bfd_generic_link_hash_table_free (obfd);
7113 }
7114
7115 /* This is a hook for the ELF emulation code in the generic linker to
7116    tell the backend linker what file name to use for the DT_NEEDED
7117    entry for a dynamic object.  */
7118
7119 void
7120 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7121 {
7122   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7123       && bfd_get_format (abfd) == bfd_object)
7124     elf_dt_name (abfd) = name;
7125 }
7126
7127 int
7128 bfd_elf_get_dyn_lib_class (bfd *abfd)
7129 {
7130   int lib_class;
7131   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7132       && bfd_get_format (abfd) == bfd_object)
7133     lib_class = elf_dyn_lib_class (abfd);
7134   else
7135     lib_class = 0;
7136   return lib_class;
7137 }
7138
7139 void
7140 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7141 {
7142   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7143       && bfd_get_format (abfd) == bfd_object)
7144     elf_dyn_lib_class (abfd) = lib_class;
7145 }
7146
7147 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7148    the linker ELF emulation code.  */
7149
7150 struct bfd_link_needed_list *
7151 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7152                          struct bfd_link_info *info)
7153 {
7154   if (! is_elf_hash_table (info->hash))
7155     return NULL;
7156   return elf_hash_table (info)->needed;
7157 }
7158
7159 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7160    hook for the linker ELF emulation code.  */
7161
7162 struct bfd_link_needed_list *
7163 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7164                           struct bfd_link_info *info)
7165 {
7166   if (! is_elf_hash_table (info->hash))
7167     return NULL;
7168   return elf_hash_table (info)->runpath;
7169 }
7170
7171 /* Get the name actually used for a dynamic object for a link.  This
7172    is the SONAME entry if there is one.  Otherwise, it is the string
7173    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7174
7175 const char *
7176 bfd_elf_get_dt_soname (bfd *abfd)
7177 {
7178   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7179       && bfd_get_format (abfd) == bfd_object)
7180     return elf_dt_name (abfd);
7181   return NULL;
7182 }
7183
7184 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7185    the ELF linker emulation code.  */
7186
7187 bfd_boolean
7188 bfd_elf_get_bfd_needed_list (bfd *abfd,
7189                              struct bfd_link_needed_list **pneeded)
7190 {
7191   asection *s;
7192   bfd_byte *dynbuf = NULL;
7193   unsigned int elfsec;
7194   unsigned long shlink;
7195   bfd_byte *extdyn, *extdynend;
7196   size_t extdynsize;
7197   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7198
7199   *pneeded = NULL;
7200
7201   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7202       || bfd_get_format (abfd) != bfd_object)
7203     return TRUE;
7204
7205   s = bfd_get_section_by_name (abfd, ".dynamic");
7206   if (s == NULL || s->size == 0)
7207     return TRUE;
7208
7209   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7210     goto error_return;
7211
7212   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7213   if (elfsec == SHN_BAD)
7214     goto error_return;
7215
7216   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7217
7218   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7219   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7220
7221   extdyn = dynbuf;
7222   extdynend = extdyn + s->size;
7223   for (; extdyn < extdynend; extdyn += extdynsize)
7224     {
7225       Elf_Internal_Dyn dyn;
7226
7227       (*swap_dyn_in) (abfd, extdyn, &dyn);
7228
7229       if (dyn.d_tag == DT_NULL)
7230         break;
7231
7232       if (dyn.d_tag == DT_NEEDED)
7233         {
7234           const char *string;
7235           struct bfd_link_needed_list *l;
7236           unsigned int tagv = dyn.d_un.d_val;
7237           bfd_size_type amt;
7238
7239           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7240           if (string == NULL)
7241             goto error_return;
7242
7243           amt = sizeof *l;
7244           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7245           if (l == NULL)
7246             goto error_return;
7247
7248           l->by = abfd;
7249           l->name = string;
7250           l->next = *pneeded;
7251           *pneeded = l;
7252         }
7253     }
7254
7255   free (dynbuf);
7256
7257   return TRUE;
7258
7259  error_return:
7260   if (dynbuf != NULL)
7261     free (dynbuf);
7262   return FALSE;
7263 }
7264
7265 struct elf_symbuf_symbol
7266 {
7267   unsigned long st_name;        /* Symbol name, index in string tbl */
7268   unsigned char st_info;        /* Type and binding attributes */
7269   unsigned char st_other;       /* Visibilty, and target specific */
7270 };
7271
7272 struct elf_symbuf_head
7273 {
7274   struct elf_symbuf_symbol *ssym;
7275   bfd_size_type count;
7276   unsigned int st_shndx;
7277 };
7278
7279 struct elf_symbol
7280 {
7281   union
7282     {
7283       Elf_Internal_Sym *isym;
7284       struct elf_symbuf_symbol *ssym;
7285     } u;
7286   const char *name;
7287 };
7288
7289 /* Sort references to symbols by ascending section number.  */
7290
7291 static int
7292 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7293 {
7294   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7295   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7296
7297   return s1->st_shndx - s2->st_shndx;
7298 }
7299
7300 static int
7301 elf_sym_name_compare (const void *arg1, const void *arg2)
7302 {
7303   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7304   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7305   return strcmp (s1->name, s2->name);
7306 }
7307
7308 static struct elf_symbuf_head *
7309 elf_create_symbuf (bfd_size_type symcount, Elf_Internal_Sym *isymbuf)
7310 {
7311   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7312   struct elf_symbuf_symbol *ssym;
7313   struct elf_symbuf_head *ssymbuf, *ssymhead;
7314   bfd_size_type i, shndx_count, total_size;
7315
7316   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7317   if (indbuf == NULL)
7318     return NULL;
7319
7320   for (ind = indbuf, i = 0; i < symcount; i++)
7321     if (isymbuf[i].st_shndx != SHN_UNDEF)
7322       *ind++ = &isymbuf[i];
7323   indbufend = ind;
7324
7325   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7326          elf_sort_elf_symbol);
7327
7328   shndx_count = 0;
7329   if (indbufend > indbuf)
7330     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7331       if (ind[0]->st_shndx != ind[1]->st_shndx)
7332         shndx_count++;
7333
7334   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7335                 + (indbufend - indbuf) * sizeof (*ssym));
7336   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7337   if (ssymbuf == NULL)
7338     {
7339       free (indbuf);
7340       return NULL;
7341     }
7342
7343   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7344   ssymbuf->ssym = NULL;
7345   ssymbuf->count = shndx_count;
7346   ssymbuf->st_shndx = 0;
7347   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7348     {
7349       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7350         {
7351           ssymhead++;
7352           ssymhead->ssym = ssym;
7353           ssymhead->count = 0;
7354           ssymhead->st_shndx = (*ind)->st_shndx;
7355         }
7356       ssym->st_name = (*ind)->st_name;
7357       ssym->st_info = (*ind)->st_info;
7358       ssym->st_other = (*ind)->st_other;
7359       ssymhead->count++;
7360     }
7361   BFD_ASSERT ((bfd_size_type) (ssymhead - ssymbuf) == shndx_count
7362               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7363                   == total_size));
7364
7365   free (indbuf);
7366   return ssymbuf;
7367 }
7368
7369 /* Check if 2 sections define the same set of local and global
7370    symbols.  */
7371
7372 static bfd_boolean
7373 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7374                                    struct bfd_link_info *info)
7375 {
7376   bfd *bfd1, *bfd2;
7377   const struct elf_backend_data *bed1, *bed2;
7378   Elf_Internal_Shdr *hdr1, *hdr2;
7379   bfd_size_type symcount1, symcount2;
7380   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7381   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7382   Elf_Internal_Sym *isym, *isymend;
7383   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7384   bfd_size_type count1, count2, i;
7385   unsigned int shndx1, shndx2;
7386   bfd_boolean result;
7387
7388   bfd1 = sec1->owner;
7389   bfd2 = sec2->owner;
7390
7391   /* Both sections have to be in ELF.  */
7392   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7393       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7394     return FALSE;
7395
7396   if (elf_section_type (sec1) != elf_section_type (sec2))
7397     return FALSE;
7398
7399   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7400   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7401   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7402     return FALSE;
7403
7404   bed1 = get_elf_backend_data (bfd1);
7405   bed2 = get_elf_backend_data (bfd2);
7406   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7407   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7408   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7409   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7410
7411   if (symcount1 == 0 || symcount2 == 0)
7412     return FALSE;
7413
7414   result = FALSE;
7415   isymbuf1 = NULL;
7416   isymbuf2 = NULL;
7417   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7418   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7419
7420   if (ssymbuf1 == NULL)
7421     {
7422       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7423                                        NULL, NULL, NULL);
7424       if (isymbuf1 == NULL)
7425         goto done;
7426
7427       if (!info->reduce_memory_overheads)
7428         elf_tdata (bfd1)->symbuf = ssymbuf1
7429           = elf_create_symbuf (symcount1, isymbuf1);
7430     }
7431
7432   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7433     {
7434       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7435                                        NULL, NULL, NULL);
7436       if (isymbuf2 == NULL)
7437         goto done;
7438
7439       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7440         elf_tdata (bfd2)->symbuf = ssymbuf2
7441           = elf_create_symbuf (symcount2, isymbuf2);
7442     }
7443
7444   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7445     {
7446       /* Optimized faster version.  */
7447       bfd_size_type lo, hi, mid;
7448       struct elf_symbol *symp;
7449       struct elf_symbuf_symbol *ssym, *ssymend;
7450
7451       lo = 0;
7452       hi = ssymbuf1->count;
7453       ssymbuf1++;
7454       count1 = 0;
7455       while (lo < hi)
7456         {
7457           mid = (lo + hi) / 2;
7458           if (shndx1 < ssymbuf1[mid].st_shndx)
7459             hi = mid;
7460           else if (shndx1 > ssymbuf1[mid].st_shndx)
7461             lo = mid + 1;
7462           else
7463             {
7464               count1 = ssymbuf1[mid].count;
7465               ssymbuf1 += mid;
7466               break;
7467             }
7468         }
7469
7470       lo = 0;
7471       hi = ssymbuf2->count;
7472       ssymbuf2++;
7473       count2 = 0;
7474       while (lo < hi)
7475         {
7476           mid = (lo + hi) / 2;
7477           if (shndx2 < ssymbuf2[mid].st_shndx)
7478             hi = mid;
7479           else if (shndx2 > ssymbuf2[mid].st_shndx)
7480             lo = mid + 1;
7481           else
7482             {
7483               count2 = ssymbuf2[mid].count;
7484               ssymbuf2 += mid;
7485               break;
7486             }
7487         }
7488
7489       if (count1 == 0 || count2 == 0 || count1 != count2)
7490         goto done;
7491
7492       symtable1
7493         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
7494       symtable2
7495         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
7496       if (symtable1 == NULL || symtable2 == NULL)
7497         goto done;
7498
7499       symp = symtable1;
7500       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7501            ssym < ssymend; ssym++, symp++)
7502         {
7503           symp->u.ssym = ssym;
7504           symp->name = bfd_elf_string_from_elf_section (bfd1,
7505                                                         hdr1->sh_link,
7506                                                         ssym->st_name);
7507         }
7508
7509       symp = symtable2;
7510       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7511            ssym < ssymend; ssym++, symp++)
7512         {
7513           symp->u.ssym = ssym;
7514           symp->name = bfd_elf_string_from_elf_section (bfd2,
7515                                                         hdr2->sh_link,
7516                                                         ssym->st_name);
7517         }
7518
7519       /* Sort symbol by name.  */
7520       qsort (symtable1, count1, sizeof (struct elf_symbol),
7521              elf_sym_name_compare);
7522       qsort (symtable2, count1, sizeof (struct elf_symbol),
7523              elf_sym_name_compare);
7524
7525       for (i = 0; i < count1; i++)
7526         /* Two symbols must have the same binding, type and name.  */
7527         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7528             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7529             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7530           goto done;
7531
7532       result = TRUE;
7533       goto done;
7534     }
7535
7536   symtable1 = (struct elf_symbol *)
7537       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7538   symtable2 = (struct elf_symbol *)
7539       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7540   if (symtable1 == NULL || symtable2 == NULL)
7541     goto done;
7542
7543   /* Count definitions in the section.  */
7544   count1 = 0;
7545   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7546     if (isym->st_shndx == shndx1)
7547       symtable1[count1++].u.isym = isym;
7548
7549   count2 = 0;
7550   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7551     if (isym->st_shndx == shndx2)
7552       symtable2[count2++].u.isym = isym;
7553
7554   if (count1 == 0 || count2 == 0 || count1 != count2)
7555     goto done;
7556
7557   for (i = 0; i < count1; i++)
7558     symtable1[i].name
7559       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7560                                          symtable1[i].u.isym->st_name);
7561
7562   for (i = 0; i < count2; i++)
7563     symtable2[i].name
7564       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7565                                          symtable2[i].u.isym->st_name);
7566
7567   /* Sort symbol by name.  */
7568   qsort (symtable1, count1, sizeof (struct elf_symbol),
7569          elf_sym_name_compare);
7570   qsort (symtable2, count1, sizeof (struct elf_symbol),
7571          elf_sym_name_compare);
7572
7573   for (i = 0; i < count1; i++)
7574     /* Two symbols must have the same binding, type and name.  */
7575     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7576         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7577         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7578       goto done;
7579
7580   result = TRUE;
7581
7582 done:
7583   if (symtable1)
7584     free (symtable1);
7585   if (symtable2)
7586     free (symtable2);
7587   if (isymbuf1)
7588     free (isymbuf1);
7589   if (isymbuf2)
7590     free (isymbuf2);
7591
7592   return result;
7593 }
7594
7595 /* Return TRUE if 2 section types are compatible.  */
7596
7597 bfd_boolean
7598 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7599                                  bfd *bbfd, const asection *bsec)
7600 {
7601   if (asec == NULL
7602       || bsec == NULL
7603       || abfd->xvec->flavour != bfd_target_elf_flavour
7604       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7605     return TRUE;
7606
7607   return elf_section_type (asec) == elf_section_type (bsec);
7608 }
7609 \f
7610 /* Final phase of ELF linker.  */
7611
7612 /* A structure we use to avoid passing large numbers of arguments.  */
7613
7614 struct elf_final_link_info
7615 {
7616   /* General link information.  */
7617   struct bfd_link_info *info;
7618   /* Output BFD.  */
7619   bfd *output_bfd;
7620   /* Symbol string table.  */
7621   struct elf_strtab_hash *symstrtab;
7622   /* .hash section.  */
7623   asection *hash_sec;
7624   /* symbol version section (.gnu.version).  */
7625   asection *symver_sec;
7626   /* Buffer large enough to hold contents of any section.  */
7627   bfd_byte *contents;
7628   /* Buffer large enough to hold external relocs of any section.  */
7629   void *external_relocs;
7630   /* Buffer large enough to hold internal relocs of any section.  */
7631   Elf_Internal_Rela *internal_relocs;
7632   /* Buffer large enough to hold external local symbols of any input
7633      BFD.  */
7634   bfd_byte *external_syms;
7635   /* And a buffer for symbol section indices.  */
7636   Elf_External_Sym_Shndx *locsym_shndx;
7637   /* Buffer large enough to hold internal local symbols of any input
7638      BFD.  */
7639   Elf_Internal_Sym *internal_syms;
7640   /* Array large enough to hold a symbol index for each local symbol
7641      of any input BFD.  */
7642   long *indices;
7643   /* Array large enough to hold a section pointer for each local
7644      symbol of any input BFD.  */
7645   asection **sections;
7646   /* Buffer for SHT_SYMTAB_SHNDX section.  */
7647   Elf_External_Sym_Shndx *symshndxbuf;
7648   /* Number of STT_FILE syms seen.  */
7649   size_t filesym_count;
7650 };
7651
7652 /* This struct is used to pass information to elf_link_output_extsym.  */
7653
7654 struct elf_outext_info
7655 {
7656   bfd_boolean failed;
7657   bfd_boolean localsyms;
7658   bfd_boolean file_sym_done;
7659   struct elf_final_link_info *flinfo;
7660 };
7661
7662
7663 /* Support for evaluating a complex relocation.
7664
7665    Complex relocations are generalized, self-describing relocations.  The
7666    implementation of them consists of two parts: complex symbols, and the
7667    relocations themselves.
7668
7669    The relocations are use a reserved elf-wide relocation type code (R_RELC
7670    external / BFD_RELOC_RELC internal) and an encoding of relocation field
7671    information (start bit, end bit, word width, etc) into the addend.  This
7672    information is extracted from CGEN-generated operand tables within gas.
7673
7674    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
7675    internal) representing prefix-notation expressions, including but not
7676    limited to those sorts of expressions normally encoded as addends in the
7677    addend field.  The symbol mangling format is:
7678
7679    <node> := <literal>
7680           |  <unary-operator> ':' <node>
7681           |  <binary-operator> ':' <node> ':' <node>
7682           ;
7683
7684    <literal> := 's' <digits=N> ':' <N character symbol name>
7685              |  'S' <digits=N> ':' <N character section name>
7686              |  '#' <hexdigits>
7687              ;
7688
7689    <binary-operator> := as in C
7690    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
7691
7692 static void
7693 set_symbol_value (bfd *bfd_with_globals,
7694                   Elf_Internal_Sym *isymbuf,
7695                   size_t locsymcount,
7696                   size_t symidx,
7697                   bfd_vma val)
7698 {
7699   struct elf_link_hash_entry **sym_hashes;
7700   struct elf_link_hash_entry *h;
7701   size_t extsymoff = locsymcount;
7702
7703   if (symidx < locsymcount)
7704     {
7705       Elf_Internal_Sym *sym;
7706
7707       sym = isymbuf + symidx;
7708       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
7709         {
7710           /* It is a local symbol: move it to the
7711              "absolute" section and give it a value.  */
7712           sym->st_shndx = SHN_ABS;
7713           sym->st_value = val;
7714           return;
7715         }
7716       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
7717       extsymoff = 0;
7718     }
7719
7720   /* It is a global symbol: set its link type
7721      to "defined" and give it a value.  */
7722
7723   sym_hashes = elf_sym_hashes (bfd_with_globals);
7724   h = sym_hashes [symidx - extsymoff];
7725   while (h->root.type == bfd_link_hash_indirect
7726          || h->root.type == bfd_link_hash_warning)
7727     h = (struct elf_link_hash_entry *) h->root.u.i.link;
7728   h->root.type = bfd_link_hash_defined;
7729   h->root.u.def.value = val;
7730   h->root.u.def.section = bfd_abs_section_ptr;
7731 }
7732
7733 static bfd_boolean
7734 resolve_symbol (const char *name,
7735                 bfd *input_bfd,
7736                 struct elf_final_link_info *flinfo,
7737                 bfd_vma *result,
7738                 Elf_Internal_Sym *isymbuf,
7739                 size_t locsymcount)
7740 {
7741   Elf_Internal_Sym *sym;
7742   struct bfd_link_hash_entry *global_entry;
7743   const char *candidate = NULL;
7744   Elf_Internal_Shdr *symtab_hdr;
7745   size_t i;
7746
7747   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
7748
7749   for (i = 0; i < locsymcount; ++ i)
7750     {
7751       sym = isymbuf + i;
7752
7753       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
7754         continue;
7755
7756       candidate = bfd_elf_string_from_elf_section (input_bfd,
7757                                                    symtab_hdr->sh_link,
7758                                                    sym->st_name);
7759 #ifdef DEBUG
7760       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
7761               name, candidate, (unsigned long) sym->st_value);
7762 #endif
7763       if (candidate && strcmp (candidate, name) == 0)
7764         {
7765           asection *sec = flinfo->sections [i];
7766
7767           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
7768           *result += sec->output_offset + sec->output_section->vma;
7769 #ifdef DEBUG
7770           printf ("Found symbol with value %8.8lx\n",
7771                   (unsigned long) *result);
7772 #endif
7773           return TRUE;
7774         }
7775     }
7776
7777   /* Hmm, haven't found it yet. perhaps it is a global.  */
7778   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
7779                                        FALSE, FALSE, TRUE);
7780   if (!global_entry)
7781     return FALSE;
7782
7783   if (global_entry->type == bfd_link_hash_defined
7784       || global_entry->type == bfd_link_hash_defweak)
7785     {
7786       *result = (global_entry->u.def.value
7787                  + global_entry->u.def.section->output_section->vma
7788                  + global_entry->u.def.section->output_offset);
7789 #ifdef DEBUG
7790       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
7791               global_entry->root.string, (unsigned long) *result);
7792 #endif
7793       return TRUE;
7794     }
7795
7796   return FALSE;
7797 }
7798
7799 /* Looks up NAME in SECTIONS.  If found sets RESULT to NAME's address (in
7800    bytes) and returns TRUE, otherwise returns FALSE.  Accepts pseudo-section
7801    names like "foo.end" which is the end address of section "foo".  */
7802    
7803 static bfd_boolean
7804 resolve_section (const char *name,
7805                  asection *sections,
7806                  bfd_vma *result,
7807                  bfd * abfd)
7808 {
7809   asection *curr;
7810   unsigned int len;
7811
7812   for (curr = sections; curr; curr = curr->next)
7813     if (strcmp (curr->name, name) == 0)
7814       {
7815         *result = curr->vma;
7816         return TRUE;
7817       }
7818
7819   /* Hmm. still haven't found it. try pseudo-section names.  */
7820   /* FIXME: This could be coded more efficiently...  */
7821   for (curr = sections; curr; curr = curr->next)
7822     {
7823       len = strlen (curr->name);
7824       if (len > strlen (name))
7825         continue;
7826
7827       if (strncmp (curr->name, name, len) == 0)
7828         {
7829           if (strncmp (".end", name + len, 4) == 0)
7830             {
7831               *result = curr->vma + curr->size / bfd_octets_per_byte (abfd);
7832               return TRUE;
7833             }
7834
7835           /* Insert more pseudo-section names here, if you like.  */
7836         }
7837     }
7838
7839   return FALSE;
7840 }
7841
7842 static void
7843 undefined_reference (const char *reftype, const char *name)
7844 {
7845   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
7846                       reftype, name);
7847 }
7848
7849 static bfd_boolean
7850 eval_symbol (bfd_vma *result,
7851              const char **symp,
7852              bfd *input_bfd,
7853              struct elf_final_link_info *flinfo,
7854              bfd_vma dot,
7855              Elf_Internal_Sym *isymbuf,
7856              size_t locsymcount,
7857              int signed_p)
7858 {
7859   size_t len;
7860   size_t symlen;
7861   bfd_vma a;
7862   bfd_vma b;
7863   char symbuf[4096];
7864   const char *sym = *symp;
7865   const char *symend;
7866   bfd_boolean symbol_is_section = FALSE;
7867
7868   len = strlen (sym);
7869   symend = sym + len;
7870
7871   if (len < 1 || len > sizeof (symbuf))
7872     {
7873       bfd_set_error (bfd_error_invalid_operation);
7874       return FALSE;
7875     }
7876
7877   switch (* sym)
7878     {
7879     case '.':
7880       *result = dot;
7881       *symp = sym + 1;
7882       return TRUE;
7883
7884     case '#':
7885       ++sym;
7886       *result = strtoul (sym, (char **) symp, 16);
7887       return TRUE;
7888
7889     case 'S':
7890       symbol_is_section = TRUE;
7891     case 's':
7892       ++sym;
7893       symlen = strtol (sym, (char **) symp, 10);
7894       sym = *symp + 1; /* Skip the trailing ':'.  */
7895
7896       if (symend < sym || symlen + 1 > sizeof (symbuf))
7897         {
7898           bfd_set_error (bfd_error_invalid_operation);
7899           return FALSE;
7900         }
7901
7902       memcpy (symbuf, sym, symlen);
7903       symbuf[symlen] = '\0';
7904       *symp = sym + symlen;
7905
7906       /* Is it always possible, with complex symbols, that gas "mis-guessed"
7907          the symbol as a section, or vice-versa. so we're pretty liberal in our
7908          interpretation here; section means "try section first", not "must be a
7909          section", and likewise with symbol.  */
7910
7911       if (symbol_is_section)
7912         {
7913           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result, input_bfd)
7914               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
7915                                   isymbuf, locsymcount))
7916             {
7917               undefined_reference ("section", symbuf);
7918               return FALSE;
7919             }
7920         }
7921       else
7922         {
7923           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
7924                                isymbuf, locsymcount)
7925               && !resolve_section (symbuf, flinfo->output_bfd->sections,
7926                                    result, input_bfd))
7927             {
7928               undefined_reference ("symbol", symbuf);
7929               return FALSE;
7930             }
7931         }
7932
7933       return TRUE;
7934
7935       /* All that remains are operators.  */
7936
7937 #define UNARY_OP(op)                                            \
7938   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7939     {                                                           \
7940       sym += strlen (#op);                                      \
7941       if (*sym == ':')                                          \
7942         ++sym;                                                  \
7943       *symp = sym;                                              \
7944       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
7945                         isymbuf, locsymcount, signed_p))        \
7946         return FALSE;                                           \
7947       if (signed_p)                                             \
7948         *result = op ((bfd_signed_vma) a);                      \
7949       else                                                      \
7950         *result = op a;                                         \
7951       return TRUE;                                              \
7952     }
7953
7954 #define BINARY_OP(op)                                           \
7955   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
7956     {                                                           \
7957       sym += strlen (#op);                                      \
7958       if (*sym == ':')                                          \
7959         ++sym;                                                  \
7960       *symp = sym;                                              \
7961       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
7962                         isymbuf, locsymcount, signed_p))        \
7963         return FALSE;                                           \
7964       ++*symp;                                                  \
7965       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
7966                         isymbuf, locsymcount, signed_p))        \
7967         return FALSE;                                           \
7968       if (signed_p)                                             \
7969         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
7970       else                                                      \
7971         *result = a op b;                                       \
7972       return TRUE;                                              \
7973     }
7974
7975     default:
7976       UNARY_OP  (0-);
7977       BINARY_OP (<<);
7978       BINARY_OP (>>);
7979       BINARY_OP (==);
7980       BINARY_OP (!=);
7981       BINARY_OP (<=);
7982       BINARY_OP (>=);
7983       BINARY_OP (&&);
7984       BINARY_OP (||);
7985       UNARY_OP  (~);
7986       UNARY_OP  (!);
7987       BINARY_OP (*);
7988       BINARY_OP (/);
7989       BINARY_OP (%);
7990       BINARY_OP (^);
7991       BINARY_OP (|);
7992       BINARY_OP (&);
7993       BINARY_OP (+);
7994       BINARY_OP (-);
7995       BINARY_OP (<);
7996       BINARY_OP (>);
7997 #undef UNARY_OP
7998 #undef BINARY_OP
7999       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
8000       bfd_set_error (bfd_error_invalid_operation);
8001       return FALSE;
8002     }
8003 }
8004
8005 static void
8006 put_value (bfd_vma size,
8007            unsigned long chunksz,
8008            bfd *input_bfd,
8009            bfd_vma x,
8010            bfd_byte *location)
8011 {
8012   location += (size - chunksz);
8013
8014   for (; size; size -= chunksz, location -= chunksz)
8015     {
8016       switch (chunksz)
8017         {
8018         case 1:
8019           bfd_put_8 (input_bfd, x, location);
8020           x >>= 8;
8021           break;
8022         case 2:
8023           bfd_put_16 (input_bfd, x, location);
8024           x >>= 16;
8025           break;
8026         case 4:
8027           bfd_put_32 (input_bfd, x, location);
8028           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
8029           x >>= 16;
8030           x >>= 16;
8031           break;
8032 #ifdef BFD64
8033         case 8:
8034           bfd_put_64 (input_bfd, x, location);
8035           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
8036           x >>= 32;
8037           x >>= 32;
8038           break;
8039 #endif
8040         default:
8041           abort ();
8042           break;
8043         }
8044     }
8045 }
8046
8047 static bfd_vma
8048 get_value (bfd_vma size,
8049            unsigned long chunksz,
8050            bfd *input_bfd,
8051            bfd_byte *location)
8052 {
8053   int shift;
8054   bfd_vma x = 0;
8055
8056   /* Sanity checks.  */
8057   BFD_ASSERT (chunksz <= sizeof (x)
8058               && size >= chunksz
8059               && chunksz != 0
8060               && (size % chunksz) == 0
8061               && input_bfd != NULL
8062               && location != NULL);
8063
8064   if (chunksz == sizeof (x))
8065     {
8066       BFD_ASSERT (size == chunksz);
8067
8068       /* Make sure that we do not perform an undefined shift operation.
8069          We know that size == chunksz so there will only be one iteration
8070          of the loop below.  */
8071       shift = 0;
8072     }
8073   else
8074     shift = 8 * chunksz;
8075
8076   for (; size; size -= chunksz, location += chunksz)
8077     {
8078       switch (chunksz)
8079         {
8080         case 1:
8081           x = (x << shift) | bfd_get_8 (input_bfd, location);
8082           break;
8083         case 2:
8084           x = (x << shift) | bfd_get_16 (input_bfd, location);
8085           break;
8086         case 4:
8087           x = (x << shift) | bfd_get_32 (input_bfd, location);
8088           break;
8089 #ifdef BFD64
8090         case 8:
8091           x = (x << shift) | bfd_get_64 (input_bfd, location);
8092           break;
8093 #endif
8094         default:
8095           abort ();
8096         }
8097     }
8098   return x;
8099 }
8100
8101 static void
8102 decode_complex_addend (unsigned long *start,   /* in bits */
8103                        unsigned long *oplen,   /* in bits */
8104                        unsigned long *len,     /* in bits */
8105                        unsigned long *wordsz,  /* in bytes */
8106                        unsigned long *chunksz, /* in bytes */
8107                        unsigned long *lsb0_p,
8108                        unsigned long *signed_p,
8109                        unsigned long *trunc_p,
8110                        unsigned long encoded)
8111 {
8112   * start     =  encoded        & 0x3F;
8113   * len       = (encoded >>  6) & 0x3F;
8114   * oplen     = (encoded >> 12) & 0x3F;
8115   * wordsz    = (encoded >> 18) & 0xF;
8116   * chunksz   = (encoded >> 22) & 0xF;
8117   * lsb0_p    = (encoded >> 27) & 1;
8118   * signed_p  = (encoded >> 28) & 1;
8119   * trunc_p   = (encoded >> 29) & 1;
8120 }
8121
8122 bfd_reloc_status_type
8123 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8124                                     asection *input_section ATTRIBUTE_UNUSED,
8125                                     bfd_byte *contents,
8126                                     Elf_Internal_Rela *rel,
8127                                     bfd_vma relocation)
8128 {
8129   bfd_vma shift, x, mask;
8130   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8131   bfd_reloc_status_type r;
8132
8133   /*  Perform this reloc, since it is complex.
8134       (this is not to say that it necessarily refers to a complex
8135       symbol; merely that it is a self-describing CGEN based reloc.
8136       i.e. the addend has the complete reloc information (bit start, end,
8137       word size, etc) encoded within it.).  */
8138
8139   decode_complex_addend (&start, &oplen, &len, &wordsz,
8140                          &chunksz, &lsb0_p, &signed_p,
8141                          &trunc_p, rel->r_addend);
8142
8143   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8144
8145   if (lsb0_p)
8146     shift = (start + 1) - len;
8147   else
8148     shift = (8 * wordsz) - (start + len);
8149
8150   x = get_value (wordsz, chunksz, input_bfd,
8151                  contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8152
8153 #ifdef DEBUG
8154   printf ("Doing complex reloc: "
8155           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8156           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8157           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8158           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8159           oplen, (unsigned long) x, (unsigned long) mask,
8160           (unsigned long) relocation);
8161 #endif
8162
8163   r = bfd_reloc_ok;
8164   if (! trunc_p)
8165     /* Now do an overflow check.  */
8166     r = bfd_check_overflow ((signed_p
8167                              ? complain_overflow_signed
8168                              : complain_overflow_unsigned),
8169                             len, 0, (8 * wordsz),
8170                             relocation);
8171
8172   /* Do the deed.  */
8173   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8174
8175 #ifdef DEBUG
8176   printf ("           relocation: %8.8lx\n"
8177           "         shifted mask: %8.8lx\n"
8178           " shifted/masked reloc: %8.8lx\n"
8179           "               result: %8.8lx\n",
8180           (unsigned long) relocation, (unsigned long) (mask << shift),
8181           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8182 #endif
8183   put_value (wordsz, chunksz, input_bfd, x,
8184              contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8185   return r;
8186 }
8187
8188 /* Functions to read r_offset from external (target order) reloc
8189    entry.  Faster than bfd_getl32 et al, because we let the compiler
8190    know the value is aligned.  */
8191
8192 static bfd_vma
8193 ext32l_r_offset (const void *p)
8194 {
8195   union aligned32
8196   {
8197     uint32_t v;
8198     unsigned char c[4];
8199   };
8200   const union aligned32 *a
8201     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8202
8203   uint32_t aval = (  (uint32_t) a->c[0]
8204                    | (uint32_t) a->c[1] << 8
8205                    | (uint32_t) a->c[2] << 16
8206                    | (uint32_t) a->c[3] << 24);
8207   return aval;
8208 }
8209
8210 static bfd_vma
8211 ext32b_r_offset (const void *p)
8212 {
8213   union aligned32
8214   {
8215     uint32_t v;
8216     unsigned char c[4];
8217   };
8218   const union aligned32 *a
8219     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8220
8221   uint32_t aval = (  (uint32_t) a->c[0] << 24
8222                    | (uint32_t) a->c[1] << 16
8223                    | (uint32_t) a->c[2] << 8
8224                    | (uint32_t) a->c[3]);
8225   return aval;
8226 }
8227
8228 #ifdef BFD_HOST_64_BIT
8229 static bfd_vma
8230 ext64l_r_offset (const void *p)
8231 {
8232   union aligned64
8233   {
8234     uint64_t v;
8235     unsigned char c[8];
8236   };
8237   const union aligned64 *a
8238     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8239
8240   uint64_t aval = (  (uint64_t) a->c[0]
8241                    | (uint64_t) a->c[1] << 8
8242                    | (uint64_t) a->c[2] << 16
8243                    | (uint64_t) a->c[3] << 24
8244                    | (uint64_t) a->c[4] << 32
8245                    | (uint64_t) a->c[5] << 40
8246                    | (uint64_t) a->c[6] << 48
8247                    | (uint64_t) a->c[7] << 56);
8248   return aval;
8249 }
8250
8251 static bfd_vma
8252 ext64b_r_offset (const void *p)
8253 {
8254   union aligned64
8255   {
8256     uint64_t v;
8257     unsigned char c[8];
8258   };
8259   const union aligned64 *a
8260     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8261
8262   uint64_t aval = (  (uint64_t) a->c[0] << 56
8263                    | (uint64_t) a->c[1] << 48
8264                    | (uint64_t) a->c[2] << 40
8265                    | (uint64_t) a->c[3] << 32
8266                    | (uint64_t) a->c[4] << 24
8267                    | (uint64_t) a->c[5] << 16
8268                    | (uint64_t) a->c[6] << 8
8269                    | (uint64_t) a->c[7]);
8270   return aval;
8271 }
8272 #endif
8273
8274 /* When performing a relocatable link, the input relocations are
8275    preserved.  But, if they reference global symbols, the indices
8276    referenced must be updated.  Update all the relocations found in
8277    RELDATA.  */
8278
8279 static bfd_boolean
8280 elf_link_adjust_relocs (bfd *abfd,
8281                         struct bfd_elf_section_reloc_data *reldata,
8282                         bfd_boolean sort)
8283 {
8284   unsigned int i;
8285   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8286   bfd_byte *erela;
8287   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8288   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8289   bfd_vma r_type_mask;
8290   int r_sym_shift;
8291   unsigned int count = reldata->count;
8292   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8293
8294   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8295     {
8296       swap_in = bed->s->swap_reloc_in;
8297       swap_out = bed->s->swap_reloc_out;
8298     }
8299   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8300     {
8301       swap_in = bed->s->swap_reloca_in;
8302       swap_out = bed->s->swap_reloca_out;
8303     }
8304   else
8305     abort ();
8306
8307   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8308     abort ();
8309
8310   if (bed->s->arch_size == 32)
8311     {
8312       r_type_mask = 0xff;
8313       r_sym_shift = 8;
8314     }
8315   else
8316     {
8317       r_type_mask = 0xffffffff;
8318       r_sym_shift = 32;
8319     }
8320
8321   erela = reldata->hdr->contents;
8322   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8323     {
8324       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8325       unsigned int j;
8326
8327       if (*rel_hash == NULL)
8328         continue;
8329
8330       BFD_ASSERT ((*rel_hash)->indx >= 0);
8331
8332       (*swap_in) (abfd, erela, irela);
8333       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8334         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8335                            | (irela[j].r_info & r_type_mask));
8336       (*swap_out) (abfd, irela, erela);
8337     }
8338
8339   if (sort && count != 0)
8340     {
8341       bfd_vma (*ext_r_off) (const void *);
8342       bfd_vma r_off;
8343       size_t elt_size;
8344       bfd_byte *base, *end, *p, *loc;
8345       bfd_byte *buf = NULL;
8346
8347       if (bed->s->arch_size == 32)
8348         {
8349           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8350             ext_r_off = ext32l_r_offset;
8351           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8352             ext_r_off = ext32b_r_offset;
8353           else
8354             abort ();
8355         }
8356       else
8357         {
8358 #ifdef BFD_HOST_64_BIT
8359           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8360             ext_r_off = ext64l_r_offset;
8361           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8362             ext_r_off = ext64b_r_offset;
8363           else
8364 #endif
8365             abort ();
8366         }
8367
8368       /*  Must use a stable sort here.  A modified insertion sort,
8369           since the relocs are mostly sorted already.  */
8370       elt_size = reldata->hdr->sh_entsize;
8371       base = reldata->hdr->contents;
8372       end = base + count * elt_size;
8373       if (elt_size > sizeof (Elf64_External_Rela))
8374         abort ();
8375
8376       /* Ensure the first element is lowest.  This acts as a sentinel,
8377          speeding the main loop below.  */
8378       r_off = (*ext_r_off) (base);
8379       for (p = loc = base; (p += elt_size) < end; )
8380         {
8381           bfd_vma r_off2 = (*ext_r_off) (p);
8382           if (r_off > r_off2)
8383             {
8384               r_off = r_off2;
8385               loc = p;
8386             }
8387         }
8388       if (loc != base)
8389         {
8390           /* Don't just swap *base and *loc as that changes the order
8391              of the original base[0] and base[1] if they happen to
8392              have the same r_offset.  */
8393           bfd_byte onebuf[sizeof (Elf64_External_Rela)];
8394           memcpy (onebuf, loc, elt_size);
8395           memmove (base + elt_size, base, loc - base);
8396           memcpy (base, onebuf, elt_size);
8397         }
8398
8399       for (p = base + elt_size; (p += elt_size) < end; )
8400         {
8401           /* base to p is sorted, *p is next to insert.  */
8402           r_off = (*ext_r_off) (p);
8403           /* Search the sorted region for location to insert.  */
8404           loc = p - elt_size;
8405           while (r_off < (*ext_r_off) (loc))
8406             loc -= elt_size;
8407           loc += elt_size;
8408           if (loc != p)
8409             {
8410               /* Chances are there is a run of relocs to insert here,
8411                  from one of more input files.  Files are not always
8412                  linked in order due to the way elf_link_input_bfd is
8413                  called.  See pr17666.  */
8414               size_t sortlen = p - loc;
8415               bfd_vma r_off2 = (*ext_r_off) (loc);
8416               size_t runlen = elt_size;
8417               size_t buf_size = 96 * 1024;
8418               while (p + runlen < end
8419                      && (sortlen <= buf_size
8420                          || runlen + elt_size <= buf_size)
8421                      && r_off2 > (*ext_r_off) (p + runlen))
8422                 runlen += elt_size;
8423               if (buf == NULL)
8424                 {
8425                   buf = bfd_malloc (buf_size);
8426                   if (buf == NULL)
8427                     return FALSE;
8428                 }
8429               if (runlen < sortlen)
8430                 {
8431                   memcpy (buf, p, runlen);
8432                   memmove (loc + runlen, loc, sortlen);
8433                   memcpy (loc, buf, runlen);
8434                 }
8435               else
8436                 {
8437                   memcpy (buf, loc, sortlen);
8438                   memmove (loc, p, runlen);
8439                   memcpy (loc + runlen, buf, sortlen);
8440                 }
8441               p += runlen - elt_size;
8442             }
8443         }
8444       /* Hashes are no longer valid.  */
8445       free (reldata->hashes);
8446       reldata->hashes = NULL;
8447       free (buf);
8448     }
8449   return TRUE;
8450 }
8451
8452 struct elf_link_sort_rela
8453 {
8454   union {
8455     bfd_vma offset;
8456     bfd_vma sym_mask;
8457   } u;
8458   enum elf_reloc_type_class type;
8459   /* We use this as an array of size int_rels_per_ext_rel.  */
8460   Elf_Internal_Rela rela[1];
8461 };
8462
8463 static int
8464 elf_link_sort_cmp1 (const void *A, const void *B)
8465 {
8466   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8467   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8468   int relativea, relativeb;
8469
8470   relativea = a->type == reloc_class_relative;
8471   relativeb = b->type == reloc_class_relative;
8472
8473   if (relativea < relativeb)
8474     return 1;
8475   if (relativea > relativeb)
8476     return -1;
8477   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8478     return -1;
8479   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8480     return 1;
8481   if (a->rela->r_offset < b->rela->r_offset)
8482     return -1;
8483   if (a->rela->r_offset > b->rela->r_offset)
8484     return 1;
8485   return 0;
8486 }
8487
8488 static int
8489 elf_link_sort_cmp2 (const void *A, const void *B)
8490 {
8491   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8492   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8493
8494   if (a->type < b->type)
8495     return -1;
8496   if (a->type > b->type)
8497     return 1;
8498   if (a->u.offset < b->u.offset)
8499     return -1;
8500   if (a->u.offset > b->u.offset)
8501     return 1;
8502   if (a->rela->r_offset < b->rela->r_offset)
8503     return -1;
8504   if (a->rela->r_offset > b->rela->r_offset)
8505     return 1;
8506   return 0;
8507 }
8508
8509 static size_t
8510 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8511 {
8512   asection *dynamic_relocs;
8513   asection *rela_dyn;
8514   asection *rel_dyn;
8515   bfd_size_type count, size;
8516   size_t i, ret, sort_elt, ext_size;
8517   bfd_byte *sort, *s_non_relative, *p;
8518   struct elf_link_sort_rela *sq;
8519   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8520   int i2e = bed->s->int_rels_per_ext_rel;
8521   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8522   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8523   struct bfd_link_order *lo;
8524   bfd_vma r_sym_mask;
8525   bfd_boolean use_rela;
8526
8527   /* Find a dynamic reloc section.  */
8528   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8529   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8530   if (rela_dyn != NULL && rela_dyn->size > 0
8531       && rel_dyn != NULL && rel_dyn->size > 0)
8532     {
8533       bfd_boolean use_rela_initialised = FALSE;
8534
8535       /* This is just here to stop gcc from complaining.
8536          It's initialization checking code is not perfect.  */
8537       use_rela = TRUE;
8538
8539       /* Both sections are present.  Examine the sizes
8540          of the indirect sections to help us choose.  */
8541       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8542         if (lo->type == bfd_indirect_link_order)
8543           {
8544             asection *o = lo->u.indirect.section;
8545
8546             if ((o->size % bed->s->sizeof_rela) == 0)
8547               {
8548                 if ((o->size % bed->s->sizeof_rel) == 0)
8549                   /* Section size is divisible by both rel and rela sizes.
8550                      It is of no help to us.  */
8551                   ;
8552                 else
8553                   {
8554                     /* Section size is only divisible by rela.  */
8555                     if (use_rela_initialised && (use_rela == FALSE))
8556                       {
8557                         _bfd_error_handler
8558                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8559                         bfd_set_error (bfd_error_invalid_operation);
8560                         return 0;
8561                       }
8562                     else
8563                       {
8564                         use_rela = TRUE;
8565                         use_rela_initialised = TRUE;
8566                       }
8567                   }
8568               }
8569             else if ((o->size % bed->s->sizeof_rel) == 0)
8570               {
8571                 /* Section size is only divisible by rel.  */
8572                 if (use_rela_initialised && (use_rela == TRUE))
8573                   {
8574                     _bfd_error_handler
8575                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8576                     bfd_set_error (bfd_error_invalid_operation);
8577                     return 0;
8578                   }
8579                 else
8580                   {
8581                     use_rela = FALSE;
8582                     use_rela_initialised = TRUE;
8583                   }
8584               }
8585             else
8586               {
8587                 /* The section size is not divisible by either - something is wrong.  */
8588                 _bfd_error_handler
8589                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8590                 bfd_set_error (bfd_error_invalid_operation);
8591                 return 0;
8592               }
8593           }
8594
8595       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8596         if (lo->type == bfd_indirect_link_order)
8597           {
8598             asection *o = lo->u.indirect.section;
8599
8600             if ((o->size % bed->s->sizeof_rela) == 0)
8601               {
8602                 if ((o->size % bed->s->sizeof_rel) == 0)
8603                   /* Section size is divisible by both rel and rela sizes.
8604                      It is of no help to us.  */
8605                   ;
8606                 else
8607                   {
8608                     /* Section size is only divisible by rela.  */
8609                     if (use_rela_initialised && (use_rela == FALSE))
8610                       {
8611                         _bfd_error_handler
8612                           (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8613                         bfd_set_error (bfd_error_invalid_operation);
8614                         return 0;
8615                       }
8616                     else
8617                       {
8618                         use_rela = TRUE;
8619                         use_rela_initialised = TRUE;
8620                       }
8621                   }
8622               }
8623             else if ((o->size % bed->s->sizeof_rel) == 0)
8624               {
8625                 /* Section size is only divisible by rel.  */
8626                 if (use_rela_initialised && (use_rela == TRUE))
8627                   {
8628                     _bfd_error_handler
8629                       (_("%B: Unable to sort relocs - they are in more than one size"), abfd);
8630                     bfd_set_error (bfd_error_invalid_operation);
8631                     return 0;
8632                   }
8633                 else
8634                   {
8635                     use_rela = FALSE;
8636                     use_rela_initialised = TRUE;
8637                   }
8638               }
8639             else
8640               {
8641                 /* The section size is not divisible by either - something is wrong.  */
8642                 _bfd_error_handler
8643                   (_("%B: Unable to sort relocs - they are of an unknown size"), abfd);
8644                 bfd_set_error (bfd_error_invalid_operation);
8645                 return 0;
8646               }
8647           }
8648
8649       if (! use_rela_initialised)
8650         /* Make a guess.  */
8651         use_rela = TRUE;
8652     }
8653   else if (rela_dyn != NULL && rela_dyn->size > 0)
8654     use_rela = TRUE;
8655   else if (rel_dyn != NULL && rel_dyn->size > 0)
8656     use_rela = FALSE;
8657   else
8658     return 0;
8659
8660   if (use_rela)
8661     {
8662       dynamic_relocs = rela_dyn;
8663       ext_size = bed->s->sizeof_rela;
8664       swap_in = bed->s->swap_reloca_in;
8665       swap_out = bed->s->swap_reloca_out;
8666     }
8667   else
8668     {
8669       dynamic_relocs = rel_dyn;
8670       ext_size = bed->s->sizeof_rel;
8671       swap_in = bed->s->swap_reloc_in;
8672       swap_out = bed->s->swap_reloc_out;
8673     }
8674
8675   size = 0;
8676   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8677     if (lo->type == bfd_indirect_link_order)
8678       size += lo->u.indirect.section->size;
8679
8680   if (size != dynamic_relocs->size)
8681     return 0;
8682
8683   sort_elt = (sizeof (struct elf_link_sort_rela)
8684               + (i2e - 1) * sizeof (Elf_Internal_Rela));
8685
8686   count = dynamic_relocs->size / ext_size;
8687   if (count == 0)
8688     return 0;
8689   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
8690
8691   if (sort == NULL)
8692     {
8693       (*info->callbacks->warning)
8694         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
8695       return 0;
8696     }
8697
8698   if (bed->s->arch_size == 32)
8699     r_sym_mask = ~(bfd_vma) 0xff;
8700   else
8701     r_sym_mask = ~(bfd_vma) 0xffffffff;
8702
8703   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8704     if (lo->type == bfd_indirect_link_order)
8705       {
8706         bfd_byte *erel, *erelend;
8707         asection *o = lo->u.indirect.section;
8708
8709         if (o->contents == NULL && o->size != 0)
8710           {
8711             /* This is a reloc section that is being handled as a normal
8712                section.  See bfd_section_from_shdr.  We can't combine
8713                relocs in this case.  */
8714             free (sort);
8715             return 0;
8716           }
8717         erel = o->contents;
8718         erelend = o->contents + o->size;
8719         /* FIXME: octets_per_byte.  */
8720         p = sort + o->output_offset / ext_size * sort_elt;
8721
8722         while (erel < erelend)
8723           {
8724             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8725
8726             (*swap_in) (abfd, erel, s->rela);
8727             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
8728             s->u.sym_mask = r_sym_mask;
8729             p += sort_elt;
8730             erel += ext_size;
8731           }
8732       }
8733
8734   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
8735
8736   for (i = 0, p = sort; i < count; i++, p += sort_elt)
8737     {
8738       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8739       if (s->type != reloc_class_relative)
8740         break;
8741     }
8742   ret = i;
8743   s_non_relative = p;
8744
8745   sq = (struct elf_link_sort_rela *) s_non_relative;
8746   for (; i < count; i++, p += sort_elt)
8747     {
8748       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
8749       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
8750         sq = sp;
8751       sp->u.offset = sq->rela->r_offset;
8752     }
8753
8754   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
8755
8756   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8757     if (lo->type == bfd_indirect_link_order)
8758       {
8759         bfd_byte *erel, *erelend;
8760         asection *o = lo->u.indirect.section;
8761
8762         erel = o->contents;
8763         erelend = o->contents + o->size;
8764         /* FIXME: octets_per_byte.  */
8765         p = sort + o->output_offset / ext_size * sort_elt;
8766         while (erel < erelend)
8767           {
8768             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8769             (*swap_out) (abfd, s->rela, erel);
8770             p += sort_elt;
8771             erel += ext_size;
8772           }
8773       }
8774
8775   free (sort);
8776   *psec = dynamic_relocs;
8777   return ret;
8778 }
8779
8780 /* Add a symbol to the output symbol string table.  */
8781
8782 static int
8783 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
8784                            const char *name,
8785                            Elf_Internal_Sym *elfsym,
8786                            asection *input_sec,
8787                            struct elf_link_hash_entry *h)
8788 {
8789   int (*output_symbol_hook)
8790     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
8791      struct elf_link_hash_entry *);
8792   struct elf_link_hash_table *hash_table;
8793   const struct elf_backend_data *bed;
8794   bfd_size_type strtabsize;
8795
8796   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
8797
8798   bed = get_elf_backend_data (flinfo->output_bfd);
8799   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
8800   if (output_symbol_hook != NULL)
8801     {
8802       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
8803       if (ret != 1)
8804         return ret;
8805     }
8806
8807   if (name == NULL
8808       || *name == '\0'
8809       || (input_sec->flags & SEC_EXCLUDE))
8810     elfsym->st_name = (unsigned long) -1;
8811   else
8812     {
8813       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
8814          to get the final offset for st_name.  */
8815       elfsym->st_name
8816         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
8817                                                name, FALSE);
8818       if (elfsym->st_name == (unsigned long) -1)
8819         return 0;
8820     }
8821
8822   hash_table = elf_hash_table (flinfo->info);
8823   strtabsize = hash_table->strtabsize;
8824   if (strtabsize <= hash_table->strtabcount)
8825     {
8826       strtabsize += strtabsize;
8827       hash_table->strtabsize = strtabsize;
8828       strtabsize *= sizeof (*hash_table->strtab);
8829       hash_table->strtab
8830         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
8831                                                  strtabsize);
8832       if (hash_table->strtab == NULL)
8833         return 0;
8834     }
8835   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
8836   hash_table->strtab[hash_table->strtabcount].dest_index
8837     = hash_table->strtabcount;
8838   hash_table->strtab[hash_table->strtabcount].destshndx_index
8839     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
8840
8841   bfd_get_symcount (flinfo->output_bfd) += 1;
8842   hash_table->strtabcount += 1;
8843
8844   return 1;
8845 }
8846
8847 /* Swap symbols out to the symbol table and flush the output symbols to
8848    the file.  */
8849
8850 static bfd_boolean
8851 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
8852 {
8853   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
8854   bfd_size_type amt, i;
8855   const struct elf_backend_data *bed;
8856   bfd_byte *symbuf;
8857   Elf_Internal_Shdr *hdr;
8858   file_ptr pos;
8859   bfd_boolean ret;
8860
8861   if (!hash_table->strtabcount)
8862     return TRUE;
8863
8864   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
8865
8866   bed = get_elf_backend_data (flinfo->output_bfd);
8867
8868   amt = bed->s->sizeof_sym * hash_table->strtabcount;
8869   symbuf = (bfd_byte *) bfd_malloc (amt);
8870   if (symbuf == NULL)
8871     return FALSE;
8872
8873   if (flinfo->symshndxbuf)
8874     {
8875       amt = (sizeof (Elf_External_Sym_Shndx)
8876              * (bfd_get_symcount (flinfo->output_bfd)));
8877       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
8878       if (flinfo->symshndxbuf == NULL)
8879         {
8880           free (symbuf);
8881           return FALSE;
8882         }
8883     }
8884
8885   for (i = 0; i < hash_table->strtabcount; i++)
8886     {
8887       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
8888       if (elfsym->sym.st_name == (unsigned long) -1)
8889         elfsym->sym.st_name = 0;
8890       else
8891         elfsym->sym.st_name
8892           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
8893                                                     elfsym->sym.st_name);
8894       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
8895                                ((bfd_byte *) symbuf
8896                                 + (elfsym->dest_index
8897                                    * bed->s->sizeof_sym)),
8898                                (flinfo->symshndxbuf
8899                                 + elfsym->destshndx_index));
8900     }
8901
8902   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
8903   pos = hdr->sh_offset + hdr->sh_size;
8904   amt = hash_table->strtabcount * bed->s->sizeof_sym;
8905   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
8906       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
8907     {
8908       hdr->sh_size += amt;
8909       ret = TRUE;
8910     }
8911   else
8912     ret = FALSE;
8913
8914   free (symbuf);
8915
8916   free (hash_table->strtab);
8917   hash_table->strtab = NULL;
8918
8919   return ret;
8920 }
8921
8922 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
8923
8924 static bfd_boolean
8925 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
8926 {
8927   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
8928       && sym->st_shndx < SHN_LORESERVE)
8929     {
8930       /* The gABI doesn't support dynamic symbols in output sections
8931          beyond 64k.  */
8932       (*_bfd_error_handler)
8933         (_("%B: Too many sections: %d (>= %d)"),
8934          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
8935       bfd_set_error (bfd_error_nonrepresentable_section);
8936       return FALSE;
8937     }
8938   return TRUE;
8939 }
8940
8941 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
8942    allowing an unsatisfied unversioned symbol in the DSO to match a
8943    versioned symbol that would normally require an explicit version.
8944    We also handle the case that a DSO references a hidden symbol
8945    which may be satisfied by a versioned symbol in another DSO.  */
8946
8947 static bfd_boolean
8948 elf_link_check_versioned_symbol (struct bfd_link_info *info,
8949                                  const struct elf_backend_data *bed,
8950                                  struct elf_link_hash_entry *h)
8951 {
8952   bfd *abfd;
8953   struct elf_link_loaded_list *loaded;
8954
8955   if (!is_elf_hash_table (info->hash))
8956     return FALSE;
8957
8958   /* Check indirect symbol.  */
8959   while (h->root.type == bfd_link_hash_indirect)
8960     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8961
8962   switch (h->root.type)
8963     {
8964     default:
8965       abfd = NULL;
8966       break;
8967
8968     case bfd_link_hash_undefined:
8969     case bfd_link_hash_undefweak:
8970       abfd = h->root.u.undef.abfd;
8971       if ((abfd->flags & DYNAMIC) == 0
8972           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
8973         return FALSE;
8974       break;
8975
8976     case bfd_link_hash_defined:
8977     case bfd_link_hash_defweak:
8978       abfd = h->root.u.def.section->owner;
8979       break;
8980
8981     case bfd_link_hash_common:
8982       abfd = h->root.u.c.p->section->owner;
8983       break;
8984     }
8985   BFD_ASSERT (abfd != NULL);
8986
8987   for (loaded = elf_hash_table (info)->loaded;
8988        loaded != NULL;
8989        loaded = loaded->next)
8990     {
8991       bfd *input;
8992       Elf_Internal_Shdr *hdr;
8993       bfd_size_type symcount;
8994       bfd_size_type extsymcount;
8995       bfd_size_type extsymoff;
8996       Elf_Internal_Shdr *versymhdr;
8997       Elf_Internal_Sym *isym;
8998       Elf_Internal_Sym *isymend;
8999       Elf_Internal_Sym *isymbuf;
9000       Elf_External_Versym *ever;
9001       Elf_External_Versym *extversym;
9002
9003       input = loaded->abfd;
9004
9005       /* We check each DSO for a possible hidden versioned definition.  */
9006       if (input == abfd
9007           || (input->flags & DYNAMIC) == 0
9008           || elf_dynversym (input) == 0)
9009         continue;
9010
9011       hdr = &elf_tdata (input)->dynsymtab_hdr;
9012
9013       symcount = hdr->sh_size / bed->s->sizeof_sym;
9014       if (elf_bad_symtab (input))
9015         {
9016           extsymcount = symcount;
9017           extsymoff = 0;
9018         }
9019       else
9020         {
9021           extsymcount = symcount - hdr->sh_info;
9022           extsymoff = hdr->sh_info;
9023         }
9024
9025       if (extsymcount == 0)
9026         continue;
9027
9028       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
9029                                       NULL, NULL, NULL);
9030       if (isymbuf == NULL)
9031         return FALSE;
9032
9033       /* Read in any version definitions.  */
9034       versymhdr = &elf_tdata (input)->dynversym_hdr;
9035       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
9036       if (extversym == NULL)
9037         goto error_ret;
9038
9039       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
9040           || (bfd_bread (extversym, versymhdr->sh_size, input)
9041               != versymhdr->sh_size))
9042         {
9043           free (extversym);
9044         error_ret:
9045           free (isymbuf);
9046           return FALSE;
9047         }
9048
9049       ever = extversym + extsymoff;
9050       isymend = isymbuf + extsymcount;
9051       for (isym = isymbuf; isym < isymend; isym++, ever++)
9052         {
9053           const char *name;
9054           Elf_Internal_Versym iver;
9055           unsigned short version_index;
9056
9057           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
9058               || isym->st_shndx == SHN_UNDEF)
9059             continue;
9060
9061           name = bfd_elf_string_from_elf_section (input,
9062                                                   hdr->sh_link,
9063                                                   isym->st_name);
9064           if (strcmp (name, h->root.root.string) != 0)
9065             continue;
9066
9067           _bfd_elf_swap_versym_in (input, ever, &iver);
9068
9069           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
9070               && !(h->def_regular
9071                    && h->forced_local))
9072             {
9073               /* If we have a non-hidden versioned sym, then it should
9074                  have provided a definition for the undefined sym unless
9075                  it is defined in a non-shared object and forced local.
9076                */
9077               abort ();
9078             }
9079
9080           version_index = iver.vs_vers & VERSYM_VERSION;
9081           if (version_index == 1 || version_index == 2)
9082             {
9083               /* This is the base or first version.  We can use it.  */
9084               free (extversym);
9085               free (isymbuf);
9086               return TRUE;
9087             }
9088         }
9089
9090       free (extversym);
9091       free (isymbuf);
9092     }
9093
9094   return FALSE;
9095 }
9096
9097 /* Convert ELF common symbol TYPE.  */
9098
9099 static int
9100 elf_link_convert_common_type (struct bfd_link_info *info, int type)
9101 {
9102   /* Commom symbol can only appear in relocatable link.  */
9103   if (!bfd_link_relocatable (info))
9104     abort ();
9105   switch (info->elf_stt_common)
9106     {
9107     case unchanged:
9108       break;
9109     case elf_stt_common:
9110       type = STT_COMMON;
9111       break;
9112     case no_elf_stt_common:
9113       type = STT_OBJECT;
9114       break;
9115     }
9116   return type;
9117 }
9118
9119 /* Add an external symbol to the symbol table.  This is called from
9120    the hash table traversal routine.  When generating a shared object,
9121    we go through the symbol table twice.  The first time we output
9122    anything that might have been forced to local scope in a version
9123    script.  The second time we output the symbols that are still
9124    global symbols.  */
9125
9126 static bfd_boolean
9127 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
9128 {
9129   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
9130   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
9131   struct elf_final_link_info *flinfo = eoinfo->flinfo;
9132   bfd_boolean strip;
9133   Elf_Internal_Sym sym;
9134   asection *input_sec;
9135   const struct elf_backend_data *bed;
9136   long indx;
9137   int ret;
9138   unsigned int type;
9139   /* A symbol is bound locally if it is forced local or it is locally
9140      defined, hidden versioned, not referenced by shared library and
9141      not exported when linking executable.  */
9142   bfd_boolean local_bind = (h->forced_local
9143                             || (bfd_link_executable (flinfo->info)
9144                                 && !flinfo->info->export_dynamic
9145                                 && !h->dynamic
9146                                 && !h->ref_dynamic
9147                                 && h->def_regular
9148                                 && h->versioned == versioned_hidden));
9149
9150   if (h->root.type == bfd_link_hash_warning)
9151     {
9152       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9153       if (h->root.type == bfd_link_hash_new)
9154         return TRUE;
9155     }
9156
9157   /* Decide whether to output this symbol in this pass.  */
9158   if (eoinfo->localsyms)
9159     {
9160       if (!local_bind)
9161         return TRUE;
9162     }
9163   else
9164     {
9165       if (local_bind)
9166         return TRUE;
9167     }
9168
9169   bed = get_elf_backend_data (flinfo->output_bfd);
9170
9171   if (h->root.type == bfd_link_hash_undefined)
9172     {
9173       /* If we have an undefined symbol reference here then it must have
9174          come from a shared library that is being linked in.  (Undefined
9175          references in regular files have already been handled unless
9176          they are in unreferenced sections which are removed by garbage
9177          collection).  */
9178       bfd_boolean ignore_undef = FALSE;
9179
9180       /* Some symbols may be special in that the fact that they're
9181          undefined can be safely ignored - let backend determine that.  */
9182       if (bed->elf_backend_ignore_undef_symbol)
9183         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9184
9185       /* If we are reporting errors for this situation then do so now.  */
9186       if (!ignore_undef
9187           && h->ref_dynamic
9188           && (!h->ref_regular || flinfo->info->gc_sections)
9189           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9190           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9191         {
9192           if (!(flinfo->info->callbacks->undefined_symbol
9193                 (flinfo->info, h->root.root.string,
9194                  h->ref_regular ? NULL : h->root.u.undef.abfd,
9195                  NULL, 0,
9196                  (flinfo->info->unresolved_syms_in_shared_libs
9197                   == RM_GENERATE_ERROR))))
9198             {
9199               bfd_set_error (bfd_error_bad_value);
9200               eoinfo->failed = TRUE;
9201               return FALSE;
9202             }
9203         }
9204     }
9205
9206   /* We should also warn if a forced local symbol is referenced from
9207      shared libraries.  */
9208   if (bfd_link_executable (flinfo->info)
9209       && h->forced_local
9210       && h->ref_dynamic
9211       && h->def_regular
9212       && !h->dynamic_def
9213       && h->ref_dynamic_nonweak
9214       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9215     {
9216       bfd *def_bfd;
9217       const char *msg;
9218       struct elf_link_hash_entry *hi = h;
9219
9220       /* Check indirect symbol.  */
9221       while (hi->root.type == bfd_link_hash_indirect)
9222         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9223
9224       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9225         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
9226       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9227         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
9228       else
9229         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
9230       def_bfd = flinfo->output_bfd;
9231       if (hi->root.u.def.section != bfd_abs_section_ptr)
9232         def_bfd = hi->root.u.def.section->owner;
9233       (*_bfd_error_handler) (msg, flinfo->output_bfd, def_bfd,
9234                              h->root.root.string);
9235       bfd_set_error (bfd_error_bad_value);
9236       eoinfo->failed = TRUE;
9237       return FALSE;
9238     }
9239
9240   /* We don't want to output symbols that have never been mentioned by
9241      a regular file, or that we have been told to strip.  However, if
9242      h->indx is set to -2, the symbol is used by a reloc and we must
9243      output it.  */
9244   strip = FALSE;
9245   if (h->indx == -2)
9246     ;
9247   else if ((h->def_dynamic
9248             || h->ref_dynamic
9249             || h->root.type == bfd_link_hash_new)
9250            && !h->def_regular
9251            && !h->ref_regular)
9252     strip = TRUE;
9253   else if (flinfo->info->strip == strip_all)
9254     strip = TRUE;
9255   else if (flinfo->info->strip == strip_some
9256            && bfd_hash_lookup (flinfo->info->keep_hash,
9257                                h->root.root.string, FALSE, FALSE) == NULL)
9258     strip = TRUE;
9259   else if ((h->root.type == bfd_link_hash_defined
9260             || h->root.type == bfd_link_hash_defweak)
9261            && ((flinfo->info->strip_discarded
9262                 && discarded_section (h->root.u.def.section))
9263                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9264                    && h->root.u.def.section->owner != NULL
9265                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9266     strip = TRUE;
9267   else if ((h->root.type == bfd_link_hash_undefined
9268             || h->root.type == bfd_link_hash_undefweak)
9269            && h->root.u.undef.abfd != NULL
9270            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9271     strip = TRUE;
9272
9273   type = h->type;
9274
9275   /* If we're stripping it, and it's not a dynamic symbol, there's
9276      nothing else to do.   However, if it is a forced local symbol or
9277      an ifunc symbol we need to give the backend finish_dynamic_symbol
9278      function a chance to make it dynamic.  */
9279   if (strip
9280       && h->dynindx == -1
9281       && type != STT_GNU_IFUNC
9282       && !h->forced_local)
9283     return TRUE;
9284
9285   sym.st_value = 0;
9286   sym.st_size = h->size;
9287   sym.st_other = h->other;
9288   switch (h->root.type)
9289     {
9290     default:
9291     case bfd_link_hash_new:
9292     case bfd_link_hash_warning:
9293       abort ();
9294       return FALSE;
9295
9296     case bfd_link_hash_undefined:
9297     case bfd_link_hash_undefweak:
9298       input_sec = bfd_und_section_ptr;
9299       sym.st_shndx = SHN_UNDEF;
9300       break;
9301
9302     case bfd_link_hash_defined:
9303     case bfd_link_hash_defweak:
9304       {
9305         input_sec = h->root.u.def.section;
9306         if (input_sec->output_section != NULL)
9307           {
9308             sym.st_shndx =
9309               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9310                                                  input_sec->output_section);
9311             if (sym.st_shndx == SHN_BAD)
9312               {
9313                 (*_bfd_error_handler)
9314                   (_("%B: could not find output section %A for input section %A"),
9315                    flinfo->output_bfd, input_sec->output_section, input_sec);
9316                 bfd_set_error (bfd_error_nonrepresentable_section);
9317                 eoinfo->failed = TRUE;
9318                 return FALSE;
9319               }
9320
9321             /* ELF symbols in relocatable files are section relative,
9322                but in nonrelocatable files they are virtual
9323                addresses.  */
9324             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9325             if (!bfd_link_relocatable (flinfo->info))
9326               {
9327                 sym.st_value += input_sec->output_section->vma;
9328                 if (h->type == STT_TLS)
9329                   {
9330                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9331                     if (tls_sec != NULL)
9332                       sym.st_value -= tls_sec->vma;
9333                   }
9334               }
9335           }
9336         else
9337           {
9338             BFD_ASSERT (input_sec->owner == NULL
9339                         || (input_sec->owner->flags & DYNAMIC) != 0);
9340             sym.st_shndx = SHN_UNDEF;
9341             input_sec = bfd_und_section_ptr;
9342           }
9343       }
9344       break;
9345
9346     case bfd_link_hash_common:
9347       input_sec = h->root.u.c.p->section;
9348       sym.st_shndx = bed->common_section_index (input_sec);
9349       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9350       break;
9351
9352     case bfd_link_hash_indirect:
9353       /* These symbols are created by symbol versioning.  They point
9354          to the decorated version of the name.  For example, if the
9355          symbol foo@@GNU_1.2 is the default, which should be used when
9356          foo is used with no version, then we add an indirect symbol
9357          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9358          since the indirected symbol is already in the hash table.  */
9359       return TRUE;
9360     }
9361
9362   if (type == STT_COMMON || type == STT_OBJECT)
9363     switch (h->root.type)
9364       {
9365       case bfd_link_hash_common:
9366         type = elf_link_convert_common_type (flinfo->info, type);
9367         break;
9368       case bfd_link_hash_defined:
9369       case bfd_link_hash_defweak:
9370         if (bed->common_definition (&sym))
9371           type = elf_link_convert_common_type (flinfo->info, type);
9372         else
9373           type = STT_OBJECT;
9374         break;
9375       case bfd_link_hash_undefined:
9376       case bfd_link_hash_undefweak:
9377         break;
9378       default:
9379         abort ();
9380       }
9381
9382   if (local_bind)
9383     {
9384       sym.st_info = ELF_ST_INFO (STB_LOCAL, type);
9385       /* Turn off visibility on local symbol.  */
9386       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9387     }
9388   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9389   else if (h->unique_global && h->def_regular)
9390     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, type);
9391   else if (h->root.type == bfd_link_hash_undefweak
9392            || h->root.type == bfd_link_hash_defweak)
9393     sym.st_info = ELF_ST_INFO (STB_WEAK, type);
9394   else
9395     sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9396   sym.st_target_internal = h->target_internal;
9397
9398   /* Give the processor backend a chance to tweak the symbol value,
9399      and also to finish up anything that needs to be done for this
9400      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9401      forced local syms when non-shared is due to a historical quirk.
9402      STT_GNU_IFUNC symbol must go through PLT.  */
9403   if ((h->type == STT_GNU_IFUNC
9404        && h->def_regular
9405        && !bfd_link_relocatable (flinfo->info))
9406       || ((h->dynindx != -1
9407            || h->forced_local)
9408           && ((bfd_link_pic (flinfo->info)
9409                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9410                    || h->root.type != bfd_link_hash_undefweak))
9411               || !h->forced_local)
9412           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9413     {
9414       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9415              (flinfo->output_bfd, flinfo->info, h, &sym)))
9416         {
9417           eoinfo->failed = TRUE;
9418           return FALSE;
9419         }
9420     }
9421
9422   /* If we are marking the symbol as undefined, and there are no
9423      non-weak references to this symbol from a regular object, then
9424      mark the symbol as weak undefined; if there are non-weak
9425      references, mark the symbol as strong.  We can't do this earlier,
9426      because it might not be marked as undefined until the
9427      finish_dynamic_symbol routine gets through with it.  */
9428   if (sym.st_shndx == SHN_UNDEF
9429       && h->ref_regular
9430       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9431           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9432     {
9433       int bindtype;
9434       type = ELF_ST_TYPE (sym.st_info);
9435
9436       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9437       if (type == STT_GNU_IFUNC)
9438         type = STT_FUNC;
9439
9440       if (h->ref_regular_nonweak)
9441         bindtype = STB_GLOBAL;
9442       else
9443         bindtype = STB_WEAK;
9444       sym.st_info = ELF_ST_INFO (bindtype, type);
9445     }
9446
9447   /* If this is a symbol defined in a dynamic library, don't use the
9448      symbol size from the dynamic library.  Relinking an executable
9449      against a new library may introduce gratuitous changes in the
9450      executable's symbols if we keep the size.  */
9451   if (sym.st_shndx == SHN_UNDEF
9452       && !h->def_regular
9453       && h->def_dynamic)
9454     sym.st_size = 0;
9455
9456   /* If a non-weak symbol with non-default visibility is not defined
9457      locally, it is a fatal error.  */
9458   if (!bfd_link_relocatable (flinfo->info)
9459       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9460       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9461       && h->root.type == bfd_link_hash_undefined
9462       && !h->def_regular)
9463     {
9464       const char *msg;
9465
9466       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9467         msg = _("%B: protected symbol `%s' isn't defined");
9468       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9469         msg = _("%B: internal symbol `%s' isn't defined");
9470       else
9471         msg = _("%B: hidden symbol `%s' isn't defined");
9472       (*_bfd_error_handler) (msg, flinfo->output_bfd, h->root.root.string);
9473       bfd_set_error (bfd_error_bad_value);
9474       eoinfo->failed = TRUE;
9475       return FALSE;
9476     }
9477
9478   /* If this symbol should be put in the .dynsym section, then put it
9479      there now.  We already know the symbol index.  We also fill in
9480      the entry in the .hash section.  */
9481   if (elf_hash_table (flinfo->info)->dynsym != NULL
9482       && h->dynindx != -1
9483       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9484     {
9485       bfd_byte *esym;
9486
9487       /* Since there is no version information in the dynamic string,
9488          if there is no version info in symbol version section, we will
9489          have a run-time problem if not linking executable, referenced
9490          by shared library, not locally defined, or not bound locally.
9491       */
9492       if (h->verinfo.verdef == NULL
9493           && !local_bind
9494           && (!bfd_link_executable (flinfo->info)
9495               || h->ref_dynamic
9496               || !h->def_regular))
9497         {
9498           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9499
9500           if (p && p [1] != '\0')
9501             {
9502               (*_bfd_error_handler)
9503                 (_("%B: No symbol version section for versioned symbol `%s'"),
9504                  flinfo->output_bfd, h->root.root.string);
9505               eoinfo->failed = TRUE;
9506               return FALSE;
9507             }
9508         }
9509
9510       sym.st_name = h->dynstr_index;
9511       esym = (elf_hash_table (flinfo->info)->dynsym->contents
9512               + h->dynindx * bed->s->sizeof_sym);
9513       if (!check_dynsym (flinfo->output_bfd, &sym))
9514         {
9515           eoinfo->failed = TRUE;
9516           return FALSE;
9517         }
9518       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9519
9520       if (flinfo->hash_sec != NULL)
9521         {
9522           size_t hash_entry_size;
9523           bfd_byte *bucketpos;
9524           bfd_vma chain;
9525           size_t bucketcount;
9526           size_t bucket;
9527
9528           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9529           bucket = h->u.elf_hash_value % bucketcount;
9530
9531           hash_entry_size
9532             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9533           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9534                        + (bucket + 2) * hash_entry_size);
9535           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9536           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9537                    bucketpos);
9538           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9539                    ((bfd_byte *) flinfo->hash_sec->contents
9540                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9541         }
9542
9543       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9544         {
9545           Elf_Internal_Versym iversym;
9546           Elf_External_Versym *eversym;
9547
9548           if (!h->def_regular)
9549             {
9550               if (h->verinfo.verdef == NULL
9551                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9552                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9553                 iversym.vs_vers = 0;
9554               else
9555                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9556             }
9557           else
9558             {
9559               if (h->verinfo.vertree == NULL)
9560                 iversym.vs_vers = 1;
9561               else
9562                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9563               if (flinfo->info->create_default_symver)
9564                 iversym.vs_vers++;
9565             }
9566
9567           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
9568              defined locally.  */
9569           if (h->versioned == versioned_hidden && h->def_regular)
9570             iversym.vs_vers |= VERSYM_HIDDEN;
9571
9572           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
9573           eversym += h->dynindx;
9574           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
9575         }
9576     }
9577
9578   /* If the symbol is undefined, and we didn't output it to .dynsym,
9579      strip it from .symtab too.  Obviously we can't do this for
9580      relocatable output or when needed for --emit-relocs.  */
9581   else if (input_sec == bfd_und_section_ptr
9582            && h->indx != -2
9583            && !bfd_link_relocatable (flinfo->info))
9584     return TRUE;
9585   /* Also strip others that we couldn't earlier due to dynamic symbol
9586      processing.  */
9587   if (strip)
9588     return TRUE;
9589   if ((input_sec->flags & SEC_EXCLUDE) != 0)
9590     return TRUE;
9591
9592   /* Output a FILE symbol so that following locals are not associated
9593      with the wrong input file.  We need one for forced local symbols
9594      if we've seen more than one FILE symbol or when we have exactly
9595      one FILE symbol but global symbols are present in a file other
9596      than the one with the FILE symbol.  We also need one if linker
9597      defined symbols are present.  In practice these conditions are
9598      always met, so just emit the FILE symbol unconditionally.  */
9599   if (eoinfo->localsyms
9600       && !eoinfo->file_sym_done
9601       && eoinfo->flinfo->filesym_count != 0)
9602     {
9603       Elf_Internal_Sym fsym;
9604
9605       memset (&fsym, 0, sizeof (fsym));
9606       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9607       fsym.st_shndx = SHN_ABS;
9608       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
9609                                       bfd_und_section_ptr, NULL))
9610         return FALSE;
9611
9612       eoinfo->file_sym_done = TRUE;
9613     }
9614
9615   indx = bfd_get_symcount (flinfo->output_bfd);
9616   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
9617                                    input_sec, h);
9618   if (ret == 0)
9619     {
9620       eoinfo->failed = TRUE;
9621       return FALSE;
9622     }
9623   else if (ret == 1)
9624     h->indx = indx;
9625   else if (h->indx == -2)
9626     abort();
9627
9628   return TRUE;
9629 }
9630
9631 /* Return TRUE if special handling is done for relocs in SEC against
9632    symbols defined in discarded sections.  */
9633
9634 static bfd_boolean
9635 elf_section_ignore_discarded_relocs (asection *sec)
9636 {
9637   const struct elf_backend_data *bed;
9638
9639   switch (sec->sec_info_type)
9640     {
9641     case SEC_INFO_TYPE_STABS:
9642     case SEC_INFO_TYPE_EH_FRAME:
9643     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
9644       return TRUE;
9645     default:
9646       break;
9647     }
9648
9649   bed = get_elf_backend_data (sec->owner);
9650   if (bed->elf_backend_ignore_discarded_relocs != NULL
9651       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
9652     return TRUE;
9653
9654   return FALSE;
9655 }
9656
9657 /* Return a mask saying how ld should treat relocations in SEC against
9658    symbols defined in discarded sections.  If this function returns
9659    COMPLAIN set, ld will issue a warning message.  If this function
9660    returns PRETEND set, and the discarded section was link-once and the
9661    same size as the kept link-once section, ld will pretend that the
9662    symbol was actually defined in the kept section.  Otherwise ld will
9663    zero the reloc (at least that is the intent, but some cooperation by
9664    the target dependent code is needed, particularly for REL targets).  */
9665
9666 unsigned int
9667 _bfd_elf_default_action_discarded (asection *sec)
9668 {
9669   if (sec->flags & SEC_DEBUGGING)
9670     return PRETEND;
9671
9672   if (strcmp (".eh_frame", sec->name) == 0)
9673     return 0;
9674
9675   if (strcmp (".gcc_except_table", sec->name) == 0)
9676     return 0;
9677
9678   return COMPLAIN | PRETEND;
9679 }
9680
9681 /* Find a match between a section and a member of a section group.  */
9682
9683 static asection *
9684 match_group_member (asection *sec, asection *group,
9685                     struct bfd_link_info *info)
9686 {
9687   asection *first = elf_next_in_group (group);
9688   asection *s = first;
9689
9690   while (s != NULL)
9691     {
9692       if (bfd_elf_match_symbols_in_sections (s, sec, info))
9693         return s;
9694
9695       s = elf_next_in_group (s);
9696       if (s == first)
9697         break;
9698     }
9699
9700   return NULL;
9701 }
9702
9703 /* Check if the kept section of a discarded section SEC can be used
9704    to replace it.  Return the replacement if it is OK.  Otherwise return
9705    NULL.  */
9706
9707 asection *
9708 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
9709 {
9710   asection *kept;
9711
9712   kept = sec->kept_section;
9713   if (kept != NULL)
9714     {
9715       if ((kept->flags & SEC_GROUP) != 0)
9716         kept = match_group_member (sec, kept, info);
9717       if (kept != NULL
9718           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
9719               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
9720         kept = NULL;
9721       sec->kept_section = kept;
9722     }
9723   return kept;
9724 }
9725
9726 /* Link an input file into the linker output file.  This function
9727    handles all the sections and relocations of the input file at once.
9728    This is so that we only have to read the local symbols once, and
9729    don't have to keep them in memory.  */
9730
9731 static bfd_boolean
9732 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
9733 {
9734   int (*relocate_section)
9735     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
9736      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
9737   bfd *output_bfd;
9738   Elf_Internal_Shdr *symtab_hdr;
9739   size_t locsymcount;
9740   size_t extsymoff;
9741   Elf_Internal_Sym *isymbuf;
9742   Elf_Internal_Sym *isym;
9743   Elf_Internal_Sym *isymend;
9744   long *pindex;
9745   asection **ppsection;
9746   asection *o;
9747   const struct elf_backend_data *bed;
9748   struct elf_link_hash_entry **sym_hashes;
9749   bfd_size_type address_size;
9750   bfd_vma r_type_mask;
9751   int r_sym_shift;
9752   bfd_boolean have_file_sym = FALSE;
9753
9754   output_bfd = flinfo->output_bfd;
9755   bed = get_elf_backend_data (output_bfd);
9756   relocate_section = bed->elf_backend_relocate_section;
9757
9758   /* If this is a dynamic object, we don't want to do anything here:
9759      we don't want the local symbols, and we don't want the section
9760      contents.  */
9761   if ((input_bfd->flags & DYNAMIC) != 0)
9762     return TRUE;
9763
9764   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9765   if (elf_bad_symtab (input_bfd))
9766     {
9767       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
9768       extsymoff = 0;
9769     }
9770   else
9771     {
9772       locsymcount = symtab_hdr->sh_info;
9773       extsymoff = symtab_hdr->sh_info;
9774     }
9775
9776   /* Read the local symbols.  */
9777   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
9778   if (isymbuf == NULL && locsymcount != 0)
9779     {
9780       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
9781                                       flinfo->internal_syms,
9782                                       flinfo->external_syms,
9783                                       flinfo->locsym_shndx);
9784       if (isymbuf == NULL)
9785         return FALSE;
9786     }
9787
9788   /* Find local symbol sections and adjust values of symbols in
9789      SEC_MERGE sections.  Write out those local symbols we know are
9790      going into the output file.  */
9791   isymend = isymbuf + locsymcount;
9792   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
9793        isym < isymend;
9794        isym++, pindex++, ppsection++)
9795     {
9796       asection *isec;
9797       const char *name;
9798       Elf_Internal_Sym osym;
9799       long indx;
9800       int ret;
9801
9802       *pindex = -1;
9803
9804       if (elf_bad_symtab (input_bfd))
9805         {
9806           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
9807             {
9808               *ppsection = NULL;
9809               continue;
9810             }
9811         }
9812
9813       if (isym->st_shndx == SHN_UNDEF)
9814         isec = bfd_und_section_ptr;
9815       else if (isym->st_shndx == SHN_ABS)
9816         isec = bfd_abs_section_ptr;
9817       else if (isym->st_shndx == SHN_COMMON)
9818         isec = bfd_com_section_ptr;
9819       else
9820         {
9821           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
9822           if (isec == NULL)
9823             {
9824               /* Don't attempt to output symbols with st_shnx in the
9825                  reserved range other than SHN_ABS and SHN_COMMON.  */
9826               *ppsection = NULL;
9827               continue;
9828             }
9829           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
9830                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
9831             isym->st_value =
9832               _bfd_merged_section_offset (output_bfd, &isec,
9833                                           elf_section_data (isec)->sec_info,
9834                                           isym->st_value);
9835         }
9836
9837       *ppsection = isec;
9838
9839       /* Don't output the first, undefined, symbol.  In fact, don't
9840          output any undefined local symbol.  */
9841       if (isec == bfd_und_section_ptr)
9842         continue;
9843
9844       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
9845         {
9846           /* We never output section symbols.  Instead, we use the
9847              section symbol of the corresponding section in the output
9848              file.  */
9849           continue;
9850         }
9851
9852       /* If we are stripping all symbols, we don't want to output this
9853          one.  */
9854       if (flinfo->info->strip == strip_all)
9855         continue;
9856
9857       /* If we are discarding all local symbols, we don't want to
9858          output this one.  If we are generating a relocatable output
9859          file, then some of the local symbols may be required by
9860          relocs; we output them below as we discover that they are
9861          needed.  */
9862       if (flinfo->info->discard == discard_all)
9863         continue;
9864
9865       /* If this symbol is defined in a section which we are
9866          discarding, we don't need to keep it.  */
9867       if (isym->st_shndx != SHN_UNDEF
9868           && isym->st_shndx < SHN_LORESERVE
9869           && bfd_section_removed_from_list (output_bfd,
9870                                             isec->output_section))
9871         continue;
9872
9873       /* Get the name of the symbol.  */
9874       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
9875                                               isym->st_name);
9876       if (name == NULL)
9877         return FALSE;
9878
9879       /* See if we are discarding symbols with this name.  */
9880       if ((flinfo->info->strip == strip_some
9881            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
9882                == NULL))
9883           || (((flinfo->info->discard == discard_sec_merge
9884                 && (isec->flags & SEC_MERGE)
9885                 && !bfd_link_relocatable (flinfo->info))
9886                || flinfo->info->discard == discard_l)
9887               && bfd_is_local_label_name (input_bfd, name)))
9888         continue;
9889
9890       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
9891         {
9892           if (input_bfd->lto_output)
9893             /* -flto puts a temp file name here.  This means builds
9894                are not reproducible.  Discard the symbol.  */
9895             continue;
9896           have_file_sym = TRUE;
9897           flinfo->filesym_count += 1;
9898         }
9899       if (!have_file_sym)
9900         {
9901           /* In the absence of debug info, bfd_find_nearest_line uses
9902              FILE symbols to determine the source file for local
9903              function symbols.  Provide a FILE symbol here if input
9904              files lack such, so that their symbols won't be
9905              associated with a previous input file.  It's not the
9906              source file, but the best we can do.  */
9907           have_file_sym = TRUE;
9908           flinfo->filesym_count += 1;
9909           memset (&osym, 0, sizeof (osym));
9910           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9911           osym.st_shndx = SHN_ABS;
9912           if (!elf_link_output_symstrtab (flinfo,
9913                                           (input_bfd->lto_output ? NULL
9914                                            : input_bfd->filename),
9915                                           &osym, bfd_abs_section_ptr,
9916                                           NULL))
9917             return FALSE;
9918         }
9919
9920       osym = *isym;
9921
9922       /* Adjust the section index for the output file.  */
9923       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
9924                                                          isec->output_section);
9925       if (osym.st_shndx == SHN_BAD)
9926         return FALSE;
9927
9928       /* ELF symbols in relocatable files are section relative, but
9929          in executable files they are virtual addresses.  Note that
9930          this code assumes that all ELF sections have an associated
9931          BFD section with a reasonable value for output_offset; below
9932          we assume that they also have a reasonable value for
9933          output_section.  Any special sections must be set up to meet
9934          these requirements.  */
9935       osym.st_value += isec->output_offset;
9936       if (!bfd_link_relocatable (flinfo->info))
9937         {
9938           osym.st_value += isec->output_section->vma;
9939           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
9940             {
9941               /* STT_TLS symbols are relative to PT_TLS segment base.  */
9942               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
9943               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
9944             }
9945         }
9946
9947       indx = bfd_get_symcount (output_bfd);
9948       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
9949       if (ret == 0)
9950         return FALSE;
9951       else if (ret == 1)
9952         *pindex = indx;
9953     }
9954
9955   if (bed->s->arch_size == 32)
9956     {
9957       r_type_mask = 0xff;
9958       r_sym_shift = 8;
9959       address_size = 4;
9960     }
9961   else
9962     {
9963       r_type_mask = 0xffffffff;
9964       r_sym_shift = 32;
9965       address_size = 8;
9966     }
9967
9968   /* Relocate the contents of each section.  */
9969   sym_hashes = elf_sym_hashes (input_bfd);
9970   for (o = input_bfd->sections; o != NULL; o = o->next)
9971     {
9972       bfd_byte *contents;
9973
9974       if (! o->linker_mark)
9975         {
9976           /* This section was omitted from the link.  */
9977           continue;
9978         }
9979
9980       if (bfd_link_relocatable (flinfo->info)
9981           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
9982         {
9983           /* Deal with the group signature symbol.  */
9984           struct bfd_elf_section_data *sec_data = elf_section_data (o);
9985           unsigned long symndx = sec_data->this_hdr.sh_info;
9986           asection *osec = o->output_section;
9987
9988           if (symndx >= locsymcount
9989               || (elf_bad_symtab (input_bfd)
9990                   && flinfo->sections[symndx] == NULL))
9991             {
9992               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
9993               while (h->root.type == bfd_link_hash_indirect
9994                      || h->root.type == bfd_link_hash_warning)
9995                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
9996               /* Arrange for symbol to be output.  */
9997               h->indx = -2;
9998               elf_section_data (osec)->this_hdr.sh_info = -2;
9999             }
10000           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
10001             {
10002               /* We'll use the output section target_index.  */
10003               asection *sec = flinfo->sections[symndx]->output_section;
10004               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
10005             }
10006           else
10007             {
10008               if (flinfo->indices[symndx] == -1)
10009                 {
10010                   /* Otherwise output the local symbol now.  */
10011                   Elf_Internal_Sym sym = isymbuf[symndx];
10012                   asection *sec = flinfo->sections[symndx]->output_section;
10013                   const char *name;
10014                   long indx;
10015                   int ret;
10016
10017                   name = bfd_elf_string_from_elf_section (input_bfd,
10018                                                           symtab_hdr->sh_link,
10019                                                           sym.st_name);
10020                   if (name == NULL)
10021                     return FALSE;
10022
10023                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10024                                                                     sec);
10025                   if (sym.st_shndx == SHN_BAD)
10026                     return FALSE;
10027
10028                   sym.st_value += o->output_offset;
10029
10030                   indx = bfd_get_symcount (output_bfd);
10031                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
10032                                                    NULL);
10033                   if (ret == 0)
10034                     return FALSE;
10035                   else if (ret == 1)
10036                     flinfo->indices[symndx] = indx;
10037                   else
10038                     abort ();
10039                 }
10040               elf_section_data (osec)->this_hdr.sh_info
10041                 = flinfo->indices[symndx];
10042             }
10043         }
10044
10045       if ((o->flags & SEC_HAS_CONTENTS) == 0
10046           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
10047         continue;
10048
10049       if ((o->flags & SEC_LINKER_CREATED) != 0)
10050         {
10051           /* Section was created by _bfd_elf_link_create_dynamic_sections
10052              or somesuch.  */
10053           continue;
10054         }
10055
10056       /* Get the contents of the section.  They have been cached by a
10057          relaxation routine.  Note that o is a section in an input
10058          file, so the contents field will not have been set by any of
10059          the routines which work on output files.  */
10060       if (elf_section_data (o)->this_hdr.contents != NULL)
10061         {
10062           contents = elf_section_data (o)->this_hdr.contents;
10063           if (bed->caches_rawsize
10064               && o->rawsize != 0
10065               && o->rawsize < o->size)
10066             {
10067               memcpy (flinfo->contents, contents, o->rawsize);
10068               contents = flinfo->contents;
10069             }
10070         }
10071       else
10072         {
10073           contents = flinfo->contents;
10074           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
10075             return FALSE;
10076         }
10077
10078       if ((o->flags & SEC_RELOC) != 0)
10079         {
10080           Elf_Internal_Rela *internal_relocs;
10081           Elf_Internal_Rela *rel, *relend;
10082           int action_discarded;
10083           int ret;
10084
10085           /* Get the swapped relocs.  */
10086           internal_relocs
10087             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
10088                                          flinfo->internal_relocs, FALSE);
10089           if (internal_relocs == NULL
10090               && o->reloc_count > 0)
10091             return FALSE;
10092
10093           /* We need to reverse-copy input .ctors/.dtors sections if
10094              they are placed in .init_array/.finit_array for output.  */
10095           if (o->size > address_size
10096               && ((strncmp (o->name, ".ctors", 6) == 0
10097                    && strcmp (o->output_section->name,
10098                               ".init_array") == 0)
10099                   || (strncmp (o->name, ".dtors", 6) == 0
10100                       && strcmp (o->output_section->name,
10101                                  ".fini_array") == 0))
10102               && (o->name[6] == 0 || o->name[6] == '.'))
10103             {
10104               if (o->size != o->reloc_count * address_size)
10105                 {
10106                   (*_bfd_error_handler)
10107                     (_("error: %B: size of section %A is not "
10108                        "multiple of address size"),
10109                      input_bfd, o);
10110                   bfd_set_error (bfd_error_on_input);
10111                   return FALSE;
10112                 }
10113               o->flags |= SEC_ELF_REVERSE_COPY;
10114             }
10115
10116           action_discarded = -1;
10117           if (!elf_section_ignore_discarded_relocs (o))
10118             action_discarded = (*bed->action_discarded) (o);
10119
10120           /* Run through the relocs evaluating complex reloc symbols and
10121              looking for relocs against symbols from discarded sections
10122              or section symbols from removed link-once sections.
10123              Complain about relocs against discarded sections.  Zero
10124              relocs against removed link-once sections.  */
10125
10126           rel = internal_relocs;
10127           relend = rel + o->reloc_count * bed->s->int_rels_per_ext_rel;
10128           for ( ; rel < relend; rel++)
10129             {
10130               unsigned long r_symndx = rel->r_info >> r_sym_shift;
10131               unsigned int s_type;
10132               asection **ps, *sec;
10133               struct elf_link_hash_entry *h = NULL;
10134               const char *sym_name;
10135
10136               if (r_symndx == STN_UNDEF)
10137                 continue;
10138
10139               if (r_symndx >= locsymcount
10140                   || (elf_bad_symtab (input_bfd)
10141                       && flinfo->sections[r_symndx] == NULL))
10142                 {
10143                   h = sym_hashes[r_symndx - extsymoff];
10144
10145                   /* Badly formatted input files can contain relocs that
10146                      reference non-existant symbols.  Check here so that
10147                      we do not seg fault.  */
10148                   if (h == NULL)
10149                     {
10150                       char buffer [32];
10151
10152                       sprintf_vma (buffer, rel->r_info);
10153                       (*_bfd_error_handler)
10154                         (_("error: %B contains a reloc (0x%s) for section %A "
10155                            "that references a non-existent global symbol"),
10156                          input_bfd, o, buffer);
10157                       bfd_set_error (bfd_error_bad_value);
10158                       return FALSE;
10159                     }
10160
10161                   while (h->root.type == bfd_link_hash_indirect
10162                          || h->root.type == bfd_link_hash_warning)
10163                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10164
10165                   s_type = h->type;
10166
10167                   /* If a plugin symbol is referenced from a non-IR file,
10168                      mark the symbol as undefined.  Note that the
10169                      linker may attach linker created dynamic sections
10170                      to the plugin bfd.  Symbols defined in linker
10171                      created sections are not plugin symbols.  */
10172                   if (h->root.non_ir_ref
10173                       && (h->root.type == bfd_link_hash_defined
10174                           || h->root.type == bfd_link_hash_defweak)
10175                       && (h->root.u.def.section->flags
10176                           & SEC_LINKER_CREATED) == 0
10177                       && h->root.u.def.section->owner != NULL
10178                       && (h->root.u.def.section->owner->flags
10179                           & BFD_PLUGIN) != 0)
10180                     {
10181                       h->root.type = bfd_link_hash_undefined;
10182                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10183                     }
10184
10185                   ps = NULL;
10186                   if (h->root.type == bfd_link_hash_defined
10187                       || h->root.type == bfd_link_hash_defweak)
10188                     ps = &h->root.u.def.section;
10189
10190                   sym_name = h->root.root.string;
10191                 }
10192               else
10193                 {
10194                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10195
10196                   s_type = ELF_ST_TYPE (sym->st_info);
10197                   ps = &flinfo->sections[r_symndx];
10198                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10199                                                sym, *ps);
10200                 }
10201
10202               if ((s_type == STT_RELC || s_type == STT_SRELC)
10203                   && !bfd_link_relocatable (flinfo->info))
10204                 {
10205                   bfd_vma val;
10206                   bfd_vma dot = (rel->r_offset
10207                                  + o->output_offset + o->output_section->vma);
10208 #ifdef DEBUG
10209                   printf ("Encountered a complex symbol!");
10210                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10211                           input_bfd->filename, o->name,
10212                           (long) (rel - internal_relocs));
10213                   printf (" symbol: idx  %8.8lx, name %s\n",
10214                           r_symndx, sym_name);
10215                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10216                           (unsigned long) rel->r_info,
10217                           (unsigned long) rel->r_offset);
10218 #endif
10219                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10220                                     isymbuf, locsymcount, s_type == STT_SRELC))
10221                     return FALSE;
10222
10223                   /* Symbol evaluated OK.  Update to absolute value.  */
10224                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10225                                     r_symndx, val);
10226                   continue;
10227                 }
10228
10229               if (action_discarded != -1 && ps != NULL)
10230                 {
10231                   /* Complain if the definition comes from a
10232                      discarded section.  */
10233                   if ((sec = *ps) != NULL && discarded_section (sec))
10234                     {
10235                       BFD_ASSERT (r_symndx != STN_UNDEF);
10236                       if (action_discarded & COMPLAIN)
10237                         (*flinfo->info->callbacks->einfo)
10238                           (_("%X`%s' referenced in section `%A' of %B: "
10239                              "defined in discarded section `%A' of %B\n"),
10240                            sym_name, o, input_bfd, sec, sec->owner);
10241
10242                       /* Try to do the best we can to support buggy old
10243                          versions of gcc.  Pretend that the symbol is
10244                          really defined in the kept linkonce section.
10245                          FIXME: This is quite broken.  Modifying the
10246                          symbol here means we will be changing all later
10247                          uses of the symbol, not just in this section.  */
10248                       if (action_discarded & PRETEND)
10249                         {
10250                           asection *kept;
10251
10252                           kept = _bfd_elf_check_kept_section (sec,
10253                                                               flinfo->info);
10254                           if (kept != NULL)
10255                             {
10256                               *ps = kept;
10257                               continue;
10258                             }
10259                         }
10260                     }
10261                 }
10262             }
10263
10264           /* Relocate the section by invoking a back end routine.
10265
10266              The back end routine is responsible for adjusting the
10267              section contents as necessary, and (if using Rela relocs
10268              and generating a relocatable output file) adjusting the
10269              reloc addend as necessary.
10270
10271              The back end routine does not have to worry about setting
10272              the reloc address or the reloc symbol index.
10273
10274              The back end routine is given a pointer to the swapped in
10275              internal symbols, and can access the hash table entries
10276              for the external symbols via elf_sym_hashes (input_bfd).
10277
10278              When generating relocatable output, the back end routine
10279              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10280              output symbol is going to be a section symbol
10281              corresponding to the output section, which will require
10282              the addend to be adjusted.  */
10283
10284           ret = (*relocate_section) (output_bfd, flinfo->info,
10285                                      input_bfd, o, contents,
10286                                      internal_relocs,
10287                                      isymbuf,
10288                                      flinfo->sections);
10289           if (!ret)
10290             return FALSE;
10291
10292           if (ret == 2
10293               || bfd_link_relocatable (flinfo->info)
10294               || flinfo->info->emitrelocations)
10295             {
10296               Elf_Internal_Rela *irela;
10297               Elf_Internal_Rela *irelaend, *irelamid;
10298               bfd_vma last_offset;
10299               struct elf_link_hash_entry **rel_hash;
10300               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10301               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10302               unsigned int next_erel;
10303               bfd_boolean rela_normal;
10304               struct bfd_elf_section_data *esdi, *esdo;
10305
10306               esdi = elf_section_data (o);
10307               esdo = elf_section_data (o->output_section);
10308               rela_normal = FALSE;
10309
10310               /* Adjust the reloc addresses and symbol indices.  */
10311
10312               irela = internal_relocs;
10313               irelaend = irela + o->reloc_count * bed->s->int_rels_per_ext_rel;
10314               rel_hash = esdo->rel.hashes + esdo->rel.count;
10315               /* We start processing the REL relocs, if any.  When we reach
10316                  IRELAMID in the loop, we switch to the RELA relocs.  */
10317               irelamid = irela;
10318               if (esdi->rel.hdr != NULL)
10319                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10320                              * bed->s->int_rels_per_ext_rel);
10321               rel_hash_list = rel_hash;
10322               rela_hash_list = NULL;
10323               last_offset = o->output_offset;
10324               if (!bfd_link_relocatable (flinfo->info))
10325                 last_offset += o->output_section->vma;
10326               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10327                 {
10328                   unsigned long r_symndx;
10329                   asection *sec;
10330                   Elf_Internal_Sym sym;
10331
10332                   if (next_erel == bed->s->int_rels_per_ext_rel)
10333                     {
10334                       rel_hash++;
10335                       next_erel = 0;
10336                     }
10337
10338                   if (irela == irelamid)
10339                     {
10340                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10341                       rela_hash_list = rel_hash;
10342                       rela_normal = bed->rela_normal;
10343                     }
10344
10345                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10346                                                              flinfo->info, o,
10347                                                              irela->r_offset);
10348                   if (irela->r_offset >= (bfd_vma) -2)
10349                     {
10350                       /* This is a reloc for a deleted entry or somesuch.
10351                          Turn it into an R_*_NONE reloc, at the same
10352                          offset as the last reloc.  elf_eh_frame.c and
10353                          bfd_elf_discard_info rely on reloc offsets
10354                          being ordered.  */
10355                       irela->r_offset = last_offset;
10356                       irela->r_info = 0;
10357                       irela->r_addend = 0;
10358                       continue;
10359                     }
10360
10361                   irela->r_offset += o->output_offset;
10362
10363                   /* Relocs in an executable have to be virtual addresses.  */
10364                   if (!bfd_link_relocatable (flinfo->info))
10365                     irela->r_offset += o->output_section->vma;
10366
10367                   last_offset = irela->r_offset;
10368
10369                   r_symndx = irela->r_info >> r_sym_shift;
10370                   if (r_symndx == STN_UNDEF)
10371                     continue;
10372
10373                   if (r_symndx >= locsymcount
10374                       || (elf_bad_symtab (input_bfd)
10375                           && flinfo->sections[r_symndx] == NULL))
10376                     {
10377                       struct elf_link_hash_entry *rh;
10378                       unsigned long indx;
10379
10380                       /* This is a reloc against a global symbol.  We
10381                          have not yet output all the local symbols, so
10382                          we do not know the symbol index of any global
10383                          symbol.  We set the rel_hash entry for this
10384                          reloc to point to the global hash table entry
10385                          for this symbol.  The symbol index is then
10386                          set at the end of bfd_elf_final_link.  */
10387                       indx = r_symndx - extsymoff;
10388                       rh = elf_sym_hashes (input_bfd)[indx];
10389                       while (rh->root.type == bfd_link_hash_indirect
10390                              || rh->root.type == bfd_link_hash_warning)
10391                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10392
10393                       /* Setting the index to -2 tells
10394                          elf_link_output_extsym that this symbol is
10395                          used by a reloc.  */
10396                       BFD_ASSERT (rh->indx < 0);
10397                       rh->indx = -2;
10398
10399                       *rel_hash = rh;
10400
10401                       continue;
10402                     }
10403
10404                   /* This is a reloc against a local symbol.  */
10405
10406                   *rel_hash = NULL;
10407                   sym = isymbuf[r_symndx];
10408                   sec = flinfo->sections[r_symndx];
10409                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10410                     {
10411                       /* I suppose the backend ought to fill in the
10412                          section of any STT_SECTION symbol against a
10413                          processor specific section.  */
10414                       r_symndx = STN_UNDEF;
10415                       if (bfd_is_abs_section (sec))
10416                         ;
10417                       else if (sec == NULL || sec->owner == NULL)
10418                         {
10419                           bfd_set_error (bfd_error_bad_value);
10420                           return FALSE;
10421                         }
10422                       else
10423                         {
10424                           asection *osec = sec->output_section;
10425
10426                           /* If we have discarded a section, the output
10427                              section will be the absolute section.  In
10428                              case of discarded SEC_MERGE sections, use
10429                              the kept section.  relocate_section should
10430                              have already handled discarded linkonce
10431                              sections.  */
10432                           if (bfd_is_abs_section (osec)
10433                               && sec->kept_section != NULL
10434                               && sec->kept_section->output_section != NULL)
10435                             {
10436                               osec = sec->kept_section->output_section;
10437                               irela->r_addend -= osec->vma;
10438                             }
10439
10440                           if (!bfd_is_abs_section (osec))
10441                             {
10442                               r_symndx = osec->target_index;
10443                               if (r_symndx == STN_UNDEF)
10444                                 {
10445                                   irela->r_addend += osec->vma;
10446                                   osec = _bfd_nearby_section (output_bfd, osec,
10447                                                               osec->vma);
10448                                   irela->r_addend -= osec->vma;
10449                                   r_symndx = osec->target_index;
10450                                 }
10451                             }
10452                         }
10453
10454                       /* Adjust the addend according to where the
10455                          section winds up in the output section.  */
10456                       if (rela_normal)
10457                         irela->r_addend += sec->output_offset;
10458                     }
10459                   else
10460                     {
10461                       if (flinfo->indices[r_symndx] == -1)
10462                         {
10463                           unsigned long shlink;
10464                           const char *name;
10465                           asection *osec;
10466                           long indx;
10467
10468                           if (flinfo->info->strip == strip_all)
10469                             {
10470                               /* You can't do ld -r -s.  */
10471                               bfd_set_error (bfd_error_invalid_operation);
10472                               return FALSE;
10473                             }
10474
10475                           /* This symbol was skipped earlier, but
10476                              since it is needed by a reloc, we
10477                              must output it now.  */
10478                           shlink = symtab_hdr->sh_link;
10479                           name = (bfd_elf_string_from_elf_section
10480                                   (input_bfd, shlink, sym.st_name));
10481                           if (name == NULL)
10482                             return FALSE;
10483
10484                           osec = sec->output_section;
10485                           sym.st_shndx =
10486                             _bfd_elf_section_from_bfd_section (output_bfd,
10487                                                                osec);
10488                           if (sym.st_shndx == SHN_BAD)
10489                             return FALSE;
10490
10491                           sym.st_value += sec->output_offset;
10492                           if (!bfd_link_relocatable (flinfo->info))
10493                             {
10494                               sym.st_value += osec->vma;
10495                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10496                                 {
10497                                   /* STT_TLS symbols are relative to PT_TLS
10498                                      segment base.  */
10499                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10500                                               ->tls_sec != NULL);
10501                                   sym.st_value -= (elf_hash_table (flinfo->info)
10502                                                    ->tls_sec->vma);
10503                                 }
10504                             }
10505
10506                           indx = bfd_get_symcount (output_bfd);
10507                           ret = elf_link_output_symstrtab (flinfo, name,
10508                                                            &sym, sec,
10509                                                            NULL);
10510                           if (ret == 0)
10511                             return FALSE;
10512                           else if (ret == 1)
10513                             flinfo->indices[r_symndx] = indx;
10514                           else
10515                             abort ();
10516                         }
10517
10518                       r_symndx = flinfo->indices[r_symndx];
10519                     }
10520
10521                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10522                                    | (irela->r_info & r_type_mask));
10523                 }
10524
10525               /* Swap out the relocs.  */
10526               input_rel_hdr = esdi->rel.hdr;
10527               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10528                 {
10529                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10530                                                      input_rel_hdr,
10531                                                      internal_relocs,
10532                                                      rel_hash_list))
10533                     return FALSE;
10534                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10535                                       * bed->s->int_rels_per_ext_rel);
10536                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10537                 }
10538
10539               input_rela_hdr = esdi->rela.hdr;
10540               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10541                 {
10542                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10543                                                      input_rela_hdr,
10544                                                      internal_relocs,
10545                                                      rela_hash_list))
10546                     return FALSE;
10547                 }
10548             }
10549         }
10550
10551       /* Write out the modified section contents.  */
10552       if (bed->elf_backend_write_section
10553           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10554                                                 contents))
10555         {
10556           /* Section written out.  */
10557         }
10558       else switch (o->sec_info_type)
10559         {
10560         case SEC_INFO_TYPE_STABS:
10561           if (! (_bfd_write_section_stabs
10562                  (output_bfd,
10563                   &elf_hash_table (flinfo->info)->stab_info,
10564                   o, &elf_section_data (o)->sec_info, contents)))
10565             return FALSE;
10566           break;
10567         case SEC_INFO_TYPE_MERGE:
10568           if (! _bfd_write_merged_section (output_bfd, o,
10569                                            elf_section_data (o)->sec_info))
10570             return FALSE;
10571           break;
10572         case SEC_INFO_TYPE_EH_FRAME:
10573           {
10574             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
10575                                                    o, contents))
10576               return FALSE;
10577           }
10578           break;
10579         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10580           {
10581             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
10582                                                          flinfo->info,
10583                                                          o, contents))
10584               return FALSE;
10585           }
10586           break;
10587         default:
10588           {
10589             if (! (o->flags & SEC_EXCLUDE))
10590               {
10591                 file_ptr offset = (file_ptr) o->output_offset;
10592                 bfd_size_type todo = o->size;
10593
10594                 offset *= bfd_octets_per_byte (output_bfd);
10595
10596                 if ((o->flags & SEC_ELF_REVERSE_COPY))
10597                   {
10598                     /* Reverse-copy input section to output.  */
10599                     do
10600                       {
10601                         todo -= address_size;
10602                         if (! bfd_set_section_contents (output_bfd,
10603                                                         o->output_section,
10604                                                         contents + todo,
10605                                                         offset,
10606                                                         address_size))
10607                           return FALSE;
10608                         if (todo == 0)
10609                           break;
10610                         offset += address_size;
10611                       }
10612                     while (1);
10613                   }
10614                 else if (! bfd_set_section_contents (output_bfd,
10615                                                      o->output_section,
10616                                                      contents,
10617                                                      offset, todo))
10618                   return FALSE;
10619               }
10620           }
10621           break;
10622         }
10623     }
10624
10625   return TRUE;
10626 }
10627
10628 /* Generate a reloc when linking an ELF file.  This is a reloc
10629    requested by the linker, and does not come from any input file.  This
10630    is used to build constructor and destructor tables when linking
10631    with -Ur.  */
10632
10633 static bfd_boolean
10634 elf_reloc_link_order (bfd *output_bfd,
10635                       struct bfd_link_info *info,
10636                       asection *output_section,
10637                       struct bfd_link_order *link_order)
10638 {
10639   reloc_howto_type *howto;
10640   long indx;
10641   bfd_vma offset;
10642   bfd_vma addend;
10643   struct bfd_elf_section_reloc_data *reldata;
10644   struct elf_link_hash_entry **rel_hash_ptr;
10645   Elf_Internal_Shdr *rel_hdr;
10646   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
10647   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
10648   bfd_byte *erel;
10649   unsigned int i;
10650   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
10651
10652   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
10653   if (howto == NULL)
10654     {
10655       bfd_set_error (bfd_error_bad_value);
10656       return FALSE;
10657     }
10658
10659   addend = link_order->u.reloc.p->addend;
10660
10661   if (esdo->rel.hdr)
10662     reldata = &esdo->rel;
10663   else if (esdo->rela.hdr)
10664     reldata = &esdo->rela;
10665   else
10666     {
10667       reldata = NULL;
10668       BFD_ASSERT (0);
10669     }
10670
10671   /* Figure out the symbol index.  */
10672   rel_hash_ptr = reldata->hashes + reldata->count;
10673   if (link_order->type == bfd_section_reloc_link_order)
10674     {
10675       indx = link_order->u.reloc.p->u.section->target_index;
10676       BFD_ASSERT (indx != 0);
10677       *rel_hash_ptr = NULL;
10678     }
10679   else
10680     {
10681       struct elf_link_hash_entry *h;
10682
10683       /* Treat a reloc against a defined symbol as though it were
10684          actually against the section.  */
10685       h = ((struct elf_link_hash_entry *)
10686            bfd_wrapped_link_hash_lookup (output_bfd, info,
10687                                          link_order->u.reloc.p->u.name,
10688                                          FALSE, FALSE, TRUE));
10689       if (h != NULL
10690           && (h->root.type == bfd_link_hash_defined
10691               || h->root.type == bfd_link_hash_defweak))
10692         {
10693           asection *section;
10694
10695           section = h->root.u.def.section;
10696           indx = section->output_section->target_index;
10697           *rel_hash_ptr = NULL;
10698           /* It seems that we ought to add the symbol value to the
10699              addend here, but in practice it has already been added
10700              because it was passed to constructor_callback.  */
10701           addend += section->output_section->vma + section->output_offset;
10702         }
10703       else if (h != NULL)
10704         {
10705           /* Setting the index to -2 tells elf_link_output_extsym that
10706              this symbol is used by a reloc.  */
10707           h->indx = -2;
10708           *rel_hash_ptr = h;
10709           indx = 0;
10710         }
10711       else
10712         {
10713           if (! ((*info->callbacks->unattached_reloc)
10714                  (info, link_order->u.reloc.p->u.name, NULL, NULL, 0)))
10715             return FALSE;
10716           indx = 0;
10717         }
10718     }
10719
10720   /* If this is an inplace reloc, we must write the addend into the
10721      object file.  */
10722   if (howto->partial_inplace && addend != 0)
10723     {
10724       bfd_size_type size;
10725       bfd_reloc_status_type rstat;
10726       bfd_byte *buf;
10727       bfd_boolean ok;
10728       const char *sym_name;
10729
10730       size = (bfd_size_type) bfd_get_reloc_size (howto);
10731       buf = (bfd_byte *) bfd_zmalloc (size);
10732       if (buf == NULL && size != 0)
10733         return FALSE;
10734       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
10735       switch (rstat)
10736         {
10737         case bfd_reloc_ok:
10738           break;
10739
10740         default:
10741         case bfd_reloc_outofrange:
10742           abort ();
10743
10744         case bfd_reloc_overflow:
10745           if (link_order->type == bfd_section_reloc_link_order)
10746             sym_name = bfd_section_name (output_bfd,
10747                                          link_order->u.reloc.p->u.section);
10748           else
10749             sym_name = link_order->u.reloc.p->u.name;
10750           if (! ((*info->callbacks->reloc_overflow)
10751                  (info, NULL, sym_name, howto->name, addend, NULL,
10752                   NULL, (bfd_vma) 0)))
10753             {
10754               free (buf);
10755               return FALSE;
10756             }
10757           break;
10758         }
10759
10760       ok = bfd_set_section_contents (output_bfd, output_section, buf,
10761                                      link_order->offset
10762                                      * bfd_octets_per_byte (output_bfd),
10763                                      size);
10764       free (buf);
10765       if (! ok)
10766         return FALSE;
10767     }
10768
10769   /* The address of a reloc is relative to the section in a
10770      relocatable file, and is a virtual address in an executable
10771      file.  */
10772   offset = link_order->offset;
10773   if (! bfd_link_relocatable (info))
10774     offset += output_section->vma;
10775
10776   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
10777     {
10778       irel[i].r_offset = offset;
10779       irel[i].r_info = 0;
10780       irel[i].r_addend = 0;
10781     }
10782   if (bed->s->arch_size == 32)
10783     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
10784   else
10785     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
10786
10787   rel_hdr = reldata->hdr;
10788   erel = rel_hdr->contents;
10789   if (rel_hdr->sh_type == SHT_REL)
10790     {
10791       erel += reldata->count * bed->s->sizeof_rel;
10792       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
10793     }
10794   else
10795     {
10796       irel[0].r_addend = addend;
10797       erel += reldata->count * bed->s->sizeof_rela;
10798       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
10799     }
10800
10801   ++reldata->count;
10802
10803   return TRUE;
10804 }
10805
10806
10807 /* Get the output vma of the section pointed to by the sh_link field.  */
10808
10809 static bfd_vma
10810 elf_get_linked_section_vma (struct bfd_link_order *p)
10811 {
10812   Elf_Internal_Shdr **elf_shdrp;
10813   asection *s;
10814   int elfsec;
10815
10816   s = p->u.indirect.section;
10817   elf_shdrp = elf_elfsections (s->owner);
10818   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
10819   elfsec = elf_shdrp[elfsec]->sh_link;
10820   /* PR 290:
10821      The Intel C compiler generates SHT_IA_64_UNWIND with
10822      SHF_LINK_ORDER.  But it doesn't set the sh_link or
10823      sh_info fields.  Hence we could get the situation
10824      where elfsec is 0.  */
10825   if (elfsec == 0)
10826     {
10827       const struct elf_backend_data *bed
10828         = get_elf_backend_data (s->owner);
10829       if (bed->link_order_error_handler)
10830         bed->link_order_error_handler
10831           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
10832       return 0;
10833     }
10834   else
10835     {
10836       s = elf_shdrp[elfsec]->bfd_section;
10837       return s->output_section->vma + s->output_offset;
10838     }
10839 }
10840
10841
10842 /* Compare two sections based on the locations of the sections they are
10843    linked to.  Used by elf_fixup_link_order.  */
10844
10845 static int
10846 compare_link_order (const void * a, const void * b)
10847 {
10848   bfd_vma apos;
10849   bfd_vma bpos;
10850
10851   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
10852   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
10853   if (apos < bpos)
10854     return -1;
10855   return apos > bpos;
10856 }
10857
10858
10859 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
10860    order as their linked sections.  Returns false if this could not be done
10861    because an output section includes both ordered and unordered
10862    sections.  Ideally we'd do this in the linker proper.  */
10863
10864 static bfd_boolean
10865 elf_fixup_link_order (bfd *abfd, asection *o)
10866 {
10867   int seen_linkorder;
10868   int seen_other;
10869   int n;
10870   struct bfd_link_order *p;
10871   bfd *sub;
10872   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
10873   unsigned elfsec;
10874   struct bfd_link_order **sections;
10875   asection *s, *other_sec, *linkorder_sec;
10876   bfd_vma offset;
10877
10878   other_sec = NULL;
10879   linkorder_sec = NULL;
10880   seen_other = 0;
10881   seen_linkorder = 0;
10882   for (p = o->map_head.link_order; p != NULL; p = p->next)
10883     {
10884       if (p->type == bfd_indirect_link_order)
10885         {
10886           s = p->u.indirect.section;
10887           sub = s->owner;
10888           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
10889               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
10890               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
10891               && elfsec < elf_numsections (sub)
10892               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
10893               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
10894             {
10895               seen_linkorder++;
10896               linkorder_sec = s;
10897             }
10898           else
10899             {
10900               seen_other++;
10901               other_sec = s;
10902             }
10903         }
10904       else
10905         seen_other++;
10906
10907       if (seen_other && seen_linkorder)
10908         {
10909           if (other_sec && linkorder_sec)
10910             (*_bfd_error_handler) (_("%A has both ordered [`%A' in %B] and unordered [`%A' in %B] sections"),
10911                                    o, linkorder_sec,
10912                                    linkorder_sec->owner, other_sec,
10913                                    other_sec->owner);
10914           else
10915             (*_bfd_error_handler) (_("%A has both ordered and unordered sections"),
10916                                    o);
10917           bfd_set_error (bfd_error_bad_value);
10918           return FALSE;
10919         }
10920     }
10921
10922   if (!seen_linkorder)
10923     return TRUE;
10924
10925   sections = (struct bfd_link_order **)
10926     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
10927   if (sections == NULL)
10928     return FALSE;
10929   seen_linkorder = 0;
10930
10931   for (p = o->map_head.link_order; p != NULL; p = p->next)
10932     {
10933       sections[seen_linkorder++] = p;
10934     }
10935   /* Sort the input sections in the order of their linked section.  */
10936   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
10937          compare_link_order);
10938
10939   /* Change the offsets of the sections.  */
10940   offset = 0;
10941   for (n = 0; n < seen_linkorder; n++)
10942     {
10943       s = sections[n]->u.indirect.section;
10944       offset &= ~(bfd_vma) 0 << s->alignment_power;
10945       s->output_offset = offset / bfd_octets_per_byte (abfd);
10946       sections[n]->offset = offset;
10947       offset += sections[n]->size;
10948     }
10949
10950   free (sections);
10951   return TRUE;
10952 }
10953
10954 static void
10955 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
10956 {
10957   asection *o;
10958
10959   if (flinfo->symstrtab != NULL)
10960     _bfd_elf_strtab_free (flinfo->symstrtab);
10961   if (flinfo->contents != NULL)
10962     free (flinfo->contents);
10963   if (flinfo->external_relocs != NULL)
10964     free (flinfo->external_relocs);
10965   if (flinfo->internal_relocs != NULL)
10966     free (flinfo->internal_relocs);
10967   if (flinfo->external_syms != NULL)
10968     free (flinfo->external_syms);
10969   if (flinfo->locsym_shndx != NULL)
10970     free (flinfo->locsym_shndx);
10971   if (flinfo->internal_syms != NULL)
10972     free (flinfo->internal_syms);
10973   if (flinfo->indices != NULL)
10974     free (flinfo->indices);
10975   if (flinfo->sections != NULL)
10976     free (flinfo->sections);
10977   if (flinfo->symshndxbuf != NULL)
10978     free (flinfo->symshndxbuf);
10979   for (o = obfd->sections; o != NULL; o = o->next)
10980     {
10981       struct bfd_elf_section_data *esdo = elf_section_data (o);
10982       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
10983         free (esdo->rel.hashes);
10984       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
10985         free (esdo->rela.hashes);
10986     }
10987 }
10988
10989 /* Do the final step of an ELF link.  */
10990
10991 bfd_boolean
10992 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
10993 {
10994   bfd_boolean dynamic;
10995   bfd_boolean emit_relocs;
10996   bfd *dynobj;
10997   struct elf_final_link_info flinfo;
10998   asection *o;
10999   struct bfd_link_order *p;
11000   bfd *sub;
11001   bfd_size_type max_contents_size;
11002   bfd_size_type max_external_reloc_size;
11003   bfd_size_type max_internal_reloc_count;
11004   bfd_size_type max_sym_count;
11005   bfd_size_type max_sym_shndx_count;
11006   Elf_Internal_Sym elfsym;
11007   unsigned int i;
11008   Elf_Internal_Shdr *symtab_hdr;
11009   Elf_Internal_Shdr *symtab_shndx_hdr;
11010   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11011   struct elf_outext_info eoinfo;
11012   bfd_boolean merged;
11013   size_t relativecount = 0;
11014   asection *reldyn = 0;
11015   bfd_size_type amt;
11016   asection *attr_section = NULL;
11017   bfd_vma attr_size = 0;
11018   const char *std_attrs_section;
11019
11020   if (! is_elf_hash_table (info->hash))
11021     return FALSE;
11022
11023   if (bfd_link_pic (info))
11024     abfd->flags |= DYNAMIC;
11025
11026   dynamic = elf_hash_table (info)->dynamic_sections_created;
11027   dynobj = elf_hash_table (info)->dynobj;
11028
11029   emit_relocs = (bfd_link_relocatable (info)
11030                  || info->emitrelocations);
11031
11032   flinfo.info = info;
11033   flinfo.output_bfd = abfd;
11034   flinfo.symstrtab = _bfd_elf_strtab_init ();
11035   if (flinfo.symstrtab == NULL)
11036     return FALSE;
11037
11038   if (! dynamic)
11039     {
11040       flinfo.hash_sec = NULL;
11041       flinfo.symver_sec = NULL;
11042     }
11043   else
11044     {
11045       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
11046       /* Note that dynsym_sec can be NULL (on VMS).  */
11047       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
11048       /* Note that it is OK if symver_sec is NULL.  */
11049     }
11050
11051   flinfo.contents = NULL;
11052   flinfo.external_relocs = NULL;
11053   flinfo.internal_relocs = NULL;
11054   flinfo.external_syms = NULL;
11055   flinfo.locsym_shndx = NULL;
11056   flinfo.internal_syms = NULL;
11057   flinfo.indices = NULL;
11058   flinfo.sections = NULL;
11059   flinfo.symshndxbuf = NULL;
11060   flinfo.filesym_count = 0;
11061
11062   /* The object attributes have been merged.  Remove the input
11063      sections from the link, and set the contents of the output
11064      secton.  */
11065   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
11066   for (o = abfd->sections; o != NULL; o = o->next)
11067     {
11068       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
11069           || strcmp (o->name, ".gnu.attributes") == 0)
11070         {
11071           for (p = o->map_head.link_order; p != NULL; p = p->next)
11072             {
11073               asection *input_section;
11074
11075               if (p->type != bfd_indirect_link_order)
11076                 continue;
11077               input_section = p->u.indirect.section;
11078               /* Hack: reset the SEC_HAS_CONTENTS flag so that
11079                  elf_link_input_bfd ignores this section.  */
11080               input_section->flags &= ~SEC_HAS_CONTENTS;
11081             }
11082
11083           attr_size = bfd_elf_obj_attr_size (abfd);
11084           if (attr_size)
11085             {
11086               bfd_set_section_size (abfd, o, attr_size);
11087               attr_section = o;
11088               /* Skip this section later on.  */
11089               o->map_head.link_order = NULL;
11090             }
11091           else
11092             o->flags |= SEC_EXCLUDE;
11093         }
11094     }
11095
11096   /* Count up the number of relocations we will output for each output
11097      section, so that we know the sizes of the reloc sections.  We
11098      also figure out some maximum sizes.  */
11099   max_contents_size = 0;
11100   max_external_reloc_size = 0;
11101   max_internal_reloc_count = 0;
11102   max_sym_count = 0;
11103   max_sym_shndx_count = 0;
11104   merged = FALSE;
11105   for (o = abfd->sections; o != NULL; o = o->next)
11106     {
11107       struct bfd_elf_section_data *esdo = elf_section_data (o);
11108       o->reloc_count = 0;
11109
11110       for (p = o->map_head.link_order; p != NULL; p = p->next)
11111         {
11112           unsigned int reloc_count = 0;
11113           unsigned int additional_reloc_count = 0;
11114           struct bfd_elf_section_data *esdi = NULL;
11115
11116           if (p->type == bfd_section_reloc_link_order
11117               || p->type == bfd_symbol_reloc_link_order)
11118             reloc_count = 1;
11119           else if (p->type == bfd_indirect_link_order)
11120             {
11121               asection *sec;
11122
11123               sec = p->u.indirect.section;
11124               esdi = elf_section_data (sec);
11125
11126               /* Mark all sections which are to be included in the
11127                  link.  This will normally be every section.  We need
11128                  to do this so that we can identify any sections which
11129                  the linker has decided to not include.  */
11130               sec->linker_mark = TRUE;
11131
11132               if (sec->flags & SEC_MERGE)
11133                 merged = TRUE;
11134
11135               if (esdo->this_hdr.sh_type == SHT_REL
11136                   || esdo->this_hdr.sh_type == SHT_RELA)
11137                 /* Some backends use reloc_count in relocation sections
11138                    to count particular types of relocs.  Of course,
11139                    reloc sections themselves can't have relocations.  */
11140                 reloc_count = 0;
11141               else if (emit_relocs)
11142                 {
11143                   reloc_count = sec->reloc_count;
11144                   if (bed->elf_backend_count_additional_relocs)
11145                     {
11146                       int c;
11147                       c = (*bed->elf_backend_count_additional_relocs) (sec);
11148                       additional_reloc_count += c;
11149                     }
11150                 }
11151               else if (bed->elf_backend_count_relocs)
11152                 reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
11153
11154               if (sec->rawsize > max_contents_size)
11155                 max_contents_size = sec->rawsize;
11156               if (sec->size > max_contents_size)
11157                 max_contents_size = sec->size;
11158
11159               /* We are interested in just local symbols, not all
11160                  symbols.  */
11161               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
11162                   && (sec->owner->flags & DYNAMIC) == 0)
11163                 {
11164                   size_t sym_count;
11165
11166                   if (elf_bad_symtab (sec->owner))
11167                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
11168                                  / bed->s->sizeof_sym);
11169                   else
11170                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
11171
11172                   if (sym_count > max_sym_count)
11173                     max_sym_count = sym_count;
11174
11175                   if (sym_count > max_sym_shndx_count
11176                       && elf_symtab_shndx_list (sec->owner) != NULL)
11177                     max_sym_shndx_count = sym_count;
11178
11179                   if ((sec->flags & SEC_RELOC) != 0)
11180                     {
11181                       size_t ext_size = 0;
11182
11183                       if (esdi->rel.hdr != NULL)
11184                         ext_size = esdi->rel.hdr->sh_size;
11185                       if (esdi->rela.hdr != NULL)
11186                         ext_size += esdi->rela.hdr->sh_size;
11187
11188                       if (ext_size > max_external_reloc_size)
11189                         max_external_reloc_size = ext_size;
11190                       if (sec->reloc_count > max_internal_reloc_count)
11191                         max_internal_reloc_count = sec->reloc_count;
11192                     }
11193                 }
11194             }
11195
11196           if (reloc_count == 0)
11197             continue;
11198
11199           reloc_count += additional_reloc_count;
11200           o->reloc_count += reloc_count;
11201
11202           if (p->type == bfd_indirect_link_order && emit_relocs)
11203             {
11204               if (esdi->rel.hdr)
11205                 {
11206                   esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11207                   esdo->rel.count += additional_reloc_count;
11208                 }
11209               if (esdi->rela.hdr)
11210                 {
11211                   esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11212                   esdo->rela.count += additional_reloc_count;
11213                 }
11214             }
11215           else
11216             {
11217               if (o->use_rela_p)
11218                 esdo->rela.count += reloc_count;
11219               else
11220                 esdo->rel.count += reloc_count;
11221             }
11222         }
11223
11224       if (o->reloc_count > 0)
11225         o->flags |= SEC_RELOC;
11226       else
11227         {
11228           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11229              set it (this is probably a bug) and if it is set
11230              assign_section_numbers will create a reloc section.  */
11231           o->flags &=~ SEC_RELOC;
11232         }
11233
11234       /* If the SEC_ALLOC flag is not set, force the section VMA to
11235          zero.  This is done in elf_fake_sections as well, but forcing
11236          the VMA to 0 here will ensure that relocs against these
11237          sections are handled correctly.  */
11238       if ((o->flags & SEC_ALLOC) == 0
11239           && ! o->user_set_vma)
11240         o->vma = 0;
11241     }
11242
11243   if (! bfd_link_relocatable (info) && merged)
11244     elf_link_hash_traverse (elf_hash_table (info),
11245                             _bfd_elf_link_sec_merge_syms, abfd);
11246
11247   /* Figure out the file positions for everything but the symbol table
11248      and the relocs.  We set symcount to force assign_section_numbers
11249      to create a symbol table.  */
11250   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11251   BFD_ASSERT (! abfd->output_has_begun);
11252   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11253     goto error_return;
11254
11255   /* Set sizes, and assign file positions for reloc sections.  */
11256   for (o = abfd->sections; o != NULL; o = o->next)
11257     {
11258       struct bfd_elf_section_data *esdo = elf_section_data (o);
11259       if ((o->flags & SEC_RELOC) != 0)
11260         {
11261           if (esdo->rel.hdr
11262               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11263             goto error_return;
11264
11265           if (esdo->rela.hdr
11266               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11267             goto error_return;
11268         }
11269
11270       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
11271          to count upwards while actually outputting the relocations.  */
11272       esdo->rel.count = 0;
11273       esdo->rela.count = 0;
11274
11275       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
11276         {
11277           /* Cache the section contents so that they can be compressed
11278              later.  Use bfd_malloc since it will be freed by
11279              bfd_compress_section_contents.  */
11280           unsigned char *contents = esdo->this_hdr.contents;
11281           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
11282             abort ();
11283           contents
11284             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
11285           if (contents == NULL)
11286             goto error_return;
11287           esdo->this_hdr.contents = contents;
11288         }
11289     }
11290
11291   /* We have now assigned file positions for all the sections except
11292      .symtab, .strtab, and non-loaded reloc sections.  We start the
11293      .symtab section at the current file position, and write directly
11294      to it.  We build the .strtab section in memory.  */
11295   bfd_get_symcount (abfd) = 0;
11296   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11297   /* sh_name is set in prep_headers.  */
11298   symtab_hdr->sh_type = SHT_SYMTAB;
11299   /* sh_flags, sh_addr and sh_size all start off zero.  */
11300   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
11301   /* sh_link is set in assign_section_numbers.  */
11302   /* sh_info is set below.  */
11303   /* sh_offset is set just below.  */
11304   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
11305
11306   if (max_sym_count < 20)
11307     max_sym_count = 20;
11308   elf_hash_table (info)->strtabsize = max_sym_count;
11309   amt = max_sym_count * sizeof (struct elf_sym_strtab);
11310   elf_hash_table (info)->strtab
11311     = (struct elf_sym_strtab *) bfd_malloc (amt);
11312   if (elf_hash_table (info)->strtab == NULL)
11313     goto error_return;
11314   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
11315   flinfo.symshndxbuf
11316     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
11317        ? (Elf_External_Sym_Shndx *) -1 : NULL);
11318
11319   if (info->strip != strip_all || emit_relocs)
11320     {
11321       file_ptr off = elf_next_file_pos (abfd);
11322
11323       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
11324
11325       /* Note that at this point elf_next_file_pos (abfd) is
11326          incorrect.  We do not yet know the size of the .symtab section.
11327          We correct next_file_pos below, after we do know the size.  */
11328
11329       /* Start writing out the symbol table.  The first symbol is always a
11330          dummy symbol.  */
11331       elfsym.st_value = 0;
11332       elfsym.st_size = 0;
11333       elfsym.st_info = 0;
11334       elfsym.st_other = 0;
11335       elfsym.st_shndx = SHN_UNDEF;
11336       elfsym.st_target_internal = 0;
11337       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
11338                                      bfd_und_section_ptr, NULL) != 1)
11339         goto error_return;
11340
11341       /* Output a symbol for each section.  We output these even if we are
11342          discarding local symbols, since they are used for relocs.  These
11343          symbols have no names.  We store the index of each one in the
11344          index field of the section, so that we can find it again when
11345          outputting relocs.  */
11346
11347       elfsym.st_size = 0;
11348       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11349       elfsym.st_other = 0;
11350       elfsym.st_value = 0;
11351       elfsym.st_target_internal = 0;
11352       for (i = 1; i < elf_numsections (abfd); i++)
11353         {
11354           o = bfd_section_from_elf_index (abfd, i);
11355           if (o != NULL)
11356             {
11357               o->target_index = bfd_get_symcount (abfd);
11358               elfsym.st_shndx = i;
11359               if (!bfd_link_relocatable (info))
11360                 elfsym.st_value = o->vma;
11361               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
11362                                              NULL) != 1)
11363                 goto error_return;
11364             }
11365         }
11366     }
11367
11368   /* Allocate some memory to hold information read in from the input
11369      files.  */
11370   if (max_contents_size != 0)
11371     {
11372       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
11373       if (flinfo.contents == NULL)
11374         goto error_return;
11375     }
11376
11377   if (max_external_reloc_size != 0)
11378     {
11379       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
11380       if (flinfo.external_relocs == NULL)
11381         goto error_return;
11382     }
11383
11384   if (max_internal_reloc_count != 0)
11385     {
11386       amt = max_internal_reloc_count * bed->s->int_rels_per_ext_rel;
11387       amt *= sizeof (Elf_Internal_Rela);
11388       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
11389       if (flinfo.internal_relocs == NULL)
11390         goto error_return;
11391     }
11392
11393   if (max_sym_count != 0)
11394     {
11395       amt = max_sym_count * bed->s->sizeof_sym;
11396       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
11397       if (flinfo.external_syms == NULL)
11398         goto error_return;
11399
11400       amt = max_sym_count * sizeof (Elf_Internal_Sym);
11401       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
11402       if (flinfo.internal_syms == NULL)
11403         goto error_return;
11404
11405       amt = max_sym_count * sizeof (long);
11406       flinfo.indices = (long int *) bfd_malloc (amt);
11407       if (flinfo.indices == NULL)
11408         goto error_return;
11409
11410       amt = max_sym_count * sizeof (asection *);
11411       flinfo.sections = (asection **) bfd_malloc (amt);
11412       if (flinfo.sections == NULL)
11413         goto error_return;
11414     }
11415
11416   if (max_sym_shndx_count != 0)
11417     {
11418       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
11419       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
11420       if (flinfo.locsym_shndx == NULL)
11421         goto error_return;
11422     }
11423
11424   if (elf_hash_table (info)->tls_sec)
11425     {
11426       bfd_vma base, end = 0;
11427       asection *sec;
11428
11429       for (sec = elf_hash_table (info)->tls_sec;
11430            sec && (sec->flags & SEC_THREAD_LOCAL);
11431            sec = sec->next)
11432         {
11433           bfd_size_type size = sec->size;
11434
11435           if (size == 0
11436               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11437             {
11438               struct bfd_link_order *ord = sec->map_tail.link_order;
11439
11440               if (ord != NULL)
11441                 size = ord->offset + ord->size;
11442             }
11443           end = sec->vma + size;
11444         }
11445       base = elf_hash_table (info)->tls_sec->vma;
11446       /* Only align end of TLS section if static TLS doesn't have special
11447          alignment requirements.  */
11448       if (bed->static_tls_alignment == 1)
11449         end = align_power (end,
11450                            elf_hash_table (info)->tls_sec->alignment_power);
11451       elf_hash_table (info)->tls_size = end - base;
11452     }
11453
11454   /* Reorder SHF_LINK_ORDER sections.  */
11455   for (o = abfd->sections; o != NULL; o = o->next)
11456     {
11457       if (!elf_fixup_link_order (abfd, o))
11458         return FALSE;
11459     }
11460
11461   if (!_bfd_elf_fixup_eh_frame_hdr (info))
11462     return FALSE;
11463
11464   /* Since ELF permits relocations to be against local symbols, we
11465      must have the local symbols available when we do the relocations.
11466      Since we would rather only read the local symbols once, and we
11467      would rather not keep them in memory, we handle all the
11468      relocations for a single input file at the same time.
11469
11470      Unfortunately, there is no way to know the total number of local
11471      symbols until we have seen all of them, and the local symbol
11472      indices precede the global symbol indices.  This means that when
11473      we are generating relocatable output, and we see a reloc against
11474      a global symbol, we can not know the symbol index until we have
11475      finished examining all the local symbols to see which ones we are
11476      going to output.  To deal with this, we keep the relocations in
11477      memory, and don't output them until the end of the link.  This is
11478      an unfortunate waste of memory, but I don't see a good way around
11479      it.  Fortunately, it only happens when performing a relocatable
11480      link, which is not the common case.  FIXME: If keep_memory is set
11481      we could write the relocs out and then read them again; I don't
11482      know how bad the memory loss will be.  */
11483
11484   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11485     sub->output_has_begun = FALSE;
11486   for (o = abfd->sections; o != NULL; o = o->next)
11487     {
11488       for (p = o->map_head.link_order; p != NULL; p = p->next)
11489         {
11490           if (p->type == bfd_indirect_link_order
11491               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
11492                   == bfd_target_elf_flavour)
11493               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
11494             {
11495               if (! sub->output_has_begun)
11496                 {
11497                   if (! elf_link_input_bfd (&flinfo, sub))
11498                     goto error_return;
11499                   sub->output_has_begun = TRUE;
11500                 }
11501             }
11502           else if (p->type == bfd_section_reloc_link_order
11503                    || p->type == bfd_symbol_reloc_link_order)
11504             {
11505               if (! elf_reloc_link_order (abfd, info, o, p))
11506                 goto error_return;
11507             }
11508           else
11509             {
11510               if (! _bfd_default_link_order (abfd, info, o, p))
11511                 {
11512                   if (p->type == bfd_indirect_link_order
11513                       && (bfd_get_flavour (sub)
11514                           == bfd_target_elf_flavour)
11515                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
11516                           != bed->s->elfclass))
11517                     {
11518                       const char *iclass, *oclass;
11519
11520                       switch (bed->s->elfclass)
11521                         {
11522                         case ELFCLASS64: oclass = "ELFCLASS64"; break;
11523                         case ELFCLASS32: oclass = "ELFCLASS32"; break;
11524                         case ELFCLASSNONE: oclass = "ELFCLASSNONE"; break;
11525                         default: abort ();
11526                         }
11527
11528                       switch (elf_elfheader (sub)->e_ident[EI_CLASS])
11529                         {
11530                         case ELFCLASS64: iclass = "ELFCLASS64"; break;
11531                         case ELFCLASS32: iclass = "ELFCLASS32"; break;
11532                         case ELFCLASSNONE: iclass = "ELFCLASSNONE"; break;
11533                         default: abort ();
11534                         }
11535
11536                       bfd_set_error (bfd_error_wrong_format);
11537                       (*_bfd_error_handler)
11538                         (_("%B: file class %s incompatible with %s"),
11539                          sub, iclass, oclass);
11540                     }
11541
11542                   goto error_return;
11543                 }
11544             }
11545         }
11546     }
11547
11548   /* Free symbol buffer if needed.  */
11549   if (!info->reduce_memory_overheads)
11550     {
11551       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11552         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11553             && elf_tdata (sub)->symbuf)
11554           {
11555             free (elf_tdata (sub)->symbuf);
11556             elf_tdata (sub)->symbuf = NULL;
11557           }
11558     }
11559
11560   /* Output any global symbols that got converted to local in a
11561      version script or due to symbol visibility.  We do this in a
11562      separate step since ELF requires all local symbols to appear
11563      prior to any global symbols.  FIXME: We should only do this if
11564      some global symbols were, in fact, converted to become local.
11565      FIXME: Will this work correctly with the Irix 5 linker?  */
11566   eoinfo.failed = FALSE;
11567   eoinfo.flinfo = &flinfo;
11568   eoinfo.localsyms = TRUE;
11569   eoinfo.file_sym_done = FALSE;
11570   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11571   if (eoinfo.failed)
11572     return FALSE;
11573
11574   /* If backend needs to output some local symbols not present in the hash
11575      table, do it now.  */
11576   if (bed->elf_backend_output_arch_local_syms
11577       && (info->strip != strip_all || emit_relocs))
11578     {
11579       typedef int (*out_sym_func)
11580         (void *, const char *, Elf_Internal_Sym *, asection *,
11581          struct elf_link_hash_entry *);
11582
11583       if (! ((*bed->elf_backend_output_arch_local_syms)
11584              (abfd, info, &flinfo,
11585               (out_sym_func) elf_link_output_symstrtab)))
11586         return FALSE;
11587     }
11588
11589   /* That wrote out all the local symbols.  Finish up the symbol table
11590      with the global symbols. Even if we want to strip everything we
11591      can, we still need to deal with those global symbols that got
11592      converted to local in a version script.  */
11593
11594   /* The sh_info field records the index of the first non local symbol.  */
11595   symtab_hdr->sh_info = bfd_get_symcount (abfd);
11596
11597   if (dynamic
11598       && elf_hash_table (info)->dynsym != NULL
11599       && (elf_hash_table (info)->dynsym->output_section
11600           != bfd_abs_section_ptr))
11601     {
11602       Elf_Internal_Sym sym;
11603       bfd_byte *dynsym = elf_hash_table (info)->dynsym->contents;
11604       long last_local = 0;
11605
11606       /* Write out the section symbols for the output sections.  */
11607       if (bfd_link_pic (info)
11608           || elf_hash_table (info)->is_relocatable_executable)
11609         {
11610           asection *s;
11611
11612           sym.st_size = 0;
11613           sym.st_name = 0;
11614           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11615           sym.st_other = 0;
11616           sym.st_target_internal = 0;
11617
11618           for (s = abfd->sections; s != NULL; s = s->next)
11619             {
11620               int indx;
11621               bfd_byte *dest;
11622               long dynindx;
11623
11624               dynindx = elf_section_data (s)->dynindx;
11625               if (dynindx <= 0)
11626                 continue;
11627               indx = elf_section_data (s)->this_idx;
11628               BFD_ASSERT (indx > 0);
11629               sym.st_shndx = indx;
11630               if (! check_dynsym (abfd, &sym))
11631                 return FALSE;
11632               sym.st_value = s->vma;
11633               dest = dynsym + dynindx * bed->s->sizeof_sym;
11634               if (last_local < dynindx)
11635                 last_local = dynindx;
11636               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11637             }
11638         }
11639
11640       /* Write out the local dynsyms.  */
11641       if (elf_hash_table (info)->dynlocal)
11642         {
11643           struct elf_link_local_dynamic_entry *e;
11644           for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
11645             {
11646               asection *s;
11647               bfd_byte *dest;
11648
11649               /* Copy the internal symbol and turn off visibility.
11650                  Note that we saved a word of storage and overwrote
11651                  the original st_name with the dynstr_index.  */
11652               sym = e->isym;
11653               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
11654
11655               s = bfd_section_from_elf_index (e->input_bfd,
11656                                               e->isym.st_shndx);
11657               if (s != NULL)
11658                 {
11659                   sym.st_shndx =
11660                     elf_section_data (s->output_section)->this_idx;
11661                   if (! check_dynsym (abfd, &sym))
11662                     return FALSE;
11663                   sym.st_value = (s->output_section->vma
11664                                   + s->output_offset
11665                                   + e->isym.st_value);
11666                 }
11667
11668               if (last_local < e->dynindx)
11669                 last_local = e->dynindx;
11670
11671               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
11672               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11673             }
11674         }
11675
11676       elf_section_data (elf_hash_table (info)->dynsym->output_section)->this_hdr.sh_info =
11677         last_local + 1;
11678     }
11679
11680   /* We get the global symbols from the hash table.  */
11681   eoinfo.failed = FALSE;
11682   eoinfo.localsyms = FALSE;
11683   eoinfo.flinfo = &flinfo;
11684   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11685   if (eoinfo.failed)
11686     return FALSE;
11687
11688   /* If backend needs to output some symbols not present in the hash
11689      table, do it now.  */
11690   if (bed->elf_backend_output_arch_syms
11691       && (info->strip != strip_all || emit_relocs))
11692     {
11693       typedef int (*out_sym_func)
11694         (void *, const char *, Elf_Internal_Sym *, asection *,
11695          struct elf_link_hash_entry *);
11696
11697       if (! ((*bed->elf_backend_output_arch_syms)
11698              (abfd, info, &flinfo,
11699               (out_sym_func) elf_link_output_symstrtab)))
11700         return FALSE;
11701     }
11702
11703   /* Finalize the .strtab section.  */
11704   _bfd_elf_strtab_finalize (flinfo.symstrtab);
11705
11706   /* Swap out the .strtab section. */
11707   if (!elf_link_swap_symbols_out (&flinfo))
11708     return FALSE;
11709
11710   /* Now we know the size of the symtab section.  */
11711   if (bfd_get_symcount (abfd) > 0)
11712     {
11713       /* Finish up and write out the symbol string table (.strtab)
11714          section.  */
11715       Elf_Internal_Shdr *symstrtab_hdr;
11716       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
11717
11718       symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
11719       if (symtab_shndx_hdr != NULL && symtab_shndx_hdr->sh_name != 0)
11720         {
11721           symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
11722           symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
11723           symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
11724           amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
11725           symtab_shndx_hdr->sh_size = amt;
11726
11727           off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
11728                                                            off, TRUE);
11729
11730           if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
11731               || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
11732             return FALSE;
11733         }
11734
11735       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
11736       /* sh_name was set in prep_headers.  */
11737       symstrtab_hdr->sh_type = SHT_STRTAB;
11738       symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
11739       symstrtab_hdr->sh_addr = 0;
11740       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
11741       symstrtab_hdr->sh_entsize = 0;
11742       symstrtab_hdr->sh_link = 0;
11743       symstrtab_hdr->sh_info = 0;
11744       /* sh_offset is set just below.  */
11745       symstrtab_hdr->sh_addralign = 1;
11746
11747       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
11748                                                        off, TRUE);
11749       elf_next_file_pos (abfd) = off;
11750
11751       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
11752           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
11753         return FALSE;
11754     }
11755
11756   /* Adjust the relocs to have the correct symbol indices.  */
11757   for (o = abfd->sections; o != NULL; o = o->next)
11758     {
11759       struct bfd_elf_section_data *esdo = elf_section_data (o);
11760       bfd_boolean sort;
11761       if ((o->flags & SEC_RELOC) == 0)
11762         continue;
11763
11764       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
11765       if (esdo->rel.hdr != NULL
11766           && !elf_link_adjust_relocs (abfd, &esdo->rel, sort))
11767         return FALSE;
11768       if (esdo->rela.hdr != NULL
11769           && !elf_link_adjust_relocs (abfd, &esdo->rela, sort))
11770         return FALSE;
11771
11772       /* Set the reloc_count field to 0 to prevent write_relocs from
11773          trying to swap the relocs out itself.  */
11774       o->reloc_count = 0;
11775     }
11776
11777   if (dynamic && info->combreloc && dynobj != NULL)
11778     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
11779
11780   /* If we are linking against a dynamic object, or generating a
11781      shared library, finish up the dynamic linking information.  */
11782   if (dynamic)
11783     {
11784       bfd_byte *dyncon, *dynconend;
11785
11786       /* Fix up .dynamic entries.  */
11787       o = bfd_get_linker_section (dynobj, ".dynamic");
11788       BFD_ASSERT (o != NULL);
11789
11790       dyncon = o->contents;
11791       dynconend = o->contents + o->size;
11792       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11793         {
11794           Elf_Internal_Dyn dyn;
11795           const char *name;
11796           unsigned int type;
11797
11798           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11799
11800           switch (dyn.d_tag)
11801             {
11802             default:
11803               continue;
11804             case DT_NULL:
11805               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
11806                 {
11807                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
11808                     {
11809                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
11810                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
11811                     default: continue;
11812                     }
11813                   dyn.d_un.d_val = relativecount;
11814                   relativecount = 0;
11815                   break;
11816                 }
11817               continue;
11818
11819             case DT_INIT:
11820               name = info->init_function;
11821               goto get_sym;
11822             case DT_FINI:
11823               name = info->fini_function;
11824             get_sym:
11825               {
11826                 struct elf_link_hash_entry *h;
11827
11828                 h = elf_link_hash_lookup (elf_hash_table (info), name,
11829                                           FALSE, FALSE, TRUE);
11830                 if (h != NULL
11831                     && (h->root.type == bfd_link_hash_defined
11832                         || h->root.type == bfd_link_hash_defweak))
11833                   {
11834                     dyn.d_un.d_ptr = h->root.u.def.value;
11835                     o = h->root.u.def.section;
11836                     if (o->output_section != NULL)
11837                       dyn.d_un.d_ptr += (o->output_section->vma
11838                                          + o->output_offset);
11839                     else
11840                       {
11841                         /* The symbol is imported from another shared
11842                            library and does not apply to this one.  */
11843                         dyn.d_un.d_ptr = 0;
11844                       }
11845                     break;
11846                   }
11847               }
11848               continue;
11849
11850             case DT_PREINIT_ARRAYSZ:
11851               name = ".preinit_array";
11852               goto get_size;
11853             case DT_INIT_ARRAYSZ:
11854               name = ".init_array";
11855               goto get_size;
11856             case DT_FINI_ARRAYSZ:
11857               name = ".fini_array";
11858             get_size:
11859               o = bfd_get_section_by_name (abfd, name);
11860               if (o == NULL)
11861                 {
11862                   (*_bfd_error_handler)
11863                     (_("%B: could not find output section %s"), abfd, name);
11864                   goto error_return;
11865                 }
11866               if (o->size == 0)
11867                 (*_bfd_error_handler)
11868                   (_("warning: %s section has zero size"), name);
11869               dyn.d_un.d_val = o->size;
11870               break;
11871
11872             case DT_PREINIT_ARRAY:
11873               name = ".preinit_array";
11874               goto get_vma;
11875             case DT_INIT_ARRAY:
11876               name = ".init_array";
11877               goto get_vma;
11878             case DT_FINI_ARRAY:
11879               name = ".fini_array";
11880               goto get_vma;
11881
11882             case DT_HASH:
11883               name = ".hash";
11884               goto get_vma;
11885             case DT_GNU_HASH:
11886               name = ".gnu.hash";
11887               goto get_vma;
11888             case DT_STRTAB:
11889               name = ".dynstr";
11890               goto get_vma;
11891             case DT_SYMTAB:
11892               name = ".dynsym";
11893               goto get_vma;
11894             case DT_VERDEF:
11895               name = ".gnu.version_d";
11896               goto get_vma;
11897             case DT_VERNEED:
11898               name = ".gnu.version_r";
11899               goto get_vma;
11900             case DT_VERSYM:
11901               name = ".gnu.version";
11902             get_vma:
11903               o = bfd_get_section_by_name (abfd, name);
11904               if (o == NULL)
11905                 {
11906                   (*_bfd_error_handler)
11907                     (_("%B: could not find output section %s"), abfd, name);
11908                   goto error_return;
11909                 }
11910               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
11911                 {
11912                   (*_bfd_error_handler)
11913                     (_("warning: section '%s' is being made into a note"), name);
11914                   bfd_set_error (bfd_error_nonrepresentable_section);
11915                   goto error_return;
11916                 }
11917               dyn.d_un.d_ptr = o->vma;
11918               break;
11919
11920             case DT_REL:
11921             case DT_RELA:
11922             case DT_RELSZ:
11923             case DT_RELASZ:
11924               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
11925                 type = SHT_REL;
11926               else
11927                 type = SHT_RELA;
11928               dyn.d_un.d_val = 0;
11929               dyn.d_un.d_ptr = 0;
11930               for (i = 1; i < elf_numsections (abfd); i++)
11931                 {
11932                   Elf_Internal_Shdr *hdr;
11933
11934                   hdr = elf_elfsections (abfd)[i];
11935                   if (hdr->sh_type == type
11936                       && (hdr->sh_flags & SHF_ALLOC) != 0)
11937                     {
11938                       if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
11939                         dyn.d_un.d_val += hdr->sh_size;
11940                       else
11941                         {
11942                           if (dyn.d_un.d_ptr == 0
11943                               || hdr->sh_addr < dyn.d_un.d_ptr)
11944                             dyn.d_un.d_ptr = hdr->sh_addr;
11945                         }
11946                     }
11947                 }
11948               break;
11949             }
11950           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
11951         }
11952     }
11953
11954   /* If we have created any dynamic sections, then output them.  */
11955   if (dynobj != NULL)
11956     {
11957       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
11958         goto error_return;
11959
11960       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
11961       if (((info->warn_shared_textrel && bfd_link_pic (info))
11962            || info->error_textrel)
11963           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
11964         {
11965           bfd_byte *dyncon, *dynconend;
11966
11967           dyncon = o->contents;
11968           dynconend = o->contents + o->size;
11969           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
11970             {
11971               Elf_Internal_Dyn dyn;
11972
11973               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
11974
11975               if (dyn.d_tag == DT_TEXTREL)
11976                 {
11977                   if (info->error_textrel)
11978                     info->callbacks->einfo
11979                       (_("%P%X: read-only segment has dynamic relocations.\n"));
11980                   else
11981                     info->callbacks->einfo
11982                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
11983                   break;
11984                 }
11985             }
11986         }
11987
11988       for (o = dynobj->sections; o != NULL; o = o->next)
11989         {
11990           if ((o->flags & SEC_HAS_CONTENTS) == 0
11991               || o->size == 0
11992               || o->output_section == bfd_abs_section_ptr)
11993             continue;
11994           if ((o->flags & SEC_LINKER_CREATED) == 0)
11995             {
11996               /* At this point, we are only interested in sections
11997                  created by _bfd_elf_link_create_dynamic_sections.  */
11998               continue;
11999             }
12000           if (elf_hash_table (info)->stab_info.stabstr == o)
12001             continue;
12002           if (elf_hash_table (info)->eh_info.hdr_sec == o)
12003             continue;
12004           if (strcmp (o->name, ".dynstr") != 0)
12005             {
12006               if (! bfd_set_section_contents (abfd, o->output_section,
12007                                               o->contents,
12008                                               (file_ptr) o->output_offset
12009                                               * bfd_octets_per_byte (abfd),
12010                                               o->size))
12011                 goto error_return;
12012             }
12013           else
12014             {
12015               /* The contents of the .dynstr section are actually in a
12016                  stringtab.  */
12017               file_ptr off;
12018
12019               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
12020               if (bfd_seek (abfd, off, SEEK_SET) != 0
12021                   || ! _bfd_elf_strtab_emit (abfd,
12022                                              elf_hash_table (info)->dynstr))
12023                 goto error_return;
12024             }
12025         }
12026     }
12027
12028   if (bfd_link_relocatable (info))
12029     {
12030       bfd_boolean failed = FALSE;
12031
12032       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
12033       if (failed)
12034         goto error_return;
12035     }
12036
12037   /* If we have optimized stabs strings, output them.  */
12038   if (elf_hash_table (info)->stab_info.stabstr != NULL)
12039     {
12040       if (! _bfd_write_stab_strings (abfd, &elf_hash_table (info)->stab_info))
12041         goto error_return;
12042     }
12043
12044   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
12045     goto error_return;
12046
12047   elf_final_link_free (abfd, &flinfo);
12048
12049   elf_linker (abfd) = TRUE;
12050
12051   if (attr_section)
12052     {
12053       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
12054       if (contents == NULL)
12055         return FALSE;   /* Bail out and fail.  */
12056       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
12057       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
12058       free (contents);
12059     }
12060
12061   return TRUE;
12062
12063  error_return:
12064   elf_final_link_free (abfd, &flinfo);
12065   return FALSE;
12066 }
12067 \f
12068 /* Initialize COOKIE for input bfd ABFD.  */
12069
12070 static bfd_boolean
12071 init_reloc_cookie (struct elf_reloc_cookie *cookie,
12072                    struct bfd_link_info *info, bfd *abfd)
12073 {
12074   Elf_Internal_Shdr *symtab_hdr;
12075   const struct elf_backend_data *bed;
12076
12077   bed = get_elf_backend_data (abfd);
12078   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12079
12080   cookie->abfd = abfd;
12081   cookie->sym_hashes = elf_sym_hashes (abfd);
12082   cookie->bad_symtab = elf_bad_symtab (abfd);
12083   if (cookie->bad_symtab)
12084     {
12085       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12086       cookie->extsymoff = 0;
12087     }
12088   else
12089     {
12090       cookie->locsymcount = symtab_hdr->sh_info;
12091       cookie->extsymoff = symtab_hdr->sh_info;
12092     }
12093
12094   if (bed->s->arch_size == 32)
12095     cookie->r_sym_shift = 8;
12096   else
12097     cookie->r_sym_shift = 32;
12098
12099   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
12100   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
12101     {
12102       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12103                                               cookie->locsymcount, 0,
12104                                               NULL, NULL, NULL);
12105       if (cookie->locsyms == NULL)
12106         {
12107           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
12108           return FALSE;
12109         }
12110       if (info->keep_memory)
12111         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
12112     }
12113   return TRUE;
12114 }
12115
12116 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
12117
12118 static void
12119 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
12120 {
12121   Elf_Internal_Shdr *symtab_hdr;
12122
12123   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12124   if (cookie->locsyms != NULL
12125       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
12126     free (cookie->locsyms);
12127 }
12128
12129 /* Initialize the relocation information in COOKIE for input section SEC
12130    of input bfd ABFD.  */
12131
12132 static bfd_boolean
12133 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12134                         struct bfd_link_info *info, bfd *abfd,
12135                         asection *sec)
12136 {
12137   const struct elf_backend_data *bed;
12138
12139   if (sec->reloc_count == 0)
12140     {
12141       cookie->rels = NULL;
12142       cookie->relend = NULL;
12143     }
12144   else
12145     {
12146       bed = get_elf_backend_data (abfd);
12147
12148       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
12149                                                 info->keep_memory);
12150       if (cookie->rels == NULL)
12151         return FALSE;
12152       cookie->rel = cookie->rels;
12153       cookie->relend = (cookie->rels
12154                         + sec->reloc_count * bed->s->int_rels_per_ext_rel);
12155     }
12156   cookie->rel = cookie->rels;
12157   return TRUE;
12158 }
12159
12160 /* Free the memory allocated by init_reloc_cookie_rels,
12161    if appropriate.  */
12162
12163 static void
12164 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12165                         asection *sec)
12166 {
12167   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
12168     free (cookie->rels);
12169 }
12170
12171 /* Initialize the whole of COOKIE for input section SEC.  */
12172
12173 static bfd_boolean
12174 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12175                                struct bfd_link_info *info,
12176                                asection *sec)
12177 {
12178   if (!init_reloc_cookie (cookie, info, sec->owner))
12179     goto error1;
12180   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
12181     goto error2;
12182   return TRUE;
12183
12184  error2:
12185   fini_reloc_cookie (cookie, sec->owner);
12186  error1:
12187   return FALSE;
12188 }
12189
12190 /* Free the memory allocated by init_reloc_cookie_for_section,
12191    if appropriate.  */
12192
12193 static void
12194 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12195                                asection *sec)
12196 {
12197   fini_reloc_cookie_rels (cookie, sec);
12198   fini_reloc_cookie (cookie, sec->owner);
12199 }
12200 \f
12201 /* Garbage collect unused sections.  */
12202
12203 /* Default gc_mark_hook.  */
12204
12205 asection *
12206 _bfd_elf_gc_mark_hook (asection *sec,
12207                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12208                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12209                        struct elf_link_hash_entry *h,
12210                        Elf_Internal_Sym *sym)
12211 {
12212   if (h != NULL)
12213     {
12214       switch (h->root.type)
12215         {
12216         case bfd_link_hash_defined:
12217         case bfd_link_hash_defweak:
12218           return h->root.u.def.section;
12219
12220         case bfd_link_hash_common:
12221           return h->root.u.c.p->section;
12222
12223         default:
12224           break;
12225         }
12226     }
12227   else
12228     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12229
12230   return NULL;
12231 }
12232
12233 /* COOKIE->rel describes a relocation against section SEC, which is
12234    a section we've decided to keep.  Return the section that contains
12235    the relocation symbol, or NULL if no section contains it.  */
12236
12237 asection *
12238 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
12239                        elf_gc_mark_hook_fn gc_mark_hook,
12240                        struct elf_reloc_cookie *cookie,
12241                        bfd_boolean *start_stop)
12242 {
12243   unsigned long r_symndx;
12244   struct elf_link_hash_entry *h;
12245
12246   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
12247   if (r_symndx == STN_UNDEF)
12248     return NULL;
12249
12250   if (r_symndx >= cookie->locsymcount
12251       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12252     {
12253       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
12254       if (h == NULL)
12255         {
12256           info->callbacks->einfo (_("%F%P: corrupt input: %B\n"),
12257                                   sec->owner);
12258           return NULL;
12259         }
12260       while (h->root.type == bfd_link_hash_indirect
12261              || h->root.type == bfd_link_hash_warning)
12262         h = (struct elf_link_hash_entry *) h->root.u.i.link;
12263       h->mark = 1;
12264       /* If this symbol is weak and there is a non-weak definition, we
12265          keep the non-weak definition because many backends put
12266          dynamic reloc info on the non-weak definition for code
12267          handling copy relocs.  */
12268       if (h->u.weakdef != NULL)
12269         h->u.weakdef->mark = 1;
12270
12271       if (start_stop != NULL
12272           && (h->root.type == bfd_link_hash_undefined
12273               || h->root.type == bfd_link_hash_undefweak))
12274         {
12275           /* To work around a glibc bug, mark all XXX input sections
12276              when there is an as yet undefined reference to __start_XXX
12277              or __stop_XXX symbols.  The linker will later define such
12278              symbols for orphan input sections that have a name
12279              representable as a C identifier.  */
12280           const char *sec_name = NULL;
12281           if (strncmp (h->root.root.string, "__start_", 8) == 0)
12282             sec_name = h->root.root.string + 8;
12283           else if (strncmp (h->root.root.string, "__stop_", 7) == 0)
12284             sec_name = h->root.root.string + 7;
12285
12286           if (sec_name != NULL && *sec_name != '\0')
12287             {
12288               bfd *i;
12289
12290               for (i = info->input_bfds; i != NULL; i = i->link.next)
12291                 {
12292                   asection *s = bfd_get_section_by_name (i, sec_name);
12293                   if (s != NULL && !s->gc_mark)
12294                     {
12295                       *start_stop = TRUE;
12296                       return s;
12297                     }
12298                 }
12299             }
12300         }
12301
12302       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
12303     }
12304
12305   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
12306                           &cookie->locsyms[r_symndx]);
12307 }
12308
12309 /* COOKIE->rel describes a relocation against section SEC, which is
12310    a section we've decided to keep.  Mark the section that contains
12311    the relocation symbol.  */
12312
12313 bfd_boolean
12314 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
12315                         asection *sec,
12316                         elf_gc_mark_hook_fn gc_mark_hook,
12317                         struct elf_reloc_cookie *cookie)
12318 {
12319   asection *rsec;
12320   bfd_boolean start_stop = FALSE;
12321
12322   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie, &start_stop);
12323   while (rsec != NULL)
12324     {
12325       if (!rsec->gc_mark)
12326         {
12327           if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
12328               || (rsec->owner->flags & DYNAMIC) != 0)
12329             rsec->gc_mark = 1;
12330           else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
12331             return FALSE;
12332         }
12333       if (!start_stop)
12334         break;
12335       rsec = bfd_get_next_section_by_name (rsec->owner, rsec);
12336     }
12337   return TRUE;
12338 }
12339
12340 /* The mark phase of garbage collection.  For a given section, mark
12341    it and any sections in this section's group, and all the sections
12342    which define symbols to which it refers.  */
12343
12344 bfd_boolean
12345 _bfd_elf_gc_mark (struct bfd_link_info *info,
12346                   asection *sec,
12347                   elf_gc_mark_hook_fn gc_mark_hook)
12348 {
12349   bfd_boolean ret;
12350   asection *group_sec, *eh_frame;
12351
12352   sec->gc_mark = 1;
12353
12354   /* Mark all the sections in the group.  */
12355   group_sec = elf_section_data (sec)->next_in_group;
12356   if (group_sec && !group_sec->gc_mark)
12357     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
12358       return FALSE;
12359
12360   /* Look through the section relocs.  */
12361   ret = TRUE;
12362   eh_frame = elf_eh_frame_section (sec->owner);
12363   if ((sec->flags & SEC_RELOC) != 0
12364       && sec->reloc_count > 0
12365       && sec != eh_frame)
12366     {
12367       struct elf_reloc_cookie cookie;
12368
12369       if (!init_reloc_cookie_for_section (&cookie, info, sec))
12370         ret = FALSE;
12371       else
12372         {
12373           for (; cookie.rel < cookie.relend; cookie.rel++)
12374             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
12375               {
12376                 ret = FALSE;
12377                 break;
12378               }
12379           fini_reloc_cookie_for_section (&cookie, sec);
12380         }
12381     }
12382
12383   if (ret && eh_frame && elf_fde_list (sec))
12384     {
12385       struct elf_reloc_cookie cookie;
12386
12387       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
12388         ret = FALSE;
12389       else
12390         {
12391           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
12392                                       gc_mark_hook, &cookie))
12393             ret = FALSE;
12394           fini_reloc_cookie_for_section (&cookie, eh_frame);
12395         }
12396     }
12397
12398   eh_frame = elf_section_eh_frame_entry (sec);
12399   if (ret && eh_frame && !eh_frame->gc_mark)
12400     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
12401       ret = FALSE;
12402
12403   return ret;
12404 }
12405
12406 /* Scan and mark sections in a special or debug section group.  */
12407
12408 static void
12409 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
12410 {
12411   /* Point to first section of section group.  */
12412   asection *ssec;
12413   /* Used to iterate the section group.  */
12414   asection *msec;
12415
12416   bfd_boolean is_special_grp = TRUE;
12417   bfd_boolean is_debug_grp = TRUE;
12418
12419   /* First scan to see if group contains any section other than debug
12420      and special section.  */
12421   ssec = msec = elf_next_in_group (grp);
12422   do
12423     {
12424       if ((msec->flags & SEC_DEBUGGING) == 0)
12425         is_debug_grp = FALSE;
12426
12427       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
12428         is_special_grp = FALSE;
12429
12430       msec = elf_next_in_group (msec);
12431     }
12432   while (msec != ssec);
12433
12434   /* If this is a pure debug section group or pure special section group,
12435      keep all sections in this group.  */
12436   if (is_debug_grp || is_special_grp)
12437     {
12438       do
12439         {
12440           msec->gc_mark = 1;
12441           msec = elf_next_in_group (msec);
12442         }
12443       while (msec != ssec);
12444     }
12445 }
12446
12447 /* Keep debug and special sections.  */
12448
12449 bfd_boolean
12450 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
12451                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
12452 {
12453   bfd *ibfd;
12454
12455   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
12456     {
12457       asection *isec;
12458       bfd_boolean some_kept;
12459       bfd_boolean debug_frag_seen;
12460
12461       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
12462         continue;
12463
12464       /* Ensure all linker created sections are kept,
12465          see if any other section is already marked,
12466          and note if we have any fragmented debug sections.  */
12467       debug_frag_seen = some_kept = FALSE;
12468       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12469         {
12470           if ((isec->flags & SEC_LINKER_CREATED) != 0)
12471             isec->gc_mark = 1;
12472           else if (isec->gc_mark)
12473             some_kept = TRUE;
12474
12475           if (debug_frag_seen == FALSE
12476               && (isec->flags & SEC_DEBUGGING)
12477               && CONST_STRNEQ (isec->name, ".debug_line."))
12478             debug_frag_seen = TRUE;
12479         }
12480
12481       /* If no section in this file will be kept, then we can
12482          toss out the debug and special sections.  */
12483       if (!some_kept)
12484         continue;
12485
12486       /* Keep debug and special sections like .comment when they are
12487          not part of a group.  Also keep section groups that contain
12488          just debug sections or special sections.  */
12489       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12490         {
12491           if ((isec->flags & SEC_GROUP) != 0)
12492             _bfd_elf_gc_mark_debug_special_section_group (isec);
12493           else if (((isec->flags & SEC_DEBUGGING) != 0
12494                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
12495                    && elf_next_in_group (isec) == NULL)
12496             isec->gc_mark = 1;
12497         }
12498
12499       if (! debug_frag_seen)
12500         continue;
12501
12502       /* Look for CODE sections which are going to be discarded,
12503          and find and discard any fragmented debug sections which
12504          are associated with that code section.  */
12505       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12506         if ((isec->flags & SEC_CODE) != 0
12507             && isec->gc_mark == 0)
12508           {
12509             unsigned int ilen;
12510             asection *dsec;
12511
12512             ilen = strlen (isec->name);
12513
12514             /* Association is determined by the name of the debug section
12515                containing the name of the code section as a suffix.  For
12516                example .debug_line.text.foo is a debug section associated
12517                with .text.foo.  */
12518             for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
12519               {
12520                 unsigned int dlen;
12521
12522                 if (dsec->gc_mark == 0
12523                     || (dsec->flags & SEC_DEBUGGING) == 0)
12524                   continue;
12525
12526                 dlen = strlen (dsec->name);
12527
12528                 if (dlen > ilen
12529                     && strncmp (dsec->name + (dlen - ilen),
12530                                 isec->name, ilen) == 0)
12531                   {
12532                     dsec->gc_mark = 0;
12533                   }
12534               }
12535           }
12536     }
12537   return TRUE;
12538 }
12539
12540 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
12541
12542 struct elf_gc_sweep_symbol_info
12543 {
12544   struct bfd_link_info *info;
12545   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
12546                        bfd_boolean);
12547 };
12548
12549 static bfd_boolean
12550 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
12551 {
12552   if (!h->mark
12553       && (((h->root.type == bfd_link_hash_defined
12554             || h->root.type == bfd_link_hash_defweak)
12555            && !((h->def_regular || ELF_COMMON_DEF_P (h))
12556                 && h->root.u.def.section->gc_mark))
12557           || h->root.type == bfd_link_hash_undefined
12558           || h->root.type == bfd_link_hash_undefweak))
12559     {
12560       struct elf_gc_sweep_symbol_info *inf;
12561
12562       inf = (struct elf_gc_sweep_symbol_info *) data;
12563       (*inf->hide_symbol) (inf->info, h, TRUE);
12564       h->def_regular = 0;
12565       h->ref_regular = 0;
12566       h->ref_regular_nonweak = 0;
12567     }
12568
12569   return TRUE;
12570 }
12571
12572 /* The sweep phase of garbage collection.  Remove all garbage sections.  */
12573
12574 typedef bfd_boolean (*gc_sweep_hook_fn)
12575   (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
12576
12577 static bfd_boolean
12578 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
12579 {
12580   bfd *sub;
12581   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12582   gc_sweep_hook_fn gc_sweep_hook = bed->gc_sweep_hook;
12583   unsigned long section_sym_count;
12584   struct elf_gc_sweep_symbol_info sweep_info;
12585
12586   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12587     {
12588       asection *o;
12589
12590       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
12591           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
12592         continue;
12593
12594       for (o = sub->sections; o != NULL; o = o->next)
12595         {
12596           /* When any section in a section group is kept, we keep all
12597              sections in the section group.  If the first member of
12598              the section group is excluded, we will also exclude the
12599              group section.  */
12600           if (o->flags & SEC_GROUP)
12601             {
12602               asection *first = elf_next_in_group (o);
12603               o->gc_mark = first->gc_mark;
12604             }
12605
12606           if (o->gc_mark)
12607             continue;
12608
12609           /* Skip sweeping sections already excluded.  */
12610           if (o->flags & SEC_EXCLUDE)
12611             continue;
12612
12613           /* Since this is early in the link process, it is simple
12614              to remove a section from the output.  */
12615           o->flags |= SEC_EXCLUDE;
12616
12617           if (info->print_gc_sections && o->size != 0)
12618             _bfd_error_handler (_("Removing unused section '%s' in file '%B'"), sub, o->name);
12619
12620           /* But we also have to update some of the relocation
12621              info we collected before.  */
12622           if (gc_sweep_hook
12623               && (o->flags & SEC_RELOC) != 0
12624               && o->reloc_count != 0
12625               && !((info->strip == strip_all || info->strip == strip_debugger)
12626                    && (o->flags & SEC_DEBUGGING) != 0)
12627               && !bfd_is_abs_section (o->output_section))
12628             {
12629               Elf_Internal_Rela *internal_relocs;
12630               bfd_boolean r;
12631
12632               internal_relocs
12633                 = _bfd_elf_link_read_relocs (o->owner, o, NULL, NULL,
12634                                              info->keep_memory);
12635               if (internal_relocs == NULL)
12636                 return FALSE;
12637
12638               r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
12639
12640               if (elf_section_data (o)->relocs != internal_relocs)
12641                 free (internal_relocs);
12642
12643               if (!r)
12644                 return FALSE;
12645             }
12646         }
12647     }
12648
12649   /* Remove the symbols that were in the swept sections from the dynamic
12650      symbol table.  GCFIXME: Anyone know how to get them out of the
12651      static symbol table as well?  */
12652   sweep_info.info = info;
12653   sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
12654   elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
12655                           &sweep_info);
12656
12657   _bfd_elf_link_renumber_dynsyms (abfd, info, &section_sym_count);
12658   return TRUE;
12659 }
12660
12661 /* Propagate collected vtable information.  This is called through
12662    elf_link_hash_traverse.  */
12663
12664 static bfd_boolean
12665 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
12666 {
12667   /* Those that are not vtables.  */
12668   if (h->vtable == NULL || h->vtable->parent == NULL)
12669     return TRUE;
12670
12671   /* Those vtables that do not have parents, we cannot merge.  */
12672   if (h->vtable->parent == (struct elf_link_hash_entry *) -1)
12673     return TRUE;
12674
12675   /* If we've already been done, exit.  */
12676   if (h->vtable->used && h->vtable->used[-1])
12677     return TRUE;
12678
12679   /* Make sure the parent's table is up to date.  */
12680   elf_gc_propagate_vtable_entries_used (h->vtable->parent, okp);
12681
12682   if (h->vtable->used == NULL)
12683     {
12684       /* None of this table's entries were referenced.  Re-use the
12685          parent's table.  */
12686       h->vtable->used = h->vtable->parent->vtable->used;
12687       h->vtable->size = h->vtable->parent->vtable->size;
12688     }
12689   else
12690     {
12691       size_t n;
12692       bfd_boolean *cu, *pu;
12693
12694       /* Or the parent's entries into ours.  */
12695       cu = h->vtable->used;
12696       cu[-1] = TRUE;
12697       pu = h->vtable->parent->vtable->used;
12698       if (pu != NULL)
12699         {
12700           const struct elf_backend_data *bed;
12701           unsigned int log_file_align;
12702
12703           bed = get_elf_backend_data (h->root.u.def.section->owner);
12704           log_file_align = bed->s->log_file_align;
12705           n = h->vtable->parent->vtable->size >> log_file_align;
12706           while (n--)
12707             {
12708               if (*pu)
12709                 *cu = TRUE;
12710               pu++;
12711               cu++;
12712             }
12713         }
12714     }
12715
12716   return TRUE;
12717 }
12718
12719 static bfd_boolean
12720 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
12721 {
12722   asection *sec;
12723   bfd_vma hstart, hend;
12724   Elf_Internal_Rela *relstart, *relend, *rel;
12725   const struct elf_backend_data *bed;
12726   unsigned int log_file_align;
12727
12728   /* Take care of both those symbols that do not describe vtables as
12729      well as those that are not loaded.  */
12730   if (h->vtable == NULL || h->vtable->parent == NULL)
12731     return TRUE;
12732
12733   BFD_ASSERT (h->root.type == bfd_link_hash_defined
12734               || h->root.type == bfd_link_hash_defweak);
12735
12736   sec = h->root.u.def.section;
12737   hstart = h->root.u.def.value;
12738   hend = hstart + h->size;
12739
12740   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
12741   if (!relstart)
12742     return *(bfd_boolean *) okp = FALSE;
12743   bed = get_elf_backend_data (sec->owner);
12744   log_file_align = bed->s->log_file_align;
12745
12746   relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
12747
12748   for (rel = relstart; rel < relend; ++rel)
12749     if (rel->r_offset >= hstart && rel->r_offset < hend)
12750       {
12751         /* If the entry is in use, do nothing.  */
12752         if (h->vtable->used
12753             && (rel->r_offset - hstart) < h->vtable->size)
12754           {
12755             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
12756             if (h->vtable->used[entry])
12757               continue;
12758           }
12759         /* Otherwise, kill it.  */
12760         rel->r_offset = rel->r_info = rel->r_addend = 0;
12761       }
12762
12763   return TRUE;
12764 }
12765
12766 /* Mark sections containing dynamically referenced symbols.  When
12767    building shared libraries, we must assume that any visible symbol is
12768    referenced.  */
12769
12770 bfd_boolean
12771 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
12772 {
12773   struct bfd_link_info *info = (struct bfd_link_info *) inf;
12774   struct bfd_elf_dynamic_list *d = info->dynamic_list;
12775
12776   if ((h->root.type == bfd_link_hash_defined
12777        || h->root.type == bfd_link_hash_defweak)
12778       && (h->ref_dynamic
12779           || ((h->def_regular || ELF_COMMON_DEF_P (h))
12780               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
12781               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
12782               && (!bfd_link_executable (info)
12783                   || info->export_dynamic
12784                   || (h->dynamic
12785                       && d != NULL
12786                       && (*d->match) (&d->head, NULL, h->root.root.string)))
12787               && (h->versioned >= versioned
12788                   || !bfd_hide_sym_by_version (info->version_info,
12789                                                h->root.root.string)))))
12790     h->root.u.def.section->flags |= SEC_KEEP;
12791
12792   return TRUE;
12793 }
12794
12795 /* Keep all sections containing symbols undefined on the command-line,
12796    and the section containing the entry symbol.  */
12797
12798 void
12799 _bfd_elf_gc_keep (struct bfd_link_info *info)
12800 {
12801   struct bfd_sym_chain *sym;
12802
12803   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
12804     {
12805       struct elf_link_hash_entry *h;
12806
12807       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
12808                                 FALSE, FALSE, FALSE);
12809
12810       if (h != NULL
12811           && (h->root.type == bfd_link_hash_defined
12812               || h->root.type == bfd_link_hash_defweak)
12813           && !bfd_is_abs_section (h->root.u.def.section))
12814         h->root.u.def.section->flags |= SEC_KEEP;
12815     }
12816 }
12817
12818 bfd_boolean
12819 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
12820                                 struct bfd_link_info *info)
12821 {
12822   bfd *ibfd = info->input_bfds;
12823
12824   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
12825     {
12826       asection *sec;
12827       struct elf_reloc_cookie cookie;
12828
12829       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
12830         continue;
12831
12832       if (!init_reloc_cookie (&cookie, info, ibfd))
12833         return FALSE;
12834
12835       for (sec = ibfd->sections; sec; sec = sec->next)
12836         {
12837           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
12838               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
12839             {
12840               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
12841               fini_reloc_cookie_rels (&cookie, sec);
12842             }
12843         }
12844     }
12845   return TRUE;
12846 }
12847
12848 /* Do mark and sweep of unused sections.  */
12849
12850 bfd_boolean
12851 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
12852 {
12853   bfd_boolean ok = TRUE;
12854   bfd *sub;
12855   elf_gc_mark_hook_fn gc_mark_hook;
12856   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12857   struct elf_link_hash_table *htab;
12858
12859   if (!bed->can_gc_sections
12860       || !is_elf_hash_table (info->hash))
12861     {
12862       (*_bfd_error_handler)(_("Warning: gc-sections option ignored"));
12863       return TRUE;
12864     }
12865
12866   bed->gc_keep (info);
12867   htab = elf_hash_table (info);
12868
12869   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
12870      at the .eh_frame section if we can mark the FDEs individually.  */
12871   for (sub = info->input_bfds;
12872        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
12873        sub = sub->link.next)
12874     {
12875       asection *sec;
12876       struct elf_reloc_cookie cookie;
12877
12878       sec = bfd_get_section_by_name (sub, ".eh_frame");
12879       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
12880         {
12881           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
12882           if (elf_section_data (sec)->sec_info
12883               && (sec->flags & SEC_LINKER_CREATED) == 0)
12884             elf_eh_frame_section (sub) = sec;
12885           fini_reloc_cookie_for_section (&cookie, sec);
12886           sec = bfd_get_next_section_by_name (NULL, sec);
12887         }
12888     }
12889
12890   /* Apply transitive closure to the vtable entry usage info.  */
12891   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
12892   if (!ok)
12893     return FALSE;
12894
12895   /* Kill the vtable relocations that were not used.  */
12896   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
12897   if (!ok)
12898     return FALSE;
12899
12900   /* Mark dynamically referenced symbols.  */
12901   if (htab->dynamic_sections_created)
12902     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
12903
12904   /* Grovel through relocs to find out who stays ...  */
12905   gc_mark_hook = bed->gc_mark_hook;
12906   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12907     {
12908       asection *o;
12909
12910       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
12911           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
12912         continue;
12913
12914       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
12915          Also treat note sections as a root, if the section is not part
12916          of a group.  */
12917       for (o = sub->sections; o != NULL; o = o->next)
12918         if (!o->gc_mark
12919             && (o->flags & SEC_EXCLUDE) == 0
12920             && ((o->flags & SEC_KEEP) != 0
12921                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
12922                     && elf_next_in_group (o) == NULL )))
12923           {
12924             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
12925               return FALSE;
12926           }
12927     }
12928
12929   /* Allow the backend to mark additional target specific sections.  */
12930   bed->gc_mark_extra_sections (info, gc_mark_hook);
12931
12932   /* ... and mark SEC_EXCLUDE for those that go.  */
12933   return elf_gc_sweep (abfd, info);
12934 }
12935 \f
12936 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
12937
12938 bfd_boolean
12939 bfd_elf_gc_record_vtinherit (bfd *abfd,
12940                              asection *sec,
12941                              struct elf_link_hash_entry *h,
12942                              bfd_vma offset)
12943 {
12944   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
12945   struct elf_link_hash_entry **search, *child;
12946   bfd_size_type extsymcount;
12947   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12948
12949   /* The sh_info field of the symtab header tells us where the
12950      external symbols start.  We don't care about the local symbols at
12951      this point.  */
12952   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
12953   if (!elf_bad_symtab (abfd))
12954     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
12955
12956   sym_hashes = elf_sym_hashes (abfd);
12957   sym_hashes_end = sym_hashes + extsymcount;
12958
12959   /* Hunt down the child symbol, which is in this section at the same
12960      offset as the relocation.  */
12961   for (search = sym_hashes; search != sym_hashes_end; ++search)
12962     {
12963       if ((child = *search) != NULL
12964           && (child->root.type == bfd_link_hash_defined
12965               || child->root.type == bfd_link_hash_defweak)
12966           && child->root.u.def.section == sec
12967           && child->root.u.def.value == offset)
12968         goto win;
12969     }
12970
12971   (*_bfd_error_handler) ("%B: %A+%lu: No symbol found for INHERIT",
12972                          abfd, sec, (unsigned long) offset);
12973   bfd_set_error (bfd_error_invalid_operation);
12974   return FALSE;
12975
12976  win:
12977   if (!child->vtable)
12978     {
12979       child->vtable = ((struct elf_link_virtual_table_entry *)
12980                        bfd_zalloc (abfd, sizeof (*child->vtable)));
12981       if (!child->vtable)
12982         return FALSE;
12983     }
12984   if (!h)
12985     {
12986       /* This *should* only be the absolute section.  It could potentially
12987          be that someone has defined a non-global vtable though, which
12988          would be bad.  It isn't worth paging in the local symbols to be
12989          sure though; that case should simply be handled by the assembler.  */
12990
12991       child->vtable->parent = (struct elf_link_hash_entry *) -1;
12992     }
12993   else
12994     child->vtable->parent = h;
12995
12996   return TRUE;
12997 }
12998
12999 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
13000
13001 bfd_boolean
13002 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
13003                            asection *sec ATTRIBUTE_UNUSED,
13004                            struct elf_link_hash_entry *h,
13005                            bfd_vma addend)
13006 {
13007   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13008   unsigned int log_file_align = bed->s->log_file_align;
13009
13010   if (!h->vtable)
13011     {
13012       h->vtable = ((struct elf_link_virtual_table_entry *)
13013                    bfd_zalloc (abfd, sizeof (*h->vtable)));
13014       if (!h->vtable)
13015         return FALSE;
13016     }
13017
13018   if (addend >= h->vtable->size)
13019     {
13020       size_t size, bytes, file_align;
13021       bfd_boolean *ptr = h->vtable->used;
13022
13023       /* While the symbol is undefined, we have to be prepared to handle
13024          a zero size.  */
13025       file_align = 1 << log_file_align;
13026       if (h->root.type == bfd_link_hash_undefined)
13027         size = addend + file_align;
13028       else
13029         {
13030           size = h->size;
13031           if (addend >= size)
13032             {
13033               /* Oops!  We've got a reference past the defined end of
13034                  the table.  This is probably a bug -- shall we warn?  */
13035               size = addend + file_align;
13036             }
13037         }
13038       size = (size + file_align - 1) & -file_align;
13039
13040       /* Allocate one extra entry for use as a "done" flag for the
13041          consolidation pass.  */
13042       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
13043
13044       if (ptr)
13045         {
13046           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
13047
13048           if (ptr != NULL)
13049             {
13050               size_t oldbytes;
13051
13052               oldbytes = (((h->vtable->size >> log_file_align) + 1)
13053                           * sizeof (bfd_boolean));
13054               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
13055             }
13056         }
13057       else
13058         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
13059
13060       if (ptr == NULL)
13061         return FALSE;
13062
13063       /* And arrange for that done flag to be at index -1.  */
13064       h->vtable->used = ptr + 1;
13065       h->vtable->size = size;
13066     }
13067
13068   h->vtable->used[addend >> log_file_align] = TRUE;
13069
13070   return TRUE;
13071 }
13072
13073 /* Map an ELF section header flag to its corresponding string.  */
13074 typedef struct
13075 {
13076   char *flag_name;
13077   flagword flag_value;
13078 } elf_flags_to_name_table;
13079
13080 static elf_flags_to_name_table elf_flags_to_names [] =
13081 {
13082   { "SHF_WRITE", SHF_WRITE },
13083   { "SHF_ALLOC", SHF_ALLOC },
13084   { "SHF_EXECINSTR", SHF_EXECINSTR },
13085   { "SHF_MERGE", SHF_MERGE },
13086   { "SHF_STRINGS", SHF_STRINGS },
13087   { "SHF_INFO_LINK", SHF_INFO_LINK},
13088   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
13089   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
13090   { "SHF_GROUP", SHF_GROUP },
13091   { "SHF_TLS", SHF_TLS },
13092   { "SHF_MASKOS", SHF_MASKOS },
13093   { "SHF_EXCLUDE", SHF_EXCLUDE },
13094 };
13095
13096 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
13097 bfd_boolean
13098 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
13099                               struct flag_info *flaginfo,
13100                               asection *section)
13101 {
13102   const bfd_vma sh_flags = elf_section_flags (section);
13103
13104   if (!flaginfo->flags_initialized)
13105     {
13106       bfd *obfd = info->output_bfd;
13107       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13108       struct flag_info_list *tf = flaginfo->flag_list;
13109       int with_hex = 0;
13110       int without_hex = 0;
13111
13112       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
13113         {
13114           unsigned i;
13115           flagword (*lookup) (char *);
13116
13117           lookup = bed->elf_backend_lookup_section_flags_hook;
13118           if (lookup != NULL)
13119             {
13120               flagword hexval = (*lookup) ((char *) tf->name);
13121
13122               if (hexval != 0)
13123                 {
13124                   if (tf->with == with_flags)
13125                     with_hex |= hexval;
13126                   else if (tf->with == without_flags)
13127                     without_hex |= hexval;
13128                   tf->valid = TRUE;
13129                   continue;
13130                 }
13131             }
13132           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
13133             {
13134               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
13135                 {
13136                   if (tf->with == with_flags)
13137                     with_hex |= elf_flags_to_names[i].flag_value;
13138                   else if (tf->with == without_flags)
13139                     without_hex |= elf_flags_to_names[i].flag_value;
13140                   tf->valid = TRUE;
13141                   break;
13142                 }
13143             }
13144           if (!tf->valid)
13145             {
13146               info->callbacks->einfo
13147                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
13148               return FALSE;
13149             }
13150         }
13151       flaginfo->flags_initialized = TRUE;
13152       flaginfo->only_with_flags |= with_hex;
13153       flaginfo->not_with_flags |= without_hex;
13154     }
13155
13156   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
13157     return FALSE;
13158
13159   if ((flaginfo->not_with_flags & sh_flags) != 0)
13160     return FALSE;
13161
13162   return TRUE;
13163 }
13164
13165 struct alloc_got_off_arg {
13166   bfd_vma gotoff;
13167   struct bfd_link_info *info;
13168 };
13169
13170 /* We need a special top-level link routine to convert got reference counts
13171    to real got offsets.  */
13172
13173 static bfd_boolean
13174 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
13175 {
13176   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
13177   bfd *obfd = gofarg->info->output_bfd;
13178   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13179
13180   if (h->got.refcount > 0)
13181     {
13182       h->got.offset = gofarg->gotoff;
13183       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
13184     }
13185   else
13186     h->got.offset = (bfd_vma) -1;
13187
13188   return TRUE;
13189 }
13190
13191 /* And an accompanying bit to work out final got entry offsets once
13192    we're done.  Should be called from final_link.  */
13193
13194 bfd_boolean
13195 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
13196                                         struct bfd_link_info *info)
13197 {
13198   bfd *i;
13199   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13200   bfd_vma gotoff;
13201   struct alloc_got_off_arg gofarg;
13202
13203   BFD_ASSERT (abfd == info->output_bfd);
13204
13205   if (! is_elf_hash_table (info->hash))
13206     return FALSE;
13207
13208   /* The GOT offset is relative to the .got section, but the GOT header is
13209      put into the .got.plt section, if the backend uses it.  */
13210   if (bed->want_got_plt)
13211     gotoff = 0;
13212   else
13213     gotoff = bed->got_header_size;
13214
13215   /* Do the local .got entries first.  */
13216   for (i = info->input_bfds; i; i = i->link.next)
13217     {
13218       bfd_signed_vma *local_got;
13219       bfd_size_type j, locsymcount;
13220       Elf_Internal_Shdr *symtab_hdr;
13221
13222       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13223         continue;
13224
13225       local_got = elf_local_got_refcounts (i);
13226       if (!local_got)
13227         continue;
13228
13229       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13230       if (elf_bad_symtab (i))
13231         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13232       else
13233         locsymcount = symtab_hdr->sh_info;
13234
13235       for (j = 0; j < locsymcount; ++j)
13236         {
13237           if (local_got[j] > 0)
13238             {
13239               local_got[j] = gotoff;
13240               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13241             }
13242           else
13243             local_got[j] = (bfd_vma) -1;
13244         }
13245     }
13246
13247   /* Then the global .got entries.  .plt refcounts are handled by
13248      adjust_dynamic_symbol  */
13249   gofarg.gotoff = gotoff;
13250   gofarg.info = info;
13251   elf_link_hash_traverse (elf_hash_table (info),
13252                           elf_gc_allocate_got_offsets,
13253                           &gofarg);
13254   return TRUE;
13255 }
13256
13257 /* Many folk need no more in the way of final link than this, once
13258    got entry reference counting is enabled.  */
13259
13260 bfd_boolean
13261 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
13262 {
13263   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
13264     return FALSE;
13265
13266   /* Invoke the regular ELF backend linker to do all the work.  */
13267   return bfd_elf_final_link (abfd, info);
13268 }
13269
13270 bfd_boolean
13271 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
13272 {
13273   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
13274
13275   if (rcookie->bad_symtab)
13276     rcookie->rel = rcookie->rels;
13277
13278   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
13279     {
13280       unsigned long r_symndx;
13281
13282       if (! rcookie->bad_symtab)
13283         if (rcookie->rel->r_offset > offset)
13284           return FALSE;
13285       if (rcookie->rel->r_offset != offset)
13286         continue;
13287
13288       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
13289       if (r_symndx == STN_UNDEF)
13290         return TRUE;
13291
13292       if (r_symndx >= rcookie->locsymcount
13293           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13294         {
13295           struct elf_link_hash_entry *h;
13296
13297           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
13298
13299           while (h->root.type == bfd_link_hash_indirect
13300                  || h->root.type == bfd_link_hash_warning)
13301             h = (struct elf_link_hash_entry *) h->root.u.i.link;
13302
13303           if ((h->root.type == bfd_link_hash_defined
13304                || h->root.type == bfd_link_hash_defweak)
13305               && (h->root.u.def.section->owner != rcookie->abfd
13306                   || h->root.u.def.section->kept_section != NULL
13307                   || discarded_section (h->root.u.def.section)))
13308             return TRUE;
13309         }
13310       else
13311         {
13312           /* It's not a relocation against a global symbol,
13313              but it could be a relocation against a local
13314              symbol for a discarded section.  */
13315           asection *isec;
13316           Elf_Internal_Sym *isym;
13317
13318           /* Need to: get the symbol; get the section.  */
13319           isym = &rcookie->locsyms[r_symndx];
13320           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
13321           if (isec != NULL
13322               && (isec->kept_section != NULL
13323                   || discarded_section (isec)))
13324             return TRUE;
13325         }
13326       return FALSE;
13327     }
13328   return FALSE;
13329 }
13330
13331 /* Discard unneeded references to discarded sections.
13332    Returns -1 on error, 1 if any section's size was changed, 0 if
13333    nothing changed.  This function assumes that the relocations are in
13334    sorted order, which is true for all known assemblers.  */
13335
13336 int
13337 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
13338 {
13339   struct elf_reloc_cookie cookie;
13340   asection *o;
13341   bfd *abfd;
13342   int changed = 0;
13343
13344   if (info->traditional_format
13345       || !is_elf_hash_table (info->hash))
13346     return 0;
13347
13348   o = bfd_get_section_by_name (output_bfd, ".stab");
13349   if (o != NULL)
13350     {
13351       asection *i;
13352
13353       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13354         {
13355           if (i->size == 0
13356               || i->reloc_count == 0
13357               || i->sec_info_type != SEC_INFO_TYPE_STABS)
13358             continue;
13359
13360           abfd = i->owner;
13361           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13362             continue;
13363
13364           if (!init_reloc_cookie_for_section (&cookie, info, i))
13365             return -1;
13366
13367           if (_bfd_discard_section_stabs (abfd, i,
13368                                           elf_section_data (i)->sec_info,
13369                                           bfd_elf_reloc_symbol_deleted_p,
13370                                           &cookie))
13371             changed = 1;
13372
13373           fini_reloc_cookie_for_section (&cookie, i);
13374         }
13375     }
13376
13377   o = NULL;
13378   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
13379     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
13380   if (o != NULL)
13381     {
13382       asection *i;
13383
13384       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13385         {
13386           if (i->size == 0)
13387             continue;
13388
13389           abfd = i->owner;
13390           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13391             continue;
13392
13393           if (!init_reloc_cookie_for_section (&cookie, info, i))
13394             return -1;
13395
13396           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
13397           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
13398                                                  bfd_elf_reloc_symbol_deleted_p,
13399                                                  &cookie))
13400             changed = 1;
13401
13402           fini_reloc_cookie_for_section (&cookie, i);
13403         }
13404     }
13405
13406   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
13407     {
13408       const struct elf_backend_data *bed;
13409
13410       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13411         continue;
13412
13413       bed = get_elf_backend_data (abfd);
13414
13415       if (bed->elf_backend_discard_info != NULL)
13416         {
13417           if (!init_reloc_cookie (&cookie, info, abfd))
13418             return -1;
13419
13420           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
13421             changed = 1;
13422
13423           fini_reloc_cookie (&cookie, abfd);
13424         }
13425     }
13426
13427   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
13428     _bfd_elf_end_eh_frame_parsing (info);
13429
13430   if (info->eh_frame_hdr_type
13431       && !bfd_link_relocatable (info)
13432       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
13433     changed = 1;
13434
13435   return changed;
13436 }
13437
13438 bfd_boolean
13439 _bfd_elf_section_already_linked (bfd *abfd,
13440                                  asection *sec,
13441                                  struct bfd_link_info *info)
13442 {
13443   flagword flags;
13444   const char *name, *key;
13445   struct bfd_section_already_linked *l;
13446   struct bfd_section_already_linked_hash_entry *already_linked_list;
13447
13448   if (sec->output_section == bfd_abs_section_ptr)
13449     return FALSE;
13450
13451   flags = sec->flags;
13452
13453   /* Return if it isn't a linkonce section.  A comdat group section
13454      also has SEC_LINK_ONCE set.  */
13455   if ((flags & SEC_LINK_ONCE) == 0)
13456     return FALSE;
13457
13458   /* Don't put group member sections on our list of already linked
13459      sections.  They are handled as a group via their group section.  */
13460   if (elf_sec_group (sec) != NULL)
13461     return FALSE;
13462
13463   /* For a SHT_GROUP section, use the group signature as the key.  */
13464   name = sec->name;
13465   if ((flags & SEC_GROUP) != 0
13466       && elf_next_in_group (sec) != NULL
13467       && elf_group_name (elf_next_in_group (sec)) != NULL)
13468     key = elf_group_name (elf_next_in_group (sec));
13469   else
13470     {
13471       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
13472       if (CONST_STRNEQ (name, ".gnu.linkonce.")
13473           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
13474         key++;
13475       else
13476         /* Must be a user linkonce section that doesn't follow gcc's
13477            naming convention.  In this case we won't be matching
13478            single member groups.  */
13479         key = name;
13480     }
13481
13482   already_linked_list = bfd_section_already_linked_table_lookup (key);
13483
13484   for (l = already_linked_list->entry; l != NULL; l = l->next)
13485     {
13486       /* We may have 2 different types of sections on the list: group
13487          sections with a signature of <key> (<key> is some string),
13488          and linkonce sections named .gnu.linkonce.<type>.<key>.
13489          Match like sections.  LTO plugin sections are an exception.
13490          They are always named .gnu.linkonce.t.<key> and match either
13491          type of section.  */
13492       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
13493            && ((flags & SEC_GROUP) != 0
13494                || strcmp (name, l->sec->name) == 0))
13495           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
13496         {
13497           /* The section has already been linked.  See if we should
13498              issue a warning.  */
13499           if (!_bfd_handle_already_linked (sec, l, info))
13500             return FALSE;
13501
13502           if (flags & SEC_GROUP)
13503             {
13504               asection *first = elf_next_in_group (sec);
13505               asection *s = first;
13506
13507               while (s != NULL)
13508                 {
13509                   s->output_section = bfd_abs_section_ptr;
13510                   /* Record which group discards it.  */
13511                   s->kept_section = l->sec;
13512                   s = elf_next_in_group (s);
13513                   /* These lists are circular.  */
13514                   if (s == first)
13515                     break;
13516                 }
13517             }
13518
13519           return TRUE;
13520         }
13521     }
13522
13523   /* A single member comdat group section may be discarded by a
13524      linkonce section and vice versa.  */
13525   if ((flags & SEC_GROUP) != 0)
13526     {
13527       asection *first = elf_next_in_group (sec);
13528
13529       if (first != NULL && elf_next_in_group (first) == first)
13530         /* Check this single member group against linkonce sections.  */
13531         for (l = already_linked_list->entry; l != NULL; l = l->next)
13532           if ((l->sec->flags & SEC_GROUP) == 0
13533               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
13534             {
13535               first->output_section = bfd_abs_section_ptr;
13536               first->kept_section = l->sec;
13537               sec->output_section = bfd_abs_section_ptr;
13538               break;
13539             }
13540     }
13541   else
13542     /* Check this linkonce section against single member groups.  */
13543     for (l = already_linked_list->entry; l != NULL; l = l->next)
13544       if (l->sec->flags & SEC_GROUP)
13545         {
13546           asection *first = elf_next_in_group (l->sec);
13547
13548           if (first != NULL
13549               && elf_next_in_group (first) == first
13550               && bfd_elf_match_symbols_in_sections (first, sec, info))
13551             {
13552               sec->output_section = bfd_abs_section_ptr;
13553               sec->kept_section = first;
13554               break;
13555             }
13556         }
13557
13558   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
13559      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
13560      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
13561      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
13562      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
13563      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
13564      `.gnu.linkonce.t.F' section from a different bfd not requiring any
13565      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
13566      The reverse order cannot happen as there is never a bfd with only the
13567      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
13568      matter as here were are looking only for cross-bfd sections.  */
13569
13570   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
13571     for (l = already_linked_list->entry; l != NULL; l = l->next)
13572       if ((l->sec->flags & SEC_GROUP) == 0
13573           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
13574         {
13575           if (abfd != l->sec->owner)
13576             sec->output_section = bfd_abs_section_ptr;
13577           break;
13578         }
13579
13580   /* This is the first section with this name.  Record it.  */
13581   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
13582     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
13583   return sec->output_section == bfd_abs_section_ptr;
13584 }
13585
13586 bfd_boolean
13587 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
13588 {
13589   return sym->st_shndx == SHN_COMMON;
13590 }
13591
13592 unsigned int
13593 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
13594 {
13595   return SHN_COMMON;
13596 }
13597
13598 asection *
13599 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
13600 {
13601   return bfd_com_section_ptr;
13602 }
13603
13604 bfd_vma
13605 _bfd_elf_default_got_elt_size (bfd *abfd,
13606                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
13607                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
13608                                bfd *ibfd ATTRIBUTE_UNUSED,
13609                                unsigned long symndx ATTRIBUTE_UNUSED)
13610 {
13611   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13612   return bed->s->arch_size / 8;
13613 }
13614
13615 /* Routines to support the creation of dynamic relocs.  */
13616
13617 /* Returns the name of the dynamic reloc section associated with SEC.  */
13618
13619 static const char *
13620 get_dynamic_reloc_section_name (bfd *       abfd,
13621                                 asection *  sec,
13622                                 bfd_boolean is_rela)
13623 {
13624   char *name;
13625   const char *old_name = bfd_get_section_name (NULL, sec);
13626   const char *prefix = is_rela ? ".rela" : ".rel";
13627
13628   if (old_name == NULL)
13629     return NULL;
13630
13631   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
13632   sprintf (name, "%s%s", prefix, old_name);
13633
13634   return name;
13635 }
13636
13637 /* Returns the dynamic reloc section associated with SEC.
13638    If necessary compute the name of the dynamic reloc section based
13639    on SEC's name (looked up in ABFD's string table) and the setting
13640    of IS_RELA.  */
13641
13642 asection *
13643 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
13644                                     asection *  sec,
13645                                     bfd_boolean is_rela)
13646 {
13647   asection * reloc_sec = elf_section_data (sec)->sreloc;
13648
13649   if (reloc_sec == NULL)
13650     {
13651       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13652
13653       if (name != NULL)
13654         {
13655           reloc_sec = bfd_get_linker_section (abfd, name);
13656
13657           if (reloc_sec != NULL)
13658             elf_section_data (sec)->sreloc = reloc_sec;
13659         }
13660     }
13661
13662   return reloc_sec;
13663 }
13664
13665 /* Returns the dynamic reloc section associated with SEC.  If the
13666    section does not exist it is created and attached to the DYNOBJ
13667    bfd and stored in the SRELOC field of SEC's elf_section_data
13668    structure.
13669
13670    ALIGNMENT is the alignment for the newly created section and
13671    IS_RELA defines whether the name should be .rela.<SEC's name>
13672    or .rel.<SEC's name>.  The section name is looked up in the
13673    string table associated with ABFD.  */
13674
13675 asection *
13676 _bfd_elf_make_dynamic_reloc_section (asection *sec,
13677                                      bfd *dynobj,
13678                                      unsigned int alignment,
13679                                      bfd *abfd,
13680                                      bfd_boolean is_rela)
13681 {
13682   asection * reloc_sec = elf_section_data (sec)->sreloc;
13683
13684   if (reloc_sec == NULL)
13685     {
13686       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
13687
13688       if (name == NULL)
13689         return NULL;
13690
13691       reloc_sec = bfd_get_linker_section (dynobj, name);
13692
13693       if (reloc_sec == NULL)
13694         {
13695           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
13696                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
13697           if ((sec->flags & SEC_ALLOC) != 0)
13698             flags |= SEC_ALLOC | SEC_LOAD;
13699
13700           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
13701           if (reloc_sec != NULL)
13702             {
13703               /* _bfd_elf_get_sec_type_attr chooses a section type by
13704                  name.  Override as it may be wrong, eg. for a user
13705                  section named "auto" we'll get ".relauto" which is
13706                  seen to be a .rela section.  */
13707               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
13708               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
13709                 reloc_sec = NULL;
13710             }
13711         }
13712
13713       elf_section_data (sec)->sreloc = reloc_sec;
13714     }
13715
13716   return reloc_sec;
13717 }
13718
13719 /* Copy the ELF symbol type and other attributes for a linker script
13720    assignment from HSRC to HDEST.  Generally this should be treated as
13721    if we found a strong non-dynamic definition for HDEST (except that
13722    ld ignores multiple definition errors).  */
13723 void
13724 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
13725                                      struct bfd_link_hash_entry *hdest,
13726                                      struct bfd_link_hash_entry *hsrc)
13727 {
13728   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
13729   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
13730   Elf_Internal_Sym isym;
13731
13732   ehdest->type = ehsrc->type;
13733   ehdest->target_internal = ehsrc->target_internal;
13734
13735   isym.st_other = ehsrc->other;
13736   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
13737 }
13738
13739 /* Append a RELA relocation REL to section S in BFD.  */
13740
13741 void
13742 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
13743 {
13744   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13745   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
13746   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
13747   bed->s->swap_reloca_out (abfd, rel, loc);
13748 }
13749
13750 /* Append a REL relocation REL to section S in BFD.  */
13751
13752 void
13753 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
13754 {
13755   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13756   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
13757   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
13758   bed->s->swap_reloc_out (abfd, rel, loc);
13759 }