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