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