Fix __bss_start assertion failure in _bfd_elf_fix_symbol_flags
[external/binutils.git] / bfd / elflink.c
1 /* ELF linking support for BFD.
2    Copyright (C) 1995-2019 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 "bfdlink.h"
24 #include "libbfd.h"
25 #define ARCH_SIZE 0
26 #include "elf-bfd.h"
27 #include "safe-ctype.h"
28 #include "libiberty.h"
29 #include "objalloc.h"
30 #if BFD_SUPPORTS_PLUGINS
31 #include "plugin-api.h"
32 #include "plugin.h"
33 #endif
34
35 /* This struct is used to pass information to routines called via
36    elf_link_hash_traverse which must return failure.  */
37
38 struct elf_info_failed
39 {
40   struct bfd_link_info *info;
41   bfd_boolean failed;
42 };
43
44 /* This structure is used to pass information to
45    _bfd_elf_link_find_version_dependencies.  */
46
47 struct elf_find_verdep_info
48 {
49   /* General link information.  */
50   struct bfd_link_info *info;
51   /* The number of dependencies.  */
52   unsigned int vers;
53   /* Whether we had a failure.  */
54   bfd_boolean failed;
55 };
56
57 static bfd_boolean _bfd_elf_fix_symbol_flags
58   (struct elf_link_hash_entry *, struct elf_info_failed *);
59
60 asection *
61 _bfd_elf_section_for_symbol (struct elf_reloc_cookie *cookie,
62                              unsigned long r_symndx,
63                              bfd_boolean discard)
64 {
65   if (r_symndx >= cookie->locsymcount
66       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
67     {
68       struct elf_link_hash_entry *h;
69
70       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
71
72       while (h->root.type == bfd_link_hash_indirect
73              || h->root.type == bfd_link_hash_warning)
74         h = (struct elf_link_hash_entry *) h->root.u.i.link;
75
76       if ((h->root.type == bfd_link_hash_defined
77            || h->root.type == bfd_link_hash_defweak)
78            && discarded_section (h->root.u.def.section))
79         return h->root.u.def.section;
80       else
81         return NULL;
82     }
83   else
84     {
85       /* It's not a relocation against a global symbol,
86          but it could be a relocation against a local
87          symbol for a discarded section.  */
88       asection *isec;
89       Elf_Internal_Sym *isym;
90
91       /* Need to: get the symbol; get the section.  */
92       isym = &cookie->locsyms[r_symndx];
93       isec = bfd_section_from_elf_index (cookie->abfd, isym->st_shndx);
94       if (isec != NULL
95           && discard ? discarded_section (isec) : 1)
96         return isec;
97      }
98   return NULL;
99 }
100
101 /* Define a symbol in a dynamic linkage section.  */
102
103 struct elf_link_hash_entry *
104 _bfd_elf_define_linkage_sym (bfd *abfd,
105                              struct bfd_link_info *info,
106                              asection *sec,
107                              const char *name)
108 {
109   struct elf_link_hash_entry *h;
110   struct bfd_link_hash_entry *bh;
111   const struct elf_backend_data *bed;
112
113   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
114   if (h != NULL)
115     {
116       /* Zap symbol defined in an as-needed lib that wasn't linked.
117          This is a symptom of a larger problem:  Absolute symbols
118          defined in shared libraries can't be overridden, because we
119          lose the link to the bfd which is via the symbol section.  */
120       h->root.type = bfd_link_hash_new;
121       bh = &h->root;
122     }
123   else
124     bh = NULL;
125
126   bed = get_elf_backend_data (abfd);
127   if (!_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL,
128                                          sec, 0, NULL, FALSE, bed->collect,
129                                          &bh))
130     return NULL;
131   h = (struct elf_link_hash_entry *) bh;
132   BFD_ASSERT (h != NULL);
133   h->def_regular = 1;
134   h->non_elf = 0;
135   h->root.linker_def = 1;
136   h->type = STT_OBJECT;
137   if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
138     h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
139
140   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
141   return h;
142 }
143
144 bfd_boolean
145 _bfd_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
146 {
147   flagword flags;
148   asection *s;
149   struct elf_link_hash_entry *h;
150   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
151   struct elf_link_hash_table *htab = elf_hash_table (info);
152
153   /* This function may be called more than once.  */
154   if (htab->sgot != NULL)
155     return TRUE;
156
157   flags = bed->dynamic_sec_flags;
158
159   s = bfd_make_section_anyway_with_flags (abfd,
160                                           (bed->rela_plts_and_copies_p
161                                            ? ".rela.got" : ".rel.got"),
162                                           (bed->dynamic_sec_flags
163                                            | SEC_READONLY));
164   if (s == NULL
165       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
166     return FALSE;
167   htab->srelgot = s;
168
169   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
170   if (s == NULL
171       || !bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
172     return FALSE;
173   htab->sgot = s;
174
175   if (bed->want_got_plt)
176     {
177       s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
178       if (s == NULL
179           || !bfd_set_section_alignment (abfd, s,
180                                          bed->s->log_file_align))
181         return FALSE;
182       htab->sgotplt = s;
183     }
184
185   /* The first bit of the global offset table is the header.  */
186   s->size += bed->got_header_size;
187
188   if (bed->want_got_sym)
189     {
190       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
191          (or .got.plt) section.  We don't do this in the linker script
192          because we don't want to define the symbol if we are not creating
193          a global offset table.  */
194       h = _bfd_elf_define_linkage_sym (abfd, info, s,
195                                        "_GLOBAL_OFFSET_TABLE_");
196       elf_hash_table (info)->hgot = h;
197       if (h == NULL)
198         return FALSE;
199     }
200
201   return TRUE;
202 }
203 \f
204 /* Create a strtab to hold the dynamic symbol names.  */
205 static bfd_boolean
206 _bfd_elf_link_create_dynstrtab (bfd *abfd, struct bfd_link_info *info)
207 {
208   struct elf_link_hash_table *hash_table;
209
210   hash_table = elf_hash_table (info);
211   if (hash_table->dynobj == NULL)
212     {
213       /* We may not set dynobj, an input file holding linker created
214          dynamic sections to abfd, which may be a dynamic object with
215          its own dynamic sections.  We need to find a normal input file
216          to hold linker created sections if possible.  */
217       if ((abfd->flags & (DYNAMIC | BFD_PLUGIN)) != 0)
218         {
219           bfd *ibfd;
220           asection *s;
221           for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link.next)
222             if ((ibfd->flags
223                  & (DYNAMIC | BFD_LINKER_CREATED | BFD_PLUGIN)) == 0
224                 && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
225                 && elf_object_id (ibfd) == elf_hash_table_id (hash_table)
226                 && !((s = ibfd->sections) != NULL
227                      && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS))
228               {
229                 abfd = ibfd;
230                 break;
231               }
232         }
233       hash_table->dynobj = abfd;
234     }
235
236   if (hash_table->dynstr == NULL)
237     {
238       hash_table->dynstr = _bfd_elf_strtab_init ();
239       if (hash_table->dynstr == NULL)
240         return FALSE;
241     }
242   return TRUE;
243 }
244
245 /* Create some sections which will be filled in with dynamic linking
246    information.  ABFD is an input file which requires dynamic sections
247    to be created.  The dynamic sections take up virtual memory space
248    when the final executable is run, so we need to create them before
249    addresses are assigned to the output sections.  We work out the
250    actual contents and size of these sections later.  */
251
252 bfd_boolean
253 _bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
254 {
255   flagword flags;
256   asection *s;
257   const struct elf_backend_data *bed;
258   struct elf_link_hash_entry *h;
259
260   if (! is_elf_hash_table (info->hash))
261     return FALSE;
262
263   if (elf_hash_table (info)->dynamic_sections_created)
264     return TRUE;
265
266   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
267     return FALSE;
268
269   abfd = elf_hash_table (info)->dynobj;
270   bed = get_elf_backend_data (abfd);
271
272   flags = bed->dynamic_sec_flags;
273
274   /* A dynamically linked executable has a .interp section, but a
275      shared library does not.  */
276   if (bfd_link_executable (info) && !info->nointerp)
277     {
278       s = bfd_make_section_anyway_with_flags (abfd, ".interp",
279                                               flags | SEC_READONLY);
280       if (s == NULL)
281         return FALSE;
282     }
283
284   /* Create sections to hold version informations.  These are removed
285      if they are not needed.  */
286   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_d",
287                                           flags | SEC_READONLY);
288   if (s == NULL
289       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
290     return FALSE;
291
292   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version",
293                                           flags | SEC_READONLY);
294   if (s == NULL
295       || ! bfd_set_section_alignment (abfd, s, 1))
296     return FALSE;
297
298   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_r",
299                                           flags | SEC_READONLY);
300   if (s == NULL
301       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
302     return FALSE;
303
304   s = bfd_make_section_anyway_with_flags (abfd, ".dynsym",
305                                           flags | SEC_READONLY);
306   if (s == NULL
307       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
308     return FALSE;
309   elf_hash_table (info)->dynsym = s;
310
311   s = bfd_make_section_anyway_with_flags (abfd, ".dynstr",
312                                           flags | SEC_READONLY);
313   if (s == NULL)
314     return FALSE;
315
316   s = bfd_make_section_anyway_with_flags (abfd, ".dynamic", flags);
317   if (s == NULL
318       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
319     return FALSE;
320
321   /* The special symbol _DYNAMIC is always set to the start of the
322      .dynamic section.  We could set _DYNAMIC in a linker script, but we
323      only want to define it if we are, in fact, creating a .dynamic
324      section.  We don't want to define it if there is no .dynamic
325      section, since on some ELF platforms the start up code examines it
326      to decide how to initialize the process.  */
327   h = _bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC");
328   elf_hash_table (info)->hdynamic = h;
329   if (h == NULL)
330     return FALSE;
331
332   if (info->emit_hash)
333     {
334       s = bfd_make_section_anyway_with_flags (abfd, ".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       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
340     }
341
342   if (info->emit_gnu_hash)
343     {
344       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
345                                               flags | SEC_READONLY);
346       if (s == NULL
347           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
348         return FALSE;
349       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
350          4 32-bit words followed by variable count of 64-bit words, then
351          variable count of 32-bit words.  */
352       if (bed->s->arch_size == 64)
353         elf_section_data (s)->this_hdr.sh_entsize = 0;
354       else
355         elf_section_data (s)->this_hdr.sh_entsize = 4;
356     }
357
358   /* Let the backend create the rest of the sections.  This lets the
359      backend set the right flags.  The backend will normally create
360      the .got and .plt sections.  */
361   if (bed->elf_backend_create_dynamic_sections == NULL
362       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
363     return FALSE;
364
365   elf_hash_table (info)->dynamic_sections_created = TRUE;
366
367   return TRUE;
368 }
369
370 /* Create dynamic sections when linking against a dynamic object.  */
371
372 bfd_boolean
373 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
374 {
375   flagword flags, pltflags;
376   struct elf_link_hash_entry *h;
377   asection *s;
378   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
379   struct elf_link_hash_table *htab = elf_hash_table (info);
380
381   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
382      .rel[a].bss sections.  */
383   flags = bed->dynamic_sec_flags;
384
385   pltflags = flags;
386   if (bed->plt_not_loaded)
387     /* We do not clear SEC_ALLOC here because we still want the OS to
388        allocate space for the section; it's just that there's nothing
389        to read in from the object file.  */
390     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
391   else
392     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
393   if (bed->plt_readonly)
394     pltflags |= SEC_READONLY;
395
396   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
397   if (s == NULL
398       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
399     return FALSE;
400   htab->splt = s;
401
402   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
403      .plt section.  */
404   if (bed->want_plt_sym)
405     {
406       h = _bfd_elf_define_linkage_sym (abfd, info, s,
407                                        "_PROCEDURE_LINKAGE_TABLE_");
408       elf_hash_table (info)->hplt = h;
409       if (h == NULL)
410         return FALSE;
411     }
412
413   s = bfd_make_section_anyway_with_flags (abfd,
414                                           (bed->rela_plts_and_copies_p
415                                            ? ".rela.plt" : ".rel.plt"),
416                                           flags | SEC_READONLY);
417   if (s == NULL
418       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
419     return FALSE;
420   htab->srelplt = s;
421
422   if (! _bfd_elf_create_got_section (abfd, info))
423     return FALSE;
424
425   if (bed->want_dynbss)
426     {
427       /* The .dynbss section is a place to put symbols which are defined
428          by dynamic objects, are referenced by regular objects, and are
429          not functions.  We must allocate space for them in the process
430          image and use a R_*_COPY reloc to tell the dynamic linker to
431          initialize them at run time.  The linker script puts the .dynbss
432          section into the .bss section of the final image.  */
433       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
434                                               SEC_ALLOC | SEC_LINKER_CREATED);
435       if (s == NULL)
436         return FALSE;
437       htab->sdynbss = s;
438
439       if (bed->want_dynrelro)
440         {
441           /* Similarly, but for symbols that were originally in read-only
442              sections.  This section doesn't really need to have contents,
443              but make it like other .data.rel.ro sections.  */
444           s = bfd_make_section_anyway_with_flags (abfd, ".data.rel.ro",
445                                                   flags);
446           if (s == NULL)
447             return FALSE;
448           htab->sdynrelro = s;
449         }
450
451       /* The .rel[a].bss section holds copy relocs.  This section is not
452          normally needed.  We need to create it here, though, so that the
453          linker will map it to an output section.  We can't just create it
454          only if we need it, because we will not know whether we need it
455          until we have seen all the input files, and the first time the
456          main linker code calls BFD after examining all the input files
457          (size_dynamic_sections) the input sections have already been
458          mapped to the output sections.  If the section turns out not to
459          be needed, we can discard it later.  We will never need this
460          section when generating a shared object, since they do not use
461          copy relocs.  */
462       if (bfd_link_executable (info))
463         {
464           s = bfd_make_section_anyway_with_flags (abfd,
465                                                   (bed->rela_plts_and_copies_p
466                                                    ? ".rela.bss" : ".rel.bss"),
467                                                   flags | SEC_READONLY);
468           if (s == NULL
469               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
470             return FALSE;
471           htab->srelbss = s;
472
473           if (bed->want_dynrelro)
474             {
475               s = (bfd_make_section_anyway_with_flags
476                    (abfd, (bed->rela_plts_and_copies_p
477                            ? ".rela.data.rel.ro" : ".rel.data.rel.ro"),
478                     flags | SEC_READONLY));
479               if (s == NULL
480                   || ! bfd_set_section_alignment (abfd, s,
481                                                   bed->s->log_file_align))
482                 return FALSE;
483               htab->sreldynrelro = s;
484             }
485         }
486     }
487
488   return TRUE;
489 }
490 \f
491 /* Record a new dynamic symbol.  We record the dynamic symbols as we
492    read the input files, since we need to have a list of all of them
493    before we can determine the final sizes of the output sections.
494    Note that we may actually call this function even though we are not
495    going to output any dynamic symbols; in some cases we know that a
496    symbol should be in the dynamic symbol table, but only if there is
497    one.  */
498
499 bfd_boolean
500 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
501                                     struct elf_link_hash_entry *h)
502 {
503   if (h->dynindx == -1)
504     {
505       struct elf_strtab_hash *dynstr;
506       char *p;
507       const char *name;
508       size_t indx;
509
510       /* XXX: The ABI draft says the linker must turn hidden and
511          internal symbols into STB_LOCAL symbols when producing the
512          DSO. However, if ld.so honors st_other in the dynamic table,
513          this would not be necessary.  */
514       switch (ELF_ST_VISIBILITY (h->other))
515         {
516         case STV_INTERNAL:
517         case STV_HIDDEN:
518           if (h->root.type != bfd_link_hash_undefined
519               && h->root.type != bfd_link_hash_undefweak)
520             {
521               h->forced_local = 1;
522               if (!elf_hash_table (info)->is_relocatable_executable)
523                 return TRUE;
524             }
525
526         default:
527           break;
528         }
529
530       h->dynindx = elf_hash_table (info)->dynsymcount;
531       ++elf_hash_table (info)->dynsymcount;
532
533       dynstr = elf_hash_table (info)->dynstr;
534       if (dynstr == NULL)
535         {
536           /* Create a strtab to hold the dynamic symbol names.  */
537           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
538           if (dynstr == NULL)
539             return FALSE;
540         }
541
542       /* We don't put any version information in the dynamic string
543          table.  */
544       name = h->root.root.string;
545       p = strchr (name, ELF_VER_CHR);
546       if (p != NULL)
547         /* We know that the p points into writable memory.  In fact,
548            there are only a few symbols that have read-only names, being
549            those like _GLOBAL_OFFSET_TABLE_ that are created specially
550            by the backends.  Most symbols will have names pointing into
551            an ELF string table read from a file, or to objalloc memory.  */
552         *p = 0;
553
554       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
555
556       if (p != NULL)
557         *p = ELF_VER_CHR;
558
559       if (indx == (size_t) -1)
560         return FALSE;
561       h->dynstr_index = indx;
562     }
563
564   return TRUE;
565 }
566 \f
567 /* Mark a symbol dynamic.  */
568
569 static void
570 bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
571                                   struct elf_link_hash_entry *h,
572                                   Elf_Internal_Sym *sym)
573 {
574   struct bfd_elf_dynamic_list *d = info->dynamic_list;
575
576   /* It may be called more than once on the same H.  */
577   if(h->dynamic || bfd_link_relocatable (info))
578     return;
579
580   if ((info->dynamic_data
581        && (h->type == STT_OBJECT
582            || h->type == STT_COMMON
583            || (sym != NULL
584                && (ELF_ST_TYPE (sym->st_info) == STT_OBJECT
585                    || ELF_ST_TYPE (sym->st_info) == STT_COMMON))))
586       || (d != NULL
587           && h->non_elf
588           && (*d->match) (&d->head, NULL, h->root.root.string)))
589     {
590       h->dynamic = 1;
591       /* NB: If a symbol is made dynamic by --dynamic-list, it has
592          non-IR reference.  */
593       h->root.non_ir_ref_dynamic = 1;
594     }
595 }
596
597 /* Record an assignment to a symbol made by a linker script.  We need
598    this in case some dynamic object refers to this symbol.  */
599
600 bfd_boolean
601 bfd_elf_record_link_assignment (bfd *output_bfd,
602                                 struct bfd_link_info *info,
603                                 const char *name,
604                                 bfd_boolean provide,
605                                 bfd_boolean hidden)
606 {
607   struct elf_link_hash_entry *h, *hv;
608   struct elf_link_hash_table *htab;
609   const struct elf_backend_data *bed;
610
611   if (!is_elf_hash_table (info->hash))
612     return TRUE;
613
614   htab = elf_hash_table (info);
615   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
616   if (h == NULL)
617     return provide;
618
619   if (h->root.type == bfd_link_hash_warning)
620     h = (struct elf_link_hash_entry *) h->root.u.i.link;
621
622   if (h->versioned == unknown)
623     {
624       /* Set versioned if symbol version is unknown.  */
625       char *version = strrchr (name, ELF_VER_CHR);
626       if (version)
627         {
628           if (version > name && version[-1] != ELF_VER_CHR)
629             h->versioned = versioned_hidden;
630           else
631             h->versioned = versioned;
632         }
633     }
634
635   /* Symbols defined in a linker script but not referenced anywhere
636      else will have non_elf set.  */
637   if (h->non_elf)
638     {
639       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
640       h->non_elf = 0;
641     }
642
643   switch (h->root.type)
644     {
645     case bfd_link_hash_defined:
646     case bfd_link_hash_defweak:
647     case bfd_link_hash_common:
648       break;
649     case bfd_link_hash_undefweak:
650     case bfd_link_hash_undefined:
651       /* Since we're defining the symbol, don't let it seem to have not
652          been defined.  record_dynamic_symbol and size_dynamic_sections
653          may depend on this.  */
654       h->root.type = bfd_link_hash_new;
655       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
656         bfd_link_repair_undef_list (&htab->root);
657       break;
658     case bfd_link_hash_new:
659       break;
660     case bfd_link_hash_indirect:
661       /* We had a versioned symbol in a dynamic library.  We make the
662          the versioned symbol point to this one.  */
663       bed = get_elf_backend_data (output_bfd);
664       hv = h;
665       while (hv->root.type == bfd_link_hash_indirect
666              || hv->root.type == bfd_link_hash_warning)
667         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
668       /* We don't need to update h->root.u since linker will set them
669          later.  */
670       h->root.type = bfd_link_hash_undefined;
671       hv->root.type = bfd_link_hash_indirect;
672       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
673       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
674       break;
675     default:
676       BFD_FAIL ();
677       return FALSE;
678     }
679
680   /* If this symbol is being provided by the linker script, and it is
681      currently defined by a dynamic object, but not by a regular
682      object, then mark it as undefined so that the generic linker will
683      force the correct value.  */
684   if (provide
685       && h->def_dynamic
686       && !h->def_regular)
687     h->root.type = bfd_link_hash_undefined;
688
689   /* If this symbol is currently defined by a dynamic object, but not
690      by a regular object, then clear out any version information because
691      the symbol will not be associated with the dynamic object any
692      more.  */
693   if (h->def_dynamic && !h->def_regular)
694     h->verinfo.verdef = NULL;
695
696   /* Make sure this symbol is not garbage collected.  */
697   h->mark = 1;
698
699   h->def_regular = 1;
700
701   if (hidden)
702     {
703       bed = get_elf_backend_data (output_bfd);
704       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
705         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
706       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
707     }
708
709   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
710      and executables.  */
711   if (!bfd_link_relocatable (info)
712       && h->dynindx != -1
713       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
714           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
715     h->forced_local = 1;
716
717   if ((h->def_dynamic
718        || h->ref_dynamic
719        || bfd_link_dll (info)
720        || elf_hash_table (info)->is_relocatable_executable)
721       && !h->forced_local
722       && h->dynindx == -1)
723     {
724       if (! bfd_elf_link_record_dynamic_symbol (info, h))
725         return FALSE;
726
727       /* If this is a weak defined symbol, and we know a corresponding
728          real symbol from the same dynamic object, make sure the real
729          symbol is also made into a dynamic symbol.  */
730       if (h->is_weakalias)
731         {
732           struct elf_link_hash_entry *def = weakdef (h);
733
734           if (def->dynindx == -1
735               && !bfd_elf_link_record_dynamic_symbol (info, def))
736             return FALSE;
737         }
738     }
739
740   return TRUE;
741 }
742
743 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
744    success, and 2 on a failure caused by attempting to record a symbol
745    in a discarded section, eg. a discarded link-once section symbol.  */
746
747 int
748 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
749                                           bfd *input_bfd,
750                                           long input_indx)
751 {
752   bfd_size_type amt;
753   struct elf_link_local_dynamic_entry *entry;
754   struct elf_link_hash_table *eht;
755   struct elf_strtab_hash *dynstr;
756   size_t dynstr_index;
757   char *name;
758   Elf_External_Sym_Shndx eshndx;
759   char esym[sizeof (Elf64_External_Sym)];
760
761   if (! is_elf_hash_table (info->hash))
762     return 0;
763
764   /* See if the entry exists already.  */
765   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
766     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
767       return 1;
768
769   amt = sizeof (*entry);
770   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
771   if (entry == NULL)
772     return 0;
773
774   /* Go find the symbol, so that we can find it's name.  */
775   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
776                              1, input_indx, &entry->isym, esym, &eshndx))
777     {
778       bfd_release (input_bfd, entry);
779       return 0;
780     }
781
782   if (entry->isym.st_shndx != SHN_UNDEF
783       && entry->isym.st_shndx < SHN_LORESERVE)
784     {
785       asection *s;
786
787       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
788       if (s == NULL || bfd_is_abs_section (s->output_section))
789         {
790           /* We can still bfd_release here as nothing has done another
791              bfd_alloc.  We can't do this later in this function.  */
792           bfd_release (input_bfd, entry);
793           return 2;
794         }
795     }
796
797   name = (bfd_elf_string_from_elf_section
798           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
799            entry->isym.st_name));
800
801   dynstr = elf_hash_table (info)->dynstr;
802   if (dynstr == NULL)
803     {
804       /* Create a strtab to hold the dynamic symbol names.  */
805       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
806       if (dynstr == NULL)
807         return 0;
808     }
809
810   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
811   if (dynstr_index == (size_t) -1)
812     return 0;
813   entry->isym.st_name = dynstr_index;
814
815   eht = elf_hash_table (info);
816
817   entry->next = eht->dynlocal;
818   eht->dynlocal = entry;
819   entry->input_bfd = input_bfd;
820   entry->input_indx = input_indx;
821   eht->dynsymcount++;
822
823   /* Whatever binding the symbol had before, it's now local.  */
824   entry->isym.st_info
825     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
826
827   /* The dynindx will be set at the end of size_dynamic_sections.  */
828
829   return 1;
830 }
831
832 /* Return the dynindex of a local dynamic symbol.  */
833
834 long
835 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
836                                     bfd *input_bfd,
837                                     long input_indx)
838 {
839   struct elf_link_local_dynamic_entry *e;
840
841   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
842     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
843       return e->dynindx;
844   return -1;
845 }
846
847 /* This function is used to renumber the dynamic symbols, if some of
848    them are removed because they are marked as local.  This is called
849    via elf_link_hash_traverse.  */
850
851 static bfd_boolean
852 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
853                                       void *data)
854 {
855   size_t *count = (size_t *) data;
856
857   if (h->forced_local)
858     return TRUE;
859
860   if (h->dynindx != -1)
861     h->dynindx = ++(*count);
862
863   return TRUE;
864 }
865
866
867 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
868    STB_LOCAL binding.  */
869
870 static bfd_boolean
871 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
872                                             void *data)
873 {
874   size_t *count = (size_t *) data;
875
876   if (!h->forced_local)
877     return TRUE;
878
879   if (h->dynindx != -1)
880     h->dynindx = ++(*count);
881
882   return TRUE;
883 }
884
885 /* Return true if the dynamic symbol for a given section should be
886    omitted when creating a shared library.  */
887 bfd_boolean
888 _bfd_elf_omit_section_dynsym_default (bfd *output_bfd ATTRIBUTE_UNUSED,
889                                       struct bfd_link_info *info,
890                                       asection *p)
891 {
892   struct elf_link_hash_table *htab;
893   asection *ip;
894
895   switch (elf_section_data (p)->this_hdr.sh_type)
896     {
897     case SHT_PROGBITS:
898     case SHT_NOBITS:
899       /* If sh_type is yet undecided, assume it could be
900          SHT_PROGBITS/SHT_NOBITS.  */
901     case SHT_NULL:
902       htab = elf_hash_table (info);
903       if (htab->text_index_section != NULL)
904         return p != htab->text_index_section && p != htab->data_index_section;
905
906       return (htab->dynobj != NULL
907               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
908               && ip->output_section == p);
909
910       /* There shouldn't be section relative relocations
911          against any other section.  */
912     default:
913       return TRUE;
914     }
915 }
916
917 bfd_boolean
918 _bfd_elf_omit_section_dynsym_all
919     (bfd *output_bfd ATTRIBUTE_UNUSED,
920      struct bfd_link_info *info ATTRIBUTE_UNUSED,
921      asection *p ATTRIBUTE_UNUSED)
922 {
923   return TRUE;
924 }
925
926 /* Assign dynsym indices.  In a shared library we generate a section
927    symbol for each output section, which come first.  Next come symbols
928    which have been forced to local binding.  Then all of the back-end
929    allocated local dynamic syms, followed by the rest of the global
930    symbols.  If SECTION_SYM_COUNT is NULL, section dynindx is not set.
931    (This prevents the early call before elf_backend_init_index_section
932    and strip_excluded_output_sections setting dynindx for sections
933    that are stripped.)  */
934
935 static unsigned long
936 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
937                                 struct bfd_link_info *info,
938                                 unsigned long *section_sym_count)
939 {
940   unsigned long dynsymcount = 0;
941   bfd_boolean do_sec = section_sym_count != NULL;
942
943   if (bfd_link_pic (info)
944       || elf_hash_table (info)->is_relocatable_executable)
945     {
946       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
947       asection *p;
948       for (p = output_bfd->sections; p ; p = p->next)
949         if ((p->flags & SEC_EXCLUDE) == 0
950             && (p->flags & SEC_ALLOC) != 0
951             && elf_hash_table (info)->dynamic_relocs
952             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
953           {
954             ++dynsymcount;
955             if (do_sec)
956               elf_section_data (p)->dynindx = dynsymcount;
957           }
958         else if (do_sec)
959           elf_section_data (p)->dynindx = 0;
960     }
961   if (do_sec)
962     *section_sym_count = dynsymcount;
963
964   elf_link_hash_traverse (elf_hash_table (info),
965                           elf_link_renumber_local_hash_table_dynsyms,
966                           &dynsymcount);
967
968   if (elf_hash_table (info)->dynlocal)
969     {
970       struct elf_link_local_dynamic_entry *p;
971       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
972         p->dynindx = ++dynsymcount;
973     }
974   elf_hash_table (info)->local_dynsymcount = dynsymcount;
975
976   elf_link_hash_traverse (elf_hash_table (info),
977                           elf_link_renumber_hash_table_dynsyms,
978                           &dynsymcount);
979
980   /* There is an unused NULL entry at the head of the table which we
981      must account for in our count even if the table is empty since it
982      is intended for the mandatory DT_SYMTAB tag (.dynsym section) in
983      .dynamic section.  */
984   dynsymcount++;
985
986   elf_hash_table (info)->dynsymcount = dynsymcount;
987   return dynsymcount;
988 }
989
990 /* Merge st_other field.  */
991
992 static void
993 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
994                     const Elf_Internal_Sym *isym, asection *sec,
995                     bfd_boolean definition, bfd_boolean dynamic)
996 {
997   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
998
999   /* If st_other has a processor-specific meaning, specific
1000      code might be needed here.  */
1001   if (bed->elf_backend_merge_symbol_attribute)
1002     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
1003                                                 dynamic);
1004
1005   if (!dynamic)
1006     {
1007       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
1008       unsigned hvis = ELF_ST_VISIBILITY (h->other);
1009
1010       /* Keep the most constraining visibility.  Leave the remainder
1011          of the st_other field to elf_backend_merge_symbol_attribute.  */
1012       if (symvis - 1 < hvis - 1)
1013         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
1014     }
1015   else if (definition
1016            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
1017            && (sec->flags & SEC_READONLY) == 0)
1018     h->protected_def = 1;
1019 }
1020
1021 /* This function is called when we want to merge a new symbol with an
1022    existing symbol.  It handles the various cases which arise when we
1023    find a definition in a dynamic object, or when there is already a
1024    definition in a dynamic object.  The new symbol is described by
1025    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
1026    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
1027    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
1028    of an old common symbol.  We set OVERRIDE if the old symbol is
1029    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
1030    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
1031    to change.  By OK to change, we mean that we shouldn't warn if the
1032    type or size does change.  */
1033
1034 static bfd_boolean
1035 _bfd_elf_merge_symbol (bfd *abfd,
1036                        struct bfd_link_info *info,
1037                        const char *name,
1038                        Elf_Internal_Sym *sym,
1039                        asection **psec,
1040                        bfd_vma *pvalue,
1041                        struct elf_link_hash_entry **sym_hash,
1042                        bfd **poldbfd,
1043                        bfd_boolean *pold_weak,
1044                        unsigned int *pold_alignment,
1045                        bfd_boolean *skip,
1046                        bfd_boolean *override,
1047                        bfd_boolean *type_change_ok,
1048                        bfd_boolean *size_change_ok,
1049                        bfd_boolean *matched)
1050 {
1051   asection *sec, *oldsec;
1052   struct elf_link_hash_entry *h;
1053   struct elf_link_hash_entry *hi;
1054   struct elf_link_hash_entry *flip;
1055   int bind;
1056   bfd *oldbfd;
1057   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
1058   bfd_boolean newweak, oldweak, newfunc, oldfunc;
1059   const struct elf_backend_data *bed;
1060   char *new_version;
1061   bfd_boolean default_sym = *matched;
1062
1063   *skip = FALSE;
1064   *override = FALSE;
1065
1066   sec = *psec;
1067   bind = ELF_ST_BIND (sym->st_info);
1068
1069   if (! bfd_is_und_section (sec))
1070     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
1071   else
1072     h = ((struct elf_link_hash_entry *)
1073          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
1074   if (h == NULL)
1075     return FALSE;
1076   *sym_hash = h;
1077
1078   bed = get_elf_backend_data (abfd);
1079
1080   /* NEW_VERSION is the symbol version of the new symbol.  */
1081   if (h->versioned != unversioned)
1082     {
1083       /* Symbol version is unknown or versioned.  */
1084       new_version = strrchr (name, ELF_VER_CHR);
1085       if (new_version)
1086         {
1087           if (h->versioned == unknown)
1088             {
1089               if (new_version > name && new_version[-1] != ELF_VER_CHR)
1090                 h->versioned = versioned_hidden;
1091               else
1092                 h->versioned = versioned;
1093             }
1094           new_version += 1;
1095           if (new_version[0] == '\0')
1096             new_version = NULL;
1097         }
1098       else
1099         h->versioned = unversioned;
1100     }
1101   else
1102     new_version = NULL;
1103
1104   /* For merging, we only care about real symbols.  But we need to make
1105      sure that indirect symbol dynamic flags are updated.  */
1106   hi = h;
1107   while (h->root.type == bfd_link_hash_indirect
1108          || h->root.type == bfd_link_hash_warning)
1109     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1110
1111   if (!*matched)
1112     {
1113       if (hi == h || h->root.type == bfd_link_hash_new)
1114         *matched = TRUE;
1115       else
1116         {
1117           /* OLD_HIDDEN is true if the existing symbol is only visible
1118              to the symbol with the same symbol version.  NEW_HIDDEN is
1119              true if the new symbol is only visible to the symbol with
1120              the same symbol version.  */
1121           bfd_boolean old_hidden = h->versioned == versioned_hidden;
1122           bfd_boolean new_hidden = hi->versioned == versioned_hidden;
1123           if (!old_hidden && !new_hidden)
1124             /* The new symbol matches the existing symbol if both
1125                aren't hidden.  */
1126             *matched = TRUE;
1127           else
1128             {
1129               /* OLD_VERSION is the symbol version of the existing
1130                  symbol. */
1131               char *old_version;
1132
1133               if (h->versioned >= versioned)
1134                 old_version = strrchr (h->root.root.string,
1135                                        ELF_VER_CHR) + 1;
1136               else
1137                  old_version = NULL;
1138
1139               /* The new symbol matches the existing symbol if they
1140                  have the same symbol version.  */
1141               *matched = (old_version == new_version
1142                           || (old_version != NULL
1143                               && new_version != NULL
1144                               && strcmp (old_version, new_version) == 0));
1145             }
1146         }
1147     }
1148
1149   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
1150      existing symbol.  */
1151
1152   oldbfd = NULL;
1153   oldsec = NULL;
1154   switch (h->root.type)
1155     {
1156     default:
1157       break;
1158
1159     case bfd_link_hash_undefined:
1160     case bfd_link_hash_undefweak:
1161       oldbfd = h->root.u.undef.abfd;
1162       break;
1163
1164     case bfd_link_hash_defined:
1165     case bfd_link_hash_defweak:
1166       oldbfd = h->root.u.def.section->owner;
1167       oldsec = h->root.u.def.section;
1168       break;
1169
1170     case bfd_link_hash_common:
1171       oldbfd = h->root.u.c.p->section->owner;
1172       oldsec = h->root.u.c.p->section;
1173       if (pold_alignment)
1174         *pold_alignment = h->root.u.c.p->alignment_power;
1175       break;
1176     }
1177   if (poldbfd && *poldbfd == NULL)
1178     *poldbfd = oldbfd;
1179
1180   /* Differentiate strong and weak symbols.  */
1181   newweak = bind == STB_WEAK;
1182   oldweak = (h->root.type == bfd_link_hash_defweak
1183              || h->root.type == bfd_link_hash_undefweak);
1184   if (pold_weak)
1185     *pold_weak = oldweak;
1186
1187   /* We have to check it for every instance since the first few may be
1188      references and not all compilers emit symbol type for undefined
1189      symbols.  */
1190   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
1191
1192   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1193      respectively, is from a dynamic object.  */
1194
1195   newdyn = (abfd->flags & DYNAMIC) != 0;
1196
1197   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
1198      syms and defined syms in dynamic libraries respectively.
1199      ref_dynamic on the other hand can be set for a symbol defined in
1200      a dynamic library, and def_dynamic may not be set;  When the
1201      definition in a dynamic lib is overridden by a definition in the
1202      executable use of the symbol in the dynamic lib becomes a
1203      reference to the executable symbol.  */
1204   if (newdyn)
1205     {
1206       if (bfd_is_und_section (sec))
1207         {
1208           if (bind != STB_WEAK)
1209             {
1210               h->ref_dynamic_nonweak = 1;
1211               hi->ref_dynamic_nonweak = 1;
1212             }
1213         }
1214       else
1215         {
1216           /* Update the existing symbol only if they match. */
1217           if (*matched)
1218             h->dynamic_def = 1;
1219           hi->dynamic_def = 1;
1220         }
1221     }
1222
1223   /* If we just created the symbol, mark it as being an ELF symbol.
1224      Other than that, there is nothing to do--there is no merge issue
1225      with a newly defined symbol--so we just return.  */
1226
1227   if (h->root.type == bfd_link_hash_new)
1228     {
1229       h->non_elf = 0;
1230       return TRUE;
1231     }
1232
1233   /* In cases involving weak versioned symbols, we may wind up trying
1234      to merge a symbol with itself.  Catch that here, to avoid the
1235      confusion that results if we try to override a symbol with
1236      itself.  The additional tests catch cases like
1237      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1238      dynamic object, which we do want to handle here.  */
1239   if (abfd == oldbfd
1240       && (newweak || oldweak)
1241       && ((abfd->flags & DYNAMIC) == 0
1242           || !h->def_regular))
1243     return TRUE;
1244
1245   olddyn = FALSE;
1246   if (oldbfd != NULL)
1247     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1248   else if (oldsec != NULL)
1249     {
1250       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1251          indices used by MIPS ELF.  */
1252       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1253     }
1254
1255   /* Handle a case where plugin_notice won't be called and thus won't
1256      set the non_ir_ref flags on the first pass over symbols.  */
1257   if (oldbfd != NULL
1258       && (oldbfd->flags & BFD_PLUGIN) != (abfd->flags & BFD_PLUGIN)
1259       && newdyn != olddyn)
1260     {
1261       h->root.non_ir_ref_dynamic = TRUE;
1262       hi->root.non_ir_ref_dynamic = TRUE;
1263     }
1264
1265   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1266      respectively, appear to be a definition rather than reference.  */
1267
1268   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1269
1270   olddef = (h->root.type != bfd_link_hash_undefined
1271             && h->root.type != bfd_link_hash_undefweak
1272             && h->root.type != bfd_link_hash_common);
1273
1274   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1275      respectively, appear to be a function.  */
1276
1277   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1278              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1279
1280   oldfunc = (h->type != STT_NOTYPE
1281              && bed->is_function_type (h->type));
1282
1283   if (!(newfunc && oldfunc)
1284       && ELF_ST_TYPE (sym->st_info) != h->type
1285       && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1286       && h->type != STT_NOTYPE
1287       && (newdef || bfd_is_com_section (sec))
1288       && (olddef || h->root.type == bfd_link_hash_common))
1289     {
1290       /* If creating a default indirect symbol ("foo" or "foo@") from
1291          a dynamic versioned definition ("foo@@") skip doing so if
1292          there is an existing regular definition with a different
1293          type.  We don't want, for example, a "time" variable in the
1294          executable overriding a "time" function in a shared library.  */
1295       if (newdyn
1296           && !olddyn)
1297         {
1298           *skip = TRUE;
1299           return TRUE;
1300         }
1301
1302       /* When adding a symbol from a regular object file after we have
1303          created indirect symbols, undo the indirection and any
1304          dynamic state.  */
1305       if (hi != h
1306           && !newdyn
1307           && olddyn)
1308         {
1309           h = hi;
1310           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1311           h->forced_local = 0;
1312           h->ref_dynamic = 0;
1313           h->def_dynamic = 0;
1314           h->dynamic_def = 0;
1315           if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1316             {
1317               h->root.type = bfd_link_hash_undefined;
1318               h->root.u.undef.abfd = abfd;
1319             }
1320           else
1321             {
1322               h->root.type = bfd_link_hash_new;
1323               h->root.u.undef.abfd = NULL;
1324             }
1325           return TRUE;
1326         }
1327     }
1328
1329   /* Check TLS symbols.  We don't check undefined symbols introduced
1330      by "ld -u" which have no type (and oldbfd NULL), and we don't
1331      check symbols from plugins because they also have no type.  */
1332   if (oldbfd != NULL
1333       && (oldbfd->flags & BFD_PLUGIN) == 0
1334       && (abfd->flags & BFD_PLUGIN) == 0
1335       && ELF_ST_TYPE (sym->st_info) != h->type
1336       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1337     {
1338       bfd *ntbfd, *tbfd;
1339       bfd_boolean ntdef, tdef;
1340       asection *ntsec, *tsec;
1341
1342       if (h->type == STT_TLS)
1343         {
1344           ntbfd = abfd;
1345           ntsec = sec;
1346           ntdef = newdef;
1347           tbfd = oldbfd;
1348           tsec = oldsec;
1349           tdef = olddef;
1350         }
1351       else
1352         {
1353           ntbfd = oldbfd;
1354           ntsec = oldsec;
1355           ntdef = olddef;
1356           tbfd = abfd;
1357           tsec = sec;
1358           tdef = newdef;
1359         }
1360
1361       if (tdef && ntdef)
1362         _bfd_error_handler
1363           /* xgettext:c-format */
1364           (_("%s: TLS definition in %pB section %pA "
1365              "mismatches non-TLS definition in %pB section %pA"),
1366            h->root.root.string, tbfd, tsec, ntbfd, ntsec);
1367       else if (!tdef && !ntdef)
1368         _bfd_error_handler
1369           /* xgettext:c-format */
1370           (_("%s: TLS reference in %pB "
1371              "mismatches non-TLS reference in %pB"),
1372            h->root.root.string, tbfd, ntbfd);
1373       else if (tdef)
1374         _bfd_error_handler
1375           /* xgettext:c-format */
1376           (_("%s: TLS definition in %pB section %pA "
1377              "mismatches non-TLS reference in %pB"),
1378            h->root.root.string, tbfd, tsec, ntbfd);
1379       else
1380         _bfd_error_handler
1381           /* xgettext:c-format */
1382           (_("%s: TLS reference in %pB "
1383              "mismatches non-TLS definition in %pB section %pA"),
1384            h->root.root.string, tbfd, ntbfd, ntsec);
1385
1386       bfd_set_error (bfd_error_bad_value);
1387       return FALSE;
1388     }
1389
1390   /* If the old symbol has non-default visibility, we ignore the new
1391      definition from a dynamic object.  */
1392   if (newdyn
1393       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1394       && !bfd_is_und_section (sec))
1395     {
1396       *skip = TRUE;
1397       /* Make sure this symbol is dynamic.  */
1398       h->ref_dynamic = 1;
1399       hi->ref_dynamic = 1;
1400       /* A protected symbol has external availability. Make sure it is
1401          recorded as dynamic.
1402
1403          FIXME: Should we check type and size for protected symbol?  */
1404       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1405         return bfd_elf_link_record_dynamic_symbol (info, h);
1406       else
1407         return TRUE;
1408     }
1409   else if (!newdyn
1410            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1411            && h->def_dynamic)
1412     {
1413       /* If the new symbol with non-default visibility comes from a
1414          relocatable file and the old definition comes from a dynamic
1415          object, we remove the old definition.  */
1416       if (hi->root.type == bfd_link_hash_indirect)
1417         {
1418           /* Handle the case where the old dynamic definition is
1419              default versioned.  We need to copy the symbol info from
1420              the symbol with default version to the normal one if it
1421              was referenced before.  */
1422           if (h->ref_regular)
1423             {
1424               hi->root.type = h->root.type;
1425               h->root.type = bfd_link_hash_indirect;
1426               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1427
1428               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1429               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1430                 {
1431                   /* If the new symbol is hidden or internal, completely undo
1432                      any dynamic link state.  */
1433                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1434                   h->forced_local = 0;
1435                   h->ref_dynamic = 0;
1436                 }
1437               else
1438                 h->ref_dynamic = 1;
1439
1440               h->def_dynamic = 0;
1441               /* FIXME: Should we check type and size for protected symbol?  */
1442               h->size = 0;
1443               h->type = 0;
1444
1445               h = hi;
1446             }
1447           else
1448             h = hi;
1449         }
1450
1451       /* If the old symbol was undefined before, then it will still be
1452          on the undefs list.  If the new symbol is undefined or
1453          common, we can't make it bfd_link_hash_new here, because new
1454          undefined or common symbols will be added to the undefs list
1455          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1456          added twice to the undefs list.  Also, if the new symbol is
1457          undefweak then we don't want to lose the strong undef.  */
1458       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1459         {
1460           h->root.type = bfd_link_hash_undefined;
1461           h->root.u.undef.abfd = abfd;
1462         }
1463       else
1464         {
1465           h->root.type = bfd_link_hash_new;
1466           h->root.u.undef.abfd = NULL;
1467         }
1468
1469       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1470         {
1471           /* If the new symbol is hidden or internal, completely undo
1472              any dynamic link state.  */
1473           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1474           h->forced_local = 0;
1475           h->ref_dynamic = 0;
1476         }
1477       else
1478         h->ref_dynamic = 1;
1479       h->def_dynamic = 0;
1480       /* FIXME: Should we check type and size for protected symbol?  */
1481       h->size = 0;
1482       h->type = 0;
1483       return TRUE;
1484     }
1485
1486   /* If a new weak symbol definition comes from a regular file and the
1487      old symbol comes from a dynamic library, we treat the new one as
1488      strong.  Similarly, an old weak symbol definition from a regular
1489      file is treated as strong when the new symbol comes from a dynamic
1490      library.  Further, an old weak symbol from a dynamic library is
1491      treated as strong if the new symbol is from a dynamic library.
1492      This reflects the way glibc's ld.so works.
1493
1494      Also allow a weak symbol to override a linker script symbol
1495      defined by an early pass over the script.  This is done so the
1496      linker knows the symbol is defined in an object file, for the
1497      DEFINED script function.
1498
1499      Do this before setting *type_change_ok or *size_change_ok so that
1500      we warn properly when dynamic library symbols are overridden.  */
1501
1502   if (newdef && !newdyn && (olddyn || h->root.ldscript_def))
1503     newweak = FALSE;
1504   if (olddef && newdyn)
1505     oldweak = FALSE;
1506
1507   /* Allow changes between different types of function symbol.  */
1508   if (newfunc && oldfunc)
1509     *type_change_ok = TRUE;
1510
1511   /* It's OK to change the type if either the existing symbol or the
1512      new symbol is weak.  A type change is also OK if the old symbol
1513      is undefined and the new symbol is defined.  */
1514
1515   if (oldweak
1516       || newweak
1517       || (newdef
1518           && h->root.type == bfd_link_hash_undefined))
1519     *type_change_ok = TRUE;
1520
1521   /* It's OK to change the size if either the existing symbol or the
1522      new symbol is weak, or if the old symbol is undefined.  */
1523
1524   if (*type_change_ok
1525       || h->root.type == bfd_link_hash_undefined)
1526     *size_change_ok = TRUE;
1527
1528   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1529      symbol, respectively, appears to be a common symbol in a dynamic
1530      object.  If a symbol appears in an uninitialized section, and is
1531      not weak, and is not a function, then it may be a common symbol
1532      which was resolved when the dynamic object was created.  We want
1533      to treat such symbols specially, because they raise special
1534      considerations when setting the symbol size: if the symbol
1535      appears as a common symbol in a regular object, and the size in
1536      the regular object is larger, we must make sure that we use the
1537      larger size.  This problematic case can always be avoided in C,
1538      but it must be handled correctly when using Fortran shared
1539      libraries.
1540
1541      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1542      likewise for OLDDYNCOMMON and OLDDEF.
1543
1544      Note that this test is just a heuristic, and that it is quite
1545      possible to have an uninitialized symbol in a shared object which
1546      is really a definition, rather than a common symbol.  This could
1547      lead to some minor confusion when the symbol really is a common
1548      symbol in some regular object.  However, I think it will be
1549      harmless.  */
1550
1551   if (newdyn
1552       && newdef
1553       && !newweak
1554       && (sec->flags & SEC_ALLOC) != 0
1555       && (sec->flags & SEC_LOAD) == 0
1556       && sym->st_size > 0
1557       && !newfunc)
1558     newdyncommon = TRUE;
1559   else
1560     newdyncommon = FALSE;
1561
1562   if (olddyn
1563       && olddef
1564       && h->root.type == bfd_link_hash_defined
1565       && h->def_dynamic
1566       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1567       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1568       && h->size > 0
1569       && !oldfunc)
1570     olddyncommon = TRUE;
1571   else
1572     olddyncommon = FALSE;
1573
1574   /* We now know everything about the old and new symbols.  We ask the
1575      backend to check if we can merge them.  */
1576   if (bed->merge_symbol != NULL)
1577     {
1578       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1579         return FALSE;
1580       sec = *psec;
1581     }
1582
1583   /* There are multiple definitions of a normal symbol.  Skip the
1584      default symbol as well as definition from an IR object.  */
1585   if (olddef && !olddyn && !oldweak && newdef && !newdyn && !newweak
1586       && !default_sym && h->def_regular
1587       && !(oldbfd != NULL
1588            && (oldbfd->flags & BFD_PLUGIN) != 0
1589            && (abfd->flags & BFD_PLUGIN) == 0))
1590     {
1591       /* Handle a multiple definition.  */
1592       (*info->callbacks->multiple_definition) (info, &h->root,
1593                                                abfd, sec, *pvalue);
1594       *skip = TRUE;
1595       return TRUE;
1596     }
1597
1598   /* If both the old and the new symbols look like common symbols in a
1599      dynamic object, set the size of the symbol to the larger of the
1600      two.  */
1601
1602   if (olddyncommon
1603       && newdyncommon
1604       && sym->st_size != h->size)
1605     {
1606       /* Since we think we have two common symbols, issue a multiple
1607          common warning if desired.  Note that we only warn if the
1608          size is different.  If the size is the same, we simply let
1609          the old symbol override the new one as normally happens with
1610          symbols defined in dynamic objects.  */
1611
1612       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1613                                            bfd_link_hash_common, sym->st_size);
1614       if (sym->st_size > h->size)
1615         h->size = sym->st_size;
1616
1617       *size_change_ok = TRUE;
1618     }
1619
1620   /* If we are looking at a dynamic object, and we have found a
1621      definition, we need to see if the symbol was already defined by
1622      some other object.  If so, we want to use the existing
1623      definition, and we do not want to report a multiple symbol
1624      definition error; we do this by clobbering *PSEC to be
1625      bfd_und_section_ptr.
1626
1627      We treat a common symbol as a definition if the symbol in the
1628      shared library is a function, since common symbols always
1629      represent variables; this can cause confusion in principle, but
1630      any such confusion would seem to indicate an erroneous program or
1631      shared library.  We also permit a common symbol in a regular
1632      object to override a weak symbol in a shared object.  */
1633
1634   if (newdyn
1635       && newdef
1636       && (olddef
1637           || (h->root.type == bfd_link_hash_common
1638               && (newweak || newfunc))))
1639     {
1640       *override = TRUE;
1641       newdef = FALSE;
1642       newdyncommon = FALSE;
1643
1644       *psec = sec = bfd_und_section_ptr;
1645       *size_change_ok = TRUE;
1646
1647       /* If we get here when the old symbol is a common symbol, then
1648          we are explicitly letting it override a weak symbol or
1649          function in a dynamic object, and we don't want to warn about
1650          a type change.  If the old symbol is a defined symbol, a type
1651          change warning may still be appropriate.  */
1652
1653       if (h->root.type == bfd_link_hash_common)
1654         *type_change_ok = TRUE;
1655     }
1656
1657   /* Handle the special case of an old common symbol merging with a
1658      new symbol which looks like a common symbol in a shared object.
1659      We change *PSEC and *PVALUE to make the new symbol look like a
1660      common symbol, and let _bfd_generic_link_add_one_symbol do the
1661      right thing.  */
1662
1663   if (newdyncommon
1664       && h->root.type == bfd_link_hash_common)
1665     {
1666       *override = TRUE;
1667       newdef = FALSE;
1668       newdyncommon = FALSE;
1669       *pvalue = sym->st_size;
1670       *psec = sec = bed->common_section (oldsec);
1671       *size_change_ok = TRUE;
1672     }
1673
1674   /* Skip weak definitions of symbols that are already defined.  */
1675   if (newdef && olddef && newweak)
1676     {
1677       /* Don't skip new non-IR weak syms.  */
1678       if (!(oldbfd != NULL
1679             && (oldbfd->flags & BFD_PLUGIN) != 0
1680             && (abfd->flags & BFD_PLUGIN) == 0))
1681         {
1682           newdef = FALSE;
1683           *skip = TRUE;
1684         }
1685
1686       /* Merge st_other.  If the symbol already has a dynamic index,
1687          but visibility says it should not be visible, turn it into a
1688          local symbol.  */
1689       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1690       if (h->dynindx != -1)
1691         switch (ELF_ST_VISIBILITY (h->other))
1692           {
1693           case STV_INTERNAL:
1694           case STV_HIDDEN:
1695             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1696             break;
1697           }
1698     }
1699
1700   /* If the old symbol is from a dynamic object, and the new symbol is
1701      a definition which is not from a dynamic object, then the new
1702      symbol overrides the old symbol.  Symbols from regular files
1703      always take precedence over symbols from dynamic objects, even if
1704      they are defined after the dynamic object in the link.
1705
1706      As above, we again permit a common symbol in a regular object to
1707      override a definition in a shared object if the shared object
1708      symbol is a function or is weak.  */
1709
1710   flip = NULL;
1711   if (!newdyn
1712       && (newdef
1713           || (bfd_is_com_section (sec)
1714               && (oldweak || oldfunc)))
1715       && olddyn
1716       && olddef
1717       && h->def_dynamic)
1718     {
1719       /* Change the hash table entry to undefined, and let
1720          _bfd_generic_link_add_one_symbol do the right thing with the
1721          new definition.  */
1722
1723       h->root.type = bfd_link_hash_undefined;
1724       h->root.u.undef.abfd = h->root.u.def.section->owner;
1725       *size_change_ok = TRUE;
1726
1727       olddef = FALSE;
1728       olddyncommon = FALSE;
1729
1730       /* We again permit a type change when a common symbol may be
1731          overriding a function.  */
1732
1733       if (bfd_is_com_section (sec))
1734         {
1735           if (oldfunc)
1736             {
1737               /* If a common symbol overrides a function, make sure
1738                  that it isn't defined dynamically nor has type
1739                  function.  */
1740               h->def_dynamic = 0;
1741               h->type = STT_NOTYPE;
1742             }
1743           *type_change_ok = TRUE;
1744         }
1745
1746       if (hi->root.type == bfd_link_hash_indirect)
1747         flip = hi;
1748       else
1749         /* This union may have been set to be non-NULL when this symbol
1750            was seen in a dynamic object.  We must force the union to be
1751            NULL, so that it is correct for a regular symbol.  */
1752         h->verinfo.vertree = NULL;
1753     }
1754
1755   /* Handle the special case of a new common symbol merging with an
1756      old symbol that looks like it might be a common symbol defined in
1757      a shared object.  Note that we have already handled the case in
1758      which a new common symbol should simply override the definition
1759      in the shared library.  */
1760
1761   if (! newdyn
1762       && bfd_is_com_section (sec)
1763       && olddyncommon)
1764     {
1765       /* It would be best if we could set the hash table entry to a
1766          common symbol, but we don't know what to use for the section
1767          or the alignment.  */
1768       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1769                                            bfd_link_hash_common, sym->st_size);
1770
1771       /* If the presumed common symbol in the dynamic object is
1772          larger, pretend that the new symbol has its size.  */
1773
1774       if (h->size > *pvalue)
1775         *pvalue = h->size;
1776
1777       /* We need to remember the alignment required by the symbol
1778          in the dynamic object.  */
1779       BFD_ASSERT (pold_alignment);
1780       *pold_alignment = h->root.u.def.section->alignment_power;
1781
1782       olddef = FALSE;
1783       olddyncommon = FALSE;
1784
1785       h->root.type = bfd_link_hash_undefined;
1786       h->root.u.undef.abfd = h->root.u.def.section->owner;
1787
1788       *size_change_ok = TRUE;
1789       *type_change_ok = TRUE;
1790
1791       if (hi->root.type == bfd_link_hash_indirect)
1792         flip = hi;
1793       else
1794         h->verinfo.vertree = NULL;
1795     }
1796
1797   if (flip != NULL)
1798     {
1799       /* Handle the case where we had a versioned symbol in a dynamic
1800          library and now find a definition in a normal object.  In this
1801          case, we make the versioned symbol point to the normal one.  */
1802       flip->root.type = h->root.type;
1803       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1804       h->root.type = bfd_link_hash_indirect;
1805       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1806       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1807       if (h->def_dynamic)
1808         {
1809           h->def_dynamic = 0;
1810           flip->ref_dynamic = 1;
1811         }
1812     }
1813
1814   return TRUE;
1815 }
1816
1817 /* This function is called to create an indirect symbol from the
1818    default for the symbol with the default version if needed. The
1819    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1820    set DYNSYM if the new indirect symbol is dynamic.  */
1821
1822 static bfd_boolean
1823 _bfd_elf_add_default_symbol (bfd *abfd,
1824                              struct bfd_link_info *info,
1825                              struct elf_link_hash_entry *h,
1826                              const char *name,
1827                              Elf_Internal_Sym *sym,
1828                              asection *sec,
1829                              bfd_vma value,
1830                              bfd **poldbfd,
1831                              bfd_boolean *dynsym)
1832 {
1833   bfd_boolean type_change_ok;
1834   bfd_boolean size_change_ok;
1835   bfd_boolean skip;
1836   char *shortname;
1837   struct elf_link_hash_entry *hi;
1838   struct bfd_link_hash_entry *bh;
1839   const struct elf_backend_data *bed;
1840   bfd_boolean collect;
1841   bfd_boolean dynamic;
1842   bfd_boolean override;
1843   char *p;
1844   size_t len, shortlen;
1845   asection *tmp_sec;
1846   bfd_boolean matched;
1847
1848   if (h->versioned == unversioned || h->versioned == versioned_hidden)
1849     return TRUE;
1850
1851   /* If this symbol has a version, and it is the default version, we
1852      create an indirect symbol from the default name to the fully
1853      decorated name.  This will cause external references which do not
1854      specify a version to be bound to this version of the symbol.  */
1855   p = strchr (name, ELF_VER_CHR);
1856   if (h->versioned == unknown)
1857     {
1858       if (p == NULL)
1859         {
1860           h->versioned = unversioned;
1861           return TRUE;
1862         }
1863       else
1864         {
1865           if (p[1] != ELF_VER_CHR)
1866             {
1867               h->versioned = versioned_hidden;
1868               return TRUE;
1869             }
1870           else
1871             h->versioned = versioned;
1872         }
1873     }
1874   else
1875     {
1876       /* PR ld/19073: We may see an unversioned definition after the
1877          default version.  */
1878       if (p == NULL)
1879         return TRUE;
1880     }
1881
1882   bed = get_elf_backend_data (abfd);
1883   collect = bed->collect;
1884   dynamic = (abfd->flags & DYNAMIC) != 0;
1885
1886   shortlen = p - name;
1887   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1888   if (shortname == NULL)
1889     return FALSE;
1890   memcpy (shortname, name, shortlen);
1891   shortname[shortlen] = '\0';
1892
1893   /* We are going to create a new symbol.  Merge it with any existing
1894      symbol with this name.  For the purposes of the merge, act as
1895      though we were defining the symbol we just defined, although we
1896      actually going to define an indirect symbol.  */
1897   type_change_ok = FALSE;
1898   size_change_ok = FALSE;
1899   matched = TRUE;
1900   tmp_sec = sec;
1901   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1902                               &hi, poldbfd, NULL, NULL, &skip, &override,
1903                               &type_change_ok, &size_change_ok, &matched))
1904     return FALSE;
1905
1906   if (skip)
1907     goto nondefault;
1908
1909   if (hi->def_regular)
1910     {
1911       /* If the undecorated symbol will have a version added by a
1912          script different to H, then don't indirect to/from the
1913          undecorated symbol.  This isn't ideal because we may not yet
1914          have seen symbol versions, if given by a script on the
1915          command line rather than via --version-script.  */
1916       if (hi->verinfo.vertree == NULL && info->version_info != NULL)
1917         {
1918           bfd_boolean hide;
1919
1920           hi->verinfo.vertree
1921             = bfd_find_version_for_sym (info->version_info,
1922                                         hi->root.root.string, &hide);
1923           if (hi->verinfo.vertree != NULL && hide)
1924             {
1925               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
1926               goto nondefault;
1927             }
1928         }
1929       if (hi->verinfo.vertree != NULL
1930           && strcmp (p + 1 + (p[1] == '@'), hi->verinfo.vertree->name) != 0)
1931         goto nondefault;
1932     }
1933
1934   if (! override)
1935     {
1936       /* Add the default symbol if not performing a relocatable link.  */
1937       if (! bfd_link_relocatable (info))
1938         {
1939           bh = &hi->root;
1940           if (bh->type == bfd_link_hash_defined
1941               && bh->u.def.section->owner != NULL
1942               && (bh->u.def.section->owner->flags & BFD_PLUGIN) != 0)
1943             {
1944               /* Mark the previous definition from IR object as
1945                  undefined so that the generic linker will override
1946                  it.  */
1947               bh->type = bfd_link_hash_undefined;
1948               bh->u.undef.abfd = bh->u.def.section->owner;
1949             }
1950           if (! (_bfd_generic_link_add_one_symbol
1951                  (info, abfd, shortname, BSF_INDIRECT,
1952                   bfd_ind_section_ptr,
1953                   0, name, FALSE, collect, &bh)))
1954             return FALSE;
1955           hi = (struct elf_link_hash_entry *) bh;
1956         }
1957     }
1958   else
1959     {
1960       /* In this case the symbol named SHORTNAME is overriding the
1961          indirect symbol we want to add.  We were planning on making
1962          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1963          is the name without a version.  NAME is the fully versioned
1964          name, and it is the default version.
1965
1966          Overriding means that we already saw a definition for the
1967          symbol SHORTNAME in a regular object, and it is overriding
1968          the symbol defined in the dynamic object.
1969
1970          When this happens, we actually want to change NAME, the
1971          symbol we just added, to refer to SHORTNAME.  This will cause
1972          references to NAME in the shared object to become references
1973          to SHORTNAME in the regular object.  This is what we expect
1974          when we override a function in a shared object: that the
1975          references in the shared object will be mapped to the
1976          definition in the regular object.  */
1977
1978       while (hi->root.type == bfd_link_hash_indirect
1979              || hi->root.type == bfd_link_hash_warning)
1980         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1981
1982       h->root.type = bfd_link_hash_indirect;
1983       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1984       if (h->def_dynamic)
1985         {
1986           h->def_dynamic = 0;
1987           hi->ref_dynamic = 1;
1988           if (hi->ref_regular
1989               || hi->def_regular)
1990             {
1991               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1992                 return FALSE;
1993             }
1994         }
1995
1996       /* Now set HI to H, so that the following code will set the
1997          other fields correctly.  */
1998       hi = h;
1999     }
2000
2001   /* Check if HI is a warning symbol.  */
2002   if (hi->root.type == bfd_link_hash_warning)
2003     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
2004
2005   /* If there is a duplicate definition somewhere, then HI may not
2006      point to an indirect symbol.  We will have reported an error to
2007      the user in that case.  */
2008
2009   if (hi->root.type == bfd_link_hash_indirect)
2010     {
2011       struct elf_link_hash_entry *ht;
2012
2013       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
2014       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
2015
2016       /* A reference to the SHORTNAME symbol from a dynamic library
2017          will be satisfied by the versioned symbol at runtime.  In
2018          effect, we have a reference to the versioned symbol.  */
2019       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
2020       hi->dynamic_def |= ht->dynamic_def;
2021
2022       /* See if the new flags lead us to realize that the symbol must
2023          be dynamic.  */
2024       if (! *dynsym)
2025         {
2026           if (! dynamic)
2027             {
2028               if (! bfd_link_executable (info)
2029                   || hi->def_dynamic
2030                   || hi->ref_dynamic)
2031                 *dynsym = TRUE;
2032             }
2033           else
2034             {
2035               if (hi->ref_regular)
2036                 *dynsym = TRUE;
2037             }
2038         }
2039     }
2040
2041   /* We also need to define an indirection from the nondefault version
2042      of the symbol.  */
2043
2044 nondefault:
2045   len = strlen (name);
2046   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
2047   if (shortname == NULL)
2048     return FALSE;
2049   memcpy (shortname, name, shortlen);
2050   memcpy (shortname + shortlen, p + 1, len - shortlen);
2051
2052   /* Once again, merge with any existing symbol.  */
2053   type_change_ok = FALSE;
2054   size_change_ok = FALSE;
2055   tmp_sec = sec;
2056   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
2057                               &hi, poldbfd, NULL, NULL, &skip, &override,
2058                               &type_change_ok, &size_change_ok, &matched))
2059     return FALSE;
2060
2061   if (skip)
2062     return TRUE;
2063
2064   if (override)
2065     {
2066       /* Here SHORTNAME is a versioned name, so we don't expect to see
2067          the type of override we do in the case above unless it is
2068          overridden by a versioned definition.  */
2069       if (hi->root.type != bfd_link_hash_defined
2070           && hi->root.type != bfd_link_hash_defweak)
2071         _bfd_error_handler
2072           /* xgettext:c-format */
2073           (_("%pB: unexpected redefinition of indirect versioned symbol `%s'"),
2074            abfd, shortname);
2075     }
2076   else
2077     {
2078       bh = &hi->root;
2079       if (! (_bfd_generic_link_add_one_symbol
2080              (info, abfd, shortname, BSF_INDIRECT,
2081               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
2082         return FALSE;
2083       hi = (struct elf_link_hash_entry *) bh;
2084
2085       /* If there is a duplicate definition somewhere, then HI may not
2086          point to an indirect symbol.  We will have reported an error
2087          to the user in that case.  */
2088
2089       if (hi->root.type == bfd_link_hash_indirect)
2090         {
2091           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
2092           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
2093           hi->dynamic_def |= h->dynamic_def;
2094
2095           /* See if the new flags lead us to realize that the symbol
2096              must be dynamic.  */
2097           if (! *dynsym)
2098             {
2099               if (! dynamic)
2100                 {
2101                   if (! bfd_link_executable (info)
2102                       || hi->ref_dynamic)
2103                     *dynsym = TRUE;
2104                 }
2105               else
2106                 {
2107                   if (hi->ref_regular)
2108                     *dynsym = TRUE;
2109                 }
2110             }
2111         }
2112     }
2113
2114   return TRUE;
2115 }
2116 \f
2117 /* This routine is used to export all defined symbols into the dynamic
2118    symbol table.  It is called via elf_link_hash_traverse.  */
2119
2120 static bfd_boolean
2121 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
2122 {
2123   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2124
2125   /* Ignore indirect symbols.  These are added by the versioning code.  */
2126   if (h->root.type == bfd_link_hash_indirect)
2127     return TRUE;
2128
2129   /* Ignore this if we won't export it.  */
2130   if (!eif->info->export_dynamic && !h->dynamic)
2131     return TRUE;
2132
2133   if (h->dynindx == -1
2134       && (h->def_regular || h->ref_regular)
2135       && ! bfd_hide_sym_by_version (eif->info->version_info,
2136                                     h->root.root.string))
2137     {
2138       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2139         {
2140           eif->failed = TRUE;
2141           return FALSE;
2142         }
2143     }
2144
2145   return TRUE;
2146 }
2147 \f
2148 /* Look through the symbols which are defined in other shared
2149    libraries and referenced here.  Update the list of version
2150    dependencies.  This will be put into the .gnu.version_r section.
2151    This function is called via elf_link_hash_traverse.  */
2152
2153 static bfd_boolean
2154 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
2155                                          void *data)
2156 {
2157   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
2158   Elf_Internal_Verneed *t;
2159   Elf_Internal_Vernaux *a;
2160   bfd_size_type amt;
2161
2162   /* We only care about symbols defined in shared objects with version
2163      information.  */
2164   if (!h->def_dynamic
2165       || h->def_regular
2166       || h->dynindx == -1
2167       || h->verinfo.verdef == NULL
2168       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
2169           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
2170     return TRUE;
2171
2172   /* See if we already know about this version.  */
2173   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
2174        t != NULL;
2175        t = t->vn_nextref)
2176     {
2177       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
2178         continue;
2179
2180       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
2181         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
2182           return TRUE;
2183
2184       break;
2185     }
2186
2187   /* This is a new version.  Add it to tree we are building.  */
2188
2189   if (t == NULL)
2190     {
2191       amt = sizeof *t;
2192       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
2193       if (t == NULL)
2194         {
2195           rinfo->failed = TRUE;
2196           return FALSE;
2197         }
2198
2199       t->vn_bfd = h->verinfo.verdef->vd_bfd;
2200       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
2201       elf_tdata (rinfo->info->output_bfd)->verref = t;
2202     }
2203
2204   amt = sizeof *a;
2205   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
2206   if (a == NULL)
2207     {
2208       rinfo->failed = TRUE;
2209       return FALSE;
2210     }
2211
2212   /* Note that we are copying a string pointer here, and testing it
2213      above.  If bfd_elf_string_from_elf_section is ever changed to
2214      discard the string data when low in memory, this will have to be
2215      fixed.  */
2216   a->vna_nodename = h->verinfo.verdef->vd_nodename;
2217
2218   a->vna_flags = h->verinfo.verdef->vd_flags;
2219   a->vna_nextptr = t->vn_auxptr;
2220
2221   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
2222   ++rinfo->vers;
2223
2224   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
2225
2226   t->vn_auxptr = a;
2227
2228   return TRUE;
2229 }
2230
2231 /* Return TRUE and set *HIDE to TRUE if the versioned symbol is
2232    hidden.  Set *T_P to NULL if there is no match.  */
2233
2234 static bfd_boolean
2235 _bfd_elf_link_hide_versioned_symbol (struct bfd_link_info *info,
2236                                      struct elf_link_hash_entry *h,
2237                                      const char *version_p,
2238                                      struct bfd_elf_version_tree **t_p,
2239                                      bfd_boolean *hide)
2240 {
2241   struct bfd_elf_version_tree *t;
2242
2243   /* Look for the version.  If we find it, it is no longer weak.  */
2244   for (t = info->version_info; t != NULL; t = t->next)
2245     {
2246       if (strcmp (t->name, version_p) == 0)
2247         {
2248           size_t len;
2249           char *alc;
2250           struct bfd_elf_version_expr *d;
2251
2252           len = version_p - h->root.root.string;
2253           alc = (char *) bfd_malloc (len);
2254           if (alc == NULL)
2255             return FALSE;
2256           memcpy (alc, h->root.root.string, len - 1);
2257           alc[len - 1] = '\0';
2258           if (alc[len - 2] == ELF_VER_CHR)
2259             alc[len - 2] = '\0';
2260
2261           h->verinfo.vertree = t;
2262           t->used = TRUE;
2263           d = NULL;
2264
2265           if (t->globals.list != NULL)
2266             d = (*t->match) (&t->globals, NULL, alc);
2267
2268           /* See if there is anything to force this symbol to
2269              local scope.  */
2270           if (d == NULL && t->locals.list != NULL)
2271             {
2272               d = (*t->match) (&t->locals, NULL, alc);
2273               if (d != NULL
2274                   && h->dynindx != -1
2275                   && ! info->export_dynamic)
2276                 *hide = TRUE;
2277             }
2278
2279           free (alc);
2280           break;
2281         }
2282     }
2283
2284   *t_p = t;
2285
2286   return TRUE;
2287 }
2288
2289 /* Return TRUE if the symbol H is hidden by version script.  */
2290
2291 bfd_boolean
2292 _bfd_elf_link_hide_sym_by_version (struct bfd_link_info *info,
2293                                    struct elf_link_hash_entry *h)
2294 {
2295   const char *p;
2296   bfd_boolean hide = FALSE;
2297   const struct elf_backend_data *bed
2298     = get_elf_backend_data (info->output_bfd);
2299
2300   /* Version script only hides symbols defined in regular objects.  */
2301   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
2302     return TRUE;
2303
2304   p = strchr (h->root.root.string, ELF_VER_CHR);
2305   if (p != NULL && h->verinfo.vertree == NULL)
2306     {
2307       struct bfd_elf_version_tree *t;
2308
2309       ++p;
2310       if (*p == ELF_VER_CHR)
2311         ++p;
2312
2313       if (*p != '\0'
2314           && _bfd_elf_link_hide_versioned_symbol (info, h, p, &t, &hide)
2315           && hide)
2316         {
2317           if (hide)
2318             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2319           return TRUE;
2320         }
2321     }
2322
2323   /* If we don't have a version for this symbol, see if we can find
2324      something.  */
2325   if (h->verinfo.vertree == NULL && info->version_info != NULL)
2326     {
2327       h->verinfo.vertree
2328         = bfd_find_version_for_sym (info->version_info,
2329                                     h->root.root.string, &hide);
2330       if (h->verinfo.vertree != NULL && hide)
2331         {
2332           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2333           return TRUE;
2334         }
2335     }
2336
2337   return FALSE;
2338 }
2339
2340 /* Figure out appropriate versions for all the symbols.  We may not
2341    have the version number script until we have read all of the input
2342    files, so until that point we don't know which symbols should be
2343    local.  This function is called via elf_link_hash_traverse.  */
2344
2345 static bfd_boolean
2346 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2347 {
2348   struct elf_info_failed *sinfo;
2349   struct bfd_link_info *info;
2350   const struct elf_backend_data *bed;
2351   struct elf_info_failed eif;
2352   char *p;
2353   bfd_boolean hide;
2354
2355   sinfo = (struct elf_info_failed *) data;
2356   info = sinfo->info;
2357
2358   /* Fix the symbol flags.  */
2359   eif.failed = FALSE;
2360   eif.info = info;
2361   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2362     {
2363       if (eif.failed)
2364         sinfo->failed = TRUE;
2365       return FALSE;
2366     }
2367
2368   bed = get_elf_backend_data (info->output_bfd);
2369
2370   /* We only need version numbers for symbols defined in regular
2371      objects.  */
2372   if (!h->def_regular)
2373     {
2374       /* Hide symbols defined in discarded input sections.  */
2375       if ((h->root.type == bfd_link_hash_defined
2376            || h->root.type == bfd_link_hash_defweak)
2377           && discarded_section (h->root.u.def.section))
2378         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2379       return TRUE;
2380     }
2381
2382   hide = FALSE;
2383   p = strchr (h->root.root.string, ELF_VER_CHR);
2384   if (p != NULL && h->verinfo.vertree == NULL)
2385     {
2386       struct bfd_elf_version_tree *t;
2387
2388       ++p;
2389       if (*p == ELF_VER_CHR)
2390         ++p;
2391
2392       /* If there is no version string, we can just return out.  */
2393       if (*p == '\0')
2394         return TRUE;
2395
2396       if (!_bfd_elf_link_hide_versioned_symbol (info, h, p, &t, &hide))
2397         {
2398           sinfo->failed = TRUE;
2399           return FALSE;
2400         }
2401
2402       if (hide)
2403         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2404
2405       /* If we are building an application, we need to create a
2406          version node for this version.  */
2407       if (t == NULL && bfd_link_executable (info))
2408         {
2409           struct bfd_elf_version_tree **pp;
2410           int version_index;
2411
2412           /* If we aren't going to export this symbol, we don't need
2413              to worry about it.  */
2414           if (h->dynindx == -1)
2415             return TRUE;
2416
2417           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd,
2418                                                           sizeof *t);
2419           if (t == NULL)
2420             {
2421               sinfo->failed = TRUE;
2422               return FALSE;
2423             }
2424
2425           t->name = p;
2426           t->name_indx = (unsigned int) -1;
2427           t->used = TRUE;
2428
2429           version_index = 1;
2430           /* Don't count anonymous version tag.  */
2431           if (sinfo->info->version_info != NULL
2432               && sinfo->info->version_info->vernum == 0)
2433             version_index = 0;
2434           for (pp = &sinfo->info->version_info;
2435                *pp != NULL;
2436                pp = &(*pp)->next)
2437             ++version_index;
2438           t->vernum = version_index;
2439
2440           *pp = t;
2441
2442           h->verinfo.vertree = t;
2443         }
2444       else if (t == NULL)
2445         {
2446           /* We could not find the version for a symbol when
2447              generating a shared archive.  Return an error.  */
2448           _bfd_error_handler
2449             /* xgettext:c-format */
2450             (_("%pB: version node not found for symbol %s"),
2451              info->output_bfd, h->root.root.string);
2452           bfd_set_error (bfd_error_bad_value);
2453           sinfo->failed = TRUE;
2454           return FALSE;
2455         }
2456     }
2457
2458   /* If we don't have a version for this symbol, see if we can find
2459      something.  */
2460   if (!hide
2461       && h->verinfo.vertree == NULL
2462       && sinfo->info->version_info != NULL)
2463     {
2464       h->verinfo.vertree
2465         = bfd_find_version_for_sym (sinfo->info->version_info,
2466                                     h->root.root.string, &hide);
2467       if (h->verinfo.vertree != NULL && hide)
2468         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2469     }
2470
2471   return TRUE;
2472 }
2473 \f
2474 /* Read and swap the relocs from the section indicated by SHDR.  This
2475    may be either a REL or a RELA section.  The relocations are
2476    translated into RELA relocations and stored in INTERNAL_RELOCS,
2477    which should have already been allocated to contain enough space.
2478    The EXTERNAL_RELOCS are a buffer where the external form of the
2479    relocations should be stored.
2480
2481    Returns FALSE if something goes wrong.  */
2482
2483 static bfd_boolean
2484 elf_link_read_relocs_from_section (bfd *abfd,
2485                                    asection *sec,
2486                                    Elf_Internal_Shdr *shdr,
2487                                    void *external_relocs,
2488                                    Elf_Internal_Rela *internal_relocs)
2489 {
2490   const struct elf_backend_data *bed;
2491   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2492   const bfd_byte *erela;
2493   const bfd_byte *erelaend;
2494   Elf_Internal_Rela *irela;
2495   Elf_Internal_Shdr *symtab_hdr;
2496   size_t nsyms;
2497
2498   /* Position ourselves at the start of the section.  */
2499   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2500     return FALSE;
2501
2502   /* Read the relocations.  */
2503   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2504     return FALSE;
2505
2506   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2507   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2508
2509   bed = get_elf_backend_data (abfd);
2510
2511   /* Convert the external relocations to the internal format.  */
2512   if (shdr->sh_entsize == bed->s->sizeof_rel)
2513     swap_in = bed->s->swap_reloc_in;
2514   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2515     swap_in = bed->s->swap_reloca_in;
2516   else
2517     {
2518       bfd_set_error (bfd_error_wrong_format);
2519       return FALSE;
2520     }
2521
2522   erela = (const bfd_byte *) external_relocs;
2523   /* Setting erelaend like this and comparing with <= handles case of
2524      a fuzzed object with sh_size not a multiple of sh_entsize.  */
2525   erelaend = erela + shdr->sh_size - shdr->sh_entsize;
2526   irela = internal_relocs;
2527   while (erela <= erelaend)
2528     {
2529       bfd_vma r_symndx;
2530
2531       (*swap_in) (abfd, erela, irela);
2532       r_symndx = ELF32_R_SYM (irela->r_info);
2533       if (bed->s->arch_size == 64)
2534         r_symndx >>= 24;
2535       if (nsyms > 0)
2536         {
2537           if ((size_t) r_symndx >= nsyms)
2538             {
2539               _bfd_error_handler
2540                 /* xgettext:c-format */
2541                 (_("%pB: bad reloc symbol index (%#" PRIx64 " >= %#lx)"
2542                    " for offset %#" PRIx64 " in section `%pA'"),
2543                  abfd, (uint64_t) r_symndx, (unsigned long) nsyms,
2544                  (uint64_t) irela->r_offset, sec);
2545               bfd_set_error (bfd_error_bad_value);
2546               return FALSE;
2547             }
2548         }
2549       else if (r_symndx != STN_UNDEF)
2550         {
2551           _bfd_error_handler
2552             /* xgettext:c-format */
2553             (_("%pB: non-zero symbol index (%#" PRIx64 ")"
2554                " for offset %#" PRIx64 " in section `%pA'"
2555                " when the object file has no symbol table"),
2556              abfd, (uint64_t) r_symndx,
2557              (uint64_t) irela->r_offset, sec);
2558           bfd_set_error (bfd_error_bad_value);
2559           return FALSE;
2560         }
2561       irela += bed->s->int_rels_per_ext_rel;
2562       erela += shdr->sh_entsize;
2563     }
2564
2565   return TRUE;
2566 }
2567
2568 /* Read and swap the relocs for a section O.  They may have been
2569    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2570    not NULL, they are used as buffers to read into.  They are known to
2571    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2572    the return value is allocated using either malloc or bfd_alloc,
2573    according to the KEEP_MEMORY argument.  If O has two relocation
2574    sections (both REL and RELA relocations), then the REL_HDR
2575    relocations will appear first in INTERNAL_RELOCS, followed by the
2576    RELA_HDR relocations.  */
2577
2578 Elf_Internal_Rela *
2579 _bfd_elf_link_read_relocs (bfd *abfd,
2580                            asection *o,
2581                            void *external_relocs,
2582                            Elf_Internal_Rela *internal_relocs,
2583                            bfd_boolean keep_memory)
2584 {
2585   void *alloc1 = NULL;
2586   Elf_Internal_Rela *alloc2 = NULL;
2587   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2588   struct bfd_elf_section_data *esdo = elf_section_data (o);
2589   Elf_Internal_Rela *internal_rela_relocs;
2590
2591   if (esdo->relocs != NULL)
2592     return esdo->relocs;
2593
2594   if (o->reloc_count == 0)
2595     return NULL;
2596
2597   if (internal_relocs == NULL)
2598     {
2599       bfd_size_type size;
2600
2601       size = (bfd_size_type) o->reloc_count * sizeof (Elf_Internal_Rela);
2602       if (keep_memory)
2603         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2604       else
2605         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2606       if (internal_relocs == NULL)
2607         goto error_return;
2608     }
2609
2610   if (external_relocs == NULL)
2611     {
2612       bfd_size_type size = 0;
2613
2614       if (esdo->rel.hdr)
2615         size += esdo->rel.hdr->sh_size;
2616       if (esdo->rela.hdr)
2617         size += esdo->rela.hdr->sh_size;
2618
2619       alloc1 = bfd_malloc (size);
2620       if (alloc1 == NULL)
2621         goto error_return;
2622       external_relocs = alloc1;
2623     }
2624
2625   internal_rela_relocs = internal_relocs;
2626   if (esdo->rel.hdr)
2627     {
2628       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2629                                               external_relocs,
2630                                               internal_relocs))
2631         goto error_return;
2632       external_relocs = (((bfd_byte *) external_relocs)
2633                          + esdo->rel.hdr->sh_size);
2634       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2635                                * bed->s->int_rels_per_ext_rel);
2636     }
2637
2638   if (esdo->rela.hdr
2639       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2640                                               external_relocs,
2641                                               internal_rela_relocs)))
2642     goto error_return;
2643
2644   /* Cache the results for next time, if we can.  */
2645   if (keep_memory)
2646     esdo->relocs = internal_relocs;
2647
2648   if (alloc1 != NULL)
2649     free (alloc1);
2650
2651   /* Don't free alloc2, since if it was allocated we are passing it
2652      back (under the name of internal_relocs).  */
2653
2654   return internal_relocs;
2655
2656  error_return:
2657   if (alloc1 != NULL)
2658     free (alloc1);
2659   if (alloc2 != NULL)
2660     {
2661       if (keep_memory)
2662         bfd_release (abfd, alloc2);
2663       else
2664         free (alloc2);
2665     }
2666   return NULL;
2667 }
2668
2669 /* Compute the size of, and allocate space for, REL_HDR which is the
2670    section header for a section containing relocations for O.  */
2671
2672 static bfd_boolean
2673 _bfd_elf_link_size_reloc_section (bfd *abfd,
2674                                   struct bfd_elf_section_reloc_data *reldata)
2675 {
2676   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2677
2678   /* That allows us to calculate the size of the section.  */
2679   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2680
2681   /* The contents field must last into write_object_contents, so we
2682      allocate it with bfd_alloc rather than malloc.  Also since we
2683      cannot be sure that the contents will actually be filled in,
2684      we zero the allocated space.  */
2685   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2686   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2687     return FALSE;
2688
2689   if (reldata->hashes == NULL && reldata->count)
2690     {
2691       struct elf_link_hash_entry **p;
2692
2693       p = ((struct elf_link_hash_entry **)
2694            bfd_zmalloc (reldata->count * sizeof (*p)));
2695       if (p == NULL)
2696         return FALSE;
2697
2698       reldata->hashes = p;
2699     }
2700
2701   return TRUE;
2702 }
2703
2704 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2705    originated from the section given by INPUT_REL_HDR) to the
2706    OUTPUT_BFD.  */
2707
2708 bfd_boolean
2709 _bfd_elf_link_output_relocs (bfd *output_bfd,
2710                              asection *input_section,
2711                              Elf_Internal_Shdr *input_rel_hdr,
2712                              Elf_Internal_Rela *internal_relocs,
2713                              struct elf_link_hash_entry **rel_hash
2714                                ATTRIBUTE_UNUSED)
2715 {
2716   Elf_Internal_Rela *irela;
2717   Elf_Internal_Rela *irelaend;
2718   bfd_byte *erel;
2719   struct bfd_elf_section_reloc_data *output_reldata;
2720   asection *output_section;
2721   const struct elf_backend_data *bed;
2722   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2723   struct bfd_elf_section_data *esdo;
2724
2725   output_section = input_section->output_section;
2726
2727   bed = get_elf_backend_data (output_bfd);
2728   esdo = elf_section_data (output_section);
2729   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2730     {
2731       output_reldata = &esdo->rel;
2732       swap_out = bed->s->swap_reloc_out;
2733     }
2734   else if (esdo->rela.hdr
2735            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2736     {
2737       output_reldata = &esdo->rela;
2738       swap_out = bed->s->swap_reloca_out;
2739     }
2740   else
2741     {
2742       _bfd_error_handler
2743         /* xgettext:c-format */
2744         (_("%pB: relocation size mismatch in %pB section %pA"),
2745          output_bfd, input_section->owner, input_section);
2746       bfd_set_error (bfd_error_wrong_format);
2747       return FALSE;
2748     }
2749
2750   erel = output_reldata->hdr->contents;
2751   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2752   irela = internal_relocs;
2753   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2754                       * bed->s->int_rels_per_ext_rel);
2755   while (irela < irelaend)
2756     {
2757       (*swap_out) (output_bfd, irela, erel);
2758       irela += bed->s->int_rels_per_ext_rel;
2759       erel += input_rel_hdr->sh_entsize;
2760     }
2761
2762   /* Bump the counter, so that we know where to add the next set of
2763      relocations.  */
2764   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2765
2766   return TRUE;
2767 }
2768 \f
2769 /* Make weak undefined symbols in PIE dynamic.  */
2770
2771 bfd_boolean
2772 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2773                                  struct elf_link_hash_entry *h)
2774 {
2775   if (bfd_link_pie (info)
2776       && h->dynindx == -1
2777       && h->root.type == bfd_link_hash_undefweak)
2778     return bfd_elf_link_record_dynamic_symbol (info, h);
2779
2780   return TRUE;
2781 }
2782
2783 /* Fix up the flags for a symbol.  This handles various cases which
2784    can only be fixed after all the input files are seen.  This is
2785    currently called by both adjust_dynamic_symbol and
2786    assign_sym_version, which is unnecessary but perhaps more robust in
2787    the face of future changes.  */
2788
2789 static bfd_boolean
2790 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2791                            struct elf_info_failed *eif)
2792 {
2793   const struct elf_backend_data *bed;
2794
2795   /* If this symbol was mentioned in a non-ELF file, try to set
2796      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2797      permit a non-ELF file to correctly refer to a symbol defined in
2798      an ELF dynamic object.  */
2799   if (h->non_elf)
2800     {
2801       while (h->root.type == bfd_link_hash_indirect)
2802         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2803
2804       if (h->root.type != bfd_link_hash_defined
2805           && h->root.type != bfd_link_hash_defweak)
2806         {
2807           h->ref_regular = 1;
2808           h->ref_regular_nonweak = 1;
2809         }
2810       else
2811         {
2812           if (h->root.u.def.section->owner != NULL
2813               && (bfd_get_flavour (h->root.u.def.section->owner)
2814                   == bfd_target_elf_flavour))
2815             {
2816               h->ref_regular = 1;
2817               h->ref_regular_nonweak = 1;
2818             }
2819           else
2820             h->def_regular = 1;
2821         }
2822
2823       if (h->dynindx == -1
2824           && (h->def_dynamic
2825               || h->ref_dynamic))
2826         {
2827           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2828             {
2829               eif->failed = TRUE;
2830               return FALSE;
2831             }
2832         }
2833     }
2834   else
2835     {
2836       /* Unfortunately, NON_ELF is only correct if the symbol
2837          was first seen in a non-ELF file.  Fortunately, if the symbol
2838          was first seen in an ELF file, we're probably OK unless the
2839          symbol was defined in a non-ELF file.  Catch that case here.
2840          FIXME: We're still in trouble if the symbol was first seen in
2841          a dynamic object, and then later in a non-ELF regular object.  */
2842       if ((h->root.type == bfd_link_hash_defined
2843            || h->root.type == bfd_link_hash_defweak)
2844           && !h->def_regular
2845           && (h->root.u.def.section->owner != NULL
2846               ? (bfd_get_flavour (h->root.u.def.section->owner)
2847                  != bfd_target_elf_flavour)
2848               : (bfd_is_abs_section (h->root.u.def.section)
2849                  && !h->def_dynamic)))
2850         h->def_regular = 1;
2851     }
2852
2853   /* Backend specific symbol fixup.  */
2854   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2855   if (bed->elf_backend_fixup_symbol
2856       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2857     return FALSE;
2858
2859   /* If this is a final link, and the symbol was defined as a common
2860      symbol in a regular object file, and there was no definition in
2861      any dynamic object, then the linker will have allocated space for
2862      the symbol in a common section but the DEF_REGULAR
2863      flag will not have been set.  */
2864   if (h->root.type == bfd_link_hash_defined
2865       && !h->def_regular
2866       && h->ref_regular
2867       && !h->def_dynamic
2868       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2869     h->def_regular = 1;
2870
2871   /* Symbols defined in discarded sections shouldn't be dynamic.  */
2872   if (h->root.type == bfd_link_hash_undefined && h->indx == -3)
2873     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2874
2875   /* If a weak undefined symbol has non-default visibility, we also
2876      hide it from the dynamic linker.  */
2877   else if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2878            && h->root.type == bfd_link_hash_undefweak)
2879     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2880
2881   /* A hidden versioned symbol in executable should be forced local if
2882      it is is locally defined, not referenced by shared library and not
2883      exported.  */
2884   else if (bfd_link_executable (eif->info)
2885            && h->versioned == versioned_hidden
2886            && !eif->info->export_dynamic
2887            && !h->dynamic
2888            && !h->ref_dynamic
2889            && h->def_regular)
2890     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2891
2892   /* If -Bsymbolic was used (which means to bind references to global
2893      symbols to the definition within the shared object), and this
2894      symbol was defined in a regular object, then it actually doesn't
2895      need a PLT entry.  Likewise, if the symbol has non-default
2896      visibility.  If the symbol has hidden or internal visibility, we
2897      will force it local.  */
2898   else if (h->needs_plt
2899            && bfd_link_pic (eif->info)
2900            && is_elf_hash_table (eif->info->hash)
2901            && (SYMBOLIC_BIND (eif->info, h)
2902                || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2903            && h->def_regular)
2904     {
2905       bfd_boolean force_local;
2906
2907       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2908                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2909       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2910     }
2911
2912   /* If this is a weak defined symbol in a dynamic object, and we know
2913      the real definition in the dynamic object, copy interesting flags
2914      over to the real definition.  */
2915   if (h->is_weakalias)
2916     {
2917       struct elf_link_hash_entry *def = weakdef (h);
2918
2919       /* If the real definition is defined by a regular object file,
2920          don't do anything special.  See the longer description in
2921          _bfd_elf_adjust_dynamic_symbol, below.  If the def is not
2922          bfd_link_hash_defined as it was when put on the alias list
2923          then it must have originally been a versioned symbol (for
2924          which a non-versioned indirect symbol is created) and later
2925          a definition for the non-versioned symbol is found.  In that
2926          case the indirection is flipped with the versioned symbol
2927          becoming an indirect pointing at the non-versioned symbol.
2928          Thus, not an alias any more.  */
2929       if (def->def_regular
2930           || def->root.type != bfd_link_hash_defined)
2931         {
2932           h = def;
2933           while ((h = h->u.alias) != def)
2934             h->is_weakalias = 0;
2935         }
2936       else
2937         {
2938           while (h->root.type == bfd_link_hash_indirect)
2939             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2940           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2941                       || h->root.type == bfd_link_hash_defweak);
2942           BFD_ASSERT (def->def_dynamic);
2943           (*bed->elf_backend_copy_indirect_symbol) (eif->info, def, h);
2944         }
2945     }
2946
2947   return TRUE;
2948 }
2949
2950 /* Make the backend pick a good value for a dynamic symbol.  This is
2951    called via elf_link_hash_traverse, and also calls itself
2952    recursively.  */
2953
2954 static bfd_boolean
2955 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2956 {
2957   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2958   struct elf_link_hash_table *htab;
2959   const struct elf_backend_data *bed;
2960
2961   if (! is_elf_hash_table (eif->info->hash))
2962     return FALSE;
2963
2964   /* Ignore indirect symbols.  These are added by the versioning code.  */
2965   if (h->root.type == bfd_link_hash_indirect)
2966     return TRUE;
2967
2968   /* Fix the symbol flags.  */
2969   if (! _bfd_elf_fix_symbol_flags (h, eif))
2970     return FALSE;
2971
2972   htab = elf_hash_table (eif->info);
2973   bed = get_elf_backend_data (htab->dynobj);
2974
2975   if (h->root.type == bfd_link_hash_undefweak)
2976     {
2977       if (eif->info->dynamic_undefined_weak == 0)
2978         (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2979       else if (eif->info->dynamic_undefined_weak > 0
2980                && h->ref_regular
2981                && ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2982                && !bfd_hide_sym_by_version (eif->info->version_info,
2983                                             h->root.root.string))
2984         {
2985           if (!bfd_elf_link_record_dynamic_symbol (eif->info, h))
2986             {
2987               eif->failed = TRUE;
2988               return FALSE;
2989             }
2990         }
2991     }
2992
2993   /* If this symbol does not require a PLT entry, and it is not
2994      defined by a dynamic object, or is not referenced by a regular
2995      object, ignore it.  We do have to handle a weak defined symbol,
2996      even if no regular object refers to it, if we decided to add it
2997      to the dynamic symbol table.  FIXME: Do we normally need to worry
2998      about symbols which are defined by one dynamic object and
2999      referenced by another one?  */
3000   if (!h->needs_plt
3001       && h->type != STT_GNU_IFUNC
3002       && (h->def_regular
3003           || !h->def_dynamic
3004           || (!h->ref_regular
3005               && (!h->is_weakalias || weakdef (h)->dynindx == -1))))
3006     {
3007       h->plt = elf_hash_table (eif->info)->init_plt_offset;
3008       return TRUE;
3009     }
3010
3011   /* If we've already adjusted this symbol, don't do it again.  This
3012      can happen via a recursive call.  */
3013   if (h->dynamic_adjusted)
3014     return TRUE;
3015
3016   /* Don't look at this symbol again.  Note that we must set this
3017      after checking the above conditions, because we may look at a
3018      symbol once, decide not to do anything, and then get called
3019      recursively later after REF_REGULAR is set below.  */
3020   h->dynamic_adjusted = 1;
3021
3022   /* If this is a weak definition, and we know a real definition, and
3023      the real symbol is not itself defined by a regular object file,
3024      then get a good value for the real definition.  We handle the
3025      real symbol first, for the convenience of the backend routine.
3026
3027      Note that there is a confusing case here.  If the real definition
3028      is defined by a regular object file, we don't get the real symbol
3029      from the dynamic object, but we do get the weak symbol.  If the
3030      processor backend uses a COPY reloc, then if some routine in the
3031      dynamic object changes the real symbol, we will not see that
3032      change in the corresponding weak symbol.  This is the way other
3033      ELF linkers work as well, and seems to be a result of the shared
3034      library model.
3035
3036      I will clarify this issue.  Most SVR4 shared libraries define the
3037      variable _timezone and define timezone as a weak synonym.  The
3038      tzset call changes _timezone.  If you write
3039        extern int timezone;
3040        int _timezone = 5;
3041        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
3042      you might expect that, since timezone is a synonym for _timezone,
3043      the same number will print both times.  However, if the processor
3044      backend uses a COPY reloc, then actually timezone will be copied
3045      into your process image, and, since you define _timezone
3046      yourself, _timezone will not.  Thus timezone and _timezone will
3047      wind up at different memory locations.  The tzset call will set
3048      _timezone, leaving timezone unchanged.  */
3049
3050   if (h->is_weakalias)
3051     {
3052       struct elf_link_hash_entry *def = weakdef (h);
3053
3054       /* If we get to this point, there is an implicit reference to
3055          the alias by a regular object file via the weak symbol H.  */
3056       def->ref_regular = 1;
3057
3058       /* Ensure that the backend adjust_dynamic_symbol function sees
3059          the strong alias before H by recursively calling ourselves.  */
3060       if (!_bfd_elf_adjust_dynamic_symbol (def, eif))
3061         return FALSE;
3062     }
3063
3064   /* If a symbol has no type and no size and does not require a PLT
3065      entry, then we are probably about to do the wrong thing here: we
3066      are probably going to create a COPY reloc for an empty object.
3067      This case can arise when a shared object is built with assembly
3068      code, and the assembly code fails to set the symbol type.  */
3069   if (h->size == 0
3070       && h->type == STT_NOTYPE
3071       && !h->needs_plt)
3072     _bfd_error_handler
3073       (_("warning: type and size of dynamic symbol `%s' are not defined"),
3074        h->root.root.string);
3075
3076   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
3077     {
3078       eif->failed = TRUE;
3079       return FALSE;
3080     }
3081
3082   return TRUE;
3083 }
3084
3085 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
3086    DYNBSS.  */
3087
3088 bfd_boolean
3089 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
3090                               struct elf_link_hash_entry *h,
3091                               asection *dynbss)
3092 {
3093   unsigned int power_of_two;
3094   bfd_vma mask;
3095   asection *sec = h->root.u.def.section;
3096
3097   /* The section alignment of the definition is the maximum alignment
3098      requirement of symbols defined in the section.  Since we don't
3099      know the symbol alignment requirement, we start with the
3100      maximum alignment and check low bits of the symbol address
3101      for the minimum alignment.  */
3102   power_of_two = bfd_get_section_alignment (sec->owner, sec);
3103   mask = ((bfd_vma) 1 << power_of_two) - 1;
3104   while ((h->root.u.def.value & mask) != 0)
3105     {
3106        mask >>= 1;
3107        --power_of_two;
3108     }
3109
3110   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
3111                                                 dynbss))
3112     {
3113       /* Adjust the section alignment if needed.  */
3114       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
3115                                        power_of_two))
3116         return FALSE;
3117     }
3118
3119   /* We make sure that the symbol will be aligned properly.  */
3120   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
3121
3122   /* Define the symbol as being at this point in DYNBSS.  */
3123   h->root.u.def.section = dynbss;
3124   h->root.u.def.value = dynbss->size;
3125
3126   /* Increment the size of DYNBSS to make room for the symbol.  */
3127   dynbss->size += h->size;
3128
3129   /* No error if extern_protected_data is true.  */
3130   if (h->protected_def
3131       && (!info->extern_protected_data
3132           || (info->extern_protected_data < 0
3133               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
3134     info->callbacks->einfo
3135       (_("%P: copy reloc against protected `%pT' is dangerous\n"),
3136        h->root.root.string);
3137
3138   return TRUE;
3139 }
3140
3141 /* Adjust all external symbols pointing into SEC_MERGE sections
3142    to reflect the object merging within the sections.  */
3143
3144 static bfd_boolean
3145 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
3146 {
3147   asection *sec;
3148
3149   if ((h->root.type == bfd_link_hash_defined
3150        || h->root.type == bfd_link_hash_defweak)
3151       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
3152       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
3153     {
3154       bfd *output_bfd = (bfd *) data;
3155
3156       h->root.u.def.value =
3157         _bfd_merged_section_offset (output_bfd,
3158                                     &h->root.u.def.section,
3159                                     elf_section_data (sec)->sec_info,
3160                                     h->root.u.def.value);
3161     }
3162
3163   return TRUE;
3164 }
3165
3166 /* Returns false if the symbol referred to by H should be considered
3167    to resolve local to the current module, and true if it should be
3168    considered to bind dynamically.  */
3169
3170 bfd_boolean
3171 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
3172                            struct bfd_link_info *info,
3173                            bfd_boolean not_local_protected)
3174 {
3175   bfd_boolean binding_stays_local_p;
3176   const struct elf_backend_data *bed;
3177   struct elf_link_hash_table *hash_table;
3178
3179   if (h == NULL)
3180     return FALSE;
3181
3182   while (h->root.type == bfd_link_hash_indirect
3183          || h->root.type == bfd_link_hash_warning)
3184     h = (struct elf_link_hash_entry *) h->root.u.i.link;
3185
3186   /* If it was forced local, then clearly it's not dynamic.  */
3187   if (h->dynindx == -1)
3188     return FALSE;
3189   if (h->forced_local)
3190     return FALSE;
3191
3192   /* Identify the cases where name binding rules say that a
3193      visible symbol resolves locally.  */
3194   binding_stays_local_p = (bfd_link_executable (info)
3195                            || SYMBOLIC_BIND (info, h));
3196
3197   switch (ELF_ST_VISIBILITY (h->other))
3198     {
3199     case STV_INTERNAL:
3200     case STV_HIDDEN:
3201       return FALSE;
3202
3203     case STV_PROTECTED:
3204       hash_table = elf_hash_table (info);
3205       if (!is_elf_hash_table (hash_table))
3206         return FALSE;
3207
3208       bed = get_elf_backend_data (hash_table->dynobj);
3209
3210       /* Proper resolution for function pointer equality may require
3211          that these symbols perhaps be resolved dynamically, even though
3212          we should be resolving them to the current module.  */
3213       if (!not_local_protected || !bed->is_function_type (h->type))
3214         binding_stays_local_p = TRUE;
3215       break;
3216
3217     default:
3218       break;
3219     }
3220
3221   /* If it isn't defined locally, then clearly it's dynamic.  */
3222   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
3223     return TRUE;
3224
3225   /* Otherwise, the symbol is dynamic if binding rules don't tell
3226      us that it remains local.  */
3227   return !binding_stays_local_p;
3228 }
3229
3230 /* Return true if the symbol referred to by H should be considered
3231    to resolve local to the current module, and false otherwise.  Differs
3232    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
3233    undefined symbols.  The two functions are virtually identical except
3234    for the place where dynindx == -1 is tested.  If that test is true,
3235    _bfd_elf_dynamic_symbol_p will say the symbol is local, while
3236    _bfd_elf_symbol_refs_local_p will say the symbol is local only for
3237    defined symbols.
3238    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
3239    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
3240    treatment of undefined weak symbols.  For those that do not make
3241    undefined weak symbols dynamic, both functions may return false.  */
3242
3243 bfd_boolean
3244 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
3245                               struct bfd_link_info *info,
3246                               bfd_boolean local_protected)
3247 {
3248   const struct elf_backend_data *bed;
3249   struct elf_link_hash_table *hash_table;
3250
3251   /* If it's a local sym, of course we resolve locally.  */
3252   if (h == NULL)
3253     return TRUE;
3254
3255   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
3256   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
3257       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
3258     return TRUE;
3259
3260   /* Forced local symbols resolve locally.  */
3261   if (h->forced_local)
3262     return TRUE;
3263
3264   /* Common symbols that become definitions don't get the DEF_REGULAR
3265      flag set, so test it first, and don't bail out.  */
3266   if (ELF_COMMON_DEF_P (h))
3267     /* Do nothing.  */;
3268   /* If we don't have a definition in a regular file, then we can't
3269      resolve locally.  The sym is either undefined or dynamic.  */
3270   else if (!h->def_regular)
3271     return FALSE;
3272
3273   /* Non-dynamic symbols resolve locally.  */
3274   if (h->dynindx == -1)
3275     return TRUE;
3276
3277   /* At this point, we know the symbol is defined and dynamic.  In an
3278      executable it must resolve locally, likewise when building symbolic
3279      shared libraries.  */
3280   if (bfd_link_executable (info) || SYMBOLIC_BIND (info, h))
3281     return TRUE;
3282
3283   /* Now deal with defined dynamic symbols in shared libraries.  Ones
3284      with default visibility might not resolve locally.  */
3285   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
3286     return FALSE;
3287
3288   hash_table = elf_hash_table (info);
3289   if (!is_elf_hash_table (hash_table))
3290     return TRUE;
3291
3292   bed = get_elf_backend_data (hash_table->dynobj);
3293
3294   /* If extern_protected_data is false, STV_PROTECTED non-function
3295      symbols are local.  */
3296   if ((!info->extern_protected_data
3297        || (info->extern_protected_data < 0
3298            && !bed->extern_protected_data))
3299       && !bed->is_function_type (h->type))
3300     return TRUE;
3301
3302   /* Function pointer equality tests may require that STV_PROTECTED
3303      symbols be treated as dynamic symbols.  If the address of a
3304      function not defined in an executable is set to that function's
3305      plt entry in the executable, then the address of the function in
3306      a shared library must also be the plt entry in the executable.  */
3307   return local_protected;
3308 }
3309
3310 /* Caches some TLS segment info, and ensures that the TLS segment vma is
3311    aligned.  Returns the first TLS output section.  */
3312
3313 struct bfd_section *
3314 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
3315 {
3316   struct bfd_section *sec, *tls;
3317   unsigned int align = 0;
3318
3319   for (sec = obfd->sections; sec != NULL; sec = sec->next)
3320     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
3321       break;
3322   tls = sec;
3323
3324   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
3325     if (sec->alignment_power > align)
3326       align = sec->alignment_power;
3327
3328   elf_hash_table (info)->tls_sec = tls;
3329
3330   /* Ensure the alignment of the first section is the largest alignment,
3331      so that the tls segment starts aligned.  */
3332   if (tls != NULL)
3333     tls->alignment_power = align;
3334
3335   return tls;
3336 }
3337
3338 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
3339 static bfd_boolean
3340 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
3341                                   Elf_Internal_Sym *sym)
3342 {
3343   const struct elf_backend_data *bed;
3344
3345   /* Local symbols do not count, but target specific ones might.  */
3346   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
3347       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
3348     return FALSE;
3349
3350   bed = get_elf_backend_data (abfd);
3351   /* Function symbols do not count.  */
3352   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
3353     return FALSE;
3354
3355   /* If the section is undefined, then so is the symbol.  */
3356   if (sym->st_shndx == SHN_UNDEF)
3357     return FALSE;
3358
3359   /* If the symbol is defined in the common section, then
3360      it is a common definition and so does not count.  */
3361   if (bed->common_definition (sym))
3362     return FALSE;
3363
3364   /* If the symbol is in a target specific section then we
3365      must rely upon the backend to tell us what it is.  */
3366   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3367     /* FIXME - this function is not coded yet:
3368
3369        return _bfd_is_global_symbol_definition (abfd, sym);
3370
3371        Instead for now assume that the definition is not global,
3372        Even if this is wrong, at least the linker will behave
3373        in the same way that it used to do.  */
3374     return FALSE;
3375
3376   return TRUE;
3377 }
3378
3379 /* Search the symbol table of the archive element of the archive ABFD
3380    whose archive map contains a mention of SYMDEF, and determine if
3381    the symbol is defined in this element.  */
3382 static bfd_boolean
3383 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3384 {
3385   Elf_Internal_Shdr * hdr;
3386   size_t symcount;
3387   size_t extsymcount;
3388   size_t extsymoff;
3389   Elf_Internal_Sym *isymbuf;
3390   Elf_Internal_Sym *isym;
3391   Elf_Internal_Sym *isymend;
3392   bfd_boolean result;
3393
3394   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3395   if (abfd == NULL)
3396     return FALSE;
3397
3398   if (! bfd_check_format (abfd, bfd_object))
3399     return FALSE;
3400
3401   /* Select the appropriate symbol table.  If we don't know if the
3402      object file is an IR object, give linker LTO plugin a chance to
3403      get the correct symbol table.  */
3404   if (abfd->plugin_format == bfd_plugin_yes
3405 #if BFD_SUPPORTS_PLUGINS
3406       || (abfd->plugin_format == bfd_plugin_unknown
3407           && bfd_link_plugin_object_p (abfd))
3408 #endif
3409       )
3410     {
3411       /* Use the IR symbol table if the object has been claimed by
3412          plugin.  */
3413       abfd = abfd->plugin_dummy_bfd;
3414       hdr = &elf_tdata (abfd)->symtab_hdr;
3415     }
3416   else if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3417     hdr = &elf_tdata (abfd)->symtab_hdr;
3418   else
3419     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3420
3421   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3422
3423   /* The sh_info field of the symtab header tells us where the
3424      external symbols start.  We don't care about the local symbols.  */
3425   if (elf_bad_symtab (abfd))
3426     {
3427       extsymcount = symcount;
3428       extsymoff = 0;
3429     }
3430   else
3431     {
3432       extsymcount = symcount - hdr->sh_info;
3433       extsymoff = hdr->sh_info;
3434     }
3435
3436   if (extsymcount == 0)
3437     return FALSE;
3438
3439   /* Read in the symbol table.  */
3440   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3441                                   NULL, NULL, NULL);
3442   if (isymbuf == NULL)
3443     return FALSE;
3444
3445   /* Scan the symbol table looking for SYMDEF.  */
3446   result = FALSE;
3447   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3448     {
3449       const char *name;
3450
3451       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3452                                               isym->st_name);
3453       if (name == NULL)
3454         break;
3455
3456       if (strcmp (name, symdef->name) == 0)
3457         {
3458           result = is_global_data_symbol_definition (abfd, isym);
3459           break;
3460         }
3461     }
3462
3463   free (isymbuf);
3464
3465   return result;
3466 }
3467 \f
3468 /* Add an entry to the .dynamic table.  */
3469
3470 bfd_boolean
3471 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3472                             bfd_vma tag,
3473                             bfd_vma val)
3474 {
3475   struct elf_link_hash_table *hash_table;
3476   const struct elf_backend_data *bed;
3477   asection *s;
3478   bfd_size_type newsize;
3479   bfd_byte *newcontents;
3480   Elf_Internal_Dyn dyn;
3481
3482   hash_table = elf_hash_table (info);
3483   if (! is_elf_hash_table (hash_table))
3484     return FALSE;
3485
3486   if (tag == DT_RELA || tag == DT_REL)
3487     hash_table->dynamic_relocs = TRUE;
3488
3489   bed = get_elf_backend_data (hash_table->dynobj);
3490   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3491   BFD_ASSERT (s != NULL);
3492
3493   newsize = s->size + bed->s->sizeof_dyn;
3494   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3495   if (newcontents == NULL)
3496     return FALSE;
3497
3498   dyn.d_tag = tag;
3499   dyn.d_un.d_val = val;
3500   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3501
3502   s->size = newsize;
3503   s->contents = newcontents;
3504
3505   return TRUE;
3506 }
3507
3508 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3509    otherwise just check whether one already exists.  Returns -1 on error,
3510    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3511
3512 static int
3513 elf_add_dt_needed_tag (bfd *abfd,
3514                        struct bfd_link_info *info,
3515                        const char *soname,
3516                        bfd_boolean do_it)
3517 {
3518   struct elf_link_hash_table *hash_table;
3519   size_t strindex;
3520
3521   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3522     return -1;
3523
3524   hash_table = elf_hash_table (info);
3525   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3526   if (strindex == (size_t) -1)
3527     return -1;
3528
3529   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3530     {
3531       asection *sdyn;
3532       const struct elf_backend_data *bed;
3533       bfd_byte *extdyn;
3534
3535       bed = get_elf_backend_data (hash_table->dynobj);
3536       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3537       if (sdyn != NULL)
3538         for (extdyn = sdyn->contents;
3539              extdyn < sdyn->contents + sdyn->size;
3540              extdyn += bed->s->sizeof_dyn)
3541           {
3542             Elf_Internal_Dyn dyn;
3543
3544             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3545             if (dyn.d_tag == DT_NEEDED
3546                 && dyn.d_un.d_val == strindex)
3547               {
3548                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3549                 return 1;
3550               }
3551           }
3552     }
3553
3554   if (do_it)
3555     {
3556       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3557         return -1;
3558
3559       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3560         return -1;
3561     }
3562   else
3563     /* We were just checking for existence of the tag.  */
3564     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3565
3566   return 0;
3567 }
3568
3569 /* Return true if SONAME is on the needed list between NEEDED and STOP
3570    (or the end of list if STOP is NULL), and needed by a library that
3571    will be loaded.  */
3572
3573 static bfd_boolean
3574 on_needed_list (const char *soname,
3575                 struct bfd_link_needed_list *needed,
3576                 struct bfd_link_needed_list *stop)
3577 {
3578   struct bfd_link_needed_list *look;
3579   for (look = needed; look != stop; look = look->next)
3580     if (strcmp (soname, look->name) == 0
3581         && ((elf_dyn_lib_class (look->by) & DYN_AS_NEEDED) == 0
3582             /* If needed by a library that itself is not directly
3583                needed, recursively check whether that library is
3584                indirectly needed.  Since we add DT_NEEDED entries to
3585                the end of the list, library dependencies appear after
3586                the library.  Therefore search prior to the current
3587                LOOK, preventing possible infinite recursion.  */
3588             || on_needed_list (elf_dt_name (look->by), needed, look)))
3589       return TRUE;
3590
3591   return FALSE;
3592 }
3593
3594 /* Sort symbol by value, section, and size.  */
3595 static int
3596 elf_sort_symbol (const void *arg1, const void *arg2)
3597 {
3598   const struct elf_link_hash_entry *h1;
3599   const struct elf_link_hash_entry *h2;
3600   bfd_signed_vma vdiff;
3601
3602   h1 = *(const struct elf_link_hash_entry **) arg1;
3603   h2 = *(const struct elf_link_hash_entry **) arg2;
3604   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3605   if (vdiff != 0)
3606     return vdiff > 0 ? 1 : -1;
3607   else
3608     {
3609       int sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3610       if (sdiff != 0)
3611         return sdiff > 0 ? 1 : -1;
3612     }
3613   vdiff = h1->size - h2->size;
3614   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3615 }
3616
3617 /* This function is used to adjust offsets into .dynstr for
3618    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3619
3620 static bfd_boolean
3621 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3622 {
3623   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3624
3625   if (h->dynindx != -1)
3626     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3627   return TRUE;
3628 }
3629
3630 /* Assign string offsets in .dynstr, update all structures referencing
3631    them.  */
3632
3633 static bfd_boolean
3634 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3635 {
3636   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3637   struct elf_link_local_dynamic_entry *entry;
3638   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3639   bfd *dynobj = hash_table->dynobj;
3640   asection *sdyn;
3641   bfd_size_type size;
3642   const struct elf_backend_data *bed;
3643   bfd_byte *extdyn;
3644
3645   _bfd_elf_strtab_finalize (dynstr);
3646   size = _bfd_elf_strtab_size (dynstr);
3647
3648   bed = get_elf_backend_data (dynobj);
3649   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3650   BFD_ASSERT (sdyn != NULL);
3651
3652   /* Update all .dynamic entries referencing .dynstr strings.  */
3653   for (extdyn = sdyn->contents;
3654        extdyn < sdyn->contents + sdyn->size;
3655        extdyn += bed->s->sizeof_dyn)
3656     {
3657       Elf_Internal_Dyn dyn;
3658
3659       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3660       switch (dyn.d_tag)
3661         {
3662         case DT_STRSZ:
3663           dyn.d_un.d_val = size;
3664           break;
3665         case DT_NEEDED:
3666         case DT_SONAME:
3667         case DT_RPATH:
3668         case DT_RUNPATH:
3669         case DT_FILTER:
3670         case DT_AUXILIARY:
3671         case DT_AUDIT:
3672         case DT_DEPAUDIT:
3673           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3674           break;
3675         default:
3676           continue;
3677         }
3678       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3679     }
3680
3681   /* Now update local dynamic symbols.  */
3682   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3683     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3684                                                   entry->isym.st_name);
3685
3686   /* And the rest of dynamic symbols.  */
3687   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3688
3689   /* Adjust version definitions.  */
3690   if (elf_tdata (output_bfd)->cverdefs)
3691     {
3692       asection *s;
3693       bfd_byte *p;
3694       size_t i;
3695       Elf_Internal_Verdef def;
3696       Elf_Internal_Verdaux defaux;
3697
3698       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3699       p = s->contents;
3700       do
3701         {
3702           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3703                                    &def);
3704           p += sizeof (Elf_External_Verdef);
3705           if (def.vd_aux != sizeof (Elf_External_Verdef))
3706             continue;
3707           for (i = 0; i < def.vd_cnt; ++i)
3708             {
3709               _bfd_elf_swap_verdaux_in (output_bfd,
3710                                         (Elf_External_Verdaux *) p, &defaux);
3711               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3712                                                         defaux.vda_name);
3713               _bfd_elf_swap_verdaux_out (output_bfd,
3714                                          &defaux, (Elf_External_Verdaux *) p);
3715               p += sizeof (Elf_External_Verdaux);
3716             }
3717         }
3718       while (def.vd_next);
3719     }
3720
3721   /* Adjust version references.  */
3722   if (elf_tdata (output_bfd)->verref)
3723     {
3724       asection *s;
3725       bfd_byte *p;
3726       size_t i;
3727       Elf_Internal_Verneed need;
3728       Elf_Internal_Vernaux needaux;
3729
3730       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3731       p = s->contents;
3732       do
3733         {
3734           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3735                                     &need);
3736           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3737           _bfd_elf_swap_verneed_out (output_bfd, &need,
3738                                      (Elf_External_Verneed *) p);
3739           p += sizeof (Elf_External_Verneed);
3740           for (i = 0; i < need.vn_cnt; ++i)
3741             {
3742               _bfd_elf_swap_vernaux_in (output_bfd,
3743                                         (Elf_External_Vernaux *) p, &needaux);
3744               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3745                                                          needaux.vna_name);
3746               _bfd_elf_swap_vernaux_out (output_bfd,
3747                                          &needaux,
3748                                          (Elf_External_Vernaux *) p);
3749               p += sizeof (Elf_External_Vernaux);
3750             }
3751         }
3752       while (need.vn_next);
3753     }
3754
3755   return TRUE;
3756 }
3757 \f
3758 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3759    The default is to only match when the INPUT and OUTPUT are exactly
3760    the same target.  */
3761
3762 bfd_boolean
3763 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3764                                     const bfd_target *output)
3765 {
3766   return input == output;
3767 }
3768
3769 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3770    This version is used when different targets for the same architecture
3771    are virtually identical.  */
3772
3773 bfd_boolean
3774 _bfd_elf_relocs_compatible (const bfd_target *input,
3775                             const bfd_target *output)
3776 {
3777   const struct elf_backend_data *obed, *ibed;
3778
3779   if (input == output)
3780     return TRUE;
3781
3782   ibed = xvec_get_elf_backend_data (input);
3783   obed = xvec_get_elf_backend_data (output);
3784
3785   if (ibed->arch != obed->arch)
3786     return FALSE;
3787
3788   /* If both backends are using this function, deem them compatible.  */
3789   return ibed->relocs_compatible == obed->relocs_compatible;
3790 }
3791
3792 /* Make a special call to the linker "notice" function to tell it that
3793    we are about to handle an as-needed lib, or have finished
3794    processing the lib.  */
3795
3796 bfd_boolean
3797 _bfd_elf_notice_as_needed (bfd *ibfd,
3798                            struct bfd_link_info *info,
3799                            enum notice_asneeded_action act)
3800 {
3801   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3802 }
3803
3804 /* Check relocations an ELF object file.  */
3805
3806 bfd_boolean
3807 _bfd_elf_link_check_relocs (bfd *abfd, struct bfd_link_info *info)
3808 {
3809   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3810   struct elf_link_hash_table *htab = elf_hash_table (info);
3811
3812   /* If this object is the same format as the output object, and it is
3813      not a shared library, then let the backend look through the
3814      relocs.
3815
3816      This is required to build global offset table entries and to
3817      arrange for dynamic relocs.  It is not required for the
3818      particular common case of linking non PIC code, even when linking
3819      against shared libraries, but unfortunately there is no way of
3820      knowing whether an object file has been compiled PIC or not.
3821      Looking through the relocs is not particularly time consuming.
3822      The problem is that we must either (1) keep the relocs in memory,
3823      which causes the linker to require additional runtime memory or
3824      (2) read the relocs twice from the input file, which wastes time.
3825      This would be a good case for using mmap.
3826
3827      I have no idea how to handle linking PIC code into a file of a
3828      different format.  It probably can't be done.  */
3829   if ((abfd->flags & DYNAMIC) == 0
3830       && is_elf_hash_table (htab)
3831       && bed->check_relocs != NULL
3832       && elf_object_id (abfd) == elf_hash_table_id (htab)
3833       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
3834     {
3835       asection *o;
3836
3837       for (o = abfd->sections; o != NULL; o = o->next)
3838         {
3839           Elf_Internal_Rela *internal_relocs;
3840           bfd_boolean ok;
3841
3842           /* Don't check relocations in excluded sections.  */
3843           if ((o->flags & SEC_RELOC) == 0
3844               || (o->flags & SEC_EXCLUDE) != 0
3845               || o->reloc_count == 0
3846               || ((info->strip == strip_all || info->strip == strip_debugger)
3847                   && (o->flags & SEC_DEBUGGING) != 0)
3848               || bfd_is_abs_section (o->output_section))
3849             continue;
3850
3851           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
3852                                                        info->keep_memory);
3853           if (internal_relocs == NULL)
3854             return FALSE;
3855
3856           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
3857
3858           if (elf_section_data (o)->relocs != internal_relocs)
3859             free (internal_relocs);
3860
3861           if (! ok)
3862             return FALSE;
3863         }
3864     }
3865
3866   return TRUE;
3867 }
3868
3869 /* Add symbols from an ELF object file to the linker hash table.  */
3870
3871 static bfd_boolean
3872 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3873 {
3874   Elf_Internal_Ehdr *ehdr;
3875   Elf_Internal_Shdr *hdr;
3876   size_t symcount;
3877   size_t extsymcount;
3878   size_t extsymoff;
3879   struct elf_link_hash_entry **sym_hash;
3880   bfd_boolean dynamic;
3881   Elf_External_Versym *extversym = NULL;
3882   Elf_External_Versym *extversym_end = NULL;
3883   Elf_External_Versym *ever;
3884   struct elf_link_hash_entry *weaks;
3885   struct elf_link_hash_entry **nondeflt_vers = NULL;
3886   size_t nondeflt_vers_cnt = 0;
3887   Elf_Internal_Sym *isymbuf = NULL;
3888   Elf_Internal_Sym *isym;
3889   Elf_Internal_Sym *isymend;
3890   const struct elf_backend_data *bed;
3891   bfd_boolean add_needed;
3892   struct elf_link_hash_table *htab;
3893   bfd_size_type amt;
3894   void *alloc_mark = NULL;
3895   struct bfd_hash_entry **old_table = NULL;
3896   unsigned int old_size = 0;
3897   unsigned int old_count = 0;
3898   void *old_tab = NULL;
3899   void *old_ent;
3900   struct bfd_link_hash_entry *old_undefs = NULL;
3901   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3902   void *old_strtab = NULL;
3903   size_t tabsize = 0;
3904   asection *s;
3905   bfd_boolean just_syms;
3906
3907   htab = elf_hash_table (info);
3908   bed = get_elf_backend_data (abfd);
3909
3910   if ((abfd->flags & DYNAMIC) == 0)
3911     dynamic = FALSE;
3912   else
3913     {
3914       dynamic = TRUE;
3915
3916       /* You can't use -r against a dynamic object.  Also, there's no
3917          hope of using a dynamic object which does not exactly match
3918          the format of the output file.  */
3919       if (bfd_link_relocatable (info)
3920           || !is_elf_hash_table (htab)
3921           || info->output_bfd->xvec != abfd->xvec)
3922         {
3923           if (bfd_link_relocatable (info))
3924             bfd_set_error (bfd_error_invalid_operation);
3925           else
3926             bfd_set_error (bfd_error_wrong_format);
3927           goto error_return;
3928         }
3929     }
3930
3931   ehdr = elf_elfheader (abfd);
3932   if (info->warn_alternate_em
3933       && bed->elf_machine_code != ehdr->e_machine
3934       && ((bed->elf_machine_alt1 != 0
3935            && ehdr->e_machine == bed->elf_machine_alt1)
3936           || (bed->elf_machine_alt2 != 0
3937               && ehdr->e_machine == bed->elf_machine_alt2)))
3938     _bfd_error_handler
3939       /* xgettext:c-format */
3940       (_("alternate ELF machine code found (%d) in %pB, expecting %d"),
3941        ehdr->e_machine, abfd, bed->elf_machine_code);
3942
3943   /* As a GNU extension, any input sections which are named
3944      .gnu.warning.SYMBOL are treated as warning symbols for the given
3945      symbol.  This differs from .gnu.warning sections, which generate
3946      warnings when they are included in an output file.  */
3947   /* PR 12761: Also generate this warning when building shared libraries.  */
3948   for (s = abfd->sections; s != NULL; s = s->next)
3949     {
3950       const char *name;
3951
3952       name = bfd_get_section_name (abfd, s);
3953       if (CONST_STRNEQ (name, ".gnu.warning."))
3954         {
3955           char *msg;
3956           bfd_size_type sz;
3957
3958           name += sizeof ".gnu.warning." - 1;
3959
3960           /* If this is a shared object, then look up the symbol
3961              in the hash table.  If it is there, and it is already
3962              been defined, then we will not be using the entry
3963              from this shared object, so we don't need to warn.
3964              FIXME: If we see the definition in a regular object
3965              later on, we will warn, but we shouldn't.  The only
3966              fix is to keep track of what warnings we are supposed
3967              to emit, and then handle them all at the end of the
3968              link.  */
3969           if (dynamic)
3970             {
3971               struct elf_link_hash_entry *h;
3972
3973               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3974
3975               /* FIXME: What about bfd_link_hash_common?  */
3976               if (h != NULL
3977                   && (h->root.type == bfd_link_hash_defined
3978                       || h->root.type == bfd_link_hash_defweak))
3979                 continue;
3980             }
3981
3982           sz = s->size;
3983           msg = (char *) bfd_alloc (abfd, sz + 1);
3984           if (msg == NULL)
3985             goto error_return;
3986
3987           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3988             goto error_return;
3989
3990           msg[sz] = '\0';
3991
3992           if (! (_bfd_generic_link_add_one_symbol
3993                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3994                   FALSE, bed->collect, NULL)))
3995             goto error_return;
3996
3997           if (bfd_link_executable (info))
3998             {
3999               /* Clobber the section size so that the warning does
4000                  not get copied into the output file.  */
4001               s->size = 0;
4002
4003               /* Also set SEC_EXCLUDE, so that symbols defined in
4004                  the warning section don't get copied to the output.  */
4005               s->flags |= SEC_EXCLUDE;
4006             }
4007         }
4008     }
4009
4010   just_syms = ((s = abfd->sections) != NULL
4011                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
4012
4013   add_needed = TRUE;
4014   if (! dynamic)
4015     {
4016       /* If we are creating a shared library, create all the dynamic
4017          sections immediately.  We need to attach them to something,
4018          so we attach them to this BFD, provided it is the right
4019          format and is not from ld --just-symbols.  Always create the
4020          dynamic sections for -E/--dynamic-list.  FIXME: If there
4021          are no input BFD's of the same format as the output, we can't
4022          make a shared library.  */
4023       if (!just_syms
4024           && (bfd_link_pic (info)
4025               || (!bfd_link_relocatable (info)
4026                   && info->nointerp
4027                   && (info->export_dynamic || info->dynamic)))
4028           && is_elf_hash_table (htab)
4029           && info->output_bfd->xvec == abfd->xvec
4030           && !htab->dynamic_sections_created)
4031         {
4032           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
4033             goto error_return;
4034         }
4035     }
4036   else if (!is_elf_hash_table (htab))
4037     goto error_return;
4038   else
4039     {
4040       const char *soname = NULL;
4041       char *audit = NULL;
4042       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
4043       const Elf_Internal_Phdr *phdr;
4044       int ret;
4045
4046       /* ld --just-symbols and dynamic objects don't mix very well.
4047          ld shouldn't allow it.  */
4048       if (just_syms)
4049         abort ();
4050
4051       /* If this dynamic lib was specified on the command line with
4052          --as-needed in effect, then we don't want to add a DT_NEEDED
4053          tag unless the lib is actually used.  Similary for libs brought
4054          in by another lib's DT_NEEDED.  When --no-add-needed is used
4055          on a dynamic lib, we don't want to add a DT_NEEDED entry for
4056          any dynamic library in DT_NEEDED tags in the dynamic lib at
4057          all.  */
4058       add_needed = (elf_dyn_lib_class (abfd)
4059                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
4060                        | DYN_NO_NEEDED)) == 0;
4061
4062       s = bfd_get_section_by_name (abfd, ".dynamic");
4063       if (s != NULL)
4064         {
4065           bfd_byte *dynbuf;
4066           bfd_byte *extdyn;
4067           unsigned int elfsec;
4068           unsigned long shlink;
4069
4070           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
4071             {
4072 error_free_dyn:
4073               free (dynbuf);
4074               goto error_return;
4075             }
4076
4077           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
4078           if (elfsec == SHN_BAD)
4079             goto error_free_dyn;
4080           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
4081
4082           for (extdyn = dynbuf;
4083                extdyn <= dynbuf + s->size - bed->s->sizeof_dyn;
4084                extdyn += bed->s->sizeof_dyn)
4085             {
4086               Elf_Internal_Dyn dyn;
4087
4088               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
4089               if (dyn.d_tag == DT_SONAME)
4090                 {
4091                   unsigned int tagv = dyn.d_un.d_val;
4092                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4093                   if (soname == NULL)
4094                     goto error_free_dyn;
4095                 }
4096               if (dyn.d_tag == DT_NEEDED)
4097                 {
4098                   struct bfd_link_needed_list *n, **pn;
4099                   char *fnm, *anm;
4100                   unsigned int tagv = dyn.d_un.d_val;
4101
4102                   amt = sizeof (struct bfd_link_needed_list);
4103                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
4104                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4105                   if (n == NULL || fnm == NULL)
4106                     goto error_free_dyn;
4107                   amt = strlen (fnm) + 1;
4108                   anm = (char *) bfd_alloc (abfd, amt);
4109                   if (anm == NULL)
4110                     goto error_free_dyn;
4111                   memcpy (anm, fnm, amt);
4112                   n->name = anm;
4113                   n->by = abfd;
4114                   n->next = NULL;
4115                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
4116                     ;
4117                   *pn = n;
4118                 }
4119               if (dyn.d_tag == DT_RUNPATH)
4120                 {
4121                   struct bfd_link_needed_list *n, **pn;
4122                   char *fnm, *anm;
4123                   unsigned int tagv = dyn.d_un.d_val;
4124
4125                   amt = sizeof (struct bfd_link_needed_list);
4126                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
4127                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4128                   if (n == NULL || fnm == NULL)
4129                     goto error_free_dyn;
4130                   amt = strlen (fnm) + 1;
4131                   anm = (char *) bfd_alloc (abfd, amt);
4132                   if (anm == NULL)
4133                     goto error_free_dyn;
4134                   memcpy (anm, fnm, amt);
4135                   n->name = anm;
4136                   n->by = abfd;
4137                   n->next = NULL;
4138                   for (pn = & runpath;
4139                        *pn != NULL;
4140                        pn = &(*pn)->next)
4141                     ;
4142                   *pn = n;
4143                 }
4144               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
4145               if (!runpath && dyn.d_tag == DT_RPATH)
4146                 {
4147                   struct bfd_link_needed_list *n, **pn;
4148                   char *fnm, *anm;
4149                   unsigned int tagv = dyn.d_un.d_val;
4150
4151                   amt = sizeof (struct bfd_link_needed_list);
4152                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
4153                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4154                   if (n == NULL || fnm == NULL)
4155                     goto error_free_dyn;
4156                   amt = strlen (fnm) + 1;
4157                   anm = (char *) bfd_alloc (abfd, amt);
4158                   if (anm == NULL)
4159                     goto error_free_dyn;
4160                   memcpy (anm, fnm, amt);
4161                   n->name = anm;
4162                   n->by = abfd;
4163                   n->next = NULL;
4164                   for (pn = & rpath;
4165                        *pn != NULL;
4166                        pn = &(*pn)->next)
4167                     ;
4168                   *pn = n;
4169                 }
4170               if (dyn.d_tag == DT_AUDIT)
4171                 {
4172                   unsigned int tagv = dyn.d_un.d_val;
4173                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4174                 }
4175             }
4176
4177           free (dynbuf);
4178         }
4179
4180       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
4181          frees all more recently bfd_alloc'd blocks as well.  */
4182       if (runpath)
4183         rpath = runpath;
4184
4185       if (rpath)
4186         {
4187           struct bfd_link_needed_list **pn;
4188           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
4189             ;
4190           *pn = rpath;
4191         }
4192
4193       /* If we have a PT_GNU_RELRO program header, mark as read-only
4194          all sections contained fully therein.  This makes relro
4195          shared library sections appear as they will at run-time.  */
4196       phdr = elf_tdata (abfd)->phdr + elf_elfheader (abfd)->e_phnum;
4197       while (phdr-- > elf_tdata (abfd)->phdr)
4198         if (phdr->p_type == PT_GNU_RELRO)
4199           {
4200             for (s = abfd->sections; s != NULL; s = s->next)
4201               if ((s->flags & SEC_ALLOC) != 0
4202                   && s->vma >= phdr->p_vaddr
4203                   && s->vma + s->size <= phdr->p_vaddr + phdr->p_memsz)
4204                 s->flags |= SEC_READONLY;
4205             break;
4206           }
4207
4208       /* We do not want to include any of the sections in a dynamic
4209          object in the output file.  We hack by simply clobbering the
4210          list of sections in the BFD.  This could be handled more
4211          cleanly by, say, a new section flag; the existing
4212          SEC_NEVER_LOAD flag is not the one we want, because that one
4213          still implies that the section takes up space in the output
4214          file.  */
4215       bfd_section_list_clear (abfd);
4216
4217       /* Find the name to use in a DT_NEEDED entry that refers to this
4218          object.  If the object has a DT_SONAME entry, we use it.
4219          Otherwise, if the generic linker stuck something in
4220          elf_dt_name, we use that.  Otherwise, we just use the file
4221          name.  */
4222       if (soname == NULL || *soname == '\0')
4223         {
4224           soname = elf_dt_name (abfd);
4225           if (soname == NULL || *soname == '\0')
4226             soname = bfd_get_filename (abfd);
4227         }
4228
4229       /* Save the SONAME because sometimes the linker emulation code
4230          will need to know it.  */
4231       elf_dt_name (abfd) = soname;
4232
4233       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4234       if (ret < 0)
4235         goto error_return;
4236
4237       /* If we have already included this dynamic object in the
4238          link, just ignore it.  There is no reason to include a
4239          particular dynamic object more than once.  */
4240       if (ret > 0)
4241         return TRUE;
4242
4243       /* Save the DT_AUDIT entry for the linker emulation code. */
4244       elf_dt_audit (abfd) = audit;
4245     }
4246
4247   /* If this is a dynamic object, we always link against the .dynsym
4248      symbol table, not the .symtab symbol table.  The dynamic linker
4249      will only see the .dynsym symbol table, so there is no reason to
4250      look at .symtab for a dynamic object.  */
4251
4252   if (! dynamic || elf_dynsymtab (abfd) == 0)
4253     hdr = &elf_tdata (abfd)->symtab_hdr;
4254   else
4255     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
4256
4257   symcount = hdr->sh_size / bed->s->sizeof_sym;
4258
4259   /* The sh_info field of the symtab header tells us where the
4260      external symbols start.  We don't care about the local symbols at
4261      this point.  */
4262   if (elf_bad_symtab (abfd))
4263     {
4264       extsymcount = symcount;
4265       extsymoff = 0;
4266     }
4267   else
4268     {
4269       extsymcount = symcount - hdr->sh_info;
4270       extsymoff = hdr->sh_info;
4271     }
4272
4273   sym_hash = elf_sym_hashes (abfd);
4274   if (extsymcount != 0)
4275     {
4276       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
4277                                       NULL, NULL, NULL);
4278       if (isymbuf == NULL)
4279         goto error_return;
4280
4281       if (sym_hash == NULL)
4282         {
4283           /* We store a pointer to the hash table entry for each
4284              external symbol.  */
4285           amt = extsymcount;
4286           amt *= sizeof (struct elf_link_hash_entry *);
4287           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
4288           if (sym_hash == NULL)
4289             goto error_free_sym;
4290           elf_sym_hashes (abfd) = sym_hash;
4291         }
4292     }
4293
4294   if (dynamic)
4295     {
4296       /* Read in any version definitions.  */
4297       if (!_bfd_elf_slurp_version_tables (abfd,
4298                                           info->default_imported_symver))
4299         goto error_free_sym;
4300
4301       /* Read in the symbol versions, but don't bother to convert them
4302          to internal format.  */
4303       if (elf_dynversym (abfd) != 0)
4304         {
4305           Elf_Internal_Shdr *versymhdr;
4306
4307           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
4308           amt = versymhdr->sh_size;
4309           extversym = (Elf_External_Versym *) bfd_malloc (amt);
4310           if (extversym == NULL)
4311             goto error_free_sym;
4312           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
4313               || bfd_bread (extversym, amt, abfd) != amt)
4314             goto error_free_vers;
4315           extversym_end = extversym + (amt / sizeof (* extversym));
4316         }
4317     }
4318
4319   /* If we are loading an as-needed shared lib, save the symbol table
4320      state before we start adding symbols.  If the lib turns out
4321      to be unneeded, restore the state.  */
4322   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4323     {
4324       unsigned int i;
4325       size_t entsize;
4326
4327       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
4328         {
4329           struct bfd_hash_entry *p;
4330           struct elf_link_hash_entry *h;
4331
4332           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4333             {
4334               h = (struct elf_link_hash_entry *) p;
4335               entsize += htab->root.table.entsize;
4336               if (h->root.type == bfd_link_hash_warning)
4337                 entsize += htab->root.table.entsize;
4338             }
4339         }
4340
4341       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
4342       old_tab = bfd_malloc (tabsize + entsize);
4343       if (old_tab == NULL)
4344         goto error_free_vers;
4345
4346       /* Remember the current objalloc pointer, so that all mem for
4347          symbols added can later be reclaimed.  */
4348       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
4349       if (alloc_mark == NULL)
4350         goto error_free_vers;
4351
4352       /* Make a special call to the linker "notice" function to
4353          tell it that we are about to handle an as-needed lib.  */
4354       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
4355         goto error_free_vers;
4356
4357       /* Clone the symbol table.  Remember some pointers into the
4358          symbol table, and dynamic symbol count.  */
4359       old_ent = (char *) old_tab + tabsize;
4360       memcpy (old_tab, htab->root.table.table, tabsize);
4361       old_undefs = htab->root.undefs;
4362       old_undefs_tail = htab->root.undefs_tail;
4363       old_table = htab->root.table.table;
4364       old_size = htab->root.table.size;
4365       old_count = htab->root.table.count;
4366       old_strtab = _bfd_elf_strtab_save (htab->dynstr);
4367       if (old_strtab == NULL)
4368         goto error_free_vers;
4369
4370       for (i = 0; i < htab->root.table.size; i++)
4371         {
4372           struct bfd_hash_entry *p;
4373           struct elf_link_hash_entry *h;
4374
4375           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4376             {
4377               memcpy (old_ent, p, htab->root.table.entsize);
4378               old_ent = (char *) old_ent + htab->root.table.entsize;
4379               h = (struct elf_link_hash_entry *) p;
4380               if (h->root.type == bfd_link_hash_warning)
4381                 {
4382                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
4383                   old_ent = (char *) old_ent + htab->root.table.entsize;
4384                 }
4385             }
4386         }
4387     }
4388
4389   weaks = NULL;
4390   if (extversym == NULL)
4391     ever = NULL;
4392   else if (extversym + extsymoff < extversym_end)
4393     ever = extversym + extsymoff;
4394   else
4395     {
4396       /* xgettext:c-format */
4397       _bfd_error_handler (_("%pB: invalid version offset %lx (max %lx)"),
4398                           abfd, (long) extsymoff,
4399                           (long) (extversym_end - extversym) / sizeof (* extversym));
4400       bfd_set_error (bfd_error_bad_value);
4401       goto error_free_vers;
4402     }
4403
4404   for (isym = isymbuf, isymend = isymbuf + extsymcount;
4405        isym < isymend;
4406        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
4407     {
4408       int bind;
4409       bfd_vma value;
4410       asection *sec, *new_sec;
4411       flagword flags;
4412       const char *name;
4413       struct elf_link_hash_entry *h;
4414       struct elf_link_hash_entry *hi;
4415       bfd_boolean definition;
4416       bfd_boolean size_change_ok;
4417       bfd_boolean type_change_ok;
4418       bfd_boolean new_weak;
4419       bfd_boolean old_weak;
4420       bfd_boolean override;
4421       bfd_boolean common;
4422       bfd_boolean discarded;
4423       unsigned int old_alignment;
4424       bfd *old_bfd;
4425       bfd_boolean matched;
4426
4427       override = FALSE;
4428
4429       flags = BSF_NO_FLAGS;
4430       sec = NULL;
4431       value = isym->st_value;
4432       common = bed->common_definition (isym);
4433       if (common && info->inhibit_common_definition)
4434         {
4435           /* Treat common symbol as undefined for --no-define-common.  */
4436           isym->st_shndx = SHN_UNDEF;
4437           common = FALSE;
4438         }
4439       discarded = FALSE;
4440
4441       bind = ELF_ST_BIND (isym->st_info);
4442       switch (bind)
4443         {
4444         case STB_LOCAL:
4445           /* This should be impossible, since ELF requires that all
4446              global symbols follow all local symbols, and that sh_info
4447              point to the first global symbol.  Unfortunately, Irix 5
4448              screws this up.  */
4449           if (elf_bad_symtab (abfd))
4450             continue;
4451
4452           /* If we aren't prepared to handle locals within the globals
4453              then we'll likely segfault on a NULL section.  */
4454           bfd_set_error (bfd_error_bad_value);
4455           goto error_free_vers;
4456
4457         case STB_GLOBAL:
4458           if (isym->st_shndx != SHN_UNDEF && !common)
4459             flags = BSF_GLOBAL;
4460           break;
4461
4462         case STB_WEAK:
4463           flags = BSF_WEAK;
4464           break;
4465
4466         case STB_GNU_UNIQUE:
4467           flags = BSF_GNU_UNIQUE;
4468           break;
4469
4470         default:
4471           /* Leave it up to the processor backend.  */
4472           break;
4473         }
4474
4475       if (isym->st_shndx == SHN_UNDEF)
4476         sec = bfd_und_section_ptr;
4477       else if (isym->st_shndx == SHN_ABS)
4478         sec = bfd_abs_section_ptr;
4479       else if (isym->st_shndx == SHN_COMMON)
4480         {
4481           sec = bfd_com_section_ptr;
4482           /* What ELF calls the size we call the value.  What ELF
4483              calls the value we call the alignment.  */
4484           value = isym->st_size;
4485         }
4486       else
4487         {
4488           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
4489           if (sec == NULL)
4490             sec = bfd_abs_section_ptr;
4491           else if (discarded_section (sec))
4492             {
4493               /* Symbols from discarded section are undefined.  We keep
4494                  its visibility.  */
4495               sec = bfd_und_section_ptr;
4496               discarded = TRUE;
4497               isym->st_shndx = SHN_UNDEF;
4498             }
4499           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
4500             value -= sec->vma;
4501         }
4502
4503       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4504                                               isym->st_name);
4505       if (name == NULL)
4506         goto error_free_vers;
4507
4508       if (isym->st_shndx == SHN_COMMON
4509           && (abfd->flags & BFD_PLUGIN) != 0)
4510         {
4511           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4512
4513           if (xc == NULL)
4514             {
4515               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4516                                  | SEC_EXCLUDE);
4517               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4518               if (xc == NULL)
4519                 goto error_free_vers;
4520             }
4521           sec = xc;
4522         }
4523       else if (isym->st_shndx == SHN_COMMON
4524                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4525                && !bfd_link_relocatable (info))
4526         {
4527           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4528
4529           if (tcomm == NULL)
4530             {
4531               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4532                                  | SEC_LINKER_CREATED);
4533               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4534               if (tcomm == NULL)
4535                 goto error_free_vers;
4536             }
4537           sec = tcomm;
4538         }
4539       else if (bed->elf_add_symbol_hook)
4540         {
4541           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4542                                              &sec, &value))
4543             goto error_free_vers;
4544
4545           /* The hook function sets the name to NULL if this symbol
4546              should be skipped for some reason.  */
4547           if (name == NULL)
4548             continue;
4549         }
4550
4551       /* Sanity check that all possibilities were handled.  */
4552       if (sec == NULL)
4553         {
4554           bfd_set_error (bfd_error_bad_value);
4555           goto error_free_vers;
4556         }
4557
4558       /* Silently discard TLS symbols from --just-syms.  There's
4559          no way to combine a static TLS block with a new TLS block
4560          for this executable.  */
4561       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4562           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4563         continue;
4564
4565       if (bfd_is_und_section (sec)
4566           || bfd_is_com_section (sec))
4567         definition = FALSE;
4568       else
4569         definition = TRUE;
4570
4571       size_change_ok = FALSE;
4572       type_change_ok = bed->type_change_ok;
4573       old_weak = FALSE;
4574       matched = FALSE;
4575       old_alignment = 0;
4576       old_bfd = NULL;
4577       new_sec = sec;
4578
4579       if (is_elf_hash_table (htab))
4580         {
4581           Elf_Internal_Versym iver;
4582           unsigned int vernum = 0;
4583           bfd_boolean skip;
4584
4585           if (ever == NULL)
4586             {
4587               if (info->default_imported_symver)
4588                 /* Use the default symbol version created earlier.  */
4589                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4590               else
4591                 iver.vs_vers = 0;
4592             }
4593           else if (ever >= extversym_end)
4594             {
4595               /* xgettext:c-format */
4596               _bfd_error_handler (_("%pB: not enough version information"),
4597                                   abfd);
4598               bfd_set_error (bfd_error_bad_value);
4599               goto error_free_vers;
4600             }
4601           else
4602             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4603
4604           vernum = iver.vs_vers & VERSYM_VERSION;
4605
4606           /* If this is a hidden symbol, or if it is not version
4607              1, we append the version name to the symbol name.
4608              However, we do not modify a non-hidden absolute symbol
4609              if it is not a function, because it might be the version
4610              symbol itself.  FIXME: What if it isn't?  */
4611           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4612               || (vernum > 1
4613                   && (!bfd_is_abs_section (sec)
4614                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4615             {
4616               const char *verstr;
4617               size_t namelen, verlen, newlen;
4618               char *newname, *p;
4619
4620               if (isym->st_shndx != SHN_UNDEF)
4621                 {
4622                   if (vernum > elf_tdata (abfd)->cverdefs)
4623                     verstr = NULL;
4624                   else if (vernum > 1)
4625                     verstr =
4626                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4627                   else
4628                     verstr = "";
4629
4630                   if (verstr == NULL)
4631                     {
4632                       _bfd_error_handler
4633                         /* xgettext:c-format */
4634                         (_("%pB: %s: invalid version %u (max %d)"),
4635                          abfd, name, vernum,
4636                          elf_tdata (abfd)->cverdefs);
4637                       bfd_set_error (bfd_error_bad_value);
4638                       goto error_free_vers;
4639                     }
4640                 }
4641               else
4642                 {
4643                   /* We cannot simply test for the number of
4644                      entries in the VERNEED section since the
4645                      numbers for the needed versions do not start
4646                      at 0.  */
4647                   Elf_Internal_Verneed *t;
4648
4649                   verstr = NULL;
4650                   for (t = elf_tdata (abfd)->verref;
4651                        t != NULL;
4652                        t = t->vn_nextref)
4653                     {
4654                       Elf_Internal_Vernaux *a;
4655
4656                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4657                         {
4658                           if (a->vna_other == vernum)
4659                             {
4660                               verstr = a->vna_nodename;
4661                               break;
4662                             }
4663                         }
4664                       if (a != NULL)
4665                         break;
4666                     }
4667                   if (verstr == NULL)
4668                     {
4669                       _bfd_error_handler
4670                         /* xgettext:c-format */
4671                         (_("%pB: %s: invalid needed version %d"),
4672                          abfd, name, vernum);
4673                       bfd_set_error (bfd_error_bad_value);
4674                       goto error_free_vers;
4675                     }
4676                 }
4677
4678               namelen = strlen (name);
4679               verlen = strlen (verstr);
4680               newlen = namelen + verlen + 2;
4681               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4682                   && isym->st_shndx != SHN_UNDEF)
4683                 ++newlen;
4684
4685               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4686               if (newname == NULL)
4687                 goto error_free_vers;
4688               memcpy (newname, name, namelen);
4689               p = newname + namelen;
4690               *p++ = ELF_VER_CHR;
4691               /* If this is a defined non-hidden version symbol,
4692                  we add another @ to the name.  This indicates the
4693                  default version of the symbol.  */
4694               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4695                   && isym->st_shndx != SHN_UNDEF)
4696                 *p++ = ELF_VER_CHR;
4697               memcpy (p, verstr, verlen + 1);
4698
4699               name = newname;
4700             }
4701
4702           /* If this symbol has default visibility and the user has
4703              requested we not re-export it, then mark it as hidden.  */
4704           if (!bfd_is_und_section (sec)
4705               && !dynamic
4706               && abfd->no_export
4707               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4708             isym->st_other = (STV_HIDDEN
4709                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4710
4711           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4712                                       sym_hash, &old_bfd, &old_weak,
4713                                       &old_alignment, &skip, &override,
4714                                       &type_change_ok, &size_change_ok,
4715                                       &matched))
4716             goto error_free_vers;
4717
4718           if (skip)
4719             continue;
4720
4721           /* Override a definition only if the new symbol matches the
4722              existing one.  */
4723           if (override && matched)
4724             definition = FALSE;
4725
4726           h = *sym_hash;
4727           while (h->root.type == bfd_link_hash_indirect
4728                  || h->root.type == bfd_link_hash_warning)
4729             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4730
4731           if (elf_tdata (abfd)->verdef != NULL
4732               && vernum > 1
4733               && definition)
4734             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4735         }
4736
4737       if (! (_bfd_generic_link_add_one_symbol
4738              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4739               (struct bfd_link_hash_entry **) sym_hash)))
4740         goto error_free_vers;
4741
4742       if ((abfd->flags & DYNAMIC) == 0
4743           && (bfd_get_flavour (info->output_bfd)
4744               == bfd_target_elf_flavour))
4745         {
4746           if (ELF_ST_TYPE (isym->st_info) == STT_GNU_IFUNC)
4747             elf_tdata (info->output_bfd)->has_gnu_symbols
4748               |= elf_gnu_symbol_ifunc;
4749           if ((flags & BSF_GNU_UNIQUE))
4750             elf_tdata (info->output_bfd)->has_gnu_symbols
4751               |= elf_gnu_symbol_unique;
4752         }
4753
4754       h = *sym_hash;
4755       /* We need to make sure that indirect symbol dynamic flags are
4756          updated.  */
4757       hi = h;
4758       while (h->root.type == bfd_link_hash_indirect
4759              || h->root.type == bfd_link_hash_warning)
4760         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4761
4762       /* Setting the index to -3 tells elf_link_output_extsym that
4763          this symbol is defined in a discarded section.  */
4764       if (discarded)
4765         h->indx = -3;
4766
4767       *sym_hash = h;
4768
4769       new_weak = (flags & BSF_WEAK) != 0;
4770       if (dynamic
4771           && definition
4772           && new_weak
4773           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4774           && is_elf_hash_table (htab)
4775           && h->u.alias == NULL)
4776         {
4777           /* Keep a list of all weak defined non function symbols from
4778              a dynamic object, using the alias field.  Later in this
4779              function we will set the alias field to the correct
4780              value.  We only put non-function symbols from dynamic
4781              objects on this list, because that happens to be the only
4782              time we need to know the normal symbol corresponding to a
4783              weak symbol, and the information is time consuming to
4784              figure out.  If the alias field is not already NULL,
4785              then this symbol was already defined by some previous
4786              dynamic object, and we will be using that previous
4787              definition anyhow.  */
4788
4789           h->u.alias = weaks;
4790           weaks = h;
4791         }
4792
4793       /* Set the alignment of a common symbol.  */
4794       if ((common || bfd_is_com_section (sec))
4795           && h->root.type == bfd_link_hash_common)
4796         {
4797           unsigned int align;
4798
4799           if (common)
4800             align = bfd_log2 (isym->st_value);
4801           else
4802             {
4803               /* The new symbol is a common symbol in a shared object.
4804                  We need to get the alignment from the section.  */
4805               align = new_sec->alignment_power;
4806             }
4807           if (align > old_alignment)
4808             h->root.u.c.p->alignment_power = align;
4809           else
4810             h->root.u.c.p->alignment_power = old_alignment;
4811         }
4812
4813       if (is_elf_hash_table (htab))
4814         {
4815           /* Set a flag in the hash table entry indicating the type of
4816              reference or definition we just found.  A dynamic symbol
4817              is one which is referenced or defined by both a regular
4818              object and a shared object.  */
4819           bfd_boolean dynsym = FALSE;
4820
4821           /* Plugin symbols aren't normal.  Don't set def_regular or
4822              ref_regular for them, or make them dynamic.  */
4823           if ((abfd->flags & BFD_PLUGIN) != 0)
4824             ;
4825           else if (! dynamic)
4826             {
4827               if (! definition)
4828                 {
4829                   h->ref_regular = 1;
4830                   if (bind != STB_WEAK)
4831                     h->ref_regular_nonweak = 1;
4832                 }
4833               else
4834                 {
4835                   h->def_regular = 1;
4836                   if (h->def_dynamic)
4837                     {
4838                       h->def_dynamic = 0;
4839                       h->ref_dynamic = 1;
4840                     }
4841                 }
4842
4843               /* If the indirect symbol has been forced local, don't
4844                  make the real symbol dynamic.  */
4845               if ((h == hi || !hi->forced_local)
4846                   && (bfd_link_dll (info)
4847                       || h->def_dynamic
4848                       || h->ref_dynamic))
4849                 dynsym = TRUE;
4850             }
4851           else
4852             {
4853               if (! definition)
4854                 {
4855                   h->ref_dynamic = 1;
4856                   hi->ref_dynamic = 1;
4857                 }
4858               else
4859                 {
4860                   h->def_dynamic = 1;
4861                   hi->def_dynamic = 1;
4862                 }
4863
4864               /* If the indirect symbol has been forced local, don't
4865                  make the real symbol dynamic.  */
4866               if ((h == hi || !hi->forced_local)
4867                   && (h->def_regular
4868                       || h->ref_regular
4869                       || (h->is_weakalias
4870                           && weakdef (h)->dynindx != -1)))
4871                 dynsym = TRUE;
4872             }
4873
4874           /* Check to see if we need to add an indirect symbol for
4875              the default name.  */
4876           if (definition
4877               || (!override && h->root.type == bfd_link_hash_common))
4878             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4879                                               sec, value, &old_bfd, &dynsym))
4880               goto error_free_vers;
4881
4882           /* Check the alignment when a common symbol is involved. This
4883              can change when a common symbol is overridden by a normal
4884              definition or a common symbol is ignored due to the old
4885              normal definition. We need to make sure the maximum
4886              alignment is maintained.  */
4887           if ((old_alignment || common)
4888               && h->root.type != bfd_link_hash_common)
4889             {
4890               unsigned int common_align;
4891               unsigned int normal_align;
4892               unsigned int symbol_align;
4893               bfd *normal_bfd;
4894               bfd *common_bfd;
4895
4896               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4897                           || h->root.type == bfd_link_hash_defweak);
4898
4899               symbol_align = ffs (h->root.u.def.value) - 1;
4900               if (h->root.u.def.section->owner != NULL
4901                   && (h->root.u.def.section->owner->flags
4902                        & (DYNAMIC | BFD_PLUGIN)) == 0)
4903                 {
4904                   normal_align = h->root.u.def.section->alignment_power;
4905                   if (normal_align > symbol_align)
4906                     normal_align = symbol_align;
4907                 }
4908               else
4909                 normal_align = symbol_align;
4910
4911               if (old_alignment)
4912                 {
4913                   common_align = old_alignment;
4914                   common_bfd = old_bfd;
4915                   normal_bfd = abfd;
4916                 }
4917               else
4918                 {
4919                   common_align = bfd_log2 (isym->st_value);
4920                   common_bfd = abfd;
4921                   normal_bfd = old_bfd;
4922                 }
4923
4924               if (normal_align < common_align)
4925                 {
4926                   /* PR binutils/2735 */
4927                   if (normal_bfd == NULL)
4928                     _bfd_error_handler
4929                       /* xgettext:c-format */
4930                       (_("warning: alignment %u of common symbol `%s' in %pB is"
4931                          " greater than the alignment (%u) of its section %pA"),
4932                        1 << common_align, name, common_bfd,
4933                        1 << normal_align, h->root.u.def.section);
4934                   else
4935                     _bfd_error_handler
4936                       /* xgettext:c-format */
4937                       (_("warning: alignment %u of symbol `%s' in %pB"
4938                          " is smaller than %u in %pB"),
4939                        1 << normal_align, name, normal_bfd,
4940                        1 << common_align, common_bfd);
4941                 }
4942             }
4943
4944           /* Remember the symbol size if it isn't undefined.  */
4945           if (isym->st_size != 0
4946               && isym->st_shndx != SHN_UNDEF
4947               && (definition || h->size == 0))
4948             {
4949               if (h->size != 0
4950                   && h->size != isym->st_size
4951                   && ! size_change_ok)
4952                 _bfd_error_handler
4953                   /* xgettext:c-format */
4954                   (_("warning: size of symbol `%s' changed"
4955                      " from %" PRIu64 " in %pB to %" PRIu64 " in %pB"),
4956                    name, (uint64_t) h->size, old_bfd,
4957                    (uint64_t) isym->st_size, abfd);
4958
4959               h->size = isym->st_size;
4960             }
4961
4962           /* If this is a common symbol, then we always want H->SIZE
4963              to be the size of the common symbol.  The code just above
4964              won't fix the size if a common symbol becomes larger.  We
4965              don't warn about a size change here, because that is
4966              covered by --warn-common.  Allow changes between different
4967              function types.  */
4968           if (h->root.type == bfd_link_hash_common)
4969             h->size = h->root.u.c.size;
4970
4971           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4972               && ((definition && !new_weak)
4973                   || (old_weak && h->root.type == bfd_link_hash_common)
4974                   || h->type == STT_NOTYPE))
4975             {
4976               unsigned int type = ELF_ST_TYPE (isym->st_info);
4977
4978               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4979                  symbol.  */
4980               if (type == STT_GNU_IFUNC
4981                   && (abfd->flags & DYNAMIC) != 0)
4982                 type = STT_FUNC;
4983
4984               if (h->type != type)
4985                 {
4986                   if (h->type != STT_NOTYPE && ! type_change_ok)
4987                     /* xgettext:c-format */
4988                     _bfd_error_handler
4989                       (_("warning: type of symbol `%s' changed"
4990                          " from %d to %d in %pB"),
4991                        name, h->type, type, abfd);
4992
4993                   h->type = type;
4994                 }
4995             }
4996
4997           /* Merge st_other field.  */
4998           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4999
5000           /* We don't want to make debug symbol dynamic.  */
5001           if (definition
5002               && (sec->flags & SEC_DEBUGGING)
5003               && !bfd_link_relocatable (info))
5004             dynsym = FALSE;
5005
5006           /* Nor should we make plugin symbols dynamic.  */
5007           if ((abfd->flags & BFD_PLUGIN) != 0)
5008             dynsym = FALSE;
5009
5010           if (definition)
5011             {
5012               h->target_internal = isym->st_target_internal;
5013               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
5014             }
5015
5016           if (definition && !dynamic)
5017             {
5018               char *p = strchr (name, ELF_VER_CHR);
5019               if (p != NULL && p[1] != ELF_VER_CHR)
5020                 {
5021                   /* Queue non-default versions so that .symver x, x@FOO
5022                      aliases can be checked.  */
5023                   if (!nondeflt_vers)
5024                     {
5025                       amt = ((isymend - isym + 1)
5026                              * sizeof (struct elf_link_hash_entry *));
5027                       nondeflt_vers
5028                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
5029                       if (!nondeflt_vers)
5030                         goto error_free_vers;
5031                     }
5032                   nondeflt_vers[nondeflt_vers_cnt++] = h;
5033                 }
5034             }
5035
5036           if (dynsym && h->dynindx == -1)
5037             {
5038               if (! bfd_elf_link_record_dynamic_symbol (info, h))
5039                 goto error_free_vers;
5040               if (h->is_weakalias
5041                   && weakdef (h)->dynindx == -1)
5042                 {
5043                   if (!bfd_elf_link_record_dynamic_symbol (info, weakdef (h)))
5044                     goto error_free_vers;
5045                 }
5046             }
5047           else if (h->dynindx != -1)
5048             /* If the symbol already has a dynamic index, but
5049                visibility says it should not be visible, turn it into
5050                a local symbol.  */
5051             switch (ELF_ST_VISIBILITY (h->other))
5052               {
5053               case STV_INTERNAL:
5054               case STV_HIDDEN:
5055                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
5056                 dynsym = FALSE;
5057                 break;
5058               }
5059
5060           /* Don't add DT_NEEDED for references from the dummy bfd nor
5061              for unmatched symbol.  */
5062           if (!add_needed
5063               && matched
5064               && definition
5065               && ((dynsym
5066                    && h->ref_regular_nonweak
5067                    && (old_bfd == NULL
5068                        || (old_bfd->flags & BFD_PLUGIN) == 0))
5069                   || (h->ref_dynamic_nonweak
5070                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
5071                       && !on_needed_list (elf_dt_name (abfd),
5072                                           htab->needed, NULL))))
5073             {
5074               int ret;
5075               const char *soname = elf_dt_name (abfd);
5076
5077               info->callbacks->minfo ("%!", soname, old_bfd,
5078                                       h->root.root.string);
5079
5080               /* A symbol from a library loaded via DT_NEEDED of some
5081                  other library is referenced by a regular object.
5082                  Add a DT_NEEDED entry for it.  Issue an error if
5083                  --no-add-needed is used and the reference was not
5084                  a weak one.  */
5085               if (old_bfd != NULL
5086                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
5087                 {
5088                   _bfd_error_handler
5089                     /* xgettext:c-format */
5090                     (_("%pB: undefined reference to symbol '%s'"),
5091                      old_bfd, name);
5092                   bfd_set_error (bfd_error_missing_dso);
5093                   goto error_free_vers;
5094                 }
5095
5096               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
5097                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
5098
5099               add_needed = TRUE;
5100               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
5101               if (ret < 0)
5102                 goto error_free_vers;
5103
5104               BFD_ASSERT (ret == 0);
5105             }
5106         }
5107     }
5108
5109   if (info->lto_plugin_active
5110       && !bfd_link_relocatable (info)
5111       && (abfd->flags & BFD_PLUGIN) == 0
5112       && !just_syms
5113       && extsymcount)
5114     {
5115       int r_sym_shift;
5116
5117       if (bed->s->arch_size == 32)
5118         r_sym_shift = 8;
5119       else
5120         r_sym_shift = 32;
5121
5122       /* If linker plugin is enabled, set non_ir_ref_regular on symbols
5123          referenced in regular objects so that linker plugin will get
5124          the correct symbol resolution.  */
5125
5126       sym_hash = elf_sym_hashes (abfd);
5127       for (s = abfd->sections; s != NULL; s = s->next)
5128         {
5129           Elf_Internal_Rela *internal_relocs;
5130           Elf_Internal_Rela *rel, *relend;
5131
5132           /* Don't check relocations in excluded sections.  */
5133           if ((s->flags & SEC_RELOC) == 0
5134               || s->reloc_count == 0
5135               || (s->flags & SEC_EXCLUDE) != 0
5136               || ((info->strip == strip_all
5137                    || info->strip == strip_debugger)
5138                   && (s->flags & SEC_DEBUGGING) != 0))
5139             continue;
5140
5141           internal_relocs = _bfd_elf_link_read_relocs (abfd, s, NULL,
5142                                                        NULL,
5143                                                        info->keep_memory);
5144           if (internal_relocs == NULL)
5145             goto error_free_vers;
5146
5147           rel = internal_relocs;
5148           relend = rel + s->reloc_count;
5149           for ( ; rel < relend; rel++)
5150             {
5151               unsigned long r_symndx = rel->r_info >> r_sym_shift;
5152               struct elf_link_hash_entry *h;
5153
5154               /* Skip local symbols.  */
5155               if (r_symndx < extsymoff)
5156                 continue;
5157
5158               h = sym_hash[r_symndx - extsymoff];
5159               if (h != NULL)
5160                 h->root.non_ir_ref_regular = 1;
5161             }
5162
5163           if (elf_section_data (s)->relocs != internal_relocs)
5164             free (internal_relocs);
5165         }
5166     }
5167
5168   if (extversym != NULL)
5169     {
5170       free (extversym);
5171       extversym = NULL;
5172     }
5173
5174   if (isymbuf != NULL)
5175     {
5176       free (isymbuf);
5177       isymbuf = NULL;
5178     }
5179
5180   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
5181     {
5182       unsigned int i;
5183
5184       /* Restore the symbol table.  */
5185       old_ent = (char *) old_tab + tabsize;
5186       memset (elf_sym_hashes (abfd), 0,
5187               extsymcount * sizeof (struct elf_link_hash_entry *));
5188       htab->root.table.table = old_table;
5189       htab->root.table.size = old_size;
5190       htab->root.table.count = old_count;
5191       memcpy (htab->root.table.table, old_tab, tabsize);
5192       htab->root.undefs = old_undefs;
5193       htab->root.undefs_tail = old_undefs_tail;
5194       _bfd_elf_strtab_restore (htab->dynstr, old_strtab);
5195       free (old_strtab);
5196       old_strtab = NULL;
5197       for (i = 0; i < htab->root.table.size; i++)
5198         {
5199           struct bfd_hash_entry *p;
5200           struct elf_link_hash_entry *h;
5201           bfd_size_type size;
5202           unsigned int alignment_power;
5203           unsigned int non_ir_ref_dynamic;
5204
5205           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
5206             {
5207               h = (struct elf_link_hash_entry *) p;
5208               if (h->root.type == bfd_link_hash_warning)
5209                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
5210
5211               /* Preserve the maximum alignment and size for common
5212                  symbols even if this dynamic lib isn't on DT_NEEDED
5213                  since it can still be loaded at run time by another
5214                  dynamic lib.  */
5215               if (h->root.type == bfd_link_hash_common)
5216                 {
5217                   size = h->root.u.c.size;
5218                   alignment_power = h->root.u.c.p->alignment_power;
5219                 }
5220               else
5221                 {
5222                   size = 0;
5223                   alignment_power = 0;
5224                 }
5225               /* Preserve non_ir_ref_dynamic so that this symbol
5226                  will be exported when the dynamic lib becomes needed
5227                  in the second pass.  */
5228               non_ir_ref_dynamic = h->root.non_ir_ref_dynamic;
5229               memcpy (p, old_ent, htab->root.table.entsize);
5230               old_ent = (char *) old_ent + htab->root.table.entsize;
5231               h = (struct elf_link_hash_entry *) p;
5232               if (h->root.type == bfd_link_hash_warning)
5233                 {
5234                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
5235                   old_ent = (char *) old_ent + htab->root.table.entsize;
5236                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
5237                 }
5238               if (h->root.type == bfd_link_hash_common)
5239                 {
5240                   if (size > h->root.u.c.size)
5241                     h->root.u.c.size = size;
5242                   if (alignment_power > h->root.u.c.p->alignment_power)
5243                     h->root.u.c.p->alignment_power = alignment_power;
5244                 }
5245               h->root.non_ir_ref_dynamic = non_ir_ref_dynamic;
5246             }
5247         }
5248
5249       /* Make a special call to the linker "notice" function to
5250          tell it that symbols added for crefs may need to be removed.  */
5251       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
5252         goto error_free_vers;
5253
5254       free (old_tab);
5255       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
5256                            alloc_mark);
5257       if (nondeflt_vers != NULL)
5258         free (nondeflt_vers);
5259       return TRUE;
5260     }
5261
5262   if (old_tab != NULL)
5263     {
5264       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
5265         goto error_free_vers;
5266       free (old_tab);
5267       old_tab = NULL;
5268     }
5269
5270   /* Now that all the symbols from this input file are created, if
5271      not performing a relocatable link, handle .symver foo, foo@BAR
5272      such that any relocs against foo become foo@BAR.  */
5273   if (!bfd_link_relocatable (info) && nondeflt_vers != NULL)
5274     {
5275       size_t cnt, symidx;
5276
5277       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
5278         {
5279           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
5280           char *shortname, *p;
5281
5282           p = strchr (h->root.root.string, ELF_VER_CHR);
5283           if (p == NULL
5284               || (h->root.type != bfd_link_hash_defined
5285                   && h->root.type != bfd_link_hash_defweak))
5286             continue;
5287
5288           amt = p - h->root.root.string;
5289           shortname = (char *) bfd_malloc (amt + 1);
5290           if (!shortname)
5291             goto error_free_vers;
5292           memcpy (shortname, h->root.root.string, amt);
5293           shortname[amt] = '\0';
5294
5295           hi = (struct elf_link_hash_entry *)
5296                bfd_link_hash_lookup (&htab->root, shortname,
5297                                      FALSE, FALSE, FALSE);
5298           if (hi != NULL
5299               && hi->root.type == h->root.type
5300               && hi->root.u.def.value == h->root.u.def.value
5301               && hi->root.u.def.section == h->root.u.def.section)
5302             {
5303               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
5304               hi->root.type = bfd_link_hash_indirect;
5305               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
5306               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
5307               sym_hash = elf_sym_hashes (abfd);
5308               if (sym_hash)
5309                 for (symidx = 0; symidx < extsymcount; ++symidx)
5310                   if (sym_hash[symidx] == hi)
5311                     {
5312                       sym_hash[symidx] = h;
5313                       break;
5314                     }
5315             }
5316           free (shortname);
5317         }
5318       free (nondeflt_vers);
5319       nondeflt_vers = NULL;
5320     }
5321
5322   /* Now set the alias field correctly for all the weak defined
5323      symbols we found.  The only way to do this is to search all the
5324      symbols.  Since we only need the information for non functions in
5325      dynamic objects, that's the only time we actually put anything on
5326      the list WEAKS.  We need this information so that if a regular
5327      object refers to a symbol defined weakly in a dynamic object, the
5328      real symbol in the dynamic object is also put in the dynamic
5329      symbols; we also must arrange for both symbols to point to the
5330      same memory location.  We could handle the general case of symbol
5331      aliasing, but a general symbol alias can only be generated in
5332      assembler code, handling it correctly would be very time
5333      consuming, and other ELF linkers don't handle general aliasing
5334      either.  */
5335   if (weaks != NULL)
5336     {
5337       struct elf_link_hash_entry **hpp;
5338       struct elf_link_hash_entry **hppend;
5339       struct elf_link_hash_entry **sorted_sym_hash;
5340       struct elf_link_hash_entry *h;
5341       size_t sym_count;
5342
5343       /* Since we have to search the whole symbol list for each weak
5344          defined symbol, search time for N weak defined symbols will be
5345          O(N^2). Binary search will cut it down to O(NlogN).  */
5346       amt = extsymcount;
5347       amt *= sizeof (struct elf_link_hash_entry *);
5348       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
5349       if (sorted_sym_hash == NULL)
5350         goto error_return;
5351       sym_hash = sorted_sym_hash;
5352       hpp = elf_sym_hashes (abfd);
5353       hppend = hpp + extsymcount;
5354       sym_count = 0;
5355       for (; hpp < hppend; hpp++)
5356         {
5357           h = *hpp;
5358           if (h != NULL
5359               && h->root.type == bfd_link_hash_defined
5360               && !bed->is_function_type (h->type))
5361             {
5362               *sym_hash = h;
5363               sym_hash++;
5364               sym_count++;
5365             }
5366         }
5367
5368       qsort (sorted_sym_hash, sym_count,
5369              sizeof (struct elf_link_hash_entry *),
5370              elf_sort_symbol);
5371
5372       while (weaks != NULL)
5373         {
5374           struct elf_link_hash_entry *hlook;
5375           asection *slook;
5376           bfd_vma vlook;
5377           size_t i, j, idx = 0;
5378
5379           hlook = weaks;
5380           weaks = hlook->u.alias;
5381           hlook->u.alias = NULL;
5382
5383           if (hlook->root.type != bfd_link_hash_defined
5384               && hlook->root.type != bfd_link_hash_defweak)
5385             continue;
5386
5387           slook = hlook->root.u.def.section;
5388           vlook = hlook->root.u.def.value;
5389
5390           i = 0;
5391           j = sym_count;
5392           while (i != j)
5393             {
5394               bfd_signed_vma vdiff;
5395               idx = (i + j) / 2;
5396               h = sorted_sym_hash[idx];
5397               vdiff = vlook - h->root.u.def.value;
5398               if (vdiff < 0)
5399                 j = idx;
5400               else if (vdiff > 0)
5401                 i = idx + 1;
5402               else
5403                 {
5404                   int sdiff = slook->id - h->root.u.def.section->id;
5405                   if (sdiff < 0)
5406                     j = idx;
5407                   else if (sdiff > 0)
5408                     i = idx + 1;
5409                   else
5410                     break;
5411                 }
5412             }
5413
5414           /* We didn't find a value/section match.  */
5415           if (i == j)
5416             continue;
5417
5418           /* With multiple aliases, or when the weak symbol is already
5419              strongly defined, we have multiple matching symbols and
5420              the binary search above may land on any of them.  Step
5421              one past the matching symbol(s).  */
5422           while (++idx != j)
5423             {
5424               h = sorted_sym_hash[idx];
5425               if (h->root.u.def.section != slook
5426                   || h->root.u.def.value != vlook)
5427                 break;
5428             }
5429
5430           /* Now look back over the aliases.  Since we sorted by size
5431              as well as value and section, we'll choose the one with
5432              the largest size.  */
5433           while (idx-- != i)
5434             {
5435               h = sorted_sym_hash[idx];
5436
5437               /* Stop if value or section doesn't match.  */
5438               if (h->root.u.def.section != slook
5439                   || h->root.u.def.value != vlook)
5440                 break;
5441               else if (h != hlook)
5442                 {
5443                   struct elf_link_hash_entry *t;
5444
5445                   hlook->u.alias = h;
5446                   hlook->is_weakalias = 1;
5447                   t = h;
5448                   if (t->u.alias != NULL)
5449                     while (t->u.alias != h)
5450                       t = t->u.alias;
5451                   t->u.alias = hlook;
5452
5453                   /* If the weak definition is in the list of dynamic
5454                      symbols, make sure the real definition is put
5455                      there as well.  */
5456                   if (hlook->dynindx != -1 && h->dynindx == -1)
5457                     {
5458                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
5459                         {
5460                         err_free_sym_hash:
5461                           free (sorted_sym_hash);
5462                           goto error_return;
5463                         }
5464                     }
5465
5466                   /* If the real definition is in the list of dynamic
5467                      symbols, make sure the weak definition is put
5468                      there as well.  If we don't do this, then the
5469                      dynamic loader might not merge the entries for the
5470                      real definition and the weak definition.  */
5471                   if (h->dynindx != -1 && hlook->dynindx == -1)
5472                     {
5473                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
5474                         goto err_free_sym_hash;
5475                     }
5476                   break;
5477                 }
5478             }
5479         }
5480
5481       free (sorted_sym_hash);
5482     }
5483
5484   if (bed->check_directives
5485       && !(*bed->check_directives) (abfd, info))
5486     return FALSE;
5487
5488   /* If this is a non-traditional link, try to optimize the handling
5489      of the .stab/.stabstr sections.  */
5490   if (! dynamic
5491       && ! info->traditional_format
5492       && is_elf_hash_table (htab)
5493       && (info->strip != strip_all && info->strip != strip_debugger))
5494     {
5495       asection *stabstr;
5496
5497       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
5498       if (stabstr != NULL)
5499         {
5500           bfd_size_type string_offset = 0;
5501           asection *stab;
5502
5503           for (stab = abfd->sections; stab; stab = stab->next)
5504             if (CONST_STRNEQ (stab->name, ".stab")
5505                 && (!stab->name[5] ||
5506                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
5507                 && (stab->flags & SEC_MERGE) == 0
5508                 && !bfd_is_abs_section (stab->output_section))
5509               {
5510                 struct bfd_elf_section_data *secdata;
5511
5512                 secdata = elf_section_data (stab);
5513                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
5514                                                stabstr, &secdata->sec_info,
5515                                                &string_offset))
5516                   goto error_return;
5517                 if (secdata->sec_info)
5518                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
5519             }
5520         }
5521     }
5522
5523   if (is_elf_hash_table (htab) && add_needed)
5524     {
5525       /* Add this bfd to the loaded list.  */
5526       struct elf_link_loaded_list *n;
5527
5528       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
5529       if (n == NULL)
5530         goto error_return;
5531       n->abfd = abfd;
5532       n->next = htab->loaded;
5533       htab->loaded = n;
5534     }
5535
5536   return TRUE;
5537
5538  error_free_vers:
5539   if (old_tab != NULL)
5540     free (old_tab);
5541   if (old_strtab != NULL)
5542     free (old_strtab);
5543   if (nondeflt_vers != NULL)
5544     free (nondeflt_vers);
5545   if (extversym != NULL)
5546     free (extversym);
5547  error_free_sym:
5548   if (isymbuf != NULL)
5549     free (isymbuf);
5550  error_return:
5551   return FALSE;
5552 }
5553
5554 /* Return the linker hash table entry of a symbol that might be
5555    satisfied by an archive symbol.  Return -1 on error.  */
5556
5557 struct elf_link_hash_entry *
5558 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5559                                 struct bfd_link_info *info,
5560                                 const char *name)
5561 {
5562   struct elf_link_hash_entry *h;
5563   char *p, *copy;
5564   size_t len, first;
5565
5566   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5567   if (h != NULL)
5568     return h;
5569
5570   /* If this is a default version (the name contains @@), look up the
5571      symbol again with only one `@' as well as without the version.
5572      The effect is that references to the symbol with and without the
5573      version will be matched by the default symbol in the archive.  */
5574
5575   p = strchr (name, ELF_VER_CHR);
5576   if (p == NULL || p[1] != ELF_VER_CHR)
5577     return h;
5578
5579   /* First check with only one `@'.  */
5580   len = strlen (name);
5581   copy = (char *) bfd_alloc (abfd, len);
5582   if (copy == NULL)
5583     return (struct elf_link_hash_entry *) -1;
5584
5585   first = p - name + 1;
5586   memcpy (copy, name, first);
5587   memcpy (copy + first, name + first + 1, len - first);
5588
5589   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5590   if (h == NULL)
5591     {
5592       /* We also need to check references to the symbol without the
5593          version.  */
5594       copy[first - 1] = '\0';
5595       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5596                                 FALSE, FALSE, TRUE);
5597     }
5598
5599   bfd_release (abfd, copy);
5600   return h;
5601 }
5602
5603 /* Add symbols from an ELF archive file to the linker hash table.  We
5604    don't use _bfd_generic_link_add_archive_symbols because we need to
5605    handle versioned symbols.
5606
5607    Fortunately, ELF archive handling is simpler than that done by
5608    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5609    oddities.  In ELF, if we find a symbol in the archive map, and the
5610    symbol is currently undefined, we know that we must pull in that
5611    object file.
5612
5613    Unfortunately, we do have to make multiple passes over the symbol
5614    table until nothing further is resolved.  */
5615
5616 static bfd_boolean
5617 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5618 {
5619   symindex c;
5620   unsigned char *included = NULL;
5621   carsym *symdefs;
5622   bfd_boolean loop;
5623   bfd_size_type amt;
5624   const struct elf_backend_data *bed;
5625   struct elf_link_hash_entry * (*archive_symbol_lookup)
5626     (bfd *, struct bfd_link_info *, const char *);
5627
5628   if (! bfd_has_map (abfd))
5629     {
5630       /* An empty archive is a special case.  */
5631       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5632         return TRUE;
5633       bfd_set_error (bfd_error_no_armap);
5634       return FALSE;
5635     }
5636
5637   /* Keep track of all symbols we know to be already defined, and all
5638      files we know to be already included.  This is to speed up the
5639      second and subsequent passes.  */
5640   c = bfd_ardata (abfd)->symdef_count;
5641   if (c == 0)
5642     return TRUE;
5643   amt = c;
5644   amt *= sizeof (*included);
5645   included = (unsigned char *) bfd_zmalloc (amt);
5646   if (included == NULL)
5647     return FALSE;
5648
5649   symdefs = bfd_ardata (abfd)->symdefs;
5650   bed = get_elf_backend_data (abfd);
5651   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5652
5653   do
5654     {
5655       file_ptr last;
5656       symindex i;
5657       carsym *symdef;
5658       carsym *symdefend;
5659
5660       loop = FALSE;
5661       last = -1;
5662
5663       symdef = symdefs;
5664       symdefend = symdef + c;
5665       for (i = 0; symdef < symdefend; symdef++, i++)
5666         {
5667           struct elf_link_hash_entry *h;
5668           bfd *element;
5669           struct bfd_link_hash_entry *undefs_tail;
5670           symindex mark;
5671
5672           if (included[i])
5673             continue;
5674           if (symdef->file_offset == last)
5675             {
5676               included[i] = TRUE;
5677               continue;
5678             }
5679
5680           h = archive_symbol_lookup (abfd, info, symdef->name);
5681           if (h == (struct elf_link_hash_entry *) -1)
5682             goto error_return;
5683
5684           if (h == NULL)
5685             continue;
5686
5687           if (h->root.type == bfd_link_hash_common)
5688             {
5689               /* We currently have a common symbol.  The archive map contains
5690                  a reference to this symbol, so we may want to include it.  We
5691                  only want to include it however, if this archive element
5692                  contains a definition of the symbol, not just another common
5693                  declaration of it.
5694
5695                  Unfortunately some archivers (including GNU ar) will put
5696                  declarations of common symbols into their archive maps, as
5697                  well as real definitions, so we cannot just go by the archive
5698                  map alone.  Instead we must read in the element's symbol
5699                  table and check that to see what kind of symbol definition
5700                  this is.  */
5701               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5702                 continue;
5703             }
5704           else if (h->root.type != bfd_link_hash_undefined)
5705             {
5706               if (h->root.type != bfd_link_hash_undefweak)
5707                 /* Symbol must be defined.  Don't check it again.  */
5708                 included[i] = TRUE;
5709               continue;
5710             }
5711
5712           /* We need to include this archive member.  */
5713           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5714           if (element == NULL)
5715             goto error_return;
5716
5717           if (! bfd_check_format (element, bfd_object))
5718             goto error_return;
5719
5720           undefs_tail = info->hash->undefs_tail;
5721
5722           if (!(*info->callbacks
5723                 ->add_archive_element) (info, element, symdef->name, &element))
5724             continue;
5725           if (!bfd_link_add_symbols (element, info))
5726             goto error_return;
5727
5728           /* If there are any new undefined symbols, we need to make
5729              another pass through the archive in order to see whether
5730              they can be defined.  FIXME: This isn't perfect, because
5731              common symbols wind up on undefs_tail and because an
5732              undefined symbol which is defined later on in this pass
5733              does not require another pass.  This isn't a bug, but it
5734              does make the code less efficient than it could be.  */
5735           if (undefs_tail != info->hash->undefs_tail)
5736             loop = TRUE;
5737
5738           /* Look backward to mark all symbols from this object file
5739              which we have already seen in this pass.  */
5740           mark = i;
5741           do
5742             {
5743               included[mark] = TRUE;
5744               if (mark == 0)
5745                 break;
5746               --mark;
5747             }
5748           while (symdefs[mark].file_offset == symdef->file_offset);
5749
5750           /* We mark subsequent symbols from this object file as we go
5751              on through the loop.  */
5752           last = symdef->file_offset;
5753         }
5754     }
5755   while (loop);
5756
5757   free (included);
5758
5759   return TRUE;
5760
5761  error_return:
5762   if (included != NULL)
5763     free (included);
5764   return FALSE;
5765 }
5766
5767 /* Given an ELF BFD, add symbols to the global hash table as
5768    appropriate.  */
5769
5770 bfd_boolean
5771 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5772 {
5773   switch (bfd_get_format (abfd))
5774     {
5775     case bfd_object:
5776       return elf_link_add_object_symbols (abfd, info);
5777     case bfd_archive:
5778       return elf_link_add_archive_symbols (abfd, info);
5779     default:
5780       bfd_set_error (bfd_error_wrong_format);
5781       return FALSE;
5782     }
5783 }
5784 \f
5785 struct hash_codes_info
5786 {
5787   unsigned long *hashcodes;
5788   bfd_boolean error;
5789 };
5790
5791 /* This function will be called though elf_link_hash_traverse to store
5792    all hash value of the exported symbols in an array.  */
5793
5794 static bfd_boolean
5795 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5796 {
5797   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5798   const char *name;
5799   unsigned long ha;
5800   char *alc = NULL;
5801
5802   /* Ignore indirect symbols.  These are added by the versioning code.  */
5803   if (h->dynindx == -1)
5804     return TRUE;
5805
5806   name = h->root.root.string;
5807   if (h->versioned >= versioned)
5808     {
5809       char *p = strchr (name, ELF_VER_CHR);
5810       if (p != NULL)
5811         {
5812           alc = (char *) bfd_malloc (p - name + 1);
5813           if (alc == NULL)
5814             {
5815               inf->error = TRUE;
5816               return FALSE;
5817             }
5818           memcpy (alc, name, p - name);
5819           alc[p - name] = '\0';
5820           name = alc;
5821         }
5822     }
5823
5824   /* Compute the hash value.  */
5825   ha = bfd_elf_hash (name);
5826
5827   /* Store the found hash value in the array given as the argument.  */
5828   *(inf->hashcodes)++ = ha;
5829
5830   /* And store it in the struct so that we can put it in the hash table
5831      later.  */
5832   h->u.elf_hash_value = ha;
5833
5834   if (alc != NULL)
5835     free (alc);
5836
5837   return TRUE;
5838 }
5839
5840 struct collect_gnu_hash_codes
5841 {
5842   bfd *output_bfd;
5843   const struct elf_backend_data *bed;
5844   unsigned long int nsyms;
5845   unsigned long int maskbits;
5846   unsigned long int *hashcodes;
5847   unsigned long int *hashval;
5848   unsigned long int *indx;
5849   unsigned long int *counts;
5850   bfd_vma *bitmask;
5851   bfd_byte *contents;
5852   long int min_dynindx;
5853   unsigned long int bucketcount;
5854   unsigned long int symindx;
5855   long int local_indx;
5856   long int shift1, shift2;
5857   unsigned long int mask;
5858   bfd_boolean error;
5859 };
5860
5861 /* This function will be called though elf_link_hash_traverse to store
5862    all hash value of the exported symbols in an array.  */
5863
5864 static bfd_boolean
5865 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5866 {
5867   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5868   const char *name;
5869   unsigned long ha;
5870   char *alc = NULL;
5871
5872   /* Ignore indirect symbols.  These are added by the versioning code.  */
5873   if (h->dynindx == -1)
5874     return TRUE;
5875
5876   /* Ignore also local symbols and undefined symbols.  */
5877   if (! (*s->bed->elf_hash_symbol) (h))
5878     return TRUE;
5879
5880   name = h->root.root.string;
5881   if (h->versioned >= versioned)
5882     {
5883       char *p = strchr (name, ELF_VER_CHR);
5884       if (p != NULL)
5885         {
5886           alc = (char *) bfd_malloc (p - name + 1);
5887           if (alc == NULL)
5888             {
5889               s->error = TRUE;
5890               return FALSE;
5891             }
5892           memcpy (alc, name, p - name);
5893           alc[p - name] = '\0';
5894           name = alc;
5895         }
5896     }
5897
5898   /* Compute the hash value.  */
5899   ha = bfd_elf_gnu_hash (name);
5900
5901   /* Store the found hash value in the array for compute_bucket_count,
5902      and also for .dynsym reordering purposes.  */
5903   s->hashcodes[s->nsyms] = ha;
5904   s->hashval[h->dynindx] = ha;
5905   ++s->nsyms;
5906   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5907     s->min_dynindx = h->dynindx;
5908
5909   if (alc != NULL)
5910     free (alc);
5911
5912   return TRUE;
5913 }
5914
5915 /* This function will be called though elf_link_hash_traverse to do
5916    final dynaminc symbol renumbering.  */
5917
5918 static bfd_boolean
5919 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5920 {
5921   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5922   unsigned long int bucket;
5923   unsigned long int val;
5924
5925   /* Ignore indirect symbols.  */
5926   if (h->dynindx == -1)
5927     return TRUE;
5928
5929   /* Ignore also local symbols and undefined symbols.  */
5930   if (! (*s->bed->elf_hash_symbol) (h))
5931     {
5932       if (h->dynindx >= s->min_dynindx)
5933         h->dynindx = s->local_indx++;
5934       return TRUE;
5935     }
5936
5937   bucket = s->hashval[h->dynindx] % s->bucketcount;
5938   val = (s->hashval[h->dynindx] >> s->shift1)
5939         & ((s->maskbits >> s->shift1) - 1);
5940   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5941   s->bitmask[val]
5942     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5943   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5944   if (s->counts[bucket] == 1)
5945     /* Last element terminates the chain.  */
5946     val |= 1;
5947   bfd_put_32 (s->output_bfd, val,
5948               s->contents + (s->indx[bucket] - s->symindx) * 4);
5949   --s->counts[bucket];
5950   h->dynindx = s->indx[bucket]++;
5951   return TRUE;
5952 }
5953
5954 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5955
5956 bfd_boolean
5957 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5958 {
5959   return !(h->forced_local
5960            || h->root.type == bfd_link_hash_undefined
5961            || h->root.type == bfd_link_hash_undefweak
5962            || ((h->root.type == bfd_link_hash_defined
5963                 || h->root.type == bfd_link_hash_defweak)
5964                && h->root.u.def.section->output_section == NULL));
5965 }
5966
5967 /* Array used to determine the number of hash table buckets to use
5968    based on the number of symbols there are.  If there are fewer than
5969    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5970    fewer than 37 we use 17 buckets, and so forth.  We never use more
5971    than 32771 buckets.  */
5972
5973 static const size_t elf_buckets[] =
5974 {
5975   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5976   16411, 32771, 0
5977 };
5978
5979 /* Compute bucket count for hashing table.  We do not use a static set
5980    of possible tables sizes anymore.  Instead we determine for all
5981    possible reasonable sizes of the table the outcome (i.e., the
5982    number of collisions etc) and choose the best solution.  The
5983    weighting functions are not too simple to allow the table to grow
5984    without bounds.  Instead one of the weighting factors is the size.
5985    Therefore the result is always a good payoff between few collisions
5986    (= short chain lengths) and table size.  */
5987 static size_t
5988 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5989                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5990                       unsigned long int nsyms,
5991                       int gnu_hash)
5992 {
5993   size_t best_size = 0;
5994   unsigned long int i;
5995
5996   /* We have a problem here.  The following code to optimize the table
5997      size requires an integer type with more the 32 bits.  If
5998      BFD_HOST_U_64_BIT is set we know about such a type.  */
5999 #ifdef BFD_HOST_U_64_BIT
6000   if (info->optimize)
6001     {
6002       size_t minsize;
6003       size_t maxsize;
6004       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
6005       bfd *dynobj = elf_hash_table (info)->dynobj;
6006       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
6007       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
6008       unsigned long int *counts;
6009       bfd_size_type amt;
6010       unsigned int no_improvement_count = 0;
6011
6012       /* Possible optimization parameters: if we have NSYMS symbols we say
6013          that the hashing table must at least have NSYMS/4 and at most
6014          2*NSYMS buckets.  */
6015       minsize = nsyms / 4;
6016       if (minsize == 0)
6017         minsize = 1;
6018       best_size = maxsize = nsyms * 2;
6019       if (gnu_hash)
6020         {
6021           if (minsize < 2)
6022             minsize = 2;
6023           if ((best_size & 31) == 0)
6024             ++best_size;
6025         }
6026
6027       /* Create array where we count the collisions in.  We must use bfd_malloc
6028          since the size could be large.  */
6029       amt = maxsize;
6030       amt *= sizeof (unsigned long int);
6031       counts = (unsigned long int *) bfd_malloc (amt);
6032       if (counts == NULL)
6033         return 0;
6034
6035       /* Compute the "optimal" size for the hash table.  The criteria is a
6036          minimal chain length.  The minor criteria is (of course) the size
6037          of the table.  */
6038       for (i = minsize; i < maxsize; ++i)
6039         {
6040           /* Walk through the array of hashcodes and count the collisions.  */
6041           BFD_HOST_U_64_BIT max;
6042           unsigned long int j;
6043           unsigned long int fact;
6044
6045           if (gnu_hash && (i & 31) == 0)
6046             continue;
6047
6048           memset (counts, '\0', i * sizeof (unsigned long int));
6049
6050           /* Determine how often each hash bucket is used.  */
6051           for (j = 0; j < nsyms; ++j)
6052             ++counts[hashcodes[j] % i];
6053
6054           /* For the weight function we need some information about the
6055              pagesize on the target.  This is information need not be 100%
6056              accurate.  Since this information is not available (so far) we
6057              define it here to a reasonable default value.  If it is crucial
6058              to have a better value some day simply define this value.  */
6059 # ifndef BFD_TARGET_PAGESIZE
6060 #  define BFD_TARGET_PAGESIZE   (4096)
6061 # endif
6062
6063           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
6064              and the chains.  */
6065           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
6066
6067 # if 1
6068           /* Variant 1: optimize for short chains.  We add the squares
6069              of all the chain lengths (which favors many small chain
6070              over a few long chains).  */
6071           for (j = 0; j < i; ++j)
6072             max += counts[j] * counts[j];
6073
6074           /* This adds penalties for the overall size of the table.  */
6075           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
6076           max *= fact * fact;
6077 # else
6078           /* Variant 2: Optimize a lot more for small table.  Here we
6079              also add squares of the size but we also add penalties for
6080              empty slots (the +1 term).  */
6081           for (j = 0; j < i; ++j)
6082             max += (1 + counts[j]) * (1 + counts[j]);
6083
6084           /* The overall size of the table is considered, but not as
6085              strong as in variant 1, where it is squared.  */
6086           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
6087           max *= fact;
6088 # endif
6089
6090           /* Compare with current best results.  */
6091           if (max < best_chlen)
6092             {
6093               best_chlen = max;
6094               best_size = i;
6095               no_improvement_count = 0;
6096             }
6097           /* PR 11843: Avoid futile long searches for the best bucket size
6098              when there are a large number of symbols.  */
6099           else if (++no_improvement_count == 100)
6100             break;
6101         }
6102
6103       free (counts);
6104     }
6105   else
6106 #endif /* defined (BFD_HOST_U_64_BIT) */
6107     {
6108       /* This is the fallback solution if no 64bit type is available or if we
6109          are not supposed to spend much time on optimizations.  We select the
6110          bucket count using a fixed set of numbers.  */
6111       for (i = 0; elf_buckets[i] != 0; i++)
6112         {
6113           best_size = elf_buckets[i];
6114           if (nsyms < elf_buckets[i + 1])
6115             break;
6116         }
6117       if (gnu_hash && best_size < 2)
6118         best_size = 2;
6119     }
6120
6121   return best_size;
6122 }
6123
6124 /* Size any SHT_GROUP section for ld -r.  */
6125
6126 bfd_boolean
6127 _bfd_elf_size_group_sections (struct bfd_link_info *info)
6128 {
6129   bfd *ibfd;
6130   asection *s;
6131
6132   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
6133     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
6134         && (s = ibfd->sections) != NULL
6135         && s->sec_info_type != SEC_INFO_TYPE_JUST_SYMS
6136         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
6137       return FALSE;
6138   return TRUE;
6139 }
6140
6141 /* Set a default stack segment size.  The value in INFO wins.  If it
6142    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
6143    undefined it is initialized.  */
6144
6145 bfd_boolean
6146 bfd_elf_stack_segment_size (bfd *output_bfd,
6147                             struct bfd_link_info *info,
6148                             const char *legacy_symbol,
6149                             bfd_vma default_size)
6150 {
6151   struct elf_link_hash_entry *h = NULL;
6152
6153   /* Look for legacy symbol.  */
6154   if (legacy_symbol)
6155     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
6156                               FALSE, FALSE, FALSE);
6157   if (h && (h->root.type == bfd_link_hash_defined
6158             || h->root.type == bfd_link_hash_defweak)
6159       && h->def_regular
6160       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
6161     {
6162       /* The symbol has no type if specified on the command line.  */
6163       h->type = STT_OBJECT;
6164       if (info->stacksize)
6165         /* xgettext:c-format */
6166         _bfd_error_handler (_("%pB: stack size specified and %s set"),
6167                             output_bfd, legacy_symbol);
6168       else if (h->root.u.def.section != bfd_abs_section_ptr)
6169         /* xgettext:c-format */
6170         _bfd_error_handler (_("%pB: %s not absolute"),
6171                             output_bfd, legacy_symbol);
6172       else
6173         info->stacksize = h->root.u.def.value;
6174     }
6175
6176   if (!info->stacksize)
6177     /* If the user didn't set a size, or explicitly inhibit the
6178        size, set it now.  */
6179     info->stacksize = default_size;
6180
6181   /* Provide the legacy symbol, if it is referenced.  */
6182   if (h && (h->root.type == bfd_link_hash_undefined
6183             || h->root.type == bfd_link_hash_undefweak))
6184     {
6185       struct bfd_link_hash_entry *bh = NULL;
6186
6187       if (!(_bfd_generic_link_add_one_symbol
6188             (info, output_bfd, legacy_symbol,
6189              BSF_GLOBAL, bfd_abs_section_ptr,
6190              info->stacksize >= 0 ? info->stacksize : 0,
6191              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
6192         return FALSE;
6193
6194       h = (struct elf_link_hash_entry *) bh;
6195       h->def_regular = 1;
6196       h->type = STT_OBJECT;
6197     }
6198
6199   return TRUE;
6200 }
6201
6202 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
6203
6204 struct elf_gc_sweep_symbol_info
6205 {
6206   struct bfd_link_info *info;
6207   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
6208                        bfd_boolean);
6209 };
6210
6211 static bfd_boolean
6212 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
6213 {
6214   if (!h->mark
6215       && (((h->root.type == bfd_link_hash_defined
6216             || h->root.type == bfd_link_hash_defweak)
6217            && !((h->def_regular || ELF_COMMON_DEF_P (h))
6218                 && h->root.u.def.section->gc_mark))
6219           || h->root.type == bfd_link_hash_undefined
6220           || h->root.type == bfd_link_hash_undefweak))
6221     {
6222       struct elf_gc_sweep_symbol_info *inf;
6223
6224       inf = (struct elf_gc_sweep_symbol_info *) data;
6225       (*inf->hide_symbol) (inf->info, h, TRUE);
6226       h->def_regular = 0;
6227       h->ref_regular = 0;
6228       h->ref_regular_nonweak = 0;
6229     }
6230
6231   return TRUE;
6232 }
6233
6234 /* Set up the sizes and contents of the ELF dynamic sections.  This is
6235    called by the ELF linker emulation before_allocation routine.  We
6236    must set the sizes of the sections before the linker sets the
6237    addresses of the various sections.  */
6238
6239 bfd_boolean
6240 bfd_elf_size_dynamic_sections (bfd *output_bfd,
6241                                const char *soname,
6242                                const char *rpath,
6243                                const char *filter_shlib,
6244                                const char *audit,
6245                                const char *depaudit,
6246                                const char * const *auxiliary_filters,
6247                                struct bfd_link_info *info,
6248                                asection **sinterpptr)
6249 {
6250   bfd *dynobj;
6251   const struct elf_backend_data *bed;
6252
6253   *sinterpptr = NULL;
6254
6255   if (!is_elf_hash_table (info->hash))
6256     return TRUE;
6257
6258   dynobj = elf_hash_table (info)->dynobj;
6259
6260   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6261     {
6262       struct bfd_elf_version_tree *verdefs;
6263       struct elf_info_failed asvinfo;
6264       struct bfd_elf_version_tree *t;
6265       struct bfd_elf_version_expr *d;
6266       asection *s;
6267       size_t soname_indx;
6268
6269       /* If we are supposed to export all symbols into the dynamic symbol
6270          table (this is not the normal case), then do so.  */
6271       if (info->export_dynamic
6272           || (bfd_link_executable (info) && info->dynamic))
6273         {
6274           struct elf_info_failed eif;
6275
6276           eif.info = info;
6277           eif.failed = FALSE;
6278           elf_link_hash_traverse (elf_hash_table (info),
6279                                   _bfd_elf_export_symbol,
6280                                   &eif);
6281           if (eif.failed)
6282             return FALSE;
6283         }
6284
6285       if (soname != NULL)
6286         {
6287           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6288                                              soname, TRUE);
6289           if (soname_indx == (size_t) -1
6290               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
6291             return FALSE;
6292         }
6293       else
6294         soname_indx = (size_t) -1;
6295
6296       /* Make all global versions with definition.  */
6297       for (t = info->version_info; t != NULL; t = t->next)
6298         for (d = t->globals.list; d != NULL; d = d->next)
6299           if (!d->symver && d->literal)
6300             {
6301               const char *verstr, *name;
6302               size_t namelen, verlen, newlen;
6303               char *newname, *p, leading_char;
6304               struct elf_link_hash_entry *newh;
6305
6306               leading_char = bfd_get_symbol_leading_char (output_bfd);
6307               name = d->pattern;
6308               namelen = strlen (name) + (leading_char != '\0');
6309               verstr = t->name;
6310               verlen = strlen (verstr);
6311               newlen = namelen + verlen + 3;
6312
6313               newname = (char *) bfd_malloc (newlen);
6314               if (newname == NULL)
6315                 return FALSE;
6316               newname[0] = leading_char;
6317               memcpy (newname + (leading_char != '\0'), name, namelen);
6318
6319               /* Check the hidden versioned definition.  */
6320               p = newname + namelen;
6321               *p++ = ELF_VER_CHR;
6322               memcpy (p, verstr, verlen + 1);
6323               newh = elf_link_hash_lookup (elf_hash_table (info),
6324                                            newname, FALSE, FALSE,
6325                                            FALSE);
6326               if (newh == NULL
6327                   || (newh->root.type != bfd_link_hash_defined
6328                       && newh->root.type != bfd_link_hash_defweak))
6329                 {
6330                   /* Check the default versioned definition.  */
6331                   *p++ = ELF_VER_CHR;
6332                   memcpy (p, verstr, verlen + 1);
6333                   newh = elf_link_hash_lookup (elf_hash_table (info),
6334                                                newname, FALSE, FALSE,
6335                                                FALSE);
6336                 }
6337               free (newname);
6338
6339               /* Mark this version if there is a definition and it is
6340                  not defined in a shared object.  */
6341               if (newh != NULL
6342                   && !newh->def_dynamic
6343                   && (newh->root.type == bfd_link_hash_defined
6344                       || newh->root.type == bfd_link_hash_defweak))
6345                 d->symver = 1;
6346             }
6347
6348       /* Attach all the symbols to their version information.  */
6349       asvinfo.info = info;
6350       asvinfo.failed = FALSE;
6351
6352       elf_link_hash_traverse (elf_hash_table (info),
6353                               _bfd_elf_link_assign_sym_version,
6354                               &asvinfo);
6355       if (asvinfo.failed)
6356         return FALSE;
6357
6358       if (!info->allow_undefined_version)
6359         {
6360           /* Check if all global versions have a definition.  */
6361           bfd_boolean all_defined = TRUE;
6362           for (t = info->version_info; t != NULL; t = t->next)
6363             for (d = t->globals.list; d != NULL; d = d->next)
6364               if (d->literal && !d->symver && !d->script)
6365                 {
6366                   _bfd_error_handler
6367                     (_("%s: undefined version: %s"),
6368                      d->pattern, t->name);
6369                   all_defined = FALSE;
6370                 }
6371
6372           if (!all_defined)
6373             {
6374               bfd_set_error (bfd_error_bad_value);
6375               return FALSE;
6376             }
6377         }
6378
6379       /* Set up the version definition section.  */
6380       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6381       BFD_ASSERT (s != NULL);
6382
6383       /* We may have created additional version definitions if we are
6384          just linking a regular application.  */
6385       verdefs = info->version_info;
6386
6387       /* Skip anonymous version tag.  */
6388       if (verdefs != NULL && verdefs->vernum == 0)
6389         verdefs = verdefs->next;
6390
6391       if (verdefs == NULL && !info->create_default_symver)
6392         s->flags |= SEC_EXCLUDE;
6393       else
6394         {
6395           unsigned int cdefs;
6396           bfd_size_type size;
6397           bfd_byte *p;
6398           Elf_Internal_Verdef def;
6399           Elf_Internal_Verdaux defaux;
6400           struct bfd_link_hash_entry *bh;
6401           struct elf_link_hash_entry *h;
6402           const char *name;
6403
6404           cdefs = 0;
6405           size = 0;
6406
6407           /* Make space for the base version.  */
6408           size += sizeof (Elf_External_Verdef);
6409           size += sizeof (Elf_External_Verdaux);
6410           ++cdefs;
6411
6412           /* Make space for the default version.  */
6413           if (info->create_default_symver)
6414             {
6415               size += sizeof (Elf_External_Verdef);
6416               ++cdefs;
6417             }
6418
6419           for (t = verdefs; t != NULL; t = t->next)
6420             {
6421               struct bfd_elf_version_deps *n;
6422
6423               /* Don't emit base version twice.  */
6424               if (t->vernum == 0)
6425                 continue;
6426
6427               size += sizeof (Elf_External_Verdef);
6428               size += sizeof (Elf_External_Verdaux);
6429               ++cdefs;
6430
6431               for (n = t->deps; n != NULL; n = n->next)
6432                 size += sizeof (Elf_External_Verdaux);
6433             }
6434
6435           s->size = size;
6436           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6437           if (s->contents == NULL && s->size != 0)
6438             return FALSE;
6439
6440           /* Fill in the version definition section.  */
6441
6442           p = s->contents;
6443
6444           def.vd_version = VER_DEF_CURRENT;
6445           def.vd_flags = VER_FLG_BASE;
6446           def.vd_ndx = 1;
6447           def.vd_cnt = 1;
6448           if (info->create_default_symver)
6449             {
6450               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6451               def.vd_next = sizeof (Elf_External_Verdef);
6452             }
6453           else
6454             {
6455               def.vd_aux = sizeof (Elf_External_Verdef);
6456               def.vd_next = (sizeof (Elf_External_Verdef)
6457                              + sizeof (Elf_External_Verdaux));
6458             }
6459
6460           if (soname_indx != (size_t) -1)
6461             {
6462               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6463                                       soname_indx);
6464               def.vd_hash = bfd_elf_hash (soname);
6465               defaux.vda_name = soname_indx;
6466               name = soname;
6467             }
6468           else
6469             {
6470               size_t indx;
6471
6472               name = lbasename (output_bfd->filename);
6473               def.vd_hash = bfd_elf_hash (name);
6474               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6475                                           name, FALSE);
6476               if (indx == (size_t) -1)
6477                 return FALSE;
6478               defaux.vda_name = indx;
6479             }
6480           defaux.vda_next = 0;
6481
6482           _bfd_elf_swap_verdef_out (output_bfd, &def,
6483                                     (Elf_External_Verdef *) p);
6484           p += sizeof (Elf_External_Verdef);
6485           if (info->create_default_symver)
6486             {
6487               /* Add a symbol representing this version.  */
6488               bh = NULL;
6489               if (! (_bfd_generic_link_add_one_symbol
6490                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6491                       0, NULL, FALSE,
6492                       get_elf_backend_data (dynobj)->collect, &bh)))
6493                 return FALSE;
6494               h = (struct elf_link_hash_entry *) bh;
6495               h->non_elf = 0;
6496               h->def_regular = 1;
6497               h->type = STT_OBJECT;
6498               h->verinfo.vertree = NULL;
6499
6500               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6501                 return FALSE;
6502
6503               /* Create a duplicate of the base version with the same
6504                  aux block, but different flags.  */
6505               def.vd_flags = 0;
6506               def.vd_ndx = 2;
6507               def.vd_aux = sizeof (Elf_External_Verdef);
6508               if (verdefs)
6509                 def.vd_next = (sizeof (Elf_External_Verdef)
6510                                + sizeof (Elf_External_Verdaux));
6511               else
6512                 def.vd_next = 0;
6513               _bfd_elf_swap_verdef_out (output_bfd, &def,
6514                                         (Elf_External_Verdef *) p);
6515               p += sizeof (Elf_External_Verdef);
6516             }
6517           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6518                                      (Elf_External_Verdaux *) p);
6519           p += sizeof (Elf_External_Verdaux);
6520
6521           for (t = verdefs; t != NULL; t = t->next)
6522             {
6523               unsigned int cdeps;
6524               struct bfd_elf_version_deps *n;
6525
6526               /* Don't emit the base version twice.  */
6527               if (t->vernum == 0)
6528                 continue;
6529
6530               cdeps = 0;
6531               for (n = t->deps; n != NULL; n = n->next)
6532                 ++cdeps;
6533
6534               /* Add a symbol representing this version.  */
6535               bh = NULL;
6536               if (! (_bfd_generic_link_add_one_symbol
6537                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6538                       0, NULL, FALSE,
6539                       get_elf_backend_data (dynobj)->collect, &bh)))
6540                 return FALSE;
6541               h = (struct elf_link_hash_entry *) bh;
6542               h->non_elf = 0;
6543               h->def_regular = 1;
6544               h->type = STT_OBJECT;
6545               h->verinfo.vertree = t;
6546
6547               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6548                 return FALSE;
6549
6550               def.vd_version = VER_DEF_CURRENT;
6551               def.vd_flags = 0;
6552               if (t->globals.list == NULL
6553                   && t->locals.list == NULL
6554                   && ! t->used)
6555                 def.vd_flags |= VER_FLG_WEAK;
6556               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6557               def.vd_cnt = cdeps + 1;
6558               def.vd_hash = bfd_elf_hash (t->name);
6559               def.vd_aux = sizeof (Elf_External_Verdef);
6560               def.vd_next = 0;
6561
6562               /* If a basever node is next, it *must* be the last node in
6563                  the chain, otherwise Verdef construction breaks.  */
6564               if (t->next != NULL && t->next->vernum == 0)
6565                 BFD_ASSERT (t->next->next == NULL);
6566
6567               if (t->next != NULL && t->next->vernum != 0)
6568                 def.vd_next = (sizeof (Elf_External_Verdef)
6569                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6570
6571               _bfd_elf_swap_verdef_out (output_bfd, &def,
6572                                         (Elf_External_Verdef *) p);
6573               p += sizeof (Elf_External_Verdef);
6574
6575               defaux.vda_name = h->dynstr_index;
6576               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6577                                       h->dynstr_index);
6578               defaux.vda_next = 0;
6579               if (t->deps != NULL)
6580                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6581               t->name_indx = defaux.vda_name;
6582
6583               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6584                                          (Elf_External_Verdaux *) p);
6585               p += sizeof (Elf_External_Verdaux);
6586
6587               for (n = t->deps; n != NULL; n = n->next)
6588                 {
6589                   if (n->version_needed == NULL)
6590                     {
6591                       /* This can happen if there was an error in the
6592                          version script.  */
6593                       defaux.vda_name = 0;
6594                     }
6595                   else
6596                     {
6597                       defaux.vda_name = n->version_needed->name_indx;
6598                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6599                                               defaux.vda_name);
6600                     }
6601                   if (n->next == NULL)
6602                     defaux.vda_next = 0;
6603                   else
6604                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6605
6606                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6607                                              (Elf_External_Verdaux *) p);
6608                   p += sizeof (Elf_External_Verdaux);
6609                 }
6610             }
6611
6612           elf_tdata (output_bfd)->cverdefs = cdefs;
6613         }
6614     }
6615
6616   bed = get_elf_backend_data (output_bfd);
6617
6618   if (info->gc_sections && bed->can_gc_sections)
6619     {
6620       struct elf_gc_sweep_symbol_info sweep_info;
6621
6622       /* Remove the symbols that were in the swept sections from the
6623          dynamic symbol table.  */
6624       sweep_info.info = info;
6625       sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
6626       elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
6627                               &sweep_info);
6628     }
6629
6630   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6631     {
6632       asection *s;
6633       struct elf_find_verdep_info sinfo;
6634
6635       /* Work out the size of the version reference section.  */
6636
6637       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6638       BFD_ASSERT (s != NULL);
6639
6640       sinfo.info = info;
6641       sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6642       if (sinfo.vers == 0)
6643         sinfo.vers = 1;
6644       sinfo.failed = FALSE;
6645
6646       elf_link_hash_traverse (elf_hash_table (info),
6647                               _bfd_elf_link_find_version_dependencies,
6648                               &sinfo);
6649       if (sinfo.failed)
6650         return FALSE;
6651
6652       if (elf_tdata (output_bfd)->verref == NULL)
6653         s->flags |= SEC_EXCLUDE;
6654       else
6655         {
6656           Elf_Internal_Verneed *vn;
6657           unsigned int size;
6658           unsigned int crefs;
6659           bfd_byte *p;
6660
6661           /* Build the version dependency section.  */
6662           size = 0;
6663           crefs = 0;
6664           for (vn = elf_tdata (output_bfd)->verref;
6665                vn != NULL;
6666                vn = vn->vn_nextref)
6667             {
6668               Elf_Internal_Vernaux *a;
6669
6670               size += sizeof (Elf_External_Verneed);
6671               ++crefs;
6672               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6673                 size += sizeof (Elf_External_Vernaux);
6674             }
6675
6676           s->size = size;
6677           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6678           if (s->contents == NULL)
6679             return FALSE;
6680
6681           p = s->contents;
6682           for (vn = elf_tdata (output_bfd)->verref;
6683                vn != NULL;
6684                vn = vn->vn_nextref)
6685             {
6686               unsigned int caux;
6687               Elf_Internal_Vernaux *a;
6688               size_t indx;
6689
6690               caux = 0;
6691               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6692                 ++caux;
6693
6694               vn->vn_version = VER_NEED_CURRENT;
6695               vn->vn_cnt = caux;
6696               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6697                                           elf_dt_name (vn->vn_bfd) != NULL
6698                                           ? elf_dt_name (vn->vn_bfd)
6699                                           : lbasename (vn->vn_bfd->filename),
6700                                           FALSE);
6701               if (indx == (size_t) -1)
6702                 return FALSE;
6703               vn->vn_file = indx;
6704               vn->vn_aux = sizeof (Elf_External_Verneed);
6705               if (vn->vn_nextref == NULL)
6706                 vn->vn_next = 0;
6707               else
6708                 vn->vn_next = (sizeof (Elf_External_Verneed)
6709                                + caux * sizeof (Elf_External_Vernaux));
6710
6711               _bfd_elf_swap_verneed_out (output_bfd, vn,
6712                                          (Elf_External_Verneed *) p);
6713               p += sizeof (Elf_External_Verneed);
6714
6715               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6716                 {
6717                   a->vna_hash = bfd_elf_hash (a->vna_nodename);
6718                   indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6719                                               a->vna_nodename, FALSE);
6720                   if (indx == (size_t) -1)
6721                     return FALSE;
6722                   a->vna_name = indx;
6723                   if (a->vna_nextptr == NULL)
6724                     a->vna_next = 0;
6725                   else
6726                     a->vna_next = sizeof (Elf_External_Vernaux);
6727
6728                   _bfd_elf_swap_vernaux_out (output_bfd, a,
6729                                              (Elf_External_Vernaux *) p);
6730                   p += sizeof (Elf_External_Vernaux);
6731                 }
6732             }
6733
6734           elf_tdata (output_bfd)->cverrefs = crefs;
6735         }
6736     }
6737
6738   /* Any syms created from now on start with -1 in
6739      got.refcount/offset and plt.refcount/offset.  */
6740   elf_hash_table (info)->init_got_refcount
6741     = elf_hash_table (info)->init_got_offset;
6742   elf_hash_table (info)->init_plt_refcount
6743     = elf_hash_table (info)->init_plt_offset;
6744
6745   if (bfd_link_relocatable (info)
6746       && !_bfd_elf_size_group_sections (info))
6747     return FALSE;
6748
6749   /* The backend may have to create some sections regardless of whether
6750      we're dynamic or not.  */
6751   if (bed->elf_backend_always_size_sections
6752       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
6753     return FALSE;
6754
6755   /* Determine any GNU_STACK segment requirements, after the backend
6756      has had a chance to set a default segment size.  */
6757   if (info->execstack)
6758     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
6759   else if (info->noexecstack)
6760     elf_stack_flags (output_bfd) = PF_R | PF_W;
6761   else
6762     {
6763       bfd *inputobj;
6764       asection *notesec = NULL;
6765       int exec = 0;
6766
6767       for (inputobj = info->input_bfds;
6768            inputobj;
6769            inputobj = inputobj->link.next)
6770         {
6771           asection *s;
6772
6773           if (inputobj->flags
6774               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
6775             continue;
6776           s = inputobj->sections;
6777           if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
6778             continue;
6779
6780           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
6781           if (s)
6782             {
6783               if (s->flags & SEC_CODE)
6784                 exec = PF_X;
6785               notesec = s;
6786             }
6787           else if (bed->default_execstack)
6788             exec = PF_X;
6789         }
6790       if (notesec || info->stacksize > 0)
6791         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
6792       if (notesec && exec && bfd_link_relocatable (info)
6793           && notesec->output_section != bfd_abs_section_ptr)
6794         notesec->output_section->flags |= SEC_CODE;
6795     }
6796
6797   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6798     {
6799       struct elf_info_failed eif;
6800       struct elf_link_hash_entry *h;
6801       asection *dynstr;
6802       asection *s;
6803
6804       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
6805       BFD_ASSERT (*sinterpptr != NULL || !bfd_link_executable (info) || info->nointerp);
6806
6807       if (info->symbolic)
6808         {
6809           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
6810             return FALSE;
6811           info->flags |= DF_SYMBOLIC;
6812         }
6813
6814       if (rpath != NULL)
6815         {
6816           size_t indx;
6817           bfd_vma tag;
6818
6819           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
6820                                       TRUE);
6821           if (indx == (size_t) -1)
6822             return FALSE;
6823
6824           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
6825           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
6826             return FALSE;
6827         }
6828
6829       if (filter_shlib != NULL)
6830         {
6831           size_t indx;
6832
6833           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6834                                       filter_shlib, TRUE);
6835           if (indx == (size_t) -1
6836               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
6837             return FALSE;
6838         }
6839
6840       if (auxiliary_filters != NULL)
6841         {
6842           const char * const *p;
6843
6844           for (p = auxiliary_filters; *p != NULL; p++)
6845             {
6846               size_t indx;
6847
6848               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6849                                           *p, TRUE);
6850               if (indx == (size_t) -1
6851                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
6852                 return FALSE;
6853             }
6854         }
6855
6856       if (audit != NULL)
6857         {
6858           size_t indx;
6859
6860           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
6861                                       TRUE);
6862           if (indx == (size_t) -1
6863               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
6864             return FALSE;
6865         }
6866
6867       if (depaudit != NULL)
6868         {
6869           size_t indx;
6870
6871           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
6872                                       TRUE);
6873           if (indx == (size_t) -1
6874               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
6875             return FALSE;
6876         }
6877
6878       eif.info = info;
6879       eif.failed = FALSE;
6880
6881       /* Find all symbols which were defined in a dynamic object and make
6882          the backend pick a reasonable value for them.  */
6883       elf_link_hash_traverse (elf_hash_table (info),
6884                               _bfd_elf_adjust_dynamic_symbol,
6885                               &eif);
6886       if (eif.failed)
6887         return FALSE;
6888
6889       /* Add some entries to the .dynamic section.  We fill in some of the
6890          values later, in bfd_elf_final_link, but we must add the entries
6891          now so that we know the final size of the .dynamic section.  */
6892
6893       /* If there are initialization and/or finalization functions to
6894          call then add the corresponding DT_INIT/DT_FINI entries.  */
6895       h = (info->init_function
6896            ? elf_link_hash_lookup (elf_hash_table (info),
6897                                    info->init_function, FALSE,
6898                                    FALSE, FALSE)
6899            : NULL);
6900       if (h != NULL
6901           && (h->ref_regular
6902               || h->def_regular))
6903         {
6904           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
6905             return FALSE;
6906         }
6907       h = (info->fini_function
6908            ? elf_link_hash_lookup (elf_hash_table (info),
6909                                    info->fini_function, FALSE,
6910                                    FALSE, FALSE)
6911            : NULL);
6912       if (h != NULL
6913           && (h->ref_regular
6914               || h->def_regular))
6915         {
6916           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
6917             return FALSE;
6918         }
6919
6920       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
6921       if (s != NULL && s->linker_has_input)
6922         {
6923           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
6924           if (! bfd_link_executable (info))
6925             {
6926               bfd *sub;
6927               asection *o;
6928
6929               for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
6930                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour
6931                     && (o = sub->sections) != NULL
6932                     && o->sec_info_type != SEC_INFO_TYPE_JUST_SYMS)
6933                   for (o = sub->sections; o != NULL; o = o->next)
6934                     if (elf_section_data (o)->this_hdr.sh_type
6935                         == SHT_PREINIT_ARRAY)
6936                       {
6937                         _bfd_error_handler
6938                           (_("%pB: .preinit_array section is not allowed in DSO"),
6939                            sub);
6940                         break;
6941                       }
6942
6943               bfd_set_error (bfd_error_nonrepresentable_section);
6944               return FALSE;
6945             }
6946
6947           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6948               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6949             return FALSE;
6950         }
6951       s = bfd_get_section_by_name (output_bfd, ".init_array");
6952       if (s != NULL && s->linker_has_input)
6953         {
6954           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6955               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6956             return FALSE;
6957         }
6958       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6959       if (s != NULL && s->linker_has_input)
6960         {
6961           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6962               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6963             return FALSE;
6964         }
6965
6966       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6967       /* If .dynstr is excluded from the link, we don't want any of
6968          these tags.  Strictly, we should be checking each section
6969          individually;  This quick check covers for the case where
6970          someone does a /DISCARD/ : { *(*) }.  */
6971       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6972         {
6973           bfd_size_type strsize;
6974
6975           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6976           if ((info->emit_hash
6977                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6978               || (info->emit_gnu_hash
6979                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6980               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6981               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6982               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6983               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6984                                               bed->s->sizeof_sym))
6985             return FALSE;
6986         }
6987     }
6988
6989   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6990     return FALSE;
6991
6992   /* The backend must work out the sizes of all the other dynamic
6993      sections.  */
6994   if (dynobj != NULL
6995       && bed->elf_backend_size_dynamic_sections != NULL
6996       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6997     return FALSE;
6998
6999   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
7000     {
7001       if (elf_tdata (output_bfd)->cverdefs)
7002         {
7003           unsigned int crefs = elf_tdata (output_bfd)->cverdefs;
7004
7005           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
7006               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, crefs))
7007             return FALSE;
7008         }
7009
7010       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
7011         {
7012           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
7013             return FALSE;
7014         }
7015       else if (info->flags & DF_BIND_NOW)
7016         {
7017           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
7018             return FALSE;
7019         }
7020
7021       if (info->flags_1)
7022         {
7023           if (bfd_link_executable (info))
7024             info->flags_1 &= ~ (DF_1_INITFIRST
7025                                 | DF_1_NODELETE
7026                                 | DF_1_NOOPEN);
7027           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
7028             return FALSE;
7029         }
7030
7031       if (elf_tdata (output_bfd)->cverrefs)
7032         {
7033           unsigned int crefs = elf_tdata (output_bfd)->cverrefs;
7034
7035           if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
7036               || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
7037             return FALSE;
7038         }
7039
7040       if ((elf_tdata (output_bfd)->cverrefs == 0
7041            && elf_tdata (output_bfd)->cverdefs == 0)
7042           || _bfd_elf_link_renumber_dynsyms (output_bfd, info, NULL) <= 1)
7043         {
7044           asection *s;
7045
7046           s = bfd_get_linker_section (dynobj, ".gnu.version");
7047           s->flags |= SEC_EXCLUDE;
7048         }
7049     }
7050   return TRUE;
7051 }
7052
7053 /* Find the first non-excluded output section.  We'll use its
7054    section symbol for some emitted relocs.  */
7055 void
7056 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
7057 {
7058   asection *s;
7059   asection *found = NULL;
7060
7061   for (s = output_bfd->sections; s != NULL; s = s->next)
7062     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
7063         && !_bfd_elf_omit_section_dynsym_default (output_bfd, info, s))
7064       {
7065         found = s;
7066         if ((s->flags & SEC_THREAD_LOCAL) == 0)
7067           break;
7068       }
7069   elf_hash_table (info)->text_index_section = found;
7070 }
7071
7072 /* Find two non-excluded output sections, one for code, one for data.
7073    We'll use their section symbols for some emitted relocs.  */
7074 void
7075 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
7076 {
7077   asection *s;
7078   asection *found = NULL;
7079
7080   /* Data first, since setting text_index_section changes
7081      _bfd_elf_omit_section_dynsym_default.  */
7082   for (s = output_bfd->sections; s != NULL; s = s->next)
7083     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
7084         && !(s->flags & SEC_READONLY)
7085         && !_bfd_elf_omit_section_dynsym_default (output_bfd, info, s))
7086       {
7087         found = s;
7088         if ((s->flags & SEC_THREAD_LOCAL) == 0)
7089           break;
7090       }
7091   elf_hash_table (info)->data_index_section = found;
7092
7093   for (s = output_bfd->sections; s != NULL; s = s->next)
7094     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
7095         && (s->flags & SEC_READONLY)
7096         && !_bfd_elf_omit_section_dynsym_default (output_bfd, info, s))
7097       {
7098         found = s;
7099         break;
7100       }
7101   elf_hash_table (info)->text_index_section = found;
7102 }
7103
7104 bfd_boolean
7105 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
7106 {
7107   const struct elf_backend_data *bed;
7108   unsigned long section_sym_count;
7109   bfd_size_type dynsymcount = 0;
7110
7111   if (!is_elf_hash_table (info->hash))
7112     return TRUE;
7113
7114   bed = get_elf_backend_data (output_bfd);
7115   (*bed->elf_backend_init_index_section) (output_bfd, info);
7116
7117   /* Assign dynsym indices.  In a shared library we generate a section
7118      symbol for each output section, which come first.  Next come all
7119      of the back-end allocated local dynamic syms, followed by the rest
7120      of the global symbols.
7121
7122      This is usually not needed for static binaries, however backends
7123      can request to always do it, e.g. the MIPS backend uses dynamic
7124      symbol counts to lay out GOT, which will be produced in the
7125      presence of GOT relocations even in static binaries (holding fixed
7126      data in that case, to satisfy those relocations).  */
7127
7128   if (elf_hash_table (info)->dynamic_sections_created
7129       || bed->always_renumber_dynsyms)
7130     dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
7131                                                   &section_sym_count);
7132
7133   if (elf_hash_table (info)->dynamic_sections_created)
7134     {
7135       bfd *dynobj;
7136       asection *s;
7137       unsigned int dtagcount;
7138
7139       dynobj = elf_hash_table (info)->dynobj;
7140
7141       /* Work out the size of the symbol version section.  */
7142       s = bfd_get_linker_section (dynobj, ".gnu.version");
7143       BFD_ASSERT (s != NULL);
7144       if ((s->flags & SEC_EXCLUDE) == 0)
7145         {
7146           s->size = dynsymcount * sizeof (Elf_External_Versym);
7147           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7148           if (s->contents == NULL)
7149             return FALSE;
7150
7151           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
7152             return FALSE;
7153         }
7154
7155       /* Set the size of the .dynsym and .hash sections.  We counted
7156          the number of dynamic symbols in elf_link_add_object_symbols.
7157          We will build the contents of .dynsym and .hash when we build
7158          the final symbol table, because until then we do not know the
7159          correct value to give the symbols.  We built the .dynstr
7160          section as we went along in elf_link_add_object_symbols.  */
7161       s = elf_hash_table (info)->dynsym;
7162       BFD_ASSERT (s != NULL);
7163       s->size = dynsymcount * bed->s->sizeof_sym;
7164
7165       s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
7166       if (s->contents == NULL)
7167         return FALSE;
7168
7169       /* The first entry in .dynsym is a dummy symbol.  Clear all the
7170          section syms, in case we don't output them all.  */
7171       ++section_sym_count;
7172       memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
7173
7174       elf_hash_table (info)->bucketcount = 0;
7175
7176       /* Compute the size of the hashing table.  As a side effect this
7177          computes the hash values for all the names we export.  */
7178       if (info->emit_hash)
7179         {
7180           unsigned long int *hashcodes;
7181           struct hash_codes_info hashinf;
7182           bfd_size_type amt;
7183           unsigned long int nsyms;
7184           size_t bucketcount;
7185           size_t hash_entry_size;
7186
7187           /* Compute the hash values for all exported symbols.  At the same
7188              time store the values in an array so that we could use them for
7189              optimizations.  */
7190           amt = dynsymcount * sizeof (unsigned long int);
7191           hashcodes = (unsigned long int *) bfd_malloc (amt);
7192           if (hashcodes == NULL)
7193             return FALSE;
7194           hashinf.hashcodes = hashcodes;
7195           hashinf.error = FALSE;
7196
7197           /* Put all hash values in HASHCODES.  */
7198           elf_link_hash_traverse (elf_hash_table (info),
7199                                   elf_collect_hash_codes, &hashinf);
7200           if (hashinf.error)
7201             {
7202               free (hashcodes);
7203               return FALSE;
7204             }
7205
7206           nsyms = hashinf.hashcodes - hashcodes;
7207           bucketcount
7208             = compute_bucket_count (info, hashcodes, nsyms, 0);
7209           free (hashcodes);
7210
7211           if (bucketcount == 0 && nsyms > 0)
7212             return FALSE;
7213
7214           elf_hash_table (info)->bucketcount = bucketcount;
7215
7216           s = bfd_get_linker_section (dynobj, ".hash");
7217           BFD_ASSERT (s != NULL);
7218           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
7219           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
7220           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7221           if (s->contents == NULL)
7222             return FALSE;
7223
7224           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
7225           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
7226                    s->contents + hash_entry_size);
7227         }
7228
7229       if (info->emit_gnu_hash)
7230         {
7231           size_t i, cnt;
7232           unsigned char *contents;
7233           struct collect_gnu_hash_codes cinfo;
7234           bfd_size_type amt;
7235           size_t bucketcount;
7236
7237           memset (&cinfo, 0, sizeof (cinfo));
7238
7239           /* Compute the hash values for all exported symbols.  At the same
7240              time store the values in an array so that we could use them for
7241              optimizations.  */
7242           amt = dynsymcount * 2 * sizeof (unsigned long int);
7243           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
7244           if (cinfo.hashcodes == NULL)
7245             return FALSE;
7246
7247           cinfo.hashval = cinfo.hashcodes + dynsymcount;
7248           cinfo.min_dynindx = -1;
7249           cinfo.output_bfd = output_bfd;
7250           cinfo.bed = bed;
7251
7252           /* Put all hash values in HASHCODES.  */
7253           elf_link_hash_traverse (elf_hash_table (info),
7254                                   elf_collect_gnu_hash_codes, &cinfo);
7255           if (cinfo.error)
7256             {
7257               free (cinfo.hashcodes);
7258               return FALSE;
7259             }
7260
7261           bucketcount
7262             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
7263
7264           if (bucketcount == 0)
7265             {
7266               free (cinfo.hashcodes);
7267               return FALSE;
7268             }
7269
7270           s = bfd_get_linker_section (dynobj, ".gnu.hash");
7271           BFD_ASSERT (s != NULL);
7272
7273           if (cinfo.nsyms == 0)
7274             {
7275               /* Empty .gnu.hash section is special.  */
7276               BFD_ASSERT (cinfo.min_dynindx == -1);
7277               free (cinfo.hashcodes);
7278               s->size = 5 * 4 + bed->s->arch_size / 8;
7279               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7280               if (contents == NULL)
7281                 return FALSE;
7282               s->contents = contents;
7283               /* 1 empty bucket.  */
7284               bfd_put_32 (output_bfd, 1, contents);
7285               /* SYMIDX above the special symbol 0.  */
7286               bfd_put_32 (output_bfd, 1, contents + 4);
7287               /* Just one word for bitmask.  */
7288               bfd_put_32 (output_bfd, 1, contents + 8);
7289               /* Only hash fn bloom filter.  */
7290               bfd_put_32 (output_bfd, 0, contents + 12);
7291               /* No hashes are valid - empty bitmask.  */
7292               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
7293               /* No hashes in the only bucket.  */
7294               bfd_put_32 (output_bfd, 0,
7295                           contents + 16 + bed->s->arch_size / 8);
7296             }
7297           else
7298             {
7299               unsigned long int maskwords, maskbitslog2, x;
7300               BFD_ASSERT (cinfo.min_dynindx != -1);
7301
7302               x = cinfo.nsyms;
7303               maskbitslog2 = 1;
7304               while ((x >>= 1) != 0)
7305                 ++maskbitslog2;
7306               if (maskbitslog2 < 3)
7307                 maskbitslog2 = 5;
7308               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
7309                 maskbitslog2 = maskbitslog2 + 3;
7310               else
7311                 maskbitslog2 = maskbitslog2 + 2;
7312               if (bed->s->arch_size == 64)
7313                 {
7314                   if (maskbitslog2 == 5)
7315                     maskbitslog2 = 6;
7316                   cinfo.shift1 = 6;
7317                 }
7318               else
7319                 cinfo.shift1 = 5;
7320               cinfo.mask = (1 << cinfo.shift1) - 1;
7321               cinfo.shift2 = maskbitslog2;
7322               cinfo.maskbits = 1 << maskbitslog2;
7323               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
7324               amt = bucketcount * sizeof (unsigned long int) * 2;
7325               amt += maskwords * sizeof (bfd_vma);
7326               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
7327               if (cinfo.bitmask == NULL)
7328                 {
7329                   free (cinfo.hashcodes);
7330                   return FALSE;
7331                 }
7332
7333               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
7334               cinfo.indx = cinfo.counts + bucketcount;
7335               cinfo.symindx = dynsymcount - cinfo.nsyms;
7336               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
7337
7338               /* Determine how often each hash bucket is used.  */
7339               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
7340               for (i = 0; i < cinfo.nsyms; ++i)
7341                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
7342
7343               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
7344                 if (cinfo.counts[i] != 0)
7345                   {
7346                     cinfo.indx[i] = cnt;
7347                     cnt += cinfo.counts[i];
7348                   }
7349               BFD_ASSERT (cnt == dynsymcount);
7350               cinfo.bucketcount = bucketcount;
7351               cinfo.local_indx = cinfo.min_dynindx;
7352
7353               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
7354               s->size += cinfo.maskbits / 8;
7355               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7356               if (contents == NULL)
7357                 {
7358                   free (cinfo.bitmask);
7359                   free (cinfo.hashcodes);
7360                   return FALSE;
7361                 }
7362
7363               s->contents = contents;
7364               bfd_put_32 (output_bfd, bucketcount, contents);
7365               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
7366               bfd_put_32 (output_bfd, maskwords, contents + 8);
7367               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
7368               contents += 16 + cinfo.maskbits / 8;
7369
7370               for (i = 0; i < bucketcount; ++i)
7371                 {
7372                   if (cinfo.counts[i] == 0)
7373                     bfd_put_32 (output_bfd, 0, contents);
7374                   else
7375                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
7376                   contents += 4;
7377                 }
7378
7379               cinfo.contents = contents;
7380
7381               /* Renumber dynamic symbols, populate .gnu.hash section.  */
7382               elf_link_hash_traverse (elf_hash_table (info),
7383                                       elf_renumber_gnu_hash_syms, &cinfo);
7384
7385               contents = s->contents + 16;
7386               for (i = 0; i < maskwords; ++i)
7387                 {
7388                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
7389                            contents);
7390                   contents += bed->s->arch_size / 8;
7391                 }
7392
7393               free (cinfo.bitmask);
7394               free (cinfo.hashcodes);
7395             }
7396         }
7397
7398       s = bfd_get_linker_section (dynobj, ".dynstr");
7399       BFD_ASSERT (s != NULL);
7400
7401       elf_finalize_dynstr (output_bfd, info);
7402
7403       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
7404
7405       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
7406         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
7407           return FALSE;
7408     }
7409
7410   return TRUE;
7411 }
7412 \f
7413 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
7414
7415 static void
7416 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
7417                             asection *sec)
7418 {
7419   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
7420   sec->sec_info_type = SEC_INFO_TYPE_NONE;
7421 }
7422
7423 /* Finish SHF_MERGE section merging.  */
7424
7425 bfd_boolean
7426 _bfd_elf_merge_sections (bfd *obfd, struct bfd_link_info *info)
7427 {
7428   bfd *ibfd;
7429   asection *sec;
7430
7431   if (!is_elf_hash_table (info->hash))
7432     return FALSE;
7433
7434   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
7435     if ((ibfd->flags & DYNAMIC) == 0
7436         && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
7437         && (elf_elfheader (ibfd)->e_ident[EI_CLASS]
7438             == get_elf_backend_data (obfd)->s->elfclass))
7439       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
7440         if ((sec->flags & SEC_MERGE) != 0
7441             && !bfd_is_abs_section (sec->output_section))
7442           {
7443             struct bfd_elf_section_data *secdata;
7444
7445             secdata = elf_section_data (sec);
7446             if (! _bfd_add_merge_section (obfd,
7447                                           &elf_hash_table (info)->merge_info,
7448                                           sec, &secdata->sec_info))
7449               return FALSE;
7450             else if (secdata->sec_info)
7451               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
7452           }
7453
7454   if (elf_hash_table (info)->merge_info != NULL)
7455     _bfd_merge_sections (obfd, info, elf_hash_table (info)->merge_info,
7456                          merge_sections_remove_hook);
7457   return TRUE;
7458 }
7459
7460 /* Create an entry in an ELF linker hash table.  */
7461
7462 struct bfd_hash_entry *
7463 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
7464                             struct bfd_hash_table *table,
7465                             const char *string)
7466 {
7467   /* Allocate the structure if it has not already been allocated by a
7468      subclass.  */
7469   if (entry == NULL)
7470     {
7471       entry = (struct bfd_hash_entry *)
7472         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
7473       if (entry == NULL)
7474         return entry;
7475     }
7476
7477   /* Call the allocation method of the superclass.  */
7478   entry = _bfd_link_hash_newfunc (entry, table, string);
7479   if (entry != NULL)
7480     {
7481       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
7482       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
7483
7484       /* Set local fields.  */
7485       ret->indx = -1;
7486       ret->dynindx = -1;
7487       ret->got = htab->init_got_refcount;
7488       ret->plt = htab->init_plt_refcount;
7489       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
7490                               - offsetof (struct elf_link_hash_entry, size)));
7491       /* Assume that we have been called by a non-ELF symbol reader.
7492          This flag is then reset by the code which reads an ELF input
7493          file.  This ensures that a symbol created by a non-ELF symbol
7494          reader will have the flag set correctly.  */
7495       ret->non_elf = 1;
7496     }
7497
7498   return entry;
7499 }
7500
7501 /* Copy data from an indirect symbol to its direct symbol, hiding the
7502    old indirect symbol.  Also used for copying flags to a weakdef.  */
7503
7504 void
7505 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
7506                                   struct elf_link_hash_entry *dir,
7507                                   struct elf_link_hash_entry *ind)
7508 {
7509   struct elf_link_hash_table *htab;
7510
7511   /* Copy down any references that we may have already seen to the
7512      symbol which just became indirect.  */
7513
7514   if (dir->versioned != versioned_hidden)
7515     dir->ref_dynamic |= ind->ref_dynamic;
7516   dir->ref_regular |= ind->ref_regular;
7517   dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
7518   dir->non_got_ref |= ind->non_got_ref;
7519   dir->needs_plt |= ind->needs_plt;
7520   dir->pointer_equality_needed |= ind->pointer_equality_needed;
7521
7522   if (ind->root.type != bfd_link_hash_indirect)
7523     return;
7524
7525   /* Copy over the global and procedure linkage table refcount entries.
7526      These may have been already set up by a check_relocs routine.  */
7527   htab = elf_hash_table (info);
7528   if (ind->got.refcount > htab->init_got_refcount.refcount)
7529     {
7530       if (dir->got.refcount < 0)
7531         dir->got.refcount = 0;
7532       dir->got.refcount += ind->got.refcount;
7533       ind->got.refcount = htab->init_got_refcount.refcount;
7534     }
7535
7536   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
7537     {
7538       if (dir->plt.refcount < 0)
7539         dir->plt.refcount = 0;
7540       dir->plt.refcount += ind->plt.refcount;
7541       ind->plt.refcount = htab->init_plt_refcount.refcount;
7542     }
7543
7544   if (ind->dynindx != -1)
7545     {
7546       if (dir->dynindx != -1)
7547         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
7548       dir->dynindx = ind->dynindx;
7549       dir->dynstr_index = ind->dynstr_index;
7550       ind->dynindx = -1;
7551       ind->dynstr_index = 0;
7552     }
7553 }
7554
7555 void
7556 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
7557                                 struct elf_link_hash_entry *h,
7558                                 bfd_boolean force_local)
7559 {
7560   /* STT_GNU_IFUNC symbol must go through PLT.  */
7561   if (h->type != STT_GNU_IFUNC)
7562     {
7563       h->plt = elf_hash_table (info)->init_plt_offset;
7564       h->needs_plt = 0;
7565     }
7566   if (force_local)
7567     {
7568       h->forced_local = 1;
7569       if (h->dynindx != -1)
7570         {
7571           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
7572                                   h->dynstr_index);
7573           h->dynindx = -1;
7574           h->dynstr_index = 0;
7575         }
7576     }
7577 }
7578
7579 /* Hide a symbol. */
7580
7581 void
7582 _bfd_elf_link_hide_symbol (bfd *output_bfd,
7583                            struct bfd_link_info *info,
7584                            struct bfd_link_hash_entry *h)
7585 {
7586   if (is_elf_hash_table (info->hash))
7587     {
7588       const struct elf_backend_data *bed
7589         = get_elf_backend_data (output_bfd);
7590       struct elf_link_hash_entry *eh
7591         = (struct elf_link_hash_entry *) h;
7592       bed->elf_backend_hide_symbol (info, eh, TRUE);
7593       eh->def_dynamic = 0;
7594       eh->ref_dynamic = 0;
7595       eh->dynamic_def = 0;
7596     }
7597 }
7598
7599 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
7600    caller.  */
7601
7602 bfd_boolean
7603 _bfd_elf_link_hash_table_init
7604   (struct elf_link_hash_table *table,
7605    bfd *abfd,
7606    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
7607                                       struct bfd_hash_table *,
7608                                       const char *),
7609    unsigned int entsize,
7610    enum elf_target_id target_id)
7611 {
7612   bfd_boolean ret;
7613   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
7614
7615   table->init_got_refcount.refcount = can_refcount - 1;
7616   table->init_plt_refcount.refcount = can_refcount - 1;
7617   table->init_got_offset.offset = -(bfd_vma) 1;
7618   table->init_plt_offset.offset = -(bfd_vma) 1;
7619   /* The first dynamic symbol is a dummy.  */
7620   table->dynsymcount = 1;
7621
7622   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
7623
7624   table->root.type = bfd_link_elf_hash_table;
7625   table->hash_table_id = target_id;
7626
7627   return ret;
7628 }
7629
7630 /* Create an ELF linker hash table.  */
7631
7632 struct bfd_link_hash_table *
7633 _bfd_elf_link_hash_table_create (bfd *abfd)
7634 {
7635   struct elf_link_hash_table *ret;
7636   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7637
7638   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7639   if (ret == NULL)
7640     return NULL;
7641
7642   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7643                                        sizeof (struct elf_link_hash_entry),
7644                                        GENERIC_ELF_DATA))
7645     {
7646       free (ret);
7647       return NULL;
7648     }
7649   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7650
7651   return &ret->root;
7652 }
7653
7654 /* Destroy an ELF linker hash table.  */
7655
7656 void
7657 _bfd_elf_link_hash_table_free (bfd *obfd)
7658 {
7659   struct elf_link_hash_table *htab;
7660
7661   htab = (struct elf_link_hash_table *) obfd->link.hash;
7662   if (htab->dynstr != NULL)
7663     _bfd_elf_strtab_free (htab->dynstr);
7664   _bfd_merge_sections_free (htab->merge_info);
7665   _bfd_generic_link_hash_table_free (obfd);
7666 }
7667
7668 /* This is a hook for the ELF emulation code in the generic linker to
7669    tell the backend linker what file name to use for the DT_NEEDED
7670    entry for a dynamic object.  */
7671
7672 void
7673 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7674 {
7675   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7676       && bfd_get_format (abfd) == bfd_object)
7677     elf_dt_name (abfd) = name;
7678 }
7679
7680 int
7681 bfd_elf_get_dyn_lib_class (bfd *abfd)
7682 {
7683   int lib_class;
7684   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7685       && bfd_get_format (abfd) == bfd_object)
7686     lib_class = elf_dyn_lib_class (abfd);
7687   else
7688     lib_class = 0;
7689   return lib_class;
7690 }
7691
7692 void
7693 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7694 {
7695   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7696       && bfd_get_format (abfd) == bfd_object)
7697     elf_dyn_lib_class (abfd) = lib_class;
7698 }
7699
7700 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7701    the linker ELF emulation code.  */
7702
7703 struct bfd_link_needed_list *
7704 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7705                          struct bfd_link_info *info)
7706 {
7707   if (! is_elf_hash_table (info->hash))
7708     return NULL;
7709   return elf_hash_table (info)->needed;
7710 }
7711
7712 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7713    hook for the linker ELF emulation code.  */
7714
7715 struct bfd_link_needed_list *
7716 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7717                           struct bfd_link_info *info)
7718 {
7719   if (! is_elf_hash_table (info->hash))
7720     return NULL;
7721   return elf_hash_table (info)->runpath;
7722 }
7723
7724 /* Get the name actually used for a dynamic object for a link.  This
7725    is the SONAME entry if there is one.  Otherwise, it is the string
7726    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7727
7728 const char *
7729 bfd_elf_get_dt_soname (bfd *abfd)
7730 {
7731   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7732       && bfd_get_format (abfd) == bfd_object)
7733     return elf_dt_name (abfd);
7734   return NULL;
7735 }
7736
7737 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7738    the ELF linker emulation code.  */
7739
7740 bfd_boolean
7741 bfd_elf_get_bfd_needed_list (bfd *abfd,
7742                              struct bfd_link_needed_list **pneeded)
7743 {
7744   asection *s;
7745   bfd_byte *dynbuf = NULL;
7746   unsigned int elfsec;
7747   unsigned long shlink;
7748   bfd_byte *extdyn, *extdynend;
7749   size_t extdynsize;
7750   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7751
7752   *pneeded = NULL;
7753
7754   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7755       || bfd_get_format (abfd) != bfd_object)
7756     return TRUE;
7757
7758   s = bfd_get_section_by_name (abfd, ".dynamic");
7759   if (s == NULL || s->size == 0)
7760     return TRUE;
7761
7762   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7763     goto error_return;
7764
7765   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7766   if (elfsec == SHN_BAD)
7767     goto error_return;
7768
7769   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7770
7771   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7772   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7773
7774   extdyn = dynbuf;
7775   extdynend = extdyn + s->size;
7776   for (; extdyn < extdynend; extdyn += extdynsize)
7777     {
7778       Elf_Internal_Dyn dyn;
7779
7780       (*swap_dyn_in) (abfd, extdyn, &dyn);
7781
7782       if (dyn.d_tag == DT_NULL)
7783         break;
7784
7785       if (dyn.d_tag == DT_NEEDED)
7786         {
7787           const char *string;
7788           struct bfd_link_needed_list *l;
7789           unsigned int tagv = dyn.d_un.d_val;
7790           bfd_size_type amt;
7791
7792           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7793           if (string == NULL)
7794             goto error_return;
7795
7796           amt = sizeof *l;
7797           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7798           if (l == NULL)
7799             goto error_return;
7800
7801           l->by = abfd;
7802           l->name = string;
7803           l->next = *pneeded;
7804           *pneeded = l;
7805         }
7806     }
7807
7808   free (dynbuf);
7809
7810   return TRUE;
7811
7812  error_return:
7813   if (dynbuf != NULL)
7814     free (dynbuf);
7815   return FALSE;
7816 }
7817
7818 struct elf_symbuf_symbol
7819 {
7820   unsigned long st_name;        /* Symbol name, index in string tbl */
7821   unsigned char st_info;        /* Type and binding attributes */
7822   unsigned char st_other;       /* Visibilty, and target specific */
7823 };
7824
7825 struct elf_symbuf_head
7826 {
7827   struct elf_symbuf_symbol *ssym;
7828   size_t count;
7829   unsigned int st_shndx;
7830 };
7831
7832 struct elf_symbol
7833 {
7834   union
7835     {
7836       Elf_Internal_Sym *isym;
7837       struct elf_symbuf_symbol *ssym;
7838     } u;
7839   const char *name;
7840 };
7841
7842 /* Sort references to symbols by ascending section number.  */
7843
7844 static int
7845 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7846 {
7847   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7848   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7849
7850   return s1->st_shndx - s2->st_shndx;
7851 }
7852
7853 static int
7854 elf_sym_name_compare (const void *arg1, const void *arg2)
7855 {
7856   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7857   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7858   return strcmp (s1->name, s2->name);
7859 }
7860
7861 static struct elf_symbuf_head *
7862 elf_create_symbuf (size_t symcount, Elf_Internal_Sym *isymbuf)
7863 {
7864   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7865   struct elf_symbuf_symbol *ssym;
7866   struct elf_symbuf_head *ssymbuf, *ssymhead;
7867   size_t i, shndx_count, total_size;
7868
7869   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7870   if (indbuf == NULL)
7871     return NULL;
7872
7873   for (ind = indbuf, i = 0; i < symcount; i++)
7874     if (isymbuf[i].st_shndx != SHN_UNDEF)
7875       *ind++ = &isymbuf[i];
7876   indbufend = ind;
7877
7878   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7879          elf_sort_elf_symbol);
7880
7881   shndx_count = 0;
7882   if (indbufend > indbuf)
7883     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7884       if (ind[0]->st_shndx != ind[1]->st_shndx)
7885         shndx_count++;
7886
7887   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7888                 + (indbufend - indbuf) * sizeof (*ssym));
7889   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7890   if (ssymbuf == NULL)
7891     {
7892       free (indbuf);
7893       return NULL;
7894     }
7895
7896   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7897   ssymbuf->ssym = NULL;
7898   ssymbuf->count = shndx_count;
7899   ssymbuf->st_shndx = 0;
7900   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7901     {
7902       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7903         {
7904           ssymhead++;
7905           ssymhead->ssym = ssym;
7906           ssymhead->count = 0;
7907           ssymhead->st_shndx = (*ind)->st_shndx;
7908         }
7909       ssym->st_name = (*ind)->st_name;
7910       ssym->st_info = (*ind)->st_info;
7911       ssym->st_other = (*ind)->st_other;
7912       ssymhead->count++;
7913     }
7914   BFD_ASSERT ((size_t) (ssymhead - ssymbuf) == shndx_count
7915               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7916                   == total_size));
7917
7918   free (indbuf);
7919   return ssymbuf;
7920 }
7921
7922 /* Check if 2 sections define the same set of local and global
7923    symbols.  */
7924
7925 static bfd_boolean
7926 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7927                                    struct bfd_link_info *info)
7928 {
7929   bfd *bfd1, *bfd2;
7930   const struct elf_backend_data *bed1, *bed2;
7931   Elf_Internal_Shdr *hdr1, *hdr2;
7932   size_t symcount1, symcount2;
7933   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7934   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7935   Elf_Internal_Sym *isym, *isymend;
7936   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7937   size_t count1, count2, i;
7938   unsigned int shndx1, shndx2;
7939   bfd_boolean result;
7940
7941   bfd1 = sec1->owner;
7942   bfd2 = sec2->owner;
7943
7944   /* Both sections have to be in ELF.  */
7945   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7946       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7947     return FALSE;
7948
7949   if (elf_section_type (sec1) != elf_section_type (sec2))
7950     return FALSE;
7951
7952   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7953   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7954   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7955     return FALSE;
7956
7957   bed1 = get_elf_backend_data (bfd1);
7958   bed2 = get_elf_backend_data (bfd2);
7959   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7960   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7961   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7962   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7963
7964   if (symcount1 == 0 || symcount2 == 0)
7965     return FALSE;
7966
7967   result = FALSE;
7968   isymbuf1 = NULL;
7969   isymbuf2 = NULL;
7970   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7971   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7972
7973   if (ssymbuf1 == NULL)
7974     {
7975       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7976                                        NULL, NULL, NULL);
7977       if (isymbuf1 == NULL)
7978         goto done;
7979
7980       if (!info->reduce_memory_overheads)
7981         elf_tdata (bfd1)->symbuf = ssymbuf1
7982           = elf_create_symbuf (symcount1, isymbuf1);
7983     }
7984
7985   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7986     {
7987       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7988                                        NULL, NULL, NULL);
7989       if (isymbuf2 == NULL)
7990         goto done;
7991
7992       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7993         elf_tdata (bfd2)->symbuf = ssymbuf2
7994           = elf_create_symbuf (symcount2, isymbuf2);
7995     }
7996
7997   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7998     {
7999       /* Optimized faster version.  */
8000       size_t lo, hi, mid;
8001       struct elf_symbol *symp;
8002       struct elf_symbuf_symbol *ssym, *ssymend;
8003
8004       lo = 0;
8005       hi = ssymbuf1->count;
8006       ssymbuf1++;
8007       count1 = 0;
8008       while (lo < hi)
8009         {
8010           mid = (lo + hi) / 2;
8011           if (shndx1 < ssymbuf1[mid].st_shndx)
8012             hi = mid;
8013           else if (shndx1 > ssymbuf1[mid].st_shndx)
8014             lo = mid + 1;
8015           else
8016             {
8017               count1 = ssymbuf1[mid].count;
8018               ssymbuf1 += mid;
8019               break;
8020             }
8021         }
8022
8023       lo = 0;
8024       hi = ssymbuf2->count;
8025       ssymbuf2++;
8026       count2 = 0;
8027       while (lo < hi)
8028         {
8029           mid = (lo + hi) / 2;
8030           if (shndx2 < ssymbuf2[mid].st_shndx)
8031             hi = mid;
8032           else if (shndx2 > ssymbuf2[mid].st_shndx)
8033             lo = mid + 1;
8034           else
8035             {
8036               count2 = ssymbuf2[mid].count;
8037               ssymbuf2 += mid;
8038               break;
8039             }
8040         }
8041
8042       if (count1 == 0 || count2 == 0 || count1 != count2)
8043         goto done;
8044
8045       symtable1
8046         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
8047       symtable2
8048         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
8049       if (symtable1 == NULL || symtable2 == NULL)
8050         goto done;
8051
8052       symp = symtable1;
8053       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
8054            ssym < ssymend; ssym++, symp++)
8055         {
8056           symp->u.ssym = ssym;
8057           symp->name = bfd_elf_string_from_elf_section (bfd1,
8058                                                         hdr1->sh_link,
8059                                                         ssym->st_name);
8060         }
8061
8062       symp = symtable2;
8063       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
8064            ssym < ssymend; ssym++, symp++)
8065         {
8066           symp->u.ssym = ssym;
8067           symp->name = bfd_elf_string_from_elf_section (bfd2,
8068                                                         hdr2->sh_link,
8069                                                         ssym->st_name);
8070         }
8071
8072       /* Sort symbol by name.  */
8073       qsort (symtable1, count1, sizeof (struct elf_symbol),
8074              elf_sym_name_compare);
8075       qsort (symtable2, count1, sizeof (struct elf_symbol),
8076              elf_sym_name_compare);
8077
8078       for (i = 0; i < count1; i++)
8079         /* Two symbols must have the same binding, type and name.  */
8080         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
8081             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
8082             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
8083           goto done;
8084
8085       result = TRUE;
8086       goto done;
8087     }
8088
8089   symtable1 = (struct elf_symbol *)
8090       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
8091   symtable2 = (struct elf_symbol *)
8092       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
8093   if (symtable1 == NULL || symtable2 == NULL)
8094     goto done;
8095
8096   /* Count definitions in the section.  */
8097   count1 = 0;
8098   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
8099     if (isym->st_shndx == shndx1)
8100       symtable1[count1++].u.isym = isym;
8101
8102   count2 = 0;
8103   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
8104     if (isym->st_shndx == shndx2)
8105       symtable2[count2++].u.isym = isym;
8106
8107   if (count1 == 0 || count2 == 0 || count1 != count2)
8108     goto done;
8109
8110   for (i = 0; i < count1; i++)
8111     symtable1[i].name
8112       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
8113                                          symtable1[i].u.isym->st_name);
8114
8115   for (i = 0; i < count2; i++)
8116     symtable2[i].name
8117       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
8118                                          symtable2[i].u.isym->st_name);
8119
8120   /* Sort symbol by name.  */
8121   qsort (symtable1, count1, sizeof (struct elf_symbol),
8122          elf_sym_name_compare);
8123   qsort (symtable2, count1, sizeof (struct elf_symbol),
8124          elf_sym_name_compare);
8125
8126   for (i = 0; i < count1; i++)
8127     /* Two symbols must have the same binding, type and name.  */
8128     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
8129         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
8130         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
8131       goto done;
8132
8133   result = TRUE;
8134
8135 done:
8136   if (symtable1)
8137     free (symtable1);
8138   if (symtable2)
8139     free (symtable2);
8140   if (isymbuf1)
8141     free (isymbuf1);
8142   if (isymbuf2)
8143     free (isymbuf2);
8144
8145   return result;
8146 }
8147
8148 /* Return TRUE if 2 section types are compatible.  */
8149
8150 bfd_boolean
8151 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
8152                                  bfd *bbfd, const asection *bsec)
8153 {
8154   if (asec == NULL
8155       || bsec == NULL
8156       || abfd->xvec->flavour != bfd_target_elf_flavour
8157       || bbfd->xvec->flavour != bfd_target_elf_flavour)
8158     return TRUE;
8159
8160   return elf_section_type (asec) == elf_section_type (bsec);
8161 }
8162 \f
8163 /* Final phase of ELF linker.  */
8164
8165 /* A structure we use to avoid passing large numbers of arguments.  */
8166
8167 struct elf_final_link_info
8168 {
8169   /* General link information.  */
8170   struct bfd_link_info *info;
8171   /* Output BFD.  */
8172   bfd *output_bfd;
8173   /* Symbol string table.  */
8174   struct elf_strtab_hash *symstrtab;
8175   /* .hash section.  */
8176   asection *hash_sec;
8177   /* symbol version section (.gnu.version).  */
8178   asection *symver_sec;
8179   /* Buffer large enough to hold contents of any section.  */
8180   bfd_byte *contents;
8181   /* Buffer large enough to hold external relocs of any section.  */
8182   void *external_relocs;
8183   /* Buffer large enough to hold internal relocs of any section.  */
8184   Elf_Internal_Rela *internal_relocs;
8185   /* Buffer large enough to hold external local symbols of any input
8186      BFD.  */
8187   bfd_byte *external_syms;
8188   /* And a buffer for symbol section indices.  */
8189   Elf_External_Sym_Shndx *locsym_shndx;
8190   /* Buffer large enough to hold internal local symbols of any input
8191      BFD.  */
8192   Elf_Internal_Sym *internal_syms;
8193   /* Array large enough to hold a symbol index for each local symbol
8194      of any input BFD.  */
8195   long *indices;
8196   /* Array large enough to hold a section pointer for each local
8197      symbol of any input BFD.  */
8198   asection **sections;
8199   /* Buffer for SHT_SYMTAB_SHNDX section.  */
8200   Elf_External_Sym_Shndx *symshndxbuf;
8201   /* Number of STT_FILE syms seen.  */
8202   size_t filesym_count;
8203 };
8204
8205 /* This struct is used to pass information to elf_link_output_extsym.  */
8206
8207 struct elf_outext_info
8208 {
8209   bfd_boolean failed;
8210   bfd_boolean localsyms;
8211   bfd_boolean file_sym_done;
8212   struct elf_final_link_info *flinfo;
8213 };
8214
8215
8216 /* Support for evaluating a complex relocation.
8217
8218    Complex relocations are generalized, self-describing relocations.  The
8219    implementation of them consists of two parts: complex symbols, and the
8220    relocations themselves.
8221
8222    The relocations are use a reserved elf-wide relocation type code (R_RELC
8223    external / BFD_RELOC_RELC internal) and an encoding of relocation field
8224    information (start bit, end bit, word width, etc) into the addend.  This
8225    information is extracted from CGEN-generated operand tables within gas.
8226
8227    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
8228    internal) representing prefix-notation expressions, including but not
8229    limited to those sorts of expressions normally encoded as addends in the
8230    addend field.  The symbol mangling format is:
8231
8232    <node> := <literal>
8233           |  <unary-operator> ':' <node>
8234           |  <binary-operator> ':' <node> ':' <node>
8235           ;
8236
8237    <literal> := 's' <digits=N> ':' <N character symbol name>
8238              |  'S' <digits=N> ':' <N character section name>
8239              |  '#' <hexdigits>
8240              ;
8241
8242    <binary-operator> := as in C
8243    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
8244
8245 static void
8246 set_symbol_value (bfd *bfd_with_globals,
8247                   Elf_Internal_Sym *isymbuf,
8248                   size_t locsymcount,
8249                   size_t symidx,
8250                   bfd_vma val)
8251 {
8252   struct elf_link_hash_entry **sym_hashes;
8253   struct elf_link_hash_entry *h;
8254   size_t extsymoff = locsymcount;
8255
8256   if (symidx < locsymcount)
8257     {
8258       Elf_Internal_Sym *sym;
8259
8260       sym = isymbuf + symidx;
8261       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
8262         {
8263           /* It is a local symbol: move it to the
8264              "absolute" section and give it a value.  */
8265           sym->st_shndx = SHN_ABS;
8266           sym->st_value = val;
8267           return;
8268         }
8269       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
8270       extsymoff = 0;
8271     }
8272
8273   /* It is a global symbol: set its link type
8274      to "defined" and give it a value.  */
8275
8276   sym_hashes = elf_sym_hashes (bfd_with_globals);
8277   h = sym_hashes [symidx - extsymoff];
8278   while (h->root.type == bfd_link_hash_indirect
8279          || h->root.type == bfd_link_hash_warning)
8280     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8281   h->root.type = bfd_link_hash_defined;
8282   h->root.u.def.value = val;
8283   h->root.u.def.section = bfd_abs_section_ptr;
8284 }
8285
8286 static bfd_boolean
8287 resolve_symbol (const char *name,
8288                 bfd *input_bfd,
8289                 struct elf_final_link_info *flinfo,
8290                 bfd_vma *result,
8291                 Elf_Internal_Sym *isymbuf,
8292                 size_t locsymcount)
8293 {
8294   Elf_Internal_Sym *sym;
8295   struct bfd_link_hash_entry *global_entry;
8296   const char *candidate = NULL;
8297   Elf_Internal_Shdr *symtab_hdr;
8298   size_t i;
8299
8300   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
8301
8302   for (i = 0; i < locsymcount; ++ i)
8303     {
8304       sym = isymbuf + i;
8305
8306       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
8307         continue;
8308
8309       candidate = bfd_elf_string_from_elf_section (input_bfd,
8310                                                    symtab_hdr->sh_link,
8311                                                    sym->st_name);
8312 #ifdef DEBUG
8313       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
8314               name, candidate, (unsigned long) sym->st_value);
8315 #endif
8316       if (candidate && strcmp (candidate, name) == 0)
8317         {
8318           asection *sec = flinfo->sections [i];
8319
8320           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
8321           *result += sec->output_offset + sec->output_section->vma;
8322 #ifdef DEBUG
8323           printf ("Found symbol with value %8.8lx\n",
8324                   (unsigned long) *result);
8325 #endif
8326           return TRUE;
8327         }
8328     }
8329
8330   /* Hmm, haven't found it yet. perhaps it is a global.  */
8331   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
8332                                        FALSE, FALSE, TRUE);
8333   if (!global_entry)
8334     return FALSE;
8335
8336   if (global_entry->type == bfd_link_hash_defined
8337       || global_entry->type == bfd_link_hash_defweak)
8338     {
8339       *result = (global_entry->u.def.value
8340                  + global_entry->u.def.section->output_section->vma
8341                  + global_entry->u.def.section->output_offset);
8342 #ifdef DEBUG
8343       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
8344               global_entry->root.string, (unsigned long) *result);
8345 #endif
8346       return TRUE;
8347     }
8348
8349   return FALSE;
8350 }
8351
8352 /* Looks up NAME in SECTIONS.  If found sets RESULT to NAME's address (in
8353    bytes) and returns TRUE, otherwise returns FALSE.  Accepts pseudo-section
8354    names like "foo.end" which is the end address of section "foo".  */
8355
8356 static bfd_boolean
8357 resolve_section (const char *name,
8358                  asection *sections,
8359                  bfd_vma *result,
8360                  bfd * abfd)
8361 {
8362   asection *curr;
8363   unsigned int len;
8364
8365   for (curr = sections; curr; curr = curr->next)
8366     if (strcmp (curr->name, name) == 0)
8367       {
8368         *result = curr->vma;
8369         return TRUE;
8370       }
8371
8372   /* Hmm. still haven't found it. try pseudo-section names.  */
8373   /* FIXME: This could be coded more efficiently...  */
8374   for (curr = sections; curr; curr = curr->next)
8375     {
8376       len = strlen (curr->name);
8377       if (len > strlen (name))
8378         continue;
8379
8380       if (strncmp (curr->name, name, len) == 0)
8381         {
8382           if (strncmp (".end", name + len, 4) == 0)
8383             {
8384               *result = curr->vma + curr->size / bfd_octets_per_byte (abfd);
8385               return TRUE;
8386             }
8387
8388           /* Insert more pseudo-section names here, if you like.  */
8389         }
8390     }
8391
8392   return FALSE;
8393 }
8394
8395 static void
8396 undefined_reference (const char *reftype, const char *name)
8397 {
8398   /* xgettext:c-format */
8399   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
8400                       reftype, name);
8401 }
8402
8403 static bfd_boolean
8404 eval_symbol (bfd_vma *result,
8405              const char **symp,
8406              bfd *input_bfd,
8407              struct elf_final_link_info *flinfo,
8408              bfd_vma dot,
8409              Elf_Internal_Sym *isymbuf,
8410              size_t locsymcount,
8411              int signed_p)
8412 {
8413   size_t len;
8414   size_t symlen;
8415   bfd_vma a;
8416   bfd_vma b;
8417   char symbuf[4096];
8418   const char *sym = *symp;
8419   const char *symend;
8420   bfd_boolean symbol_is_section = FALSE;
8421
8422   len = strlen (sym);
8423   symend = sym + len;
8424
8425   if (len < 1 || len > sizeof (symbuf))
8426     {
8427       bfd_set_error (bfd_error_invalid_operation);
8428       return FALSE;
8429     }
8430
8431   switch (* sym)
8432     {
8433     case '.':
8434       *result = dot;
8435       *symp = sym + 1;
8436       return TRUE;
8437
8438     case '#':
8439       ++sym;
8440       *result = strtoul (sym, (char **) symp, 16);
8441       return TRUE;
8442
8443     case 'S':
8444       symbol_is_section = TRUE;
8445       /* Fall through.  */
8446     case 's':
8447       ++sym;
8448       symlen = strtol (sym, (char **) symp, 10);
8449       sym = *symp + 1; /* Skip the trailing ':'.  */
8450
8451       if (symend < sym || symlen + 1 > sizeof (symbuf))
8452         {
8453           bfd_set_error (bfd_error_invalid_operation);
8454           return FALSE;
8455         }
8456
8457       memcpy (symbuf, sym, symlen);
8458       symbuf[symlen] = '\0';
8459       *symp = sym + symlen;
8460
8461       /* Is it always possible, with complex symbols, that gas "mis-guessed"
8462          the symbol as a section, or vice-versa. so we're pretty liberal in our
8463          interpretation here; section means "try section first", not "must be a
8464          section", and likewise with symbol.  */
8465
8466       if (symbol_is_section)
8467         {
8468           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result, input_bfd)
8469               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
8470                                   isymbuf, locsymcount))
8471             {
8472               undefined_reference ("section", symbuf);
8473               return FALSE;
8474             }
8475         }
8476       else
8477         {
8478           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
8479                                isymbuf, locsymcount)
8480               && !resolve_section (symbuf, flinfo->output_bfd->sections,
8481                                    result, input_bfd))
8482             {
8483               undefined_reference ("symbol", symbuf);
8484               return FALSE;
8485             }
8486         }
8487
8488       return TRUE;
8489
8490       /* All that remains are operators.  */
8491
8492 #define UNARY_OP(op)                                            \
8493   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8494     {                                                           \
8495       sym += strlen (#op);                                      \
8496       if (*sym == ':')                                          \
8497         ++sym;                                                  \
8498       *symp = sym;                                              \
8499       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8500                         isymbuf, locsymcount, signed_p))        \
8501         return FALSE;                                           \
8502       if (signed_p)                                             \
8503         *result = op ((bfd_signed_vma) a);                      \
8504       else                                                      \
8505         *result = op a;                                         \
8506       return TRUE;                                              \
8507     }
8508
8509 #define BINARY_OP(op)                                           \
8510   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8511     {                                                           \
8512       sym += strlen (#op);                                      \
8513       if (*sym == ':')                                          \
8514         ++sym;                                                  \
8515       *symp = sym;                                              \
8516       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8517                         isymbuf, locsymcount, signed_p))        \
8518         return FALSE;                                           \
8519       ++*symp;                                                  \
8520       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
8521                         isymbuf, locsymcount, signed_p))        \
8522         return FALSE;                                           \
8523       if (signed_p)                                             \
8524         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
8525       else                                                      \
8526         *result = a op b;                                       \
8527       return TRUE;                                              \
8528     }
8529
8530     default:
8531       UNARY_OP  (0-);
8532       BINARY_OP (<<);
8533       BINARY_OP (>>);
8534       BINARY_OP (==);
8535       BINARY_OP (!=);
8536       BINARY_OP (<=);
8537       BINARY_OP (>=);
8538       BINARY_OP (&&);
8539       BINARY_OP (||);
8540       UNARY_OP  (~);
8541       UNARY_OP  (!);
8542       BINARY_OP (*);
8543       BINARY_OP (/);
8544       BINARY_OP (%);
8545       BINARY_OP (^);
8546       BINARY_OP (|);
8547       BINARY_OP (&);
8548       BINARY_OP (+);
8549       BINARY_OP (-);
8550       BINARY_OP (<);
8551       BINARY_OP (>);
8552 #undef UNARY_OP
8553 #undef BINARY_OP
8554       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
8555       bfd_set_error (bfd_error_invalid_operation);
8556       return FALSE;
8557     }
8558 }
8559
8560 static void
8561 put_value (bfd_vma size,
8562            unsigned long chunksz,
8563            bfd *input_bfd,
8564            bfd_vma x,
8565            bfd_byte *location)
8566 {
8567   location += (size - chunksz);
8568
8569   for (; size; size -= chunksz, location -= chunksz)
8570     {
8571       switch (chunksz)
8572         {
8573         case 1:
8574           bfd_put_8 (input_bfd, x, location);
8575           x >>= 8;
8576           break;
8577         case 2:
8578           bfd_put_16 (input_bfd, x, location);
8579           x >>= 16;
8580           break;
8581         case 4:
8582           bfd_put_32 (input_bfd, x, location);
8583           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
8584           x >>= 16;
8585           x >>= 16;
8586           break;
8587 #ifdef BFD64
8588         case 8:
8589           bfd_put_64 (input_bfd, x, location);
8590           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
8591           x >>= 32;
8592           x >>= 32;
8593           break;
8594 #endif
8595         default:
8596           abort ();
8597           break;
8598         }
8599     }
8600 }
8601
8602 static bfd_vma
8603 get_value (bfd_vma size,
8604            unsigned long chunksz,
8605            bfd *input_bfd,
8606            bfd_byte *location)
8607 {
8608   int shift;
8609   bfd_vma x = 0;
8610
8611   /* Sanity checks.  */
8612   BFD_ASSERT (chunksz <= sizeof (x)
8613               && size >= chunksz
8614               && chunksz != 0
8615               && (size % chunksz) == 0
8616               && input_bfd != NULL
8617               && location != NULL);
8618
8619   if (chunksz == sizeof (x))
8620     {
8621       BFD_ASSERT (size == chunksz);
8622
8623       /* Make sure that we do not perform an undefined shift operation.
8624          We know that size == chunksz so there will only be one iteration
8625          of the loop below.  */
8626       shift = 0;
8627     }
8628   else
8629     shift = 8 * chunksz;
8630
8631   for (; size; size -= chunksz, location += chunksz)
8632     {
8633       switch (chunksz)
8634         {
8635         case 1:
8636           x = (x << shift) | bfd_get_8 (input_bfd, location);
8637           break;
8638         case 2:
8639           x = (x << shift) | bfd_get_16 (input_bfd, location);
8640           break;
8641         case 4:
8642           x = (x << shift) | bfd_get_32 (input_bfd, location);
8643           break;
8644 #ifdef BFD64
8645         case 8:
8646           x = (x << shift) | bfd_get_64 (input_bfd, location);
8647           break;
8648 #endif
8649         default:
8650           abort ();
8651         }
8652     }
8653   return x;
8654 }
8655
8656 static void
8657 decode_complex_addend (unsigned long *start,   /* in bits */
8658                        unsigned long *oplen,   /* in bits */
8659                        unsigned long *len,     /* in bits */
8660                        unsigned long *wordsz,  /* in bytes */
8661                        unsigned long *chunksz, /* in bytes */
8662                        unsigned long *lsb0_p,
8663                        unsigned long *signed_p,
8664                        unsigned long *trunc_p,
8665                        unsigned long encoded)
8666 {
8667   * start     =  encoded        & 0x3F;
8668   * len       = (encoded >>  6) & 0x3F;
8669   * oplen     = (encoded >> 12) & 0x3F;
8670   * wordsz    = (encoded >> 18) & 0xF;
8671   * chunksz   = (encoded >> 22) & 0xF;
8672   * lsb0_p    = (encoded >> 27) & 1;
8673   * signed_p  = (encoded >> 28) & 1;
8674   * trunc_p   = (encoded >> 29) & 1;
8675 }
8676
8677 bfd_reloc_status_type
8678 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8679                                     asection *input_section ATTRIBUTE_UNUSED,
8680                                     bfd_byte *contents,
8681                                     Elf_Internal_Rela *rel,
8682                                     bfd_vma relocation)
8683 {
8684   bfd_vma shift, x, mask;
8685   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8686   bfd_reloc_status_type r;
8687
8688   /*  Perform this reloc, since it is complex.
8689       (this is not to say that it necessarily refers to a complex
8690       symbol; merely that it is a self-describing CGEN based reloc.
8691       i.e. the addend has the complete reloc information (bit start, end,
8692       word size, etc) encoded within it.).  */
8693
8694   decode_complex_addend (&start, &oplen, &len, &wordsz,
8695                          &chunksz, &lsb0_p, &signed_p,
8696                          &trunc_p, rel->r_addend);
8697
8698   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8699
8700   if (lsb0_p)
8701     shift = (start + 1) - len;
8702   else
8703     shift = (8 * wordsz) - (start + len);
8704
8705   x = get_value (wordsz, chunksz, input_bfd,
8706                  contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8707
8708 #ifdef DEBUG
8709   printf ("Doing complex reloc: "
8710           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8711           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8712           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8713           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8714           oplen, (unsigned long) x, (unsigned long) mask,
8715           (unsigned long) relocation);
8716 #endif
8717
8718   r = bfd_reloc_ok;
8719   if (! trunc_p)
8720     /* Now do an overflow check.  */
8721     r = bfd_check_overflow ((signed_p
8722                              ? complain_overflow_signed
8723                              : complain_overflow_unsigned),
8724                             len, 0, (8 * wordsz),
8725                             relocation);
8726
8727   /* Do the deed.  */
8728   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8729
8730 #ifdef DEBUG
8731   printf ("           relocation: %8.8lx\n"
8732           "         shifted mask: %8.8lx\n"
8733           " shifted/masked reloc: %8.8lx\n"
8734           "               result: %8.8lx\n",
8735           (unsigned long) relocation, (unsigned long) (mask << shift),
8736           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8737 #endif
8738   put_value (wordsz, chunksz, input_bfd, x,
8739              contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8740   return r;
8741 }
8742
8743 /* Functions to read r_offset from external (target order) reloc
8744    entry.  Faster than bfd_getl32 et al, because we let the compiler
8745    know the value is aligned.  */
8746
8747 static bfd_vma
8748 ext32l_r_offset (const void *p)
8749 {
8750   union aligned32
8751   {
8752     uint32_t v;
8753     unsigned char c[4];
8754   };
8755   const union aligned32 *a
8756     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8757
8758   uint32_t aval = (  (uint32_t) a->c[0]
8759                    | (uint32_t) a->c[1] << 8
8760                    | (uint32_t) a->c[2] << 16
8761                    | (uint32_t) a->c[3] << 24);
8762   return aval;
8763 }
8764
8765 static bfd_vma
8766 ext32b_r_offset (const void *p)
8767 {
8768   union aligned32
8769   {
8770     uint32_t v;
8771     unsigned char c[4];
8772   };
8773   const union aligned32 *a
8774     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8775
8776   uint32_t aval = (  (uint32_t) a->c[0] << 24
8777                    | (uint32_t) a->c[1] << 16
8778                    | (uint32_t) a->c[2] << 8
8779                    | (uint32_t) a->c[3]);
8780   return aval;
8781 }
8782
8783 #ifdef BFD_HOST_64_BIT
8784 static bfd_vma
8785 ext64l_r_offset (const void *p)
8786 {
8787   union aligned64
8788   {
8789     uint64_t v;
8790     unsigned char c[8];
8791   };
8792   const union aligned64 *a
8793     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8794
8795   uint64_t aval = (  (uint64_t) a->c[0]
8796                    | (uint64_t) a->c[1] << 8
8797                    | (uint64_t) a->c[2] << 16
8798                    | (uint64_t) a->c[3] << 24
8799                    | (uint64_t) a->c[4] << 32
8800                    | (uint64_t) a->c[5] << 40
8801                    | (uint64_t) a->c[6] << 48
8802                    | (uint64_t) a->c[7] << 56);
8803   return aval;
8804 }
8805
8806 static bfd_vma
8807 ext64b_r_offset (const void *p)
8808 {
8809   union aligned64
8810   {
8811     uint64_t v;
8812     unsigned char c[8];
8813   };
8814   const union aligned64 *a
8815     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8816
8817   uint64_t aval = (  (uint64_t) a->c[0] << 56
8818                    | (uint64_t) a->c[1] << 48
8819                    | (uint64_t) a->c[2] << 40
8820                    | (uint64_t) a->c[3] << 32
8821                    | (uint64_t) a->c[4] << 24
8822                    | (uint64_t) a->c[5] << 16
8823                    | (uint64_t) a->c[6] << 8
8824                    | (uint64_t) a->c[7]);
8825   return aval;
8826 }
8827 #endif
8828
8829 /* When performing a relocatable link, the input relocations are
8830    preserved.  But, if they reference global symbols, the indices
8831    referenced must be updated.  Update all the relocations found in
8832    RELDATA.  */
8833
8834 static bfd_boolean
8835 elf_link_adjust_relocs (bfd *abfd,
8836                         asection *sec,
8837                         struct bfd_elf_section_reloc_data *reldata,
8838                         bfd_boolean sort,
8839                         struct bfd_link_info *info)
8840 {
8841   unsigned int i;
8842   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8843   bfd_byte *erela;
8844   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8845   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8846   bfd_vma r_type_mask;
8847   int r_sym_shift;
8848   unsigned int count = reldata->count;
8849   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8850
8851   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8852     {
8853       swap_in = bed->s->swap_reloc_in;
8854       swap_out = bed->s->swap_reloc_out;
8855     }
8856   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8857     {
8858       swap_in = bed->s->swap_reloca_in;
8859       swap_out = bed->s->swap_reloca_out;
8860     }
8861   else
8862     abort ();
8863
8864   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8865     abort ();
8866
8867   if (bed->s->arch_size == 32)
8868     {
8869       r_type_mask = 0xff;
8870       r_sym_shift = 8;
8871     }
8872   else
8873     {
8874       r_type_mask = 0xffffffff;
8875       r_sym_shift = 32;
8876     }
8877
8878   erela = reldata->hdr->contents;
8879   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8880     {
8881       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8882       unsigned int j;
8883
8884       if (*rel_hash == NULL)
8885         continue;
8886
8887       if ((*rel_hash)->indx == -2
8888           && info->gc_sections
8889           && ! info->gc_keep_exported)
8890         {
8891           /* PR 21524: Let the user know if a symbol was removed by garbage collection.  */
8892           _bfd_error_handler (_("%pB:%pA: error: relocation references symbol %s which was removed by garbage collection"),
8893                               abfd, sec,
8894                               (*rel_hash)->root.root.string);
8895           _bfd_error_handler (_("%pB:%pA: error: try relinking with --gc-keep-exported enabled"),
8896                               abfd, sec);
8897           bfd_set_error (bfd_error_invalid_operation);
8898           return FALSE;
8899         }
8900       BFD_ASSERT ((*rel_hash)->indx >= 0);
8901
8902       (*swap_in) (abfd, erela, irela);
8903       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8904         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8905                            | (irela[j].r_info & r_type_mask));
8906       (*swap_out) (abfd, irela, erela);
8907     }
8908
8909   if (bed->elf_backend_update_relocs)
8910     (*bed->elf_backend_update_relocs) (sec, reldata);
8911
8912   if (sort && count != 0)
8913     {
8914       bfd_vma (*ext_r_off) (const void *);
8915       bfd_vma r_off;
8916       size_t elt_size;
8917       bfd_byte *base, *end, *p, *loc;
8918       bfd_byte *buf = NULL;
8919
8920       if (bed->s->arch_size == 32)
8921         {
8922           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8923             ext_r_off = ext32l_r_offset;
8924           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8925             ext_r_off = ext32b_r_offset;
8926           else
8927             abort ();
8928         }
8929       else
8930         {
8931 #ifdef BFD_HOST_64_BIT
8932           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8933             ext_r_off = ext64l_r_offset;
8934           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8935             ext_r_off = ext64b_r_offset;
8936           else
8937 #endif
8938             abort ();
8939         }
8940
8941       /*  Must use a stable sort here.  A modified insertion sort,
8942           since the relocs are mostly sorted already.  */
8943       elt_size = reldata->hdr->sh_entsize;
8944       base = reldata->hdr->contents;
8945       end = base + count * elt_size;
8946       if (elt_size > sizeof (Elf64_External_Rela))
8947         abort ();
8948
8949       /* Ensure the first element is lowest.  This acts as a sentinel,
8950          speeding the main loop below.  */
8951       r_off = (*ext_r_off) (base);
8952       for (p = loc = base; (p += elt_size) < end; )
8953         {
8954           bfd_vma r_off2 = (*ext_r_off) (p);
8955           if (r_off > r_off2)
8956             {
8957               r_off = r_off2;
8958               loc = p;
8959             }
8960         }
8961       if (loc != base)
8962         {
8963           /* Don't just swap *base and *loc as that changes the order
8964              of the original base[0] and base[1] if they happen to
8965              have the same r_offset.  */
8966           bfd_byte onebuf[sizeof (Elf64_External_Rela)];
8967           memcpy (onebuf, loc, elt_size);
8968           memmove (base + elt_size, base, loc - base);
8969           memcpy (base, onebuf, elt_size);
8970         }
8971
8972       for (p = base + elt_size; (p += elt_size) < end; )
8973         {
8974           /* base to p is sorted, *p is next to insert.  */
8975           r_off = (*ext_r_off) (p);
8976           /* Search the sorted region for location to insert.  */
8977           loc = p - elt_size;
8978           while (r_off < (*ext_r_off) (loc))
8979             loc -= elt_size;
8980           loc += elt_size;
8981           if (loc != p)
8982             {
8983               /* Chances are there is a run of relocs to insert here,
8984                  from one of more input files.  Files are not always
8985                  linked in order due to the way elf_link_input_bfd is
8986                  called.  See pr17666.  */
8987               size_t sortlen = p - loc;
8988               bfd_vma r_off2 = (*ext_r_off) (loc);
8989               size_t runlen = elt_size;
8990               size_t buf_size = 96 * 1024;
8991               while (p + runlen < end
8992                      && (sortlen <= buf_size
8993                          || runlen + elt_size <= buf_size)
8994                      && r_off2 > (*ext_r_off) (p + runlen))
8995                 runlen += elt_size;
8996               if (buf == NULL)
8997                 {
8998                   buf = bfd_malloc (buf_size);
8999                   if (buf == NULL)
9000                     return FALSE;
9001                 }
9002               if (runlen < sortlen)
9003                 {
9004                   memcpy (buf, p, runlen);
9005                   memmove (loc + runlen, loc, sortlen);
9006                   memcpy (loc, buf, runlen);
9007                 }
9008               else
9009                 {
9010                   memcpy (buf, loc, sortlen);
9011                   memmove (loc, p, runlen);
9012                   memcpy (loc + runlen, buf, sortlen);
9013                 }
9014               p += runlen - elt_size;
9015             }
9016         }
9017       /* Hashes are no longer valid.  */
9018       free (reldata->hashes);
9019       reldata->hashes = NULL;
9020       free (buf);
9021     }
9022   return TRUE;
9023 }
9024
9025 struct elf_link_sort_rela
9026 {
9027   union {
9028     bfd_vma offset;
9029     bfd_vma sym_mask;
9030   } u;
9031   enum elf_reloc_type_class type;
9032   /* We use this as an array of size int_rels_per_ext_rel.  */
9033   Elf_Internal_Rela rela[1];
9034 };
9035
9036 static int
9037 elf_link_sort_cmp1 (const void *A, const void *B)
9038 {
9039   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
9040   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
9041   int relativea, relativeb;
9042
9043   relativea = a->type == reloc_class_relative;
9044   relativeb = b->type == reloc_class_relative;
9045
9046   if (relativea < relativeb)
9047     return 1;
9048   if (relativea > relativeb)
9049     return -1;
9050   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
9051     return -1;
9052   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
9053     return 1;
9054   if (a->rela->r_offset < b->rela->r_offset)
9055     return -1;
9056   if (a->rela->r_offset > b->rela->r_offset)
9057     return 1;
9058   return 0;
9059 }
9060
9061 static int
9062 elf_link_sort_cmp2 (const void *A, const void *B)
9063 {
9064   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
9065   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
9066
9067   if (a->type < b->type)
9068     return -1;
9069   if (a->type > b->type)
9070     return 1;
9071   if (a->u.offset < b->u.offset)
9072     return -1;
9073   if (a->u.offset > b->u.offset)
9074     return 1;
9075   if (a->rela->r_offset < b->rela->r_offset)
9076     return -1;
9077   if (a->rela->r_offset > b->rela->r_offset)
9078     return 1;
9079   return 0;
9080 }
9081
9082 static size_t
9083 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
9084 {
9085   asection *dynamic_relocs;
9086   asection *rela_dyn;
9087   asection *rel_dyn;
9088   bfd_size_type count, size;
9089   size_t i, ret, sort_elt, ext_size;
9090   bfd_byte *sort, *s_non_relative, *p;
9091   struct elf_link_sort_rela *sq;
9092   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9093   int i2e = bed->s->int_rels_per_ext_rel;
9094   unsigned int opb = bfd_octets_per_byte (abfd);
9095   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
9096   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
9097   struct bfd_link_order *lo;
9098   bfd_vma r_sym_mask;
9099   bfd_boolean use_rela;
9100
9101   /* Find a dynamic reloc section.  */
9102   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
9103   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
9104   if (rela_dyn != NULL && rela_dyn->size > 0
9105       && rel_dyn != NULL && rel_dyn->size > 0)
9106     {
9107       bfd_boolean use_rela_initialised = FALSE;
9108
9109       /* This is just here to stop gcc from complaining.
9110          Its initialization checking code is not perfect.  */
9111       use_rela = TRUE;
9112
9113       /* Both sections are present.  Examine the sizes
9114          of the indirect sections to help us choose.  */
9115       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
9116         if (lo->type == bfd_indirect_link_order)
9117           {
9118             asection *o = lo->u.indirect.section;
9119
9120             if ((o->size % bed->s->sizeof_rela) == 0)
9121               {
9122                 if ((o->size % bed->s->sizeof_rel) == 0)
9123                   /* Section size is divisible by both rel and rela sizes.
9124                      It is of no help to us.  */
9125                   ;
9126                 else
9127                   {
9128                     /* Section size is only divisible by rela.  */
9129                     if (use_rela_initialised && !use_rela)
9130                       {
9131                         _bfd_error_handler (_("%pB: unable to sort relocs - "
9132                                               "they are in more than one size"),
9133                                             abfd);
9134                         bfd_set_error (bfd_error_invalid_operation);
9135                         return 0;
9136                       }
9137                     else
9138                       {
9139                         use_rela = TRUE;
9140                         use_rela_initialised = TRUE;
9141                       }
9142                   }
9143               }
9144             else if ((o->size % bed->s->sizeof_rel) == 0)
9145               {
9146                 /* Section size is only divisible by rel.  */
9147                 if (use_rela_initialised && use_rela)
9148                   {
9149                     _bfd_error_handler (_("%pB: unable to sort relocs - "
9150                                           "they are in more than one size"),
9151                                         abfd);
9152                     bfd_set_error (bfd_error_invalid_operation);
9153                     return 0;
9154                   }
9155                 else
9156                   {
9157                     use_rela = FALSE;
9158                     use_rela_initialised = TRUE;
9159                   }
9160               }
9161             else
9162               {
9163                 /* The section size is not divisible by either -
9164                    something is wrong.  */
9165                 _bfd_error_handler (_("%pB: unable to sort relocs - "
9166                                       "they are of an unknown size"), abfd);
9167                 bfd_set_error (bfd_error_invalid_operation);
9168                 return 0;
9169               }
9170           }
9171
9172       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
9173         if (lo->type == bfd_indirect_link_order)
9174           {
9175             asection *o = lo->u.indirect.section;
9176
9177             if ((o->size % bed->s->sizeof_rela) == 0)
9178               {
9179                 if ((o->size % bed->s->sizeof_rel) == 0)
9180                   /* Section size is divisible by both rel and rela sizes.
9181                      It is of no help to us.  */
9182                   ;
9183                 else
9184                   {
9185                     /* Section size is only divisible by rela.  */
9186                     if (use_rela_initialised && !use_rela)
9187                       {
9188                         _bfd_error_handler (_("%pB: unable to sort relocs - "
9189                                               "they are in more than one size"),
9190                                             abfd);
9191                         bfd_set_error (bfd_error_invalid_operation);
9192                         return 0;
9193                       }
9194                     else
9195                       {
9196                         use_rela = TRUE;
9197                         use_rela_initialised = TRUE;
9198                       }
9199                   }
9200               }
9201             else if ((o->size % bed->s->sizeof_rel) == 0)
9202               {
9203                 /* Section size is only divisible by rel.  */
9204                 if (use_rela_initialised && use_rela)
9205                   {
9206                     _bfd_error_handler (_("%pB: unable to sort relocs - "
9207                                           "they are in more than one size"),
9208                                         abfd);
9209                     bfd_set_error (bfd_error_invalid_operation);
9210                     return 0;
9211                   }
9212                 else
9213                   {
9214                     use_rela = FALSE;
9215                     use_rela_initialised = TRUE;
9216                   }
9217               }
9218             else
9219               {
9220                 /* The section size is not divisible by either -
9221                    something is wrong.  */
9222                 _bfd_error_handler (_("%pB: unable to sort relocs - "
9223                                       "they are of an unknown size"), abfd);
9224                 bfd_set_error (bfd_error_invalid_operation);
9225                 return 0;
9226               }
9227           }
9228
9229       if (! use_rela_initialised)
9230         /* Make a guess.  */
9231         use_rela = TRUE;
9232     }
9233   else if (rela_dyn != NULL && rela_dyn->size > 0)
9234     use_rela = TRUE;
9235   else if (rel_dyn != NULL && rel_dyn->size > 0)
9236     use_rela = FALSE;
9237   else
9238     return 0;
9239
9240   if (use_rela)
9241     {
9242       dynamic_relocs = rela_dyn;
9243       ext_size = bed->s->sizeof_rela;
9244       swap_in = bed->s->swap_reloca_in;
9245       swap_out = bed->s->swap_reloca_out;
9246     }
9247   else
9248     {
9249       dynamic_relocs = rel_dyn;
9250       ext_size = bed->s->sizeof_rel;
9251       swap_in = bed->s->swap_reloc_in;
9252       swap_out = bed->s->swap_reloc_out;
9253     }
9254
9255   size = 0;
9256   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9257     if (lo->type == bfd_indirect_link_order)
9258       size += lo->u.indirect.section->size;
9259
9260   if (size != dynamic_relocs->size)
9261     return 0;
9262
9263   sort_elt = (sizeof (struct elf_link_sort_rela)
9264               + (i2e - 1) * sizeof (Elf_Internal_Rela));
9265
9266   count = dynamic_relocs->size / ext_size;
9267   if (count == 0)
9268     return 0;
9269   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
9270
9271   if (sort == NULL)
9272     {
9273       (*info->callbacks->warning)
9274         (info, _("not enough memory to sort relocations"), 0, abfd, 0, 0);
9275       return 0;
9276     }
9277
9278   if (bed->s->arch_size == 32)
9279     r_sym_mask = ~(bfd_vma) 0xff;
9280   else
9281     r_sym_mask = ~(bfd_vma) 0xffffffff;
9282
9283   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9284     if (lo->type == bfd_indirect_link_order)
9285       {
9286         bfd_byte *erel, *erelend;
9287         asection *o = lo->u.indirect.section;
9288
9289         if (o->contents == NULL && o->size != 0)
9290           {
9291             /* This is a reloc section that is being handled as a normal
9292                section.  See bfd_section_from_shdr.  We can't combine
9293                relocs in this case.  */
9294             free (sort);
9295             return 0;
9296           }
9297         erel = o->contents;
9298         erelend = o->contents + o->size;
9299         p = sort + o->output_offset * opb / ext_size * sort_elt;
9300
9301         while (erel < erelend)
9302           {
9303             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9304
9305             (*swap_in) (abfd, erel, s->rela);
9306             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
9307             s->u.sym_mask = r_sym_mask;
9308             p += sort_elt;
9309             erel += ext_size;
9310           }
9311       }
9312
9313   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
9314
9315   for (i = 0, p = sort; i < count; i++, p += sort_elt)
9316     {
9317       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9318       if (s->type != reloc_class_relative)
9319         break;
9320     }
9321   ret = i;
9322   s_non_relative = p;
9323
9324   sq = (struct elf_link_sort_rela *) s_non_relative;
9325   for (; i < count; i++, p += sort_elt)
9326     {
9327       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
9328       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
9329         sq = sp;
9330       sp->u.offset = sq->rela->r_offset;
9331     }
9332
9333   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
9334
9335   struct elf_link_hash_table *htab = elf_hash_table (info);
9336   if (htab->srelplt && htab->srelplt->output_section == dynamic_relocs)
9337     {
9338       /* We have plt relocs in .rela.dyn.  */
9339       sq = (struct elf_link_sort_rela *) sort;
9340       for (i = 0; i < count; i++)
9341         if (sq[count - i - 1].type != reloc_class_plt)
9342           break;
9343       if (i != 0 && htab->srelplt->size == i * ext_size)
9344         {
9345           struct bfd_link_order **plo;
9346           /* Put srelplt link_order last.  This is so the output_offset
9347              set in the next loop is correct for DT_JMPREL.  */
9348           for (plo = &dynamic_relocs->map_head.link_order; *plo != NULL; )
9349             if ((*plo)->type == bfd_indirect_link_order
9350                 && (*plo)->u.indirect.section == htab->srelplt)
9351               {
9352                 lo = *plo;
9353                 *plo = lo->next;
9354               }
9355             else
9356               plo = &(*plo)->next;
9357           *plo = lo;
9358           lo->next = NULL;
9359           dynamic_relocs->map_tail.link_order = lo;
9360         }
9361     }
9362
9363   p = sort;
9364   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9365     if (lo->type == bfd_indirect_link_order)
9366       {
9367         bfd_byte *erel, *erelend;
9368         asection *o = lo->u.indirect.section;
9369
9370         erel = o->contents;
9371         erelend = o->contents + o->size;
9372         o->output_offset = (p - sort) / sort_elt * ext_size / opb;
9373         while (erel < erelend)
9374           {
9375             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9376             (*swap_out) (abfd, s->rela, erel);
9377             p += sort_elt;
9378             erel += ext_size;
9379           }
9380       }
9381
9382   free (sort);
9383   *psec = dynamic_relocs;
9384   return ret;
9385 }
9386
9387 /* Add a symbol to the output symbol string table.  */
9388
9389 static int
9390 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
9391                            const char *name,
9392                            Elf_Internal_Sym *elfsym,
9393                            asection *input_sec,
9394                            struct elf_link_hash_entry *h)
9395 {
9396   int (*output_symbol_hook)
9397     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
9398      struct elf_link_hash_entry *);
9399   struct elf_link_hash_table *hash_table;
9400   const struct elf_backend_data *bed;
9401   bfd_size_type strtabsize;
9402
9403   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9404
9405   bed = get_elf_backend_data (flinfo->output_bfd);
9406   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
9407   if (output_symbol_hook != NULL)
9408     {
9409       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
9410       if (ret != 1)
9411         return ret;
9412     }
9413
9414   if (name == NULL
9415       || *name == '\0'
9416       || (input_sec->flags & SEC_EXCLUDE))
9417     elfsym->st_name = (unsigned long) -1;
9418   else
9419     {
9420       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
9421          to get the final offset for st_name.  */
9422       elfsym->st_name
9423         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
9424                                                name, FALSE);
9425       if (elfsym->st_name == (unsigned long) -1)
9426         return 0;
9427     }
9428
9429   hash_table = elf_hash_table (flinfo->info);
9430   strtabsize = hash_table->strtabsize;
9431   if (strtabsize <= hash_table->strtabcount)
9432     {
9433       strtabsize += strtabsize;
9434       hash_table->strtabsize = strtabsize;
9435       strtabsize *= sizeof (*hash_table->strtab);
9436       hash_table->strtab
9437         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
9438                                                  strtabsize);
9439       if (hash_table->strtab == NULL)
9440         return 0;
9441     }
9442   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
9443   hash_table->strtab[hash_table->strtabcount].dest_index
9444     = hash_table->strtabcount;
9445   hash_table->strtab[hash_table->strtabcount].destshndx_index
9446     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
9447
9448   bfd_get_symcount (flinfo->output_bfd) += 1;
9449   hash_table->strtabcount += 1;
9450
9451   return 1;
9452 }
9453
9454 /* Swap symbols out to the symbol table and flush the output symbols to
9455    the file.  */
9456
9457 static bfd_boolean
9458 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
9459 {
9460   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
9461   bfd_size_type amt;
9462   size_t i;
9463   const struct elf_backend_data *bed;
9464   bfd_byte *symbuf;
9465   Elf_Internal_Shdr *hdr;
9466   file_ptr pos;
9467   bfd_boolean ret;
9468
9469   if (!hash_table->strtabcount)
9470     return TRUE;
9471
9472   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9473
9474   bed = get_elf_backend_data (flinfo->output_bfd);
9475
9476   amt = bed->s->sizeof_sym * hash_table->strtabcount;
9477   symbuf = (bfd_byte *) bfd_malloc (amt);
9478   if (symbuf == NULL)
9479     return FALSE;
9480
9481   if (flinfo->symshndxbuf)
9482     {
9483       amt = sizeof (Elf_External_Sym_Shndx);
9484       amt *= bfd_get_symcount (flinfo->output_bfd);
9485       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
9486       if (flinfo->symshndxbuf == NULL)
9487         {
9488           free (symbuf);
9489           return FALSE;
9490         }
9491     }
9492
9493   for (i = 0; i < hash_table->strtabcount; i++)
9494     {
9495       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
9496       if (elfsym->sym.st_name == (unsigned long) -1)
9497         elfsym->sym.st_name = 0;
9498       else
9499         elfsym->sym.st_name
9500           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
9501                                                     elfsym->sym.st_name);
9502       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
9503                                ((bfd_byte *) symbuf
9504                                 + (elfsym->dest_index
9505                                    * bed->s->sizeof_sym)),
9506                                (flinfo->symshndxbuf
9507                                 + elfsym->destshndx_index));
9508     }
9509
9510   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
9511   pos = hdr->sh_offset + hdr->sh_size;
9512   amt = hash_table->strtabcount * bed->s->sizeof_sym;
9513   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
9514       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
9515     {
9516       hdr->sh_size += amt;
9517       ret = TRUE;
9518     }
9519   else
9520     ret = FALSE;
9521
9522   free (symbuf);
9523
9524   free (hash_table->strtab);
9525   hash_table->strtab = NULL;
9526
9527   return ret;
9528 }
9529
9530 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
9531
9532 static bfd_boolean
9533 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
9534 {
9535   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
9536       && sym->st_shndx < SHN_LORESERVE)
9537     {
9538       /* The gABI doesn't support dynamic symbols in output sections
9539          beyond 64k.  */
9540       _bfd_error_handler
9541         /* xgettext:c-format */
9542         (_("%pB: too many sections: %d (>= %d)"),
9543          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
9544       bfd_set_error (bfd_error_nonrepresentable_section);
9545       return FALSE;
9546     }
9547   return TRUE;
9548 }
9549
9550 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
9551    allowing an unsatisfied unversioned symbol in the DSO to match a
9552    versioned symbol that would normally require an explicit version.
9553    We also handle the case that a DSO references a hidden symbol
9554    which may be satisfied by a versioned symbol in another DSO.  */
9555
9556 static bfd_boolean
9557 elf_link_check_versioned_symbol (struct bfd_link_info *info,
9558                                  const struct elf_backend_data *bed,
9559                                  struct elf_link_hash_entry *h)
9560 {
9561   bfd *abfd;
9562   struct elf_link_loaded_list *loaded;
9563
9564   if (!is_elf_hash_table (info->hash))
9565     return FALSE;
9566
9567   /* Check indirect symbol.  */
9568   while (h->root.type == bfd_link_hash_indirect)
9569     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9570
9571   switch (h->root.type)
9572     {
9573     default:
9574       abfd = NULL;
9575       break;
9576
9577     case bfd_link_hash_undefined:
9578     case bfd_link_hash_undefweak:
9579       abfd = h->root.u.undef.abfd;
9580       if (abfd == NULL
9581           || (abfd->flags & DYNAMIC) == 0
9582           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
9583         return FALSE;
9584       break;
9585
9586     case bfd_link_hash_defined:
9587     case bfd_link_hash_defweak:
9588       abfd = h->root.u.def.section->owner;
9589       break;
9590
9591     case bfd_link_hash_common:
9592       abfd = h->root.u.c.p->section->owner;
9593       break;
9594     }
9595   BFD_ASSERT (abfd != NULL);
9596
9597   for (loaded = elf_hash_table (info)->loaded;
9598        loaded != NULL;
9599        loaded = loaded->next)
9600     {
9601       bfd *input;
9602       Elf_Internal_Shdr *hdr;
9603       size_t symcount;
9604       size_t extsymcount;
9605       size_t extsymoff;
9606       Elf_Internal_Shdr *versymhdr;
9607       Elf_Internal_Sym *isym;
9608       Elf_Internal_Sym *isymend;
9609       Elf_Internal_Sym *isymbuf;
9610       Elf_External_Versym *ever;
9611       Elf_External_Versym *extversym;
9612
9613       input = loaded->abfd;
9614
9615       /* We check each DSO for a possible hidden versioned definition.  */
9616       if (input == abfd
9617           || (input->flags & DYNAMIC) == 0
9618           || elf_dynversym (input) == 0)
9619         continue;
9620
9621       hdr = &elf_tdata (input)->dynsymtab_hdr;
9622
9623       symcount = hdr->sh_size / bed->s->sizeof_sym;
9624       if (elf_bad_symtab (input))
9625         {
9626           extsymcount = symcount;
9627           extsymoff = 0;
9628         }
9629       else
9630         {
9631           extsymcount = symcount - hdr->sh_info;
9632           extsymoff = hdr->sh_info;
9633         }
9634
9635       if (extsymcount == 0)
9636         continue;
9637
9638       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
9639                                       NULL, NULL, NULL);
9640       if (isymbuf == NULL)
9641         return FALSE;
9642
9643       /* Read in any version definitions.  */
9644       versymhdr = &elf_tdata (input)->dynversym_hdr;
9645       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
9646       if (extversym == NULL)
9647         goto error_ret;
9648
9649       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
9650           || (bfd_bread (extversym, versymhdr->sh_size, input)
9651               != versymhdr->sh_size))
9652         {
9653           free (extversym);
9654         error_ret:
9655           free (isymbuf);
9656           return FALSE;
9657         }
9658
9659       ever = extversym + extsymoff;
9660       isymend = isymbuf + extsymcount;
9661       for (isym = isymbuf; isym < isymend; isym++, ever++)
9662         {
9663           const char *name;
9664           Elf_Internal_Versym iver;
9665           unsigned short version_index;
9666
9667           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
9668               || isym->st_shndx == SHN_UNDEF)
9669             continue;
9670
9671           name = bfd_elf_string_from_elf_section (input,
9672                                                   hdr->sh_link,
9673                                                   isym->st_name);
9674           if (strcmp (name, h->root.root.string) != 0)
9675             continue;
9676
9677           _bfd_elf_swap_versym_in (input, ever, &iver);
9678
9679           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
9680               && !(h->def_regular
9681                    && h->forced_local))
9682             {
9683               /* If we have a non-hidden versioned sym, then it should
9684                  have provided a definition for the undefined sym unless
9685                  it is defined in a non-shared object and forced local.
9686                */
9687               abort ();
9688             }
9689
9690           version_index = iver.vs_vers & VERSYM_VERSION;
9691           if (version_index == 1 || version_index == 2)
9692             {
9693               /* This is the base or first version.  We can use it.  */
9694               free (extversym);
9695               free (isymbuf);
9696               return TRUE;
9697             }
9698         }
9699
9700       free (extversym);
9701       free (isymbuf);
9702     }
9703
9704   return FALSE;
9705 }
9706
9707 /* Convert ELF common symbol TYPE.  */
9708
9709 static int
9710 elf_link_convert_common_type (struct bfd_link_info *info, int type)
9711 {
9712   /* Commom symbol can only appear in relocatable link.  */
9713   if (!bfd_link_relocatable (info))
9714     abort ();
9715   switch (info->elf_stt_common)
9716     {
9717     case unchanged:
9718       break;
9719     case elf_stt_common:
9720       type = STT_COMMON;
9721       break;
9722     case no_elf_stt_common:
9723       type = STT_OBJECT;
9724       break;
9725     }
9726   return type;
9727 }
9728
9729 /* Add an external symbol to the symbol table.  This is called from
9730    the hash table traversal routine.  When generating a shared object,
9731    we go through the symbol table twice.  The first time we output
9732    anything that might have been forced to local scope in a version
9733    script.  The second time we output the symbols that are still
9734    global symbols.  */
9735
9736 static bfd_boolean
9737 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
9738 {
9739   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
9740   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
9741   struct elf_final_link_info *flinfo = eoinfo->flinfo;
9742   bfd_boolean strip;
9743   Elf_Internal_Sym sym;
9744   asection *input_sec;
9745   const struct elf_backend_data *bed;
9746   long indx;
9747   int ret;
9748   unsigned int type;
9749
9750   if (h->root.type == bfd_link_hash_warning)
9751     {
9752       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9753       if (h->root.type == bfd_link_hash_new)
9754         return TRUE;
9755     }
9756
9757   /* Decide whether to output this symbol in this pass.  */
9758   if (eoinfo->localsyms)
9759     {
9760       if (!h->forced_local)
9761         return TRUE;
9762     }
9763   else
9764     {
9765       if (h->forced_local)
9766         return TRUE;
9767     }
9768
9769   bed = get_elf_backend_data (flinfo->output_bfd);
9770
9771   if (h->root.type == bfd_link_hash_undefined)
9772     {
9773       /* If we have an undefined symbol reference here then it must have
9774          come from a shared library that is being linked in.  (Undefined
9775          references in regular files have already been handled unless
9776          they are in unreferenced sections which are removed by garbage
9777          collection).  */
9778       bfd_boolean ignore_undef = FALSE;
9779
9780       /* Some symbols may be special in that the fact that they're
9781          undefined can be safely ignored - let backend determine that.  */
9782       if (bed->elf_backend_ignore_undef_symbol)
9783         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9784
9785       /* If we are reporting errors for this situation then do so now.  */
9786       if (!ignore_undef
9787           && h->ref_dynamic_nonweak
9788           && (!h->ref_regular || flinfo->info->gc_sections)
9789           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9790           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9791         (*flinfo->info->callbacks->undefined_symbol)
9792           (flinfo->info, h->root.root.string,
9793            h->ref_regular ? NULL : h->root.u.undef.abfd,
9794            NULL, 0,
9795            flinfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR);
9796
9797       /* Strip a global symbol defined in a discarded section.  */
9798       if (h->indx == -3)
9799         return TRUE;
9800     }
9801
9802   /* We should also warn if a forced local symbol is referenced from
9803      shared libraries.  */
9804   if (bfd_link_executable (flinfo->info)
9805       && h->forced_local
9806       && h->ref_dynamic
9807       && h->def_regular
9808       && !h->dynamic_def
9809       && h->ref_dynamic_nonweak
9810       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9811     {
9812       bfd *def_bfd;
9813       const char *msg;
9814       struct elf_link_hash_entry *hi = h;
9815
9816       /* Check indirect symbol.  */
9817       while (hi->root.type == bfd_link_hash_indirect)
9818         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9819
9820       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9821         /* xgettext:c-format */
9822         msg = _("%pB: internal symbol `%s' in %pB is referenced by DSO");
9823       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9824         /* xgettext:c-format */
9825         msg = _("%pB: hidden symbol `%s' in %pB is referenced by DSO");
9826       else
9827         /* xgettext:c-format */
9828         msg = _("%pB: local symbol `%s' in %pB is referenced by DSO");
9829       def_bfd = flinfo->output_bfd;
9830       if (hi->root.u.def.section != bfd_abs_section_ptr)
9831         def_bfd = hi->root.u.def.section->owner;
9832       _bfd_error_handler (msg, flinfo->output_bfd,
9833                           h->root.root.string, def_bfd);
9834       bfd_set_error (bfd_error_bad_value);
9835       eoinfo->failed = TRUE;
9836       return FALSE;
9837     }
9838
9839   /* We don't want to output symbols that have never been mentioned by
9840      a regular file, or that we have been told to strip.  However, if
9841      h->indx is set to -2, the symbol is used by a reloc and we must
9842      output it.  */
9843   strip = FALSE;
9844   if (h->indx == -2)
9845     ;
9846   else if ((h->def_dynamic
9847             || h->ref_dynamic
9848             || h->root.type == bfd_link_hash_new)
9849            && !h->def_regular
9850            && !h->ref_regular)
9851     strip = TRUE;
9852   else if (flinfo->info->strip == strip_all)
9853     strip = TRUE;
9854   else if (flinfo->info->strip == strip_some
9855            && bfd_hash_lookup (flinfo->info->keep_hash,
9856                                h->root.root.string, FALSE, FALSE) == NULL)
9857     strip = TRUE;
9858   else if ((h->root.type == bfd_link_hash_defined
9859             || h->root.type == bfd_link_hash_defweak)
9860            && ((flinfo->info->strip_discarded
9861                 && discarded_section (h->root.u.def.section))
9862                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9863                    && h->root.u.def.section->owner != NULL
9864                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9865     strip = TRUE;
9866   else if ((h->root.type == bfd_link_hash_undefined
9867             || h->root.type == bfd_link_hash_undefweak)
9868            && h->root.u.undef.abfd != NULL
9869            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9870     strip = TRUE;
9871
9872   type = h->type;
9873
9874   /* If we're stripping it, and it's not a dynamic symbol, there's
9875      nothing else to do.   However, if it is a forced local symbol or
9876      an ifunc symbol we need to give the backend finish_dynamic_symbol
9877      function a chance to make it dynamic.  */
9878   if (strip
9879       && h->dynindx == -1
9880       && type != STT_GNU_IFUNC
9881       && !h->forced_local)
9882     return TRUE;
9883
9884   sym.st_value = 0;
9885   sym.st_size = h->size;
9886   sym.st_other = h->other;
9887   switch (h->root.type)
9888     {
9889     default:
9890     case bfd_link_hash_new:
9891     case bfd_link_hash_warning:
9892       abort ();
9893       return FALSE;
9894
9895     case bfd_link_hash_undefined:
9896     case bfd_link_hash_undefweak:
9897       input_sec = bfd_und_section_ptr;
9898       sym.st_shndx = SHN_UNDEF;
9899       break;
9900
9901     case bfd_link_hash_defined:
9902     case bfd_link_hash_defweak:
9903       {
9904         input_sec = h->root.u.def.section;
9905         if (input_sec->output_section != NULL)
9906           {
9907             sym.st_shndx =
9908               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9909                                                  input_sec->output_section);
9910             if (sym.st_shndx == SHN_BAD)
9911               {
9912                 _bfd_error_handler
9913                   /* xgettext:c-format */
9914                   (_("%pB: could not find output section %pA for input section %pA"),
9915                    flinfo->output_bfd, input_sec->output_section, input_sec);
9916                 bfd_set_error (bfd_error_nonrepresentable_section);
9917                 eoinfo->failed = TRUE;
9918                 return FALSE;
9919               }
9920
9921             /* ELF symbols in relocatable files are section relative,
9922                but in nonrelocatable files they are virtual
9923                addresses.  */
9924             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9925             if (!bfd_link_relocatable (flinfo->info))
9926               {
9927                 sym.st_value += input_sec->output_section->vma;
9928                 if (h->type == STT_TLS)
9929                   {
9930                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9931                     if (tls_sec != NULL)
9932                       sym.st_value -= tls_sec->vma;
9933                   }
9934               }
9935           }
9936         else
9937           {
9938             BFD_ASSERT (input_sec->owner == NULL
9939                         || (input_sec->owner->flags & DYNAMIC) != 0);
9940             sym.st_shndx = SHN_UNDEF;
9941             input_sec = bfd_und_section_ptr;
9942           }
9943       }
9944       break;
9945
9946     case bfd_link_hash_common:
9947       input_sec = h->root.u.c.p->section;
9948       sym.st_shndx = bed->common_section_index (input_sec);
9949       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9950       break;
9951
9952     case bfd_link_hash_indirect:
9953       /* These symbols are created by symbol versioning.  They point
9954          to the decorated version of the name.  For example, if the
9955          symbol foo@@GNU_1.2 is the default, which should be used when
9956          foo is used with no version, then we add an indirect symbol
9957          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9958          since the indirected symbol is already in the hash table.  */
9959       return TRUE;
9960     }
9961
9962   if (type == STT_COMMON || type == STT_OBJECT)
9963     switch (h->root.type)
9964       {
9965       case bfd_link_hash_common:
9966         type = elf_link_convert_common_type (flinfo->info, type);
9967         break;
9968       case bfd_link_hash_defined:
9969       case bfd_link_hash_defweak:
9970         if (bed->common_definition (&sym))
9971           type = elf_link_convert_common_type (flinfo->info, type);
9972         else
9973           type = STT_OBJECT;
9974         break;
9975       case bfd_link_hash_undefined:
9976       case bfd_link_hash_undefweak:
9977         break;
9978       default:
9979         abort ();
9980       }
9981
9982   if (h->forced_local)
9983     {
9984       sym.st_info = ELF_ST_INFO (STB_LOCAL, type);
9985       /* Turn off visibility on local symbol.  */
9986       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9987     }
9988   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9989   else if (h->unique_global && h->def_regular)
9990     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, type);
9991   else if (h->root.type == bfd_link_hash_undefweak
9992            || h->root.type == bfd_link_hash_defweak)
9993     sym.st_info = ELF_ST_INFO (STB_WEAK, type);
9994   else
9995     sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9996   sym.st_target_internal = h->target_internal;
9997
9998   /* Give the processor backend a chance to tweak the symbol value,
9999      and also to finish up anything that needs to be done for this
10000      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
10001      forced local syms when non-shared is due to a historical quirk.
10002      STT_GNU_IFUNC symbol must go through PLT.  */
10003   if ((h->type == STT_GNU_IFUNC
10004        && h->def_regular
10005        && !bfd_link_relocatable (flinfo->info))
10006       || ((h->dynindx != -1
10007            || h->forced_local)
10008           && ((bfd_link_pic (flinfo->info)
10009                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
10010                    || h->root.type != bfd_link_hash_undefweak))
10011               || !h->forced_local)
10012           && elf_hash_table (flinfo->info)->dynamic_sections_created))
10013     {
10014       if (! ((*bed->elf_backend_finish_dynamic_symbol)
10015              (flinfo->output_bfd, flinfo->info, h, &sym)))
10016         {
10017           eoinfo->failed = TRUE;
10018           return FALSE;
10019         }
10020     }
10021
10022   /* If we are marking the symbol as undefined, and there are no
10023      non-weak references to this symbol from a regular object, then
10024      mark the symbol as weak undefined; if there are non-weak
10025      references, mark the symbol as strong.  We can't do this earlier,
10026      because it might not be marked as undefined until the
10027      finish_dynamic_symbol routine gets through with it.  */
10028   if (sym.st_shndx == SHN_UNDEF
10029       && h->ref_regular
10030       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
10031           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
10032     {
10033       int bindtype;
10034       type = ELF_ST_TYPE (sym.st_info);
10035
10036       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
10037       if (type == STT_GNU_IFUNC)
10038         type = STT_FUNC;
10039
10040       if (h->ref_regular_nonweak)
10041         bindtype = STB_GLOBAL;
10042       else
10043         bindtype = STB_WEAK;
10044       sym.st_info = ELF_ST_INFO (bindtype, type);
10045     }
10046
10047   /* If this is a symbol defined in a dynamic library, don't use the
10048      symbol size from the dynamic library.  Relinking an executable
10049      against a new library may introduce gratuitous changes in the
10050      executable's symbols if we keep the size.  */
10051   if (sym.st_shndx == SHN_UNDEF
10052       && !h->def_regular
10053       && h->def_dynamic)
10054     sym.st_size = 0;
10055
10056   /* If a non-weak symbol with non-default visibility is not defined
10057      locally, it is a fatal error.  */
10058   if (!bfd_link_relocatable (flinfo->info)
10059       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
10060       && ELF_ST_BIND (sym.st_info) != STB_WEAK
10061       && h->root.type == bfd_link_hash_undefined
10062       && !h->def_regular)
10063     {
10064       const char *msg;
10065
10066       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
10067         /* xgettext:c-format */
10068         msg = _("%pB: protected symbol `%s' isn't defined");
10069       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
10070         /* xgettext:c-format */
10071         msg = _("%pB: internal symbol `%s' isn't defined");
10072       else
10073         /* xgettext:c-format */
10074         msg = _("%pB: hidden symbol `%s' isn't defined");
10075       _bfd_error_handler (msg, flinfo->output_bfd, h->root.root.string);
10076       bfd_set_error (bfd_error_bad_value);
10077       eoinfo->failed = TRUE;
10078       return FALSE;
10079     }
10080
10081   /* If this symbol should be put in the .dynsym section, then put it
10082      there now.  We already know the symbol index.  We also fill in
10083      the entry in the .hash section.  */
10084   if (h->dynindx != -1
10085       && elf_hash_table (flinfo->info)->dynamic_sections_created
10086       && elf_hash_table (flinfo->info)->dynsym != NULL
10087       && !discarded_section (elf_hash_table (flinfo->info)->dynsym))
10088     {
10089       bfd_byte *esym;
10090
10091       /* Since there is no version information in the dynamic string,
10092          if there is no version info in symbol version section, we will
10093          have a run-time problem if not linking executable, referenced
10094          by shared library, or not bound locally.  */
10095       if (h->verinfo.verdef == NULL
10096           && (!bfd_link_executable (flinfo->info)
10097               || h->ref_dynamic
10098               || !h->def_regular))
10099         {
10100           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
10101
10102           if (p && p [1] != '\0')
10103             {
10104               _bfd_error_handler
10105                 /* xgettext:c-format */
10106                 (_("%pB: no symbol version section for versioned symbol `%s'"),
10107                  flinfo->output_bfd, h->root.root.string);
10108               eoinfo->failed = TRUE;
10109               return FALSE;
10110             }
10111         }
10112
10113       sym.st_name = h->dynstr_index;
10114       esym = (elf_hash_table (flinfo->info)->dynsym->contents
10115               + h->dynindx * bed->s->sizeof_sym);
10116       if (!check_dynsym (flinfo->output_bfd, &sym))
10117         {
10118           eoinfo->failed = TRUE;
10119           return FALSE;
10120         }
10121       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
10122
10123       if (flinfo->hash_sec != NULL)
10124         {
10125           size_t hash_entry_size;
10126           bfd_byte *bucketpos;
10127           bfd_vma chain;
10128           size_t bucketcount;
10129           size_t bucket;
10130
10131           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
10132           bucket = h->u.elf_hash_value % bucketcount;
10133
10134           hash_entry_size
10135             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
10136           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
10137                        + (bucket + 2) * hash_entry_size);
10138           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
10139           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
10140                    bucketpos);
10141           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
10142                    ((bfd_byte *) flinfo->hash_sec->contents
10143                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
10144         }
10145
10146       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
10147         {
10148           Elf_Internal_Versym iversym;
10149           Elf_External_Versym *eversym;
10150
10151           if (!h->def_regular)
10152             {
10153               if (h->verinfo.verdef == NULL
10154                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
10155                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
10156                 iversym.vs_vers = 0;
10157               else
10158                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
10159             }
10160           else
10161             {
10162               if (h->verinfo.vertree == NULL)
10163                 iversym.vs_vers = 1;
10164               else
10165                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
10166               if (flinfo->info->create_default_symver)
10167                 iversym.vs_vers++;
10168             }
10169
10170           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
10171              defined locally.  */
10172           if (h->versioned == versioned_hidden && h->def_regular)
10173             iversym.vs_vers |= VERSYM_HIDDEN;
10174
10175           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
10176           eversym += h->dynindx;
10177           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
10178         }
10179     }
10180
10181   /* If the symbol is undefined, and we didn't output it to .dynsym,
10182      strip it from .symtab too.  Obviously we can't do this for
10183      relocatable output or when needed for --emit-relocs.  */
10184   else if (input_sec == bfd_und_section_ptr
10185            && h->indx != -2
10186            /* PR 22319 Do not strip global undefined symbols marked as being needed.  */
10187            && (h->mark != 1 || ELF_ST_BIND (sym.st_info) != STB_GLOBAL)
10188            && !bfd_link_relocatable (flinfo->info))
10189     return TRUE;
10190
10191   /* Also strip others that we couldn't earlier due to dynamic symbol
10192      processing.  */
10193   if (strip)
10194     return TRUE;
10195   if ((input_sec->flags & SEC_EXCLUDE) != 0)
10196     return TRUE;
10197
10198   /* Output a FILE symbol so that following locals are not associated
10199      with the wrong input file.  We need one for forced local symbols
10200      if we've seen more than one FILE symbol or when we have exactly
10201      one FILE symbol but global symbols are present in a file other
10202      than the one with the FILE symbol.  We also need one if linker
10203      defined symbols are present.  In practice these conditions are
10204      always met, so just emit the FILE symbol unconditionally.  */
10205   if (eoinfo->localsyms
10206       && !eoinfo->file_sym_done
10207       && eoinfo->flinfo->filesym_count != 0)
10208     {
10209       Elf_Internal_Sym fsym;
10210
10211       memset (&fsym, 0, sizeof (fsym));
10212       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10213       fsym.st_shndx = SHN_ABS;
10214       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
10215                                       bfd_und_section_ptr, NULL))
10216         return FALSE;
10217
10218       eoinfo->file_sym_done = TRUE;
10219     }
10220
10221   indx = bfd_get_symcount (flinfo->output_bfd);
10222   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
10223                                    input_sec, h);
10224   if (ret == 0)
10225     {
10226       eoinfo->failed = TRUE;
10227       return FALSE;
10228     }
10229   else if (ret == 1)
10230     h->indx = indx;
10231   else if (h->indx == -2)
10232     abort();
10233
10234   return TRUE;
10235 }
10236
10237 /* Return TRUE if special handling is done for relocs in SEC against
10238    symbols defined in discarded sections.  */
10239
10240 static bfd_boolean
10241 elf_section_ignore_discarded_relocs (asection *sec)
10242 {
10243   const struct elf_backend_data *bed;
10244
10245   switch (sec->sec_info_type)
10246     {
10247     case SEC_INFO_TYPE_STABS:
10248     case SEC_INFO_TYPE_EH_FRAME:
10249     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10250       return TRUE;
10251     default:
10252       break;
10253     }
10254
10255   bed = get_elf_backend_data (sec->owner);
10256   if (bed->elf_backend_ignore_discarded_relocs != NULL
10257       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
10258     return TRUE;
10259
10260   return FALSE;
10261 }
10262
10263 /* Return a mask saying how ld should treat relocations in SEC against
10264    symbols defined in discarded sections.  If this function returns
10265    COMPLAIN set, ld will issue a warning message.  If this function
10266    returns PRETEND set, and the discarded section was link-once and the
10267    same size as the kept link-once section, ld will pretend that the
10268    symbol was actually defined in the kept section.  Otherwise ld will
10269    zero the reloc (at least that is the intent, but some cooperation by
10270    the target dependent code is needed, particularly for REL targets).  */
10271
10272 unsigned int
10273 _bfd_elf_default_action_discarded (asection *sec)
10274 {
10275   if (sec->flags & SEC_DEBUGGING)
10276     return PRETEND;
10277
10278   if (strcmp (".eh_frame", sec->name) == 0)
10279     return 0;
10280
10281   if (strcmp (".gcc_except_table", sec->name) == 0)
10282     return 0;
10283
10284   return COMPLAIN | PRETEND;
10285 }
10286
10287 /* Find a match between a section and a member of a section group.  */
10288
10289 static asection *
10290 match_group_member (asection *sec, asection *group,
10291                     struct bfd_link_info *info)
10292 {
10293   asection *first = elf_next_in_group (group);
10294   asection *s = first;
10295
10296   while (s != NULL)
10297     {
10298       if (bfd_elf_match_symbols_in_sections (s, sec, info))
10299         return s;
10300
10301       s = elf_next_in_group (s);
10302       if (s == first)
10303         break;
10304     }
10305
10306   return NULL;
10307 }
10308
10309 /* Check if the kept section of a discarded section SEC can be used
10310    to replace it.  Return the replacement if it is OK.  Otherwise return
10311    NULL.  */
10312
10313 asection *
10314 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
10315 {
10316   asection *kept;
10317
10318   kept = sec->kept_section;
10319   if (kept != NULL)
10320     {
10321       if ((kept->flags & SEC_GROUP) != 0)
10322         kept = match_group_member (sec, kept, info);
10323       if (kept != NULL
10324           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
10325               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
10326         kept = NULL;
10327       sec->kept_section = kept;
10328     }
10329   return kept;
10330 }
10331
10332 /* Link an input file into the linker output file.  This function
10333    handles all the sections and relocations of the input file at once.
10334    This is so that we only have to read the local symbols once, and
10335    don't have to keep them in memory.  */
10336
10337 static bfd_boolean
10338 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
10339 {
10340   int (*relocate_section)
10341     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
10342      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
10343   bfd *output_bfd;
10344   Elf_Internal_Shdr *symtab_hdr;
10345   size_t locsymcount;
10346   size_t extsymoff;
10347   Elf_Internal_Sym *isymbuf;
10348   Elf_Internal_Sym *isym;
10349   Elf_Internal_Sym *isymend;
10350   long *pindex;
10351   asection **ppsection;
10352   asection *o;
10353   const struct elf_backend_data *bed;
10354   struct elf_link_hash_entry **sym_hashes;
10355   bfd_size_type address_size;
10356   bfd_vma r_type_mask;
10357   int r_sym_shift;
10358   bfd_boolean have_file_sym = FALSE;
10359
10360   output_bfd = flinfo->output_bfd;
10361   bed = get_elf_backend_data (output_bfd);
10362   relocate_section = bed->elf_backend_relocate_section;
10363
10364   /* If this is a dynamic object, we don't want to do anything here:
10365      we don't want the local symbols, and we don't want the section
10366      contents.  */
10367   if ((input_bfd->flags & DYNAMIC) != 0)
10368     return TRUE;
10369
10370   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
10371   if (elf_bad_symtab (input_bfd))
10372     {
10373       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
10374       extsymoff = 0;
10375     }
10376   else
10377     {
10378       locsymcount = symtab_hdr->sh_info;
10379       extsymoff = symtab_hdr->sh_info;
10380     }
10381
10382   /* Read the local symbols.  */
10383   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
10384   if (isymbuf == NULL && locsymcount != 0)
10385     {
10386       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
10387                                       flinfo->internal_syms,
10388                                       flinfo->external_syms,
10389                                       flinfo->locsym_shndx);
10390       if (isymbuf == NULL)
10391         return FALSE;
10392     }
10393
10394   /* Find local symbol sections and adjust values of symbols in
10395      SEC_MERGE sections.  Write out those local symbols we know are
10396      going into the output file.  */
10397   isymend = isymbuf + locsymcount;
10398   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
10399        isym < isymend;
10400        isym++, pindex++, ppsection++)
10401     {
10402       asection *isec;
10403       const char *name;
10404       Elf_Internal_Sym osym;
10405       long indx;
10406       int ret;
10407
10408       *pindex = -1;
10409
10410       if (elf_bad_symtab (input_bfd))
10411         {
10412           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
10413             {
10414               *ppsection = NULL;
10415               continue;
10416             }
10417         }
10418
10419       if (isym->st_shndx == SHN_UNDEF)
10420         isec = bfd_und_section_ptr;
10421       else if (isym->st_shndx == SHN_ABS)
10422         isec = bfd_abs_section_ptr;
10423       else if (isym->st_shndx == SHN_COMMON)
10424         isec = bfd_com_section_ptr;
10425       else
10426         {
10427           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
10428           if (isec == NULL)
10429             {
10430               /* Don't attempt to output symbols with st_shnx in the
10431                  reserved range other than SHN_ABS and SHN_COMMON.  */
10432               isec = bfd_und_section_ptr;
10433             }
10434           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
10435                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
10436             isym->st_value =
10437               _bfd_merged_section_offset (output_bfd, &isec,
10438                                           elf_section_data (isec)->sec_info,
10439                                           isym->st_value);
10440         }
10441
10442       *ppsection = isec;
10443
10444       /* Don't output the first, undefined, symbol.  In fact, don't
10445          output any undefined local symbol.  */
10446       if (isec == bfd_und_section_ptr)
10447         continue;
10448
10449       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
10450         {
10451           /* We never output section symbols.  Instead, we use the
10452              section symbol of the corresponding section in the output
10453              file.  */
10454           continue;
10455         }
10456
10457       /* If we are stripping all symbols, we don't want to output this
10458          one.  */
10459       if (flinfo->info->strip == strip_all)
10460         continue;
10461
10462       /* If we are discarding all local symbols, we don't want to
10463          output this one.  If we are generating a relocatable output
10464          file, then some of the local symbols may be required by
10465          relocs; we output them below as we discover that they are
10466          needed.  */
10467       if (flinfo->info->discard == discard_all)
10468         continue;
10469
10470       /* If this symbol is defined in a section which we are
10471          discarding, we don't need to keep it.  */
10472       if (isym->st_shndx != SHN_UNDEF
10473           && isym->st_shndx < SHN_LORESERVE
10474           && bfd_section_removed_from_list (output_bfd,
10475                                             isec->output_section))
10476         continue;
10477
10478       /* Get the name of the symbol.  */
10479       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
10480                                               isym->st_name);
10481       if (name == NULL)
10482         return FALSE;
10483
10484       /* See if we are discarding symbols with this name.  */
10485       if ((flinfo->info->strip == strip_some
10486            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
10487                == NULL))
10488           || (((flinfo->info->discard == discard_sec_merge
10489                 && (isec->flags & SEC_MERGE)
10490                 && !bfd_link_relocatable (flinfo->info))
10491                || flinfo->info->discard == discard_l)
10492               && bfd_is_local_label_name (input_bfd, name)))
10493         continue;
10494
10495       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
10496         {
10497           if (input_bfd->lto_output)
10498             /* -flto puts a temp file name here.  This means builds
10499                are not reproducible.  Discard the symbol.  */
10500             continue;
10501           have_file_sym = TRUE;
10502           flinfo->filesym_count += 1;
10503         }
10504       if (!have_file_sym)
10505         {
10506           /* In the absence of debug info, bfd_find_nearest_line uses
10507              FILE symbols to determine the source file for local
10508              function symbols.  Provide a FILE symbol here if input
10509              files lack such, so that their symbols won't be
10510              associated with a previous input file.  It's not the
10511              source file, but the best we can do.  */
10512           have_file_sym = TRUE;
10513           flinfo->filesym_count += 1;
10514           memset (&osym, 0, sizeof (osym));
10515           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10516           osym.st_shndx = SHN_ABS;
10517           if (!elf_link_output_symstrtab (flinfo,
10518                                           (input_bfd->lto_output ? NULL
10519                                            : input_bfd->filename),
10520                                           &osym, bfd_abs_section_ptr,
10521                                           NULL))
10522             return FALSE;
10523         }
10524
10525       osym = *isym;
10526
10527       /* Adjust the section index for the output file.  */
10528       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10529                                                          isec->output_section);
10530       if (osym.st_shndx == SHN_BAD)
10531         return FALSE;
10532
10533       /* ELF symbols in relocatable files are section relative, but
10534          in executable files they are virtual addresses.  Note that
10535          this code assumes that all ELF sections have an associated
10536          BFD section with a reasonable value for output_offset; below
10537          we assume that they also have a reasonable value for
10538          output_section.  Any special sections must be set up to meet
10539          these requirements.  */
10540       osym.st_value += isec->output_offset;
10541       if (!bfd_link_relocatable (flinfo->info))
10542         {
10543           osym.st_value += isec->output_section->vma;
10544           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
10545             {
10546               /* STT_TLS symbols are relative to PT_TLS segment base.  */
10547               if (elf_hash_table (flinfo->info)->tls_sec != NULL)
10548                 osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
10549               else
10550                 osym.st_info = ELF_ST_INFO (ELF_ST_BIND (osym.st_info),
10551                                             STT_NOTYPE);
10552             }
10553         }
10554
10555       indx = bfd_get_symcount (output_bfd);
10556       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
10557       if (ret == 0)
10558         return FALSE;
10559       else if (ret == 1)
10560         *pindex = indx;
10561     }
10562
10563   if (bed->s->arch_size == 32)
10564     {
10565       r_type_mask = 0xff;
10566       r_sym_shift = 8;
10567       address_size = 4;
10568     }
10569   else
10570     {
10571       r_type_mask = 0xffffffff;
10572       r_sym_shift = 32;
10573       address_size = 8;
10574     }
10575
10576   /* Relocate the contents of each section.  */
10577   sym_hashes = elf_sym_hashes (input_bfd);
10578   for (o = input_bfd->sections; o != NULL; o = o->next)
10579     {
10580       bfd_byte *contents;
10581
10582       if (! o->linker_mark)
10583         {
10584           /* This section was omitted from the link.  */
10585           continue;
10586         }
10587
10588       if (!flinfo->info->resolve_section_groups
10589           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
10590         {
10591           /* Deal with the group signature symbol.  */
10592           struct bfd_elf_section_data *sec_data = elf_section_data (o);
10593           unsigned long symndx = sec_data->this_hdr.sh_info;
10594           asection *osec = o->output_section;
10595
10596           BFD_ASSERT (bfd_link_relocatable (flinfo->info));
10597           if (symndx >= locsymcount
10598               || (elf_bad_symtab (input_bfd)
10599                   && flinfo->sections[symndx] == NULL))
10600             {
10601               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
10602               while (h->root.type == bfd_link_hash_indirect
10603                      || h->root.type == bfd_link_hash_warning)
10604                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
10605               /* Arrange for symbol to be output.  */
10606               h->indx = -2;
10607               elf_section_data (osec)->this_hdr.sh_info = -2;
10608             }
10609           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
10610             {
10611               /* We'll use the output section target_index.  */
10612               asection *sec = flinfo->sections[symndx]->output_section;
10613               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
10614             }
10615           else
10616             {
10617               if (flinfo->indices[symndx] == -1)
10618                 {
10619                   /* Otherwise output the local symbol now.  */
10620                   Elf_Internal_Sym sym = isymbuf[symndx];
10621                   asection *sec = flinfo->sections[symndx]->output_section;
10622                   const char *name;
10623                   long indx;
10624                   int ret;
10625
10626                   name = bfd_elf_string_from_elf_section (input_bfd,
10627                                                           symtab_hdr->sh_link,
10628                                                           sym.st_name);
10629                   if (name == NULL)
10630                     return FALSE;
10631
10632                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10633                                                                     sec);
10634                   if (sym.st_shndx == SHN_BAD)
10635                     return FALSE;
10636
10637                   sym.st_value += o->output_offset;
10638
10639                   indx = bfd_get_symcount (output_bfd);
10640                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
10641                                                    NULL);
10642                   if (ret == 0)
10643                     return FALSE;
10644                   else if (ret == 1)
10645                     flinfo->indices[symndx] = indx;
10646                   else
10647                     abort ();
10648                 }
10649               elf_section_data (osec)->this_hdr.sh_info
10650                 = flinfo->indices[symndx];
10651             }
10652         }
10653
10654       if ((o->flags & SEC_HAS_CONTENTS) == 0
10655           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
10656         continue;
10657
10658       if ((o->flags & SEC_LINKER_CREATED) != 0)
10659         {
10660           /* Section was created by _bfd_elf_link_create_dynamic_sections
10661              or somesuch.  */
10662           continue;
10663         }
10664
10665       /* Get the contents of the section.  They have been cached by a
10666          relaxation routine.  Note that o is a section in an input
10667          file, so the contents field will not have been set by any of
10668          the routines which work on output files.  */
10669       if (elf_section_data (o)->this_hdr.contents != NULL)
10670         {
10671           contents = elf_section_data (o)->this_hdr.contents;
10672           if (bed->caches_rawsize
10673               && o->rawsize != 0
10674               && o->rawsize < o->size)
10675             {
10676               memcpy (flinfo->contents, contents, o->rawsize);
10677               contents = flinfo->contents;
10678             }
10679         }
10680       else
10681         {
10682           contents = flinfo->contents;
10683           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
10684             return FALSE;
10685         }
10686
10687       if ((o->flags & SEC_RELOC) != 0)
10688         {
10689           Elf_Internal_Rela *internal_relocs;
10690           Elf_Internal_Rela *rel, *relend;
10691           int action_discarded;
10692           int ret;
10693
10694           /* Get the swapped relocs.  */
10695           internal_relocs
10696             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
10697                                          flinfo->internal_relocs, FALSE);
10698           if (internal_relocs == NULL
10699               && o->reloc_count > 0)
10700             return FALSE;
10701
10702           /* We need to reverse-copy input .ctors/.dtors sections if
10703              they are placed in .init_array/.finit_array for output.  */
10704           if (o->size > address_size
10705               && ((strncmp (o->name, ".ctors", 6) == 0
10706                    && strcmp (o->output_section->name,
10707                               ".init_array") == 0)
10708                   || (strncmp (o->name, ".dtors", 6) == 0
10709                       && strcmp (o->output_section->name,
10710                                  ".fini_array") == 0))
10711               && (o->name[6] == 0 || o->name[6] == '.'))
10712             {
10713               if (o->size * bed->s->int_rels_per_ext_rel
10714                   != o->reloc_count * address_size)
10715                 {
10716                   _bfd_error_handler
10717                     /* xgettext:c-format */
10718                     (_("error: %pB: size of section %pA is not "
10719                        "multiple of address size"),
10720                      input_bfd, o);
10721                   bfd_set_error (bfd_error_bad_value);
10722                   return FALSE;
10723                 }
10724               o->flags |= SEC_ELF_REVERSE_COPY;
10725             }
10726
10727           action_discarded = -1;
10728           if (!elf_section_ignore_discarded_relocs (o))
10729             action_discarded = (*bed->action_discarded) (o);
10730
10731           /* Run through the relocs evaluating complex reloc symbols and
10732              looking for relocs against symbols from discarded sections
10733              or section symbols from removed link-once sections.
10734              Complain about relocs against discarded sections.  Zero
10735              relocs against removed link-once sections.  */
10736
10737           rel = internal_relocs;
10738           relend = rel + o->reloc_count;
10739           for ( ; rel < relend; rel++)
10740             {
10741               unsigned long r_symndx = rel->r_info >> r_sym_shift;
10742               unsigned int s_type;
10743               asection **ps, *sec;
10744               struct elf_link_hash_entry *h = NULL;
10745               const char *sym_name;
10746
10747               if (r_symndx == STN_UNDEF)
10748                 continue;
10749
10750               if (r_symndx >= locsymcount
10751                   || (elf_bad_symtab (input_bfd)
10752                       && flinfo->sections[r_symndx] == NULL))
10753                 {
10754                   h = sym_hashes[r_symndx - extsymoff];
10755
10756                   /* Badly formatted input files can contain relocs that
10757                      reference non-existant symbols.  Check here so that
10758                      we do not seg fault.  */
10759                   if (h == NULL)
10760                     {
10761                       _bfd_error_handler
10762                         /* xgettext:c-format */
10763                         (_("error: %pB contains a reloc (%#" PRIx64 ") for section %pA "
10764                            "that references a non-existent global symbol"),
10765                          input_bfd, (uint64_t) rel->r_info, o);
10766                       bfd_set_error (bfd_error_bad_value);
10767                       return FALSE;
10768                     }
10769
10770                   while (h->root.type == bfd_link_hash_indirect
10771                          || h->root.type == bfd_link_hash_warning)
10772                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10773
10774                   s_type = h->type;
10775
10776                   /* If a plugin symbol is referenced from a non-IR file,
10777                      mark the symbol as undefined.  Note that the
10778                      linker may attach linker created dynamic sections
10779                      to the plugin bfd.  Symbols defined in linker
10780                      created sections are not plugin symbols.  */
10781                   if ((h->root.non_ir_ref_regular
10782                        || h->root.non_ir_ref_dynamic)
10783                       && (h->root.type == bfd_link_hash_defined
10784                           || h->root.type == bfd_link_hash_defweak)
10785                       && (h->root.u.def.section->flags
10786                           & SEC_LINKER_CREATED) == 0
10787                       && h->root.u.def.section->owner != NULL
10788                       && (h->root.u.def.section->owner->flags
10789                           & BFD_PLUGIN) != 0)
10790                     {
10791                       h->root.type = bfd_link_hash_undefined;
10792                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10793                     }
10794
10795                   ps = NULL;
10796                   if (h->root.type == bfd_link_hash_defined
10797                       || h->root.type == bfd_link_hash_defweak)
10798                     ps = &h->root.u.def.section;
10799
10800                   sym_name = h->root.root.string;
10801                 }
10802               else
10803                 {
10804                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10805
10806                   s_type = ELF_ST_TYPE (sym->st_info);
10807                   ps = &flinfo->sections[r_symndx];
10808                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10809                                                sym, *ps);
10810                 }
10811
10812               if ((s_type == STT_RELC || s_type == STT_SRELC)
10813                   && !bfd_link_relocatable (flinfo->info))
10814                 {
10815                   bfd_vma val;
10816                   bfd_vma dot = (rel->r_offset
10817                                  + o->output_offset + o->output_section->vma);
10818 #ifdef DEBUG
10819                   printf ("Encountered a complex symbol!");
10820                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10821                           input_bfd->filename, o->name,
10822                           (long) (rel - internal_relocs));
10823                   printf (" symbol: idx  %8.8lx, name %s\n",
10824                           r_symndx, sym_name);
10825                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10826                           (unsigned long) rel->r_info,
10827                           (unsigned long) rel->r_offset);
10828 #endif
10829                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10830                                     isymbuf, locsymcount, s_type == STT_SRELC))
10831                     return FALSE;
10832
10833                   /* Symbol evaluated OK.  Update to absolute value.  */
10834                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10835                                     r_symndx, val);
10836                   continue;
10837                 }
10838
10839               if (action_discarded != -1 && ps != NULL)
10840                 {
10841                   /* Complain if the definition comes from a
10842                      discarded section.  */
10843                   if ((sec = *ps) != NULL && discarded_section (sec))
10844                     {
10845                       BFD_ASSERT (r_symndx != STN_UNDEF);
10846                       if (action_discarded & COMPLAIN)
10847                         (*flinfo->info->callbacks->einfo)
10848                           /* xgettext:c-format */
10849                           (_("%X`%s' referenced in section `%pA' of %pB: "
10850                              "defined in discarded section `%pA' of %pB\n"),
10851                            sym_name, o, input_bfd, sec, sec->owner);
10852
10853                       /* Try to do the best we can to support buggy old
10854                          versions of gcc.  Pretend that the symbol is
10855                          really defined in the kept linkonce section.
10856                          FIXME: This is quite broken.  Modifying the
10857                          symbol here means we will be changing all later
10858                          uses of the symbol, not just in this section.  */
10859                       if (action_discarded & PRETEND)
10860                         {
10861                           asection *kept;
10862
10863                           kept = _bfd_elf_check_kept_section (sec,
10864                                                               flinfo->info);
10865                           if (kept != NULL)
10866                             {
10867                               *ps = kept;
10868                               continue;
10869                             }
10870                         }
10871                     }
10872                 }
10873             }
10874
10875           /* Relocate the section by invoking a back end routine.
10876
10877              The back end routine is responsible for adjusting the
10878              section contents as necessary, and (if using Rela relocs
10879              and generating a relocatable output file) adjusting the
10880              reloc addend as necessary.
10881
10882              The back end routine does not have to worry about setting
10883              the reloc address or the reloc symbol index.
10884
10885              The back end routine is given a pointer to the swapped in
10886              internal symbols, and can access the hash table entries
10887              for the external symbols via elf_sym_hashes (input_bfd).
10888
10889              When generating relocatable output, the back end routine
10890              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10891              output symbol is going to be a section symbol
10892              corresponding to the output section, which will require
10893              the addend to be adjusted.  */
10894
10895           ret = (*relocate_section) (output_bfd, flinfo->info,
10896                                      input_bfd, o, contents,
10897                                      internal_relocs,
10898                                      isymbuf,
10899                                      flinfo->sections);
10900           if (!ret)
10901             return FALSE;
10902
10903           if (ret == 2
10904               || bfd_link_relocatable (flinfo->info)
10905               || flinfo->info->emitrelocations)
10906             {
10907               Elf_Internal_Rela *irela;
10908               Elf_Internal_Rela *irelaend, *irelamid;
10909               bfd_vma last_offset;
10910               struct elf_link_hash_entry **rel_hash;
10911               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10912               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10913               unsigned int next_erel;
10914               bfd_boolean rela_normal;
10915               struct bfd_elf_section_data *esdi, *esdo;
10916
10917               esdi = elf_section_data (o);
10918               esdo = elf_section_data (o->output_section);
10919               rela_normal = FALSE;
10920
10921               /* Adjust the reloc addresses and symbol indices.  */
10922
10923               irela = internal_relocs;
10924               irelaend = irela + o->reloc_count;
10925               rel_hash = esdo->rel.hashes + esdo->rel.count;
10926               /* We start processing the REL relocs, if any.  When we reach
10927                  IRELAMID in the loop, we switch to the RELA relocs.  */
10928               irelamid = irela;
10929               if (esdi->rel.hdr != NULL)
10930                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10931                              * bed->s->int_rels_per_ext_rel);
10932               rel_hash_list = rel_hash;
10933               rela_hash_list = NULL;
10934               last_offset = o->output_offset;
10935               if (!bfd_link_relocatable (flinfo->info))
10936                 last_offset += o->output_section->vma;
10937               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10938                 {
10939                   unsigned long r_symndx;
10940                   asection *sec;
10941                   Elf_Internal_Sym sym;
10942
10943                   if (next_erel == bed->s->int_rels_per_ext_rel)
10944                     {
10945                       rel_hash++;
10946                       next_erel = 0;
10947                     }
10948
10949                   if (irela == irelamid)
10950                     {
10951                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10952                       rela_hash_list = rel_hash;
10953                       rela_normal = bed->rela_normal;
10954                     }
10955
10956                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10957                                                              flinfo->info, o,
10958                                                              irela->r_offset);
10959                   if (irela->r_offset >= (bfd_vma) -2)
10960                     {
10961                       /* This is a reloc for a deleted entry or somesuch.
10962                          Turn it into an R_*_NONE reloc, at the same
10963                          offset as the last reloc.  elf_eh_frame.c and
10964                          bfd_elf_discard_info rely on reloc offsets
10965                          being ordered.  */
10966                       irela->r_offset = last_offset;
10967                       irela->r_info = 0;
10968                       irela->r_addend = 0;
10969                       continue;
10970                     }
10971
10972                   irela->r_offset += o->output_offset;
10973
10974                   /* Relocs in an executable have to be virtual addresses.  */
10975                   if (!bfd_link_relocatable (flinfo->info))
10976                     irela->r_offset += o->output_section->vma;
10977
10978                   last_offset = irela->r_offset;
10979
10980                   r_symndx = irela->r_info >> r_sym_shift;
10981                   if (r_symndx == STN_UNDEF)
10982                     continue;
10983
10984                   if (r_symndx >= locsymcount
10985                       || (elf_bad_symtab (input_bfd)
10986                           && flinfo->sections[r_symndx] == NULL))
10987                     {
10988                       struct elf_link_hash_entry *rh;
10989                       unsigned long indx;
10990
10991                       /* This is a reloc against a global symbol.  We
10992                          have not yet output all the local symbols, so
10993                          we do not know the symbol index of any global
10994                          symbol.  We set the rel_hash entry for this
10995                          reloc to point to the global hash table entry
10996                          for this symbol.  The symbol index is then
10997                          set at the end of bfd_elf_final_link.  */
10998                       indx = r_symndx - extsymoff;
10999                       rh = elf_sym_hashes (input_bfd)[indx];
11000                       while (rh->root.type == bfd_link_hash_indirect
11001                              || rh->root.type == bfd_link_hash_warning)
11002                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
11003
11004                       /* Setting the index to -2 tells
11005                          elf_link_output_extsym that this symbol is
11006                          used by a reloc.  */
11007                       BFD_ASSERT (rh->indx < 0);
11008                       rh->indx = -2;
11009                       *rel_hash = rh;
11010
11011                       continue;
11012                     }
11013
11014                   /* This is a reloc against a local symbol.  */
11015
11016                   *rel_hash = NULL;
11017                   sym = isymbuf[r_symndx];
11018                   sec = flinfo->sections[r_symndx];
11019                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
11020                     {
11021                       /* I suppose the backend ought to fill in the
11022                          section of any STT_SECTION symbol against a
11023                          processor specific section.  */
11024                       r_symndx = STN_UNDEF;
11025                       if (bfd_is_abs_section (sec))
11026                         ;
11027                       else if (sec == NULL || sec->owner == NULL)
11028                         {
11029                           bfd_set_error (bfd_error_bad_value);
11030                           return FALSE;
11031                         }
11032                       else
11033                         {
11034                           asection *osec = sec->output_section;
11035
11036                           /* If we have discarded a section, the output
11037                              section will be the absolute section.  In
11038                              case of discarded SEC_MERGE sections, use
11039                              the kept section.  relocate_section should
11040                              have already handled discarded linkonce
11041                              sections.  */
11042                           if (bfd_is_abs_section (osec)
11043                               && sec->kept_section != NULL
11044                               && sec->kept_section->output_section != NULL)
11045                             {
11046                               osec = sec->kept_section->output_section;
11047                               irela->r_addend -= osec->vma;
11048                             }
11049
11050                           if (!bfd_is_abs_section (osec))
11051                             {
11052                               r_symndx = osec->target_index;
11053                               if (r_symndx == STN_UNDEF)
11054                                 {
11055                                   irela->r_addend += osec->vma;
11056                                   osec = _bfd_nearby_section (output_bfd, osec,
11057                                                               osec->vma);
11058                                   irela->r_addend -= osec->vma;
11059                                   r_symndx = osec->target_index;
11060                                 }
11061                             }
11062                         }
11063
11064                       /* Adjust the addend according to where the
11065                          section winds up in the output section.  */
11066                       if (rela_normal)
11067                         irela->r_addend += sec->output_offset;
11068                     }
11069                   else
11070                     {
11071                       if (flinfo->indices[r_symndx] == -1)
11072                         {
11073                           unsigned long shlink;
11074                           const char *name;
11075                           asection *osec;
11076                           long indx;
11077
11078                           if (flinfo->info->strip == strip_all)
11079                             {
11080                               /* You can't do ld -r -s.  */
11081                               bfd_set_error (bfd_error_invalid_operation);
11082                               return FALSE;
11083                             }
11084
11085                           /* This symbol was skipped earlier, but
11086                              since it is needed by a reloc, we
11087                              must output it now.  */
11088                           shlink = symtab_hdr->sh_link;
11089                           name = (bfd_elf_string_from_elf_section
11090                                   (input_bfd, shlink, sym.st_name));
11091                           if (name == NULL)
11092                             return FALSE;
11093
11094                           osec = sec->output_section;
11095                           sym.st_shndx =
11096                             _bfd_elf_section_from_bfd_section (output_bfd,
11097                                                                osec);
11098                           if (sym.st_shndx == SHN_BAD)
11099                             return FALSE;
11100
11101                           sym.st_value += sec->output_offset;
11102                           if (!bfd_link_relocatable (flinfo->info))
11103                             {
11104                               sym.st_value += osec->vma;
11105                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
11106                                 {
11107                                   struct elf_link_hash_table *htab
11108                                     = elf_hash_table (flinfo->info);
11109
11110                                   /* STT_TLS symbols are relative to PT_TLS
11111                                      segment base.  */
11112                                   if (htab->tls_sec != NULL)
11113                                     sym.st_value -= htab->tls_sec->vma;
11114                                   else
11115                                     sym.st_info
11116                                       = ELF_ST_INFO (ELF_ST_BIND (sym.st_info),
11117                                                      STT_NOTYPE);
11118                                 }
11119                             }
11120
11121                           indx = bfd_get_symcount (output_bfd);
11122                           ret = elf_link_output_symstrtab (flinfo, name,
11123                                                            &sym, sec,
11124                                                            NULL);
11125                           if (ret == 0)
11126                             return FALSE;
11127                           else if (ret == 1)
11128                             flinfo->indices[r_symndx] = indx;
11129                           else
11130                             abort ();
11131                         }
11132
11133                       r_symndx = flinfo->indices[r_symndx];
11134                     }
11135
11136                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
11137                                    | (irela->r_info & r_type_mask));
11138                 }
11139
11140               /* Swap out the relocs.  */
11141               input_rel_hdr = esdi->rel.hdr;
11142               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
11143                 {
11144                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
11145                                                      input_rel_hdr,
11146                                                      internal_relocs,
11147                                                      rel_hash_list))
11148                     return FALSE;
11149                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
11150                                       * bed->s->int_rels_per_ext_rel);
11151                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
11152                 }
11153
11154               input_rela_hdr = esdi->rela.hdr;
11155               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
11156                 {
11157                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
11158                                                      input_rela_hdr,
11159                                                      internal_relocs,
11160                                                      rela_hash_list))
11161                     return FALSE;
11162                 }
11163             }
11164         }
11165
11166       /* Write out the modified section contents.  */
11167       if (bed->elf_backend_write_section
11168           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
11169                                                 contents))
11170         {
11171           /* Section written out.  */
11172         }
11173       else switch (o->sec_info_type)
11174         {
11175         case SEC_INFO_TYPE_STABS:
11176           if (! (_bfd_write_section_stabs
11177                  (output_bfd,
11178                   &elf_hash_table (flinfo->info)->stab_info,
11179                   o, &elf_section_data (o)->sec_info, contents)))
11180             return FALSE;
11181           break;
11182         case SEC_INFO_TYPE_MERGE:
11183           if (! _bfd_write_merged_section (output_bfd, o,
11184                                            elf_section_data (o)->sec_info))
11185             return FALSE;
11186           break;
11187         case SEC_INFO_TYPE_EH_FRAME:
11188           {
11189             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
11190                                                    o, contents))
11191               return FALSE;
11192           }
11193           break;
11194         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
11195           {
11196             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
11197                                                          flinfo->info,
11198                                                          o, contents))
11199               return FALSE;
11200           }
11201           break;
11202         default:
11203           {
11204             if (! (o->flags & SEC_EXCLUDE))
11205               {
11206                 file_ptr offset = (file_ptr) o->output_offset;
11207                 bfd_size_type todo = o->size;
11208
11209                 offset *= bfd_octets_per_byte (output_bfd);
11210
11211                 if ((o->flags & SEC_ELF_REVERSE_COPY))
11212                   {
11213                     /* Reverse-copy input section to output.  */
11214                     do
11215                       {
11216                         todo -= address_size;
11217                         if (! bfd_set_section_contents (output_bfd,
11218                                                         o->output_section,
11219                                                         contents + todo,
11220                                                         offset,
11221                                                         address_size))
11222                           return FALSE;
11223                         if (todo == 0)
11224                           break;
11225                         offset += address_size;
11226                       }
11227                     while (1);
11228                   }
11229                 else if (! bfd_set_section_contents (output_bfd,
11230                                                      o->output_section,
11231                                                      contents,
11232                                                      offset, todo))
11233                   return FALSE;
11234               }
11235           }
11236           break;
11237         }
11238     }
11239
11240   return TRUE;
11241 }
11242
11243 /* Generate a reloc when linking an ELF file.  This is a reloc
11244    requested by the linker, and does not come from any input file.  This
11245    is used to build constructor and destructor tables when linking
11246    with -Ur.  */
11247
11248 static bfd_boolean
11249 elf_reloc_link_order (bfd *output_bfd,
11250                       struct bfd_link_info *info,
11251                       asection *output_section,
11252                       struct bfd_link_order *link_order)
11253 {
11254   reloc_howto_type *howto;
11255   long indx;
11256   bfd_vma offset;
11257   bfd_vma addend;
11258   struct bfd_elf_section_reloc_data *reldata;
11259   struct elf_link_hash_entry **rel_hash_ptr;
11260   Elf_Internal_Shdr *rel_hdr;
11261   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
11262   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
11263   bfd_byte *erel;
11264   unsigned int i;
11265   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
11266
11267   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
11268   if (howto == NULL)
11269     {
11270       bfd_set_error (bfd_error_bad_value);
11271       return FALSE;
11272     }
11273
11274   addend = link_order->u.reloc.p->addend;
11275
11276   if (esdo->rel.hdr)
11277     reldata = &esdo->rel;
11278   else if (esdo->rela.hdr)
11279     reldata = &esdo->rela;
11280   else
11281     {
11282       reldata = NULL;
11283       BFD_ASSERT (0);
11284     }
11285
11286   /* Figure out the symbol index.  */
11287   rel_hash_ptr = reldata->hashes + reldata->count;
11288   if (link_order->type == bfd_section_reloc_link_order)
11289     {
11290       indx = link_order->u.reloc.p->u.section->target_index;
11291       BFD_ASSERT (indx != 0);
11292       *rel_hash_ptr = NULL;
11293     }
11294   else
11295     {
11296       struct elf_link_hash_entry *h;
11297
11298       /* Treat a reloc against a defined symbol as though it were
11299          actually against the section.  */
11300       h = ((struct elf_link_hash_entry *)
11301            bfd_wrapped_link_hash_lookup (output_bfd, info,
11302                                          link_order->u.reloc.p->u.name,
11303                                          FALSE, FALSE, TRUE));
11304       if (h != NULL
11305           && (h->root.type == bfd_link_hash_defined
11306               || h->root.type == bfd_link_hash_defweak))
11307         {
11308           asection *section;
11309
11310           section = h->root.u.def.section;
11311           indx = section->output_section->target_index;
11312           *rel_hash_ptr = NULL;
11313           /* It seems that we ought to add the symbol value to the
11314              addend here, but in practice it has already been added
11315              because it was passed to constructor_callback.  */
11316           addend += section->output_section->vma + section->output_offset;
11317         }
11318       else if (h != NULL)
11319         {
11320           /* Setting the index to -2 tells elf_link_output_extsym that
11321              this symbol is used by a reloc.  */
11322           h->indx = -2;
11323           *rel_hash_ptr = h;
11324           indx = 0;
11325         }
11326       else
11327         {
11328           (*info->callbacks->unattached_reloc)
11329             (info, link_order->u.reloc.p->u.name, NULL, NULL, 0);
11330           indx = 0;
11331         }
11332     }
11333
11334   /* If this is an inplace reloc, we must write the addend into the
11335      object file.  */
11336   if (howto->partial_inplace && addend != 0)
11337     {
11338       bfd_size_type size;
11339       bfd_reloc_status_type rstat;
11340       bfd_byte *buf;
11341       bfd_boolean ok;
11342       const char *sym_name;
11343
11344       size = (bfd_size_type) bfd_get_reloc_size (howto);
11345       buf = (bfd_byte *) bfd_zmalloc (size);
11346       if (buf == NULL && size != 0)
11347         return FALSE;
11348       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
11349       switch (rstat)
11350         {
11351         case bfd_reloc_ok:
11352           break;
11353
11354         default:
11355         case bfd_reloc_outofrange:
11356           abort ();
11357
11358         case bfd_reloc_overflow:
11359           if (link_order->type == bfd_section_reloc_link_order)
11360             sym_name = bfd_section_name (output_bfd,
11361                                          link_order->u.reloc.p->u.section);
11362           else
11363             sym_name = link_order->u.reloc.p->u.name;
11364           (*info->callbacks->reloc_overflow) (info, NULL, sym_name,
11365                                               howto->name, addend, NULL, NULL,
11366                                               (bfd_vma) 0);
11367           break;
11368         }
11369
11370       ok = bfd_set_section_contents (output_bfd, output_section, buf,
11371                                      link_order->offset
11372                                      * bfd_octets_per_byte (output_bfd),
11373                                      size);
11374       free (buf);
11375       if (! ok)
11376         return FALSE;
11377     }
11378
11379   /* The address of a reloc is relative to the section in a
11380      relocatable file, and is a virtual address in an executable
11381      file.  */
11382   offset = link_order->offset;
11383   if (! bfd_link_relocatable (info))
11384     offset += output_section->vma;
11385
11386   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
11387     {
11388       irel[i].r_offset = offset;
11389       irel[i].r_info = 0;
11390       irel[i].r_addend = 0;
11391     }
11392   if (bed->s->arch_size == 32)
11393     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
11394   else
11395     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
11396
11397   rel_hdr = reldata->hdr;
11398   erel = rel_hdr->contents;
11399   if (rel_hdr->sh_type == SHT_REL)
11400     {
11401       erel += reldata->count * bed->s->sizeof_rel;
11402       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
11403     }
11404   else
11405     {
11406       irel[0].r_addend = addend;
11407       erel += reldata->count * bed->s->sizeof_rela;
11408       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
11409     }
11410
11411   ++reldata->count;
11412
11413   return TRUE;
11414 }
11415
11416
11417 /* Get the output vma of the section pointed to by the sh_link field.  */
11418
11419 static bfd_vma
11420 elf_get_linked_section_vma (struct bfd_link_order *p)
11421 {
11422   Elf_Internal_Shdr **elf_shdrp;
11423   asection *s;
11424   int elfsec;
11425
11426   s = p->u.indirect.section;
11427   elf_shdrp = elf_elfsections (s->owner);
11428   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
11429   elfsec = elf_shdrp[elfsec]->sh_link;
11430   /* PR 290:
11431      The Intel C compiler generates SHT_IA_64_UNWIND with
11432      SHF_LINK_ORDER.  But it doesn't set the sh_link or
11433      sh_info fields.  Hence we could get the situation
11434      where elfsec is 0.  */
11435   if (elfsec == 0)
11436     {
11437       const struct elf_backend_data *bed
11438         = get_elf_backend_data (s->owner);
11439       if (bed->link_order_error_handler)
11440         bed->link_order_error_handler
11441           /* xgettext:c-format */
11442           (_("%pB: warning: sh_link not set for section `%pA'"), s->owner, s);
11443       return 0;
11444     }
11445   else
11446     {
11447       s = elf_shdrp[elfsec]->bfd_section;
11448       return s->output_section->vma + s->output_offset;
11449     }
11450 }
11451
11452
11453 /* Compare two sections based on the locations of the sections they are
11454    linked to.  Used by elf_fixup_link_order.  */
11455
11456 static int
11457 compare_link_order (const void * a, const void * b)
11458 {
11459   bfd_vma apos;
11460   bfd_vma bpos;
11461
11462   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
11463   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
11464   if (apos < bpos)
11465     return -1;
11466   return apos > bpos;
11467 }
11468
11469
11470 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
11471    order as their linked sections.  Returns false if this could not be done
11472    because an output section includes both ordered and unordered
11473    sections.  Ideally we'd do this in the linker proper.  */
11474
11475 static bfd_boolean
11476 elf_fixup_link_order (bfd *abfd, asection *o)
11477 {
11478   int seen_linkorder;
11479   int seen_other;
11480   int n;
11481   struct bfd_link_order *p;
11482   bfd *sub;
11483   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11484   unsigned elfsec;
11485   struct bfd_link_order **sections;
11486   asection *s, *other_sec, *linkorder_sec;
11487   bfd_vma offset;
11488
11489   other_sec = NULL;
11490   linkorder_sec = NULL;
11491   seen_other = 0;
11492   seen_linkorder = 0;
11493   for (p = o->map_head.link_order; p != NULL; p = p->next)
11494     {
11495       if (p->type == bfd_indirect_link_order)
11496         {
11497           s = p->u.indirect.section;
11498           sub = s->owner;
11499           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11500               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
11501               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
11502               && elfsec < elf_numsections (sub)
11503               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
11504               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
11505             {
11506               seen_linkorder++;
11507               linkorder_sec = s;
11508             }
11509           else
11510             {
11511               seen_other++;
11512               other_sec = s;
11513             }
11514         }
11515       else
11516         seen_other++;
11517
11518       if (seen_other && seen_linkorder)
11519         {
11520           if (other_sec && linkorder_sec)
11521             _bfd_error_handler
11522               /* xgettext:c-format */
11523               (_("%pA has both ordered [`%pA' in %pB] "
11524                  "and unordered [`%pA' in %pB] sections"),
11525                o, linkorder_sec, linkorder_sec->owner,
11526                other_sec, other_sec->owner);
11527           else
11528             _bfd_error_handler
11529               (_("%pA has both ordered and unordered sections"), o);
11530           bfd_set_error (bfd_error_bad_value);
11531           return FALSE;
11532         }
11533     }
11534
11535   if (!seen_linkorder)
11536     return TRUE;
11537
11538   sections = (struct bfd_link_order **)
11539     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
11540   if (sections == NULL)
11541     return FALSE;
11542   seen_linkorder = 0;
11543
11544   for (p = o->map_head.link_order; p != NULL; p = p->next)
11545     {
11546       sections[seen_linkorder++] = p;
11547     }
11548   /* Sort the input sections in the order of their linked section.  */
11549   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
11550          compare_link_order);
11551
11552   /* Change the offsets of the sections.  */
11553   offset = 0;
11554   for (n = 0; n < seen_linkorder; n++)
11555     {
11556       s = sections[n]->u.indirect.section;
11557       offset &= ~(bfd_vma) 0 << s->alignment_power;
11558       s->output_offset = offset / bfd_octets_per_byte (abfd);
11559       sections[n]->offset = offset;
11560       offset += sections[n]->size;
11561     }
11562
11563   free (sections);
11564   return TRUE;
11565 }
11566
11567 /* Generate an import library in INFO->implib_bfd from symbols in ABFD.
11568    Returns TRUE upon success, FALSE otherwise.  */
11569
11570 static bfd_boolean
11571 elf_output_implib (bfd *abfd, struct bfd_link_info *info)
11572 {
11573   bfd_boolean ret = FALSE;
11574   bfd *implib_bfd;
11575   const struct elf_backend_data *bed;
11576   flagword flags;
11577   enum bfd_architecture arch;
11578   unsigned int mach;
11579   asymbol **sympp = NULL;
11580   long symsize;
11581   long symcount;
11582   long src_count;
11583   elf_symbol_type *osymbuf;
11584
11585   implib_bfd = info->out_implib_bfd;
11586   bed = get_elf_backend_data (abfd);
11587
11588   if (!bfd_set_format (implib_bfd, bfd_object))
11589     return FALSE;
11590
11591   /* Use flag from executable but make it a relocatable object.  */
11592   flags = bfd_get_file_flags (abfd);
11593   flags &= ~HAS_RELOC;
11594   if (!bfd_set_start_address (implib_bfd, 0)
11595       || !bfd_set_file_flags (implib_bfd, flags & ~EXEC_P))
11596     return FALSE;
11597
11598   /* Copy architecture of output file to import library file.  */
11599   arch = bfd_get_arch (abfd);
11600   mach = bfd_get_mach (abfd);
11601   if (!bfd_set_arch_mach (implib_bfd, arch, mach)
11602       && (abfd->target_defaulted
11603           || bfd_get_arch (abfd) != bfd_get_arch (implib_bfd)))
11604     return FALSE;
11605
11606   /* Get symbol table size.  */
11607   symsize = bfd_get_symtab_upper_bound (abfd);
11608   if (symsize < 0)
11609     return FALSE;
11610
11611   /* Read in the symbol table.  */
11612   sympp = (asymbol **) xmalloc (symsize);
11613   symcount = bfd_canonicalize_symtab (abfd, sympp);
11614   if (symcount < 0)
11615     goto free_sym_buf;
11616
11617   /* Allow the BFD backend to copy any private header data it
11618      understands from the output BFD to the import library BFD.  */
11619   if (! bfd_copy_private_header_data (abfd, implib_bfd))
11620     goto free_sym_buf;
11621
11622   /* Filter symbols to appear in the import library.  */
11623   if (bed->elf_backend_filter_implib_symbols)
11624     symcount = bed->elf_backend_filter_implib_symbols (abfd, info, sympp,
11625                                                        symcount);
11626   else
11627     symcount = _bfd_elf_filter_global_symbols (abfd, info, sympp, symcount);
11628   if (symcount == 0)
11629     {
11630       bfd_set_error (bfd_error_no_symbols);
11631       _bfd_error_handler (_("%pB: no symbol found for import library"),
11632                           implib_bfd);
11633       goto free_sym_buf;
11634     }
11635
11636
11637   /* Make symbols absolute.  */
11638   osymbuf = (elf_symbol_type *) bfd_alloc2 (implib_bfd, symcount,
11639                                             sizeof (*osymbuf));
11640   for (src_count = 0; src_count < symcount; src_count++)
11641     {
11642       memcpy (&osymbuf[src_count], (elf_symbol_type *) sympp[src_count],
11643               sizeof (*osymbuf));
11644       osymbuf[src_count].symbol.section = bfd_abs_section_ptr;
11645       osymbuf[src_count].internal_elf_sym.st_shndx = SHN_ABS;
11646       osymbuf[src_count].symbol.value += sympp[src_count]->section->vma;
11647       osymbuf[src_count].internal_elf_sym.st_value =
11648         osymbuf[src_count].symbol.value;
11649       sympp[src_count] = &osymbuf[src_count].symbol;
11650     }
11651
11652   bfd_set_symtab (implib_bfd, sympp, symcount);
11653
11654   /* Allow the BFD backend to copy any private data it understands
11655      from the output BFD to the import library BFD.  This is done last
11656      to permit the routine to look at the filtered symbol table.  */
11657   if (! bfd_copy_private_bfd_data (abfd, implib_bfd))
11658     goto free_sym_buf;
11659
11660   if (!bfd_close (implib_bfd))
11661     goto free_sym_buf;
11662
11663   ret = TRUE;
11664
11665 free_sym_buf:
11666   free (sympp);
11667   return ret;
11668 }
11669
11670 static void
11671 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
11672 {
11673   asection *o;
11674
11675   if (flinfo->symstrtab != NULL)
11676     _bfd_elf_strtab_free (flinfo->symstrtab);
11677   if (flinfo->contents != NULL)
11678     free (flinfo->contents);
11679   if (flinfo->external_relocs != NULL)
11680     free (flinfo->external_relocs);
11681   if (flinfo->internal_relocs != NULL)
11682     free (flinfo->internal_relocs);
11683   if (flinfo->external_syms != NULL)
11684     free (flinfo->external_syms);
11685   if (flinfo->locsym_shndx != NULL)
11686     free (flinfo->locsym_shndx);
11687   if (flinfo->internal_syms != NULL)
11688     free (flinfo->internal_syms);
11689   if (flinfo->indices != NULL)
11690     free (flinfo->indices);
11691   if (flinfo->sections != NULL)
11692     free (flinfo->sections);
11693   if (flinfo->symshndxbuf != NULL
11694       && flinfo->symshndxbuf != (Elf_External_Sym_Shndx *) -1)
11695     free (flinfo->symshndxbuf);
11696   for (o = obfd->sections; o != NULL; o = o->next)
11697     {
11698       struct bfd_elf_section_data *esdo = elf_section_data (o);
11699       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11700         free (esdo->rel.hashes);
11701       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11702         free (esdo->rela.hashes);
11703     }
11704 }
11705
11706 /* Do the final step of an ELF link.  */
11707
11708 bfd_boolean
11709 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
11710 {
11711   bfd_boolean dynamic;
11712   bfd_boolean emit_relocs;
11713   bfd *dynobj;
11714   struct elf_final_link_info flinfo;
11715   asection *o;
11716   struct bfd_link_order *p;
11717   bfd *sub;
11718   bfd_size_type max_contents_size;
11719   bfd_size_type max_external_reloc_size;
11720   bfd_size_type max_internal_reloc_count;
11721   bfd_size_type max_sym_count;
11722   bfd_size_type max_sym_shndx_count;
11723   Elf_Internal_Sym elfsym;
11724   unsigned int i;
11725   Elf_Internal_Shdr *symtab_hdr;
11726   Elf_Internal_Shdr *symtab_shndx_hdr;
11727   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11728   struct elf_outext_info eoinfo;
11729   bfd_boolean merged;
11730   size_t relativecount = 0;
11731   asection *reldyn = 0;
11732   bfd_size_type amt;
11733   asection *attr_section = NULL;
11734   bfd_vma attr_size = 0;
11735   const char *std_attrs_section;
11736   struct elf_link_hash_table *htab = elf_hash_table (info);
11737
11738   if (!is_elf_hash_table (htab))
11739     return FALSE;
11740
11741   if (bfd_link_pic (info))
11742     abfd->flags |= DYNAMIC;
11743
11744   dynamic = htab->dynamic_sections_created;
11745   dynobj = htab->dynobj;
11746
11747   emit_relocs = (bfd_link_relocatable (info)
11748                  || info->emitrelocations);
11749
11750   flinfo.info = info;
11751   flinfo.output_bfd = abfd;
11752   flinfo.symstrtab = _bfd_elf_strtab_init ();
11753   if (flinfo.symstrtab == NULL)
11754     return FALSE;
11755
11756   if (! dynamic)
11757     {
11758       flinfo.hash_sec = NULL;
11759       flinfo.symver_sec = NULL;
11760     }
11761   else
11762     {
11763       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
11764       /* Note that dynsym_sec can be NULL (on VMS).  */
11765       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
11766       /* Note that it is OK if symver_sec is NULL.  */
11767     }
11768
11769   flinfo.contents = NULL;
11770   flinfo.external_relocs = NULL;
11771   flinfo.internal_relocs = NULL;
11772   flinfo.external_syms = NULL;
11773   flinfo.locsym_shndx = NULL;
11774   flinfo.internal_syms = NULL;
11775   flinfo.indices = NULL;
11776   flinfo.sections = NULL;
11777   flinfo.symshndxbuf = NULL;
11778   flinfo.filesym_count = 0;
11779
11780   /* The object attributes have been merged.  Remove the input
11781      sections from the link, and set the contents of the output
11782      secton.  */
11783   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
11784   for (o = abfd->sections; o != NULL; o = o->next)
11785     {
11786       bfd_boolean remove_section = FALSE;
11787
11788       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
11789           || strcmp (o->name, ".gnu.attributes") == 0)
11790         {
11791           for (p = o->map_head.link_order; p != NULL; p = p->next)
11792             {
11793               asection *input_section;
11794
11795               if (p->type != bfd_indirect_link_order)
11796                 continue;
11797               input_section = p->u.indirect.section;
11798               /* Hack: reset the SEC_HAS_CONTENTS flag so that
11799                  elf_link_input_bfd ignores this section.  */
11800               input_section->flags &= ~SEC_HAS_CONTENTS;
11801             }
11802
11803           attr_size = bfd_elf_obj_attr_size (abfd);
11804           bfd_set_section_size (abfd, o, attr_size);
11805           /* Skip this section later on.  */
11806           o->map_head.link_order = NULL;
11807           if (attr_size)
11808             attr_section = o;
11809           else
11810             remove_section = TRUE;
11811         }
11812       else if ((o->flags & SEC_GROUP) != 0 && o->size == 0)
11813         {
11814           /* Remove empty group section from linker output.  */
11815           remove_section = TRUE;
11816         }
11817       if (remove_section)
11818         {
11819           o->flags |= SEC_EXCLUDE;
11820           bfd_section_list_remove (abfd, o);
11821           abfd->section_count--;
11822         }
11823     }
11824
11825   /* Count up the number of relocations we will output for each output
11826      section, so that we know the sizes of the reloc sections.  We
11827      also figure out some maximum sizes.  */
11828   max_contents_size = 0;
11829   max_external_reloc_size = 0;
11830   max_internal_reloc_count = 0;
11831   max_sym_count = 0;
11832   max_sym_shndx_count = 0;
11833   merged = FALSE;
11834   for (o = abfd->sections; o != NULL; o = o->next)
11835     {
11836       struct bfd_elf_section_data *esdo = elf_section_data (o);
11837       o->reloc_count = 0;
11838
11839       for (p = o->map_head.link_order; p != NULL; p = p->next)
11840         {
11841           unsigned int reloc_count = 0;
11842           unsigned int additional_reloc_count = 0;
11843           struct bfd_elf_section_data *esdi = NULL;
11844
11845           if (p->type == bfd_section_reloc_link_order
11846               || p->type == bfd_symbol_reloc_link_order)
11847             reloc_count = 1;
11848           else if (p->type == bfd_indirect_link_order)
11849             {
11850               asection *sec;
11851
11852               sec = p->u.indirect.section;
11853
11854               /* Mark all sections which are to be included in the
11855                  link.  This will normally be every section.  We need
11856                  to do this so that we can identify any sections which
11857                  the linker has decided to not include.  */
11858               sec->linker_mark = TRUE;
11859
11860               if (sec->flags & SEC_MERGE)
11861                 merged = TRUE;
11862
11863               if (sec->rawsize > max_contents_size)
11864                 max_contents_size = sec->rawsize;
11865               if (sec->size > max_contents_size)
11866                 max_contents_size = sec->size;
11867
11868               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
11869                   && (sec->owner->flags & DYNAMIC) == 0)
11870                 {
11871                   size_t sym_count;
11872
11873                   /* We are interested in just local symbols, not all
11874                      symbols.  */
11875                   if (elf_bad_symtab (sec->owner))
11876                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
11877                                  / bed->s->sizeof_sym);
11878                   else
11879                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
11880
11881                   if (sym_count > max_sym_count)
11882                     max_sym_count = sym_count;
11883
11884                   if (sym_count > max_sym_shndx_count
11885                       && elf_symtab_shndx_list (sec->owner) != NULL)
11886                     max_sym_shndx_count = sym_count;
11887
11888                   if (esdo->this_hdr.sh_type == SHT_REL
11889                       || esdo->this_hdr.sh_type == SHT_RELA)
11890                     /* Some backends use reloc_count in relocation sections
11891                        to count particular types of relocs.  Of course,
11892                        reloc sections themselves can't have relocations.  */
11893                     ;
11894                   else if (emit_relocs)
11895                     {
11896                       reloc_count = sec->reloc_count;
11897                       if (bed->elf_backend_count_additional_relocs)
11898                         {
11899                           int c;
11900                           c = (*bed->elf_backend_count_additional_relocs) (sec);
11901                           additional_reloc_count += c;
11902                         }
11903                     }
11904                   else if (bed->elf_backend_count_relocs)
11905                     reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
11906
11907                   esdi = elf_section_data (sec);
11908
11909                   if ((sec->flags & SEC_RELOC) != 0)
11910                     {
11911                       size_t ext_size = 0;
11912
11913                       if (esdi->rel.hdr != NULL)
11914                         ext_size = esdi->rel.hdr->sh_size;
11915                       if (esdi->rela.hdr != NULL)
11916                         ext_size += esdi->rela.hdr->sh_size;
11917
11918                       if (ext_size > max_external_reloc_size)
11919                         max_external_reloc_size = ext_size;
11920                       if (sec->reloc_count > max_internal_reloc_count)
11921                         max_internal_reloc_count = sec->reloc_count;
11922                     }
11923                 }
11924             }
11925
11926           if (reloc_count == 0)
11927             continue;
11928
11929           reloc_count += additional_reloc_count;
11930           o->reloc_count += reloc_count;
11931
11932           if (p->type == bfd_indirect_link_order && emit_relocs)
11933             {
11934               if (esdi->rel.hdr)
11935                 {
11936                   esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11937                   esdo->rel.count += additional_reloc_count;
11938                 }
11939               if (esdi->rela.hdr)
11940                 {
11941                   esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11942                   esdo->rela.count += additional_reloc_count;
11943                 }
11944             }
11945           else
11946             {
11947               if (o->use_rela_p)
11948                 esdo->rela.count += reloc_count;
11949               else
11950                 esdo->rel.count += reloc_count;
11951             }
11952         }
11953
11954       if (o->reloc_count > 0)
11955         o->flags |= SEC_RELOC;
11956       else
11957         {
11958           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11959              set it (this is probably a bug) and if it is set
11960              assign_section_numbers will create a reloc section.  */
11961           o->flags &=~ SEC_RELOC;
11962         }
11963
11964       /* If the SEC_ALLOC flag is not set, force the section VMA to
11965          zero.  This is done in elf_fake_sections as well, but forcing
11966          the VMA to 0 here will ensure that relocs against these
11967          sections are handled correctly.  */
11968       if ((o->flags & SEC_ALLOC) == 0
11969           && ! o->user_set_vma)
11970         o->vma = 0;
11971     }
11972
11973   if (! bfd_link_relocatable (info) && merged)
11974     elf_link_hash_traverse (htab, _bfd_elf_link_sec_merge_syms, abfd);
11975
11976   /* Figure out the file positions for everything but the symbol table
11977      and the relocs.  We set symcount to force assign_section_numbers
11978      to create a symbol table.  */
11979   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11980   BFD_ASSERT (! abfd->output_has_begun);
11981   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11982     goto error_return;
11983
11984   /* Set sizes, and assign file positions for reloc sections.  */
11985   for (o = abfd->sections; o != NULL; o = o->next)
11986     {
11987       struct bfd_elf_section_data *esdo = elf_section_data (o);
11988       if ((o->flags & SEC_RELOC) != 0)
11989         {
11990           if (esdo->rel.hdr
11991               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11992             goto error_return;
11993
11994           if (esdo->rela.hdr
11995               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11996             goto error_return;
11997         }
11998
11999       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
12000          to count upwards while actually outputting the relocations.  */
12001       esdo->rel.count = 0;
12002       esdo->rela.count = 0;
12003
12004       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
12005         {
12006           /* Cache the section contents so that they can be compressed
12007              later.  Use bfd_malloc since it will be freed by
12008              bfd_compress_section_contents.  */
12009           unsigned char *contents = esdo->this_hdr.contents;
12010           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
12011             abort ();
12012           contents
12013             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
12014           if (contents == NULL)
12015             goto error_return;
12016           esdo->this_hdr.contents = contents;
12017         }
12018     }
12019
12020   /* We have now assigned file positions for all the sections except
12021      .symtab, .strtab, and non-loaded reloc sections.  We start the
12022      .symtab section at the current file position, and write directly
12023      to it.  We build the .strtab section in memory.  */
12024   bfd_get_symcount (abfd) = 0;
12025   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12026   /* sh_name is set in prep_headers.  */
12027   symtab_hdr->sh_type = SHT_SYMTAB;
12028   /* sh_flags, sh_addr and sh_size all start off zero.  */
12029   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
12030   /* sh_link is set in assign_section_numbers.  */
12031   /* sh_info is set below.  */
12032   /* sh_offset is set just below.  */
12033   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
12034
12035   if (max_sym_count < 20)
12036     max_sym_count = 20;
12037   htab->strtabsize = max_sym_count;
12038   amt = max_sym_count * sizeof (struct elf_sym_strtab);
12039   htab->strtab = (struct elf_sym_strtab *) bfd_malloc (amt);
12040   if (htab->strtab == NULL)
12041     goto error_return;
12042   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
12043   flinfo.symshndxbuf
12044     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
12045        ? (Elf_External_Sym_Shndx *) -1 : NULL);
12046
12047   if (info->strip != strip_all || emit_relocs)
12048     {
12049       file_ptr off = elf_next_file_pos (abfd);
12050
12051       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
12052
12053       /* Note that at this point elf_next_file_pos (abfd) is
12054          incorrect.  We do not yet know the size of the .symtab section.
12055          We correct next_file_pos below, after we do know the size.  */
12056
12057       /* Start writing out the symbol table.  The first symbol is always a
12058          dummy symbol.  */
12059       elfsym.st_value = 0;
12060       elfsym.st_size = 0;
12061       elfsym.st_info = 0;
12062       elfsym.st_other = 0;
12063       elfsym.st_shndx = SHN_UNDEF;
12064       elfsym.st_target_internal = 0;
12065       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
12066                                      bfd_und_section_ptr, NULL) != 1)
12067         goto error_return;
12068
12069       /* Output a symbol for each section.  We output these even if we are
12070          discarding local symbols, since they are used for relocs.  These
12071          symbols have no names.  We store the index of each one in the
12072          index field of the section, so that we can find it again when
12073          outputting relocs.  */
12074
12075       elfsym.st_size = 0;
12076       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
12077       elfsym.st_other = 0;
12078       elfsym.st_value = 0;
12079       elfsym.st_target_internal = 0;
12080       for (i = 1; i < elf_numsections (abfd); i++)
12081         {
12082           o = bfd_section_from_elf_index (abfd, i);
12083           if (o != NULL)
12084             {
12085               o->target_index = bfd_get_symcount (abfd);
12086               elfsym.st_shndx = i;
12087               if (!bfd_link_relocatable (info))
12088                 elfsym.st_value = o->vma;
12089               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
12090                                              NULL) != 1)
12091                 goto error_return;
12092             }
12093         }
12094     }
12095
12096   /* Allocate some memory to hold information read in from the input
12097      files.  */
12098   if (max_contents_size != 0)
12099     {
12100       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
12101       if (flinfo.contents == NULL)
12102         goto error_return;
12103     }
12104
12105   if (max_external_reloc_size != 0)
12106     {
12107       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
12108       if (flinfo.external_relocs == NULL)
12109         goto error_return;
12110     }
12111
12112   if (max_internal_reloc_count != 0)
12113     {
12114       amt = max_internal_reloc_count * sizeof (Elf_Internal_Rela);
12115       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
12116       if (flinfo.internal_relocs == NULL)
12117         goto error_return;
12118     }
12119
12120   if (max_sym_count != 0)
12121     {
12122       amt = max_sym_count * bed->s->sizeof_sym;
12123       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
12124       if (flinfo.external_syms == NULL)
12125         goto error_return;
12126
12127       amt = max_sym_count * sizeof (Elf_Internal_Sym);
12128       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
12129       if (flinfo.internal_syms == NULL)
12130         goto error_return;
12131
12132       amt = max_sym_count * sizeof (long);
12133       flinfo.indices = (long int *) bfd_malloc (amt);
12134       if (flinfo.indices == NULL)
12135         goto error_return;
12136
12137       amt = max_sym_count * sizeof (asection *);
12138       flinfo.sections = (asection **) bfd_malloc (amt);
12139       if (flinfo.sections == NULL)
12140         goto error_return;
12141     }
12142
12143   if (max_sym_shndx_count != 0)
12144     {
12145       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
12146       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
12147       if (flinfo.locsym_shndx == NULL)
12148         goto error_return;
12149     }
12150
12151   if (htab->tls_sec)
12152     {
12153       bfd_vma base, end = 0;
12154       asection *sec;
12155
12156       for (sec = htab->tls_sec;
12157            sec && (sec->flags & SEC_THREAD_LOCAL);
12158            sec = sec->next)
12159         {
12160           bfd_size_type size = sec->size;
12161
12162           if (size == 0
12163               && (sec->flags & SEC_HAS_CONTENTS) == 0)
12164             {
12165               struct bfd_link_order *ord = sec->map_tail.link_order;
12166
12167               if (ord != NULL)
12168                 size = ord->offset + ord->size;
12169             }
12170           end = sec->vma + size;
12171         }
12172       base = htab->tls_sec->vma;
12173       /* Only align end of TLS section if static TLS doesn't have special
12174          alignment requirements.  */
12175       if (bed->static_tls_alignment == 1)
12176         end = align_power (end, htab->tls_sec->alignment_power);
12177       htab->tls_size = end - base;
12178     }
12179
12180   /* Reorder SHF_LINK_ORDER sections.  */
12181   for (o = abfd->sections; o != NULL; o = o->next)
12182     {
12183       if (!elf_fixup_link_order (abfd, o))
12184         return FALSE;
12185     }
12186
12187   if (!_bfd_elf_fixup_eh_frame_hdr (info))
12188     return FALSE;
12189
12190   /* Since ELF permits relocations to be against local symbols, we
12191      must have the local symbols available when we do the relocations.
12192      Since we would rather only read the local symbols once, and we
12193      would rather not keep them in memory, we handle all the
12194      relocations for a single input file at the same time.
12195
12196      Unfortunately, there is no way to know the total number of local
12197      symbols until we have seen all of them, and the local symbol
12198      indices precede the global symbol indices.  This means that when
12199      we are generating relocatable output, and we see a reloc against
12200      a global symbol, we can not know the symbol index until we have
12201      finished examining all the local symbols to see which ones we are
12202      going to output.  To deal with this, we keep the relocations in
12203      memory, and don't output them until the end of the link.  This is
12204      an unfortunate waste of memory, but I don't see a good way around
12205      it.  Fortunately, it only happens when performing a relocatable
12206      link, which is not the common case.  FIXME: If keep_memory is set
12207      we could write the relocs out and then read them again; I don't
12208      know how bad the memory loss will be.  */
12209
12210   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12211     sub->output_has_begun = FALSE;
12212   for (o = abfd->sections; o != NULL; o = o->next)
12213     {
12214       for (p = o->map_head.link_order; p != NULL; p = p->next)
12215         {
12216           if (p->type == bfd_indirect_link_order
12217               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
12218                   == bfd_target_elf_flavour)
12219               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
12220             {
12221               if (! sub->output_has_begun)
12222                 {
12223                   if (! elf_link_input_bfd (&flinfo, sub))
12224                     goto error_return;
12225                   sub->output_has_begun = TRUE;
12226                 }
12227             }
12228           else if (p->type == bfd_section_reloc_link_order
12229                    || p->type == bfd_symbol_reloc_link_order)
12230             {
12231               if (! elf_reloc_link_order (abfd, info, o, p))
12232                 goto error_return;
12233             }
12234           else
12235             {
12236               if (! _bfd_default_link_order (abfd, info, o, p))
12237                 {
12238                   if (p->type == bfd_indirect_link_order
12239                       && (bfd_get_flavour (sub)
12240                           == bfd_target_elf_flavour)
12241                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
12242                           != bed->s->elfclass))
12243                     {
12244                       const char *iclass, *oclass;
12245
12246                       switch (bed->s->elfclass)
12247                         {
12248                         case ELFCLASS64: oclass = "ELFCLASS64"; break;
12249                         case ELFCLASS32: oclass = "ELFCLASS32"; break;
12250                         case ELFCLASSNONE: oclass = "ELFCLASSNONE"; break;
12251                         default: abort ();
12252                         }
12253
12254                       switch (elf_elfheader (sub)->e_ident[EI_CLASS])
12255                         {
12256                         case ELFCLASS64: iclass = "ELFCLASS64"; break;
12257                         case ELFCLASS32: iclass = "ELFCLASS32"; break;
12258                         case ELFCLASSNONE: iclass = "ELFCLASSNONE"; break;
12259                         default: abort ();
12260                         }
12261
12262                       bfd_set_error (bfd_error_wrong_format);
12263                       _bfd_error_handler
12264                         /* xgettext:c-format */
12265                         (_("%pB: file class %s incompatible with %s"),
12266                          sub, iclass, oclass);
12267                     }
12268
12269                   goto error_return;
12270                 }
12271             }
12272         }
12273     }
12274
12275   /* Free symbol buffer if needed.  */
12276   if (!info->reduce_memory_overheads)
12277     {
12278       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12279         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
12280             && elf_tdata (sub)->symbuf)
12281           {
12282             free (elf_tdata (sub)->symbuf);
12283             elf_tdata (sub)->symbuf = NULL;
12284           }
12285     }
12286
12287   /* Output any global symbols that got converted to local in a
12288      version script or due to symbol visibility.  We do this in a
12289      separate step since ELF requires all local symbols to appear
12290      prior to any global symbols.  FIXME: We should only do this if
12291      some global symbols were, in fact, converted to become local.
12292      FIXME: Will this work correctly with the Irix 5 linker?  */
12293   eoinfo.failed = FALSE;
12294   eoinfo.flinfo = &flinfo;
12295   eoinfo.localsyms = TRUE;
12296   eoinfo.file_sym_done = FALSE;
12297   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12298   if (eoinfo.failed)
12299     return FALSE;
12300
12301   /* If backend needs to output some local symbols not present in the hash
12302      table, do it now.  */
12303   if (bed->elf_backend_output_arch_local_syms
12304       && (info->strip != strip_all || emit_relocs))
12305     {
12306       typedef int (*out_sym_func)
12307         (void *, const char *, Elf_Internal_Sym *, asection *,
12308          struct elf_link_hash_entry *);
12309
12310       if (! ((*bed->elf_backend_output_arch_local_syms)
12311              (abfd, info, &flinfo,
12312               (out_sym_func) elf_link_output_symstrtab)))
12313         return FALSE;
12314     }
12315
12316   /* That wrote out all the local symbols.  Finish up the symbol table
12317      with the global symbols. Even if we want to strip everything we
12318      can, we still need to deal with those global symbols that got
12319      converted to local in a version script.  */
12320
12321   /* The sh_info field records the index of the first non local symbol.  */
12322   symtab_hdr->sh_info = bfd_get_symcount (abfd);
12323
12324   if (dynamic
12325       && htab->dynsym != NULL
12326       && htab->dynsym->output_section != bfd_abs_section_ptr)
12327     {
12328       Elf_Internal_Sym sym;
12329       bfd_byte *dynsym = htab->dynsym->contents;
12330
12331       o = htab->dynsym->output_section;
12332       elf_section_data (o)->this_hdr.sh_info = htab->local_dynsymcount + 1;
12333
12334       /* Write out the section symbols for the output sections.  */
12335       if (bfd_link_pic (info)
12336           || htab->is_relocatable_executable)
12337         {
12338           asection *s;
12339
12340           sym.st_size = 0;
12341           sym.st_name = 0;
12342           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
12343           sym.st_other = 0;
12344           sym.st_target_internal = 0;
12345
12346           for (s = abfd->sections; s != NULL; s = s->next)
12347             {
12348               int indx;
12349               bfd_byte *dest;
12350               long dynindx;
12351
12352               dynindx = elf_section_data (s)->dynindx;
12353               if (dynindx <= 0)
12354                 continue;
12355               indx = elf_section_data (s)->this_idx;
12356               BFD_ASSERT (indx > 0);
12357               sym.st_shndx = indx;
12358               if (! check_dynsym (abfd, &sym))
12359                 return FALSE;
12360               sym.st_value = s->vma;
12361               dest = dynsym + dynindx * bed->s->sizeof_sym;
12362               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12363             }
12364         }
12365
12366       /* Write out the local dynsyms.  */
12367       if (htab->dynlocal)
12368         {
12369           struct elf_link_local_dynamic_entry *e;
12370           for (e = htab->dynlocal; e ; e = e->next)
12371             {
12372               asection *s;
12373               bfd_byte *dest;
12374
12375               /* Copy the internal symbol and turn off visibility.
12376                  Note that we saved a word of storage and overwrote
12377                  the original st_name with the dynstr_index.  */
12378               sym = e->isym;
12379               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
12380
12381               s = bfd_section_from_elf_index (e->input_bfd,
12382                                               e->isym.st_shndx);
12383               if (s != NULL)
12384                 {
12385                   sym.st_shndx =
12386                     elf_section_data (s->output_section)->this_idx;
12387                   if (! check_dynsym (abfd, &sym))
12388                     return FALSE;
12389                   sym.st_value = (s->output_section->vma
12390                                   + s->output_offset
12391                                   + e->isym.st_value);
12392                 }
12393
12394               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
12395               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12396             }
12397         }
12398     }
12399
12400   /* We get the global symbols from the hash table.  */
12401   eoinfo.failed = FALSE;
12402   eoinfo.localsyms = FALSE;
12403   eoinfo.flinfo = &flinfo;
12404   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12405   if (eoinfo.failed)
12406     return FALSE;
12407
12408   /* If backend needs to output some symbols not present in the hash
12409      table, do it now.  */
12410   if (bed->elf_backend_output_arch_syms
12411       && (info->strip != strip_all || emit_relocs))
12412     {
12413       typedef int (*out_sym_func)
12414         (void *, const char *, Elf_Internal_Sym *, asection *,
12415          struct elf_link_hash_entry *);
12416
12417       if (! ((*bed->elf_backend_output_arch_syms)
12418              (abfd, info, &flinfo,
12419               (out_sym_func) elf_link_output_symstrtab)))
12420         return FALSE;
12421     }
12422
12423   /* Finalize the .strtab section.  */
12424   _bfd_elf_strtab_finalize (flinfo.symstrtab);
12425
12426   /* Swap out the .strtab section. */
12427   if (!elf_link_swap_symbols_out (&flinfo))
12428     return FALSE;
12429
12430   /* Now we know the size of the symtab section.  */
12431   if (bfd_get_symcount (abfd) > 0)
12432     {
12433       /* Finish up and write out the symbol string table (.strtab)
12434          section.  */
12435       Elf_Internal_Shdr *symstrtab_hdr = NULL;
12436       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
12437
12438       if (elf_symtab_shndx_list (abfd))
12439         {
12440           symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
12441
12442           if (symtab_shndx_hdr != NULL && symtab_shndx_hdr->sh_name != 0)
12443             {
12444               symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
12445               symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
12446               symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
12447               amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
12448               symtab_shndx_hdr->sh_size = amt;
12449
12450               off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
12451                                                                off, TRUE);
12452
12453               if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
12454                   || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
12455                 return FALSE;
12456             }
12457         }
12458
12459       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
12460       /* sh_name was set in prep_headers.  */
12461       symstrtab_hdr->sh_type = SHT_STRTAB;
12462       symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
12463       symstrtab_hdr->sh_addr = 0;
12464       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
12465       symstrtab_hdr->sh_entsize = 0;
12466       symstrtab_hdr->sh_link = 0;
12467       symstrtab_hdr->sh_info = 0;
12468       /* sh_offset is set just below.  */
12469       symstrtab_hdr->sh_addralign = 1;
12470
12471       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
12472                                                        off, TRUE);
12473       elf_next_file_pos (abfd) = off;
12474
12475       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
12476           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
12477         return FALSE;
12478     }
12479
12480   if (info->out_implib_bfd && !elf_output_implib (abfd, info))
12481     {
12482       _bfd_error_handler (_("%pB: failed to generate import library"),
12483                           info->out_implib_bfd);
12484       return FALSE;
12485     }
12486
12487   /* Adjust the relocs to have the correct symbol indices.  */
12488   for (o = abfd->sections; o != NULL; o = o->next)
12489     {
12490       struct bfd_elf_section_data *esdo = elf_section_data (o);
12491       bfd_boolean sort;
12492
12493       if ((o->flags & SEC_RELOC) == 0)
12494         continue;
12495
12496       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
12497       if (esdo->rel.hdr != NULL
12498           && !elf_link_adjust_relocs (abfd, o, &esdo->rel, sort, info))
12499         return FALSE;
12500       if (esdo->rela.hdr != NULL
12501           && !elf_link_adjust_relocs (abfd, o, &esdo->rela, sort, info))
12502         return FALSE;
12503
12504       /* Set the reloc_count field to 0 to prevent write_relocs from
12505          trying to swap the relocs out itself.  */
12506       o->reloc_count = 0;
12507     }
12508
12509   if (dynamic && info->combreloc && dynobj != NULL)
12510     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
12511
12512   /* If we are linking against a dynamic object, or generating a
12513      shared library, finish up the dynamic linking information.  */
12514   if (dynamic)
12515     {
12516       bfd_byte *dyncon, *dynconend;
12517
12518       /* Fix up .dynamic entries.  */
12519       o = bfd_get_linker_section (dynobj, ".dynamic");
12520       BFD_ASSERT (o != NULL);
12521
12522       dyncon = o->contents;
12523       dynconend = o->contents + o->size;
12524       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12525         {
12526           Elf_Internal_Dyn dyn;
12527           const char *name;
12528           unsigned int type;
12529           bfd_size_type sh_size;
12530           bfd_vma sh_addr;
12531
12532           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12533
12534           switch (dyn.d_tag)
12535             {
12536             default:
12537               continue;
12538             case DT_NULL:
12539               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
12540                 {
12541                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
12542                     {
12543                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
12544                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
12545                     default: continue;
12546                     }
12547                   dyn.d_un.d_val = relativecount;
12548                   relativecount = 0;
12549                   break;
12550                 }
12551               continue;
12552
12553             case DT_INIT:
12554               name = info->init_function;
12555               goto get_sym;
12556             case DT_FINI:
12557               name = info->fini_function;
12558             get_sym:
12559               {
12560                 struct elf_link_hash_entry *h;
12561
12562                 h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
12563                 if (h != NULL
12564                     && (h->root.type == bfd_link_hash_defined
12565                         || h->root.type == bfd_link_hash_defweak))
12566                   {
12567                     dyn.d_un.d_ptr = h->root.u.def.value;
12568                     o = h->root.u.def.section;
12569                     if (o->output_section != NULL)
12570                       dyn.d_un.d_ptr += (o->output_section->vma
12571                                          + o->output_offset);
12572                     else
12573                       {
12574                         /* The symbol is imported from another shared
12575                            library and does not apply to this one.  */
12576                         dyn.d_un.d_ptr = 0;
12577                       }
12578                     break;
12579                   }
12580               }
12581               continue;
12582
12583             case DT_PREINIT_ARRAYSZ:
12584               name = ".preinit_array";
12585               goto get_out_size;
12586             case DT_INIT_ARRAYSZ:
12587               name = ".init_array";
12588               goto get_out_size;
12589             case DT_FINI_ARRAYSZ:
12590               name = ".fini_array";
12591             get_out_size:
12592               o = bfd_get_section_by_name (abfd, name);
12593               if (o == NULL)
12594                 {
12595                   _bfd_error_handler
12596                     (_("could not find section %s"), name);
12597                   goto error_return;
12598                 }
12599               if (o->size == 0)
12600                 _bfd_error_handler
12601                   (_("warning: %s section has zero size"), name);
12602               dyn.d_un.d_val = o->size;
12603               break;
12604
12605             case DT_PREINIT_ARRAY:
12606               name = ".preinit_array";
12607               goto get_out_vma;
12608             case DT_INIT_ARRAY:
12609               name = ".init_array";
12610               goto get_out_vma;
12611             case DT_FINI_ARRAY:
12612               name = ".fini_array";
12613             get_out_vma:
12614               o = bfd_get_section_by_name (abfd, name);
12615               goto do_vma;
12616
12617             case DT_HASH:
12618               name = ".hash";
12619               goto get_vma;
12620             case DT_GNU_HASH:
12621               name = ".gnu.hash";
12622               goto get_vma;
12623             case DT_STRTAB:
12624               name = ".dynstr";
12625               goto get_vma;
12626             case DT_SYMTAB:
12627               name = ".dynsym";
12628               goto get_vma;
12629             case DT_VERDEF:
12630               name = ".gnu.version_d";
12631               goto get_vma;
12632             case DT_VERNEED:
12633               name = ".gnu.version_r";
12634               goto get_vma;
12635             case DT_VERSYM:
12636               name = ".gnu.version";
12637             get_vma:
12638               o = bfd_get_linker_section (dynobj, name);
12639             do_vma:
12640               if (o == NULL || bfd_is_abs_section (o->output_section))
12641                 {
12642                   _bfd_error_handler
12643                     (_("could not find section %s"), name);
12644                   goto error_return;
12645                 }
12646               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
12647                 {
12648                   _bfd_error_handler
12649                     (_("warning: section '%s' is being made into a note"), name);
12650                   bfd_set_error (bfd_error_nonrepresentable_section);
12651                   goto error_return;
12652                 }
12653               dyn.d_un.d_ptr = o->output_section->vma + o->output_offset;
12654               break;
12655
12656             case DT_REL:
12657             case DT_RELA:
12658             case DT_RELSZ:
12659             case DT_RELASZ:
12660               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
12661                 type = SHT_REL;
12662               else
12663                 type = SHT_RELA;
12664               sh_size = 0;
12665               sh_addr = 0;
12666               for (i = 1; i < elf_numsections (abfd); i++)
12667                 {
12668                   Elf_Internal_Shdr *hdr;
12669
12670                   hdr = elf_elfsections (abfd)[i];
12671                   if (hdr->sh_type == type
12672                       && (hdr->sh_flags & SHF_ALLOC) != 0)
12673                     {
12674                       sh_size += hdr->sh_size;
12675                       if (sh_addr == 0
12676                           || sh_addr > hdr->sh_addr)
12677                         sh_addr = hdr->sh_addr;
12678                     }
12679                 }
12680
12681               if (bed->dtrel_excludes_plt && htab->srelplt != NULL)
12682                 {
12683                   /* Don't count procedure linkage table relocs in the
12684                      overall reloc count.  */
12685                   sh_size -= htab->srelplt->size;
12686                   if (sh_size == 0)
12687                     /* If the size is zero, make the address zero too.
12688                        This is to avoid a glibc bug.  If the backend
12689                        emits DT_RELA/DT_RELASZ even when DT_RELASZ is
12690                        zero, then we'll put DT_RELA at the end of
12691                        DT_JMPREL.  glibc will interpret the end of
12692                        DT_RELA matching the end of DT_JMPREL as the
12693                        case where DT_RELA includes DT_JMPREL, and for
12694                        LD_BIND_NOW will decide that processing DT_RELA
12695                        will process the PLT relocs too.  Net result:
12696                        No PLT relocs applied.  */
12697                     sh_addr = 0;
12698
12699                   /* If .rela.plt is the first .rela section, exclude
12700                      it from DT_RELA.  */
12701                   else if (sh_addr == (htab->srelplt->output_section->vma
12702                                        + htab->srelplt->output_offset))
12703                     sh_addr += htab->srelplt->size;
12704                 }
12705
12706               if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
12707                 dyn.d_un.d_val = sh_size;
12708               else
12709                 dyn.d_un.d_ptr = sh_addr;
12710               break;
12711             }
12712           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
12713         }
12714     }
12715
12716   /* If we have created any dynamic sections, then output them.  */
12717   if (dynobj != NULL)
12718     {
12719       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
12720         goto error_return;
12721
12722       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
12723       if (((info->warn_shared_textrel && bfd_link_pic (info))
12724            || info->error_textrel)
12725           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
12726         {
12727           bfd_byte *dyncon, *dynconend;
12728
12729           dyncon = o->contents;
12730           dynconend = o->contents + o->size;
12731           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12732             {
12733               Elf_Internal_Dyn dyn;
12734
12735               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12736
12737               if (dyn.d_tag == DT_TEXTREL)
12738                 {
12739                   if (info->error_textrel)
12740                     info->callbacks->einfo
12741                       (_("%P%X: read-only segment has dynamic relocations\n"));
12742                   else
12743                     info->callbacks->einfo
12744                       (_("%P: warning: creating a DT_TEXTREL in a shared object\n"));
12745                   break;
12746                 }
12747             }
12748         }
12749
12750       for (o = dynobj->sections; o != NULL; o = o->next)
12751         {
12752           if ((o->flags & SEC_HAS_CONTENTS) == 0
12753               || o->size == 0
12754               || o->output_section == bfd_abs_section_ptr)
12755             continue;
12756           if ((o->flags & SEC_LINKER_CREATED) == 0)
12757             {
12758               /* At this point, we are only interested in sections
12759                  created by _bfd_elf_link_create_dynamic_sections.  */
12760               continue;
12761             }
12762           if (htab->stab_info.stabstr == o)
12763             continue;
12764           if (htab->eh_info.hdr_sec == o)
12765             continue;
12766           if (strcmp (o->name, ".dynstr") != 0)
12767             {
12768               if (! bfd_set_section_contents (abfd, o->output_section,
12769                                               o->contents,
12770                                               (file_ptr) o->output_offset
12771                                               * bfd_octets_per_byte (abfd),
12772                                               o->size))
12773                 goto error_return;
12774             }
12775           else
12776             {
12777               /* The contents of the .dynstr section are actually in a
12778                  stringtab.  */
12779               file_ptr off;
12780
12781               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
12782               if (bfd_seek (abfd, off, SEEK_SET) != 0
12783                   || !_bfd_elf_strtab_emit (abfd, htab->dynstr))
12784                 goto error_return;
12785             }
12786         }
12787     }
12788
12789   if (!info->resolve_section_groups)
12790     {
12791       bfd_boolean failed = FALSE;
12792
12793       BFD_ASSERT (bfd_link_relocatable (info));
12794       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
12795       if (failed)
12796         goto error_return;
12797     }
12798
12799   /* If we have optimized stabs strings, output them.  */
12800   if (htab->stab_info.stabstr != NULL)
12801     {
12802       if (!_bfd_write_stab_strings (abfd, &htab->stab_info))
12803         goto error_return;
12804     }
12805
12806   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
12807     goto error_return;
12808
12809   elf_final_link_free (abfd, &flinfo);
12810
12811   elf_linker (abfd) = TRUE;
12812
12813   if (attr_section)
12814     {
12815       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
12816       if (contents == NULL)
12817         return FALSE;   /* Bail out and fail.  */
12818       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
12819       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
12820       free (contents);
12821     }
12822
12823   return TRUE;
12824
12825  error_return:
12826   elf_final_link_free (abfd, &flinfo);
12827   return FALSE;
12828 }
12829 \f
12830 /* Initialize COOKIE for input bfd ABFD.  */
12831
12832 static bfd_boolean
12833 init_reloc_cookie (struct elf_reloc_cookie *cookie,
12834                    struct bfd_link_info *info, bfd *abfd)
12835 {
12836   Elf_Internal_Shdr *symtab_hdr;
12837   const struct elf_backend_data *bed;
12838
12839   bed = get_elf_backend_data (abfd);
12840   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12841
12842   cookie->abfd = abfd;
12843   cookie->sym_hashes = elf_sym_hashes (abfd);
12844   cookie->bad_symtab = elf_bad_symtab (abfd);
12845   if (cookie->bad_symtab)
12846     {
12847       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12848       cookie->extsymoff = 0;
12849     }
12850   else
12851     {
12852       cookie->locsymcount = symtab_hdr->sh_info;
12853       cookie->extsymoff = symtab_hdr->sh_info;
12854     }
12855
12856   if (bed->s->arch_size == 32)
12857     cookie->r_sym_shift = 8;
12858   else
12859     cookie->r_sym_shift = 32;
12860
12861   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
12862   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
12863     {
12864       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12865                                               cookie->locsymcount, 0,
12866                                               NULL, NULL, NULL);
12867       if (cookie->locsyms == NULL)
12868         {
12869           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
12870           return FALSE;
12871         }
12872       if (info->keep_memory)
12873         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
12874     }
12875   return TRUE;
12876 }
12877
12878 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
12879
12880 static void
12881 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
12882 {
12883   Elf_Internal_Shdr *symtab_hdr;
12884
12885   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12886   if (cookie->locsyms != NULL
12887       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
12888     free (cookie->locsyms);
12889 }
12890
12891 /* Initialize the relocation information in COOKIE for input section SEC
12892    of input bfd ABFD.  */
12893
12894 static bfd_boolean
12895 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12896                         struct bfd_link_info *info, bfd *abfd,
12897                         asection *sec)
12898 {
12899   if (sec->reloc_count == 0)
12900     {
12901       cookie->rels = NULL;
12902       cookie->relend = NULL;
12903     }
12904   else
12905     {
12906       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
12907                                                 info->keep_memory);
12908       if (cookie->rels == NULL)
12909         return FALSE;
12910       cookie->rel = cookie->rels;
12911       cookie->relend = cookie->rels + sec->reloc_count;
12912     }
12913   cookie->rel = cookie->rels;
12914   return TRUE;
12915 }
12916
12917 /* Free the memory allocated by init_reloc_cookie_rels,
12918    if appropriate.  */
12919
12920 static void
12921 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12922                         asection *sec)
12923 {
12924   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
12925     free (cookie->rels);
12926 }
12927
12928 /* Initialize the whole of COOKIE for input section SEC.  */
12929
12930 static bfd_boolean
12931 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12932                                struct bfd_link_info *info,
12933                                asection *sec)
12934 {
12935   if (!init_reloc_cookie (cookie, info, sec->owner))
12936     goto error1;
12937   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
12938     goto error2;
12939   return TRUE;
12940
12941  error2:
12942   fini_reloc_cookie (cookie, sec->owner);
12943  error1:
12944   return FALSE;
12945 }
12946
12947 /* Free the memory allocated by init_reloc_cookie_for_section,
12948    if appropriate.  */
12949
12950 static void
12951 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12952                                asection *sec)
12953 {
12954   fini_reloc_cookie_rels (cookie, sec);
12955   fini_reloc_cookie (cookie, sec->owner);
12956 }
12957 \f
12958 /* Garbage collect unused sections.  */
12959
12960 /* Default gc_mark_hook.  */
12961
12962 asection *
12963 _bfd_elf_gc_mark_hook (asection *sec,
12964                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12965                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12966                        struct elf_link_hash_entry *h,
12967                        Elf_Internal_Sym *sym)
12968 {
12969   if (h != NULL)
12970     {
12971       switch (h->root.type)
12972         {
12973         case bfd_link_hash_defined:
12974         case bfd_link_hash_defweak:
12975           return h->root.u.def.section;
12976
12977         case bfd_link_hash_common:
12978           return h->root.u.c.p->section;
12979
12980         default:
12981           break;
12982         }
12983     }
12984   else
12985     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12986
12987   return NULL;
12988 }
12989
12990 /* Return the debug definition section.  */
12991
12992 static asection *
12993 elf_gc_mark_debug_section (asection *sec ATTRIBUTE_UNUSED,
12994                            struct bfd_link_info *info ATTRIBUTE_UNUSED,
12995                            Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12996                            struct elf_link_hash_entry *h,
12997                            Elf_Internal_Sym *sym)
12998 {
12999   if (h != NULL)
13000     {
13001       /* Return the global debug definition section.  */
13002       if ((h->root.type == bfd_link_hash_defined
13003            || h->root.type == bfd_link_hash_defweak)
13004           && (h->root.u.def.section->flags & SEC_DEBUGGING) != 0)
13005         return h->root.u.def.section;
13006     }
13007   else
13008     {
13009       /* Return the local debug definition section.  */
13010       asection *isec = bfd_section_from_elf_index (sec->owner,
13011                                                    sym->st_shndx);
13012       if ((isec->flags & SEC_DEBUGGING) != 0)
13013         return isec;
13014     }
13015
13016   return NULL;
13017 }
13018
13019 /* COOKIE->rel describes a relocation against section SEC, which is
13020    a section we've decided to keep.  Return the section that contains
13021    the relocation symbol, or NULL if no section contains it.  */
13022
13023 asection *
13024 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
13025                        elf_gc_mark_hook_fn gc_mark_hook,
13026                        struct elf_reloc_cookie *cookie,
13027                        bfd_boolean *start_stop)
13028 {
13029   unsigned long r_symndx;
13030   struct elf_link_hash_entry *h;
13031
13032   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
13033   if (r_symndx == STN_UNDEF)
13034     return NULL;
13035
13036   if (r_symndx >= cookie->locsymcount
13037       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13038     {
13039       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
13040       if (h == NULL)
13041         {
13042           info->callbacks->einfo (_("%F%P: corrupt input: %pB\n"),
13043                                   sec->owner);
13044           return NULL;
13045         }
13046       while (h->root.type == bfd_link_hash_indirect
13047              || h->root.type == bfd_link_hash_warning)
13048         h = (struct elf_link_hash_entry *) h->root.u.i.link;
13049       h->mark = 1;
13050       /* If this symbol is weak and there is a non-weak definition, we
13051          keep the non-weak definition because many backends put
13052          dynamic reloc info on the non-weak definition for code
13053          handling copy relocs.  */
13054       if (h->is_weakalias)
13055         weakdef (h)->mark = 1;
13056
13057       if (start_stop != NULL)
13058         {
13059           /* To work around a glibc bug, mark XXX input sections
13060              when there is a reference to __start_XXX or __stop_XXX
13061              symbols.  */
13062           if (h->start_stop)
13063             {
13064               asection *s = h->u2.start_stop_section;
13065               *start_stop = !s->gc_mark;
13066               return s;
13067             }
13068         }
13069
13070       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
13071     }
13072
13073   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
13074                           &cookie->locsyms[r_symndx]);
13075 }
13076
13077 /* COOKIE->rel describes a relocation against section SEC, which is
13078    a section we've decided to keep.  Mark the section that contains
13079    the relocation symbol.  */
13080
13081 bfd_boolean
13082 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
13083                         asection *sec,
13084                         elf_gc_mark_hook_fn gc_mark_hook,
13085                         struct elf_reloc_cookie *cookie)
13086 {
13087   asection *rsec;
13088   bfd_boolean start_stop = FALSE;
13089
13090   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie, &start_stop);
13091   while (rsec != NULL)
13092     {
13093       if (!rsec->gc_mark)
13094         {
13095           if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
13096               || (rsec->owner->flags & DYNAMIC) != 0)
13097             rsec->gc_mark = 1;
13098           else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
13099             return FALSE;
13100         }
13101       if (!start_stop)
13102         break;
13103       rsec = bfd_get_next_section_by_name (rsec->owner, rsec);
13104     }
13105   return TRUE;
13106 }
13107
13108 /* The mark phase of garbage collection.  For a given section, mark
13109    it and any sections in this section's group, and all the sections
13110    which define symbols to which it refers.  */
13111
13112 bfd_boolean
13113 _bfd_elf_gc_mark (struct bfd_link_info *info,
13114                   asection *sec,
13115                   elf_gc_mark_hook_fn gc_mark_hook)
13116 {
13117   bfd_boolean ret;
13118   asection *group_sec, *eh_frame;
13119
13120   sec->gc_mark = 1;
13121
13122   /* Mark all the sections in the group.  */
13123   group_sec = elf_section_data (sec)->next_in_group;
13124   if (group_sec && !group_sec->gc_mark)
13125     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
13126       return FALSE;
13127
13128   /* Look through the section relocs.  */
13129   ret = TRUE;
13130   eh_frame = elf_eh_frame_section (sec->owner);
13131   if ((sec->flags & SEC_RELOC) != 0
13132       && sec->reloc_count > 0
13133       && sec != eh_frame)
13134     {
13135       struct elf_reloc_cookie cookie;
13136
13137       if (!init_reloc_cookie_for_section (&cookie, info, sec))
13138         ret = FALSE;
13139       else
13140         {
13141           for (; cookie.rel < cookie.relend; cookie.rel++)
13142             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
13143               {
13144                 ret = FALSE;
13145                 break;
13146               }
13147           fini_reloc_cookie_for_section (&cookie, sec);
13148         }
13149     }
13150
13151   if (ret && eh_frame && elf_fde_list (sec))
13152     {
13153       struct elf_reloc_cookie cookie;
13154
13155       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
13156         ret = FALSE;
13157       else
13158         {
13159           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
13160                                       gc_mark_hook, &cookie))
13161             ret = FALSE;
13162           fini_reloc_cookie_for_section (&cookie, eh_frame);
13163         }
13164     }
13165
13166   eh_frame = elf_section_eh_frame_entry (sec);
13167   if (ret && eh_frame && !eh_frame->gc_mark)
13168     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
13169       ret = FALSE;
13170
13171   return ret;
13172 }
13173
13174 /* Scan and mark sections in a special or debug section group.  */
13175
13176 static void
13177 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
13178 {
13179   /* Point to first section of section group.  */
13180   asection *ssec;
13181   /* Used to iterate the section group.  */
13182   asection *msec;
13183
13184   bfd_boolean is_special_grp = TRUE;
13185   bfd_boolean is_debug_grp = TRUE;
13186
13187   /* First scan to see if group contains any section other than debug
13188      and special section.  */
13189   ssec = msec = elf_next_in_group (grp);
13190   do
13191     {
13192       if ((msec->flags & SEC_DEBUGGING) == 0)
13193         is_debug_grp = FALSE;
13194
13195       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
13196         is_special_grp = FALSE;
13197
13198       msec = elf_next_in_group (msec);
13199     }
13200   while (msec != ssec);
13201
13202   /* If this is a pure debug section group or pure special section group,
13203      keep all sections in this group.  */
13204   if (is_debug_grp || is_special_grp)
13205     {
13206       do
13207         {
13208           msec->gc_mark = 1;
13209           msec = elf_next_in_group (msec);
13210         }
13211       while (msec != ssec);
13212     }
13213 }
13214
13215 /* Keep debug and special sections.  */
13216
13217 bfd_boolean
13218 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
13219                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
13220 {
13221   bfd *ibfd;
13222
13223   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13224     {
13225       asection *isec;
13226       bfd_boolean some_kept;
13227       bfd_boolean debug_frag_seen;
13228       bfd_boolean has_kept_debug_info;
13229
13230       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13231         continue;
13232       isec = ibfd->sections;
13233       if (isec == NULL || isec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13234         continue;
13235
13236       /* Ensure all linker created sections are kept,
13237          see if any other section is already marked,
13238          and note if we have any fragmented debug sections.  */
13239       debug_frag_seen = some_kept = has_kept_debug_info = FALSE;
13240       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13241         {
13242           if ((isec->flags & SEC_LINKER_CREATED) != 0)
13243             isec->gc_mark = 1;
13244           else if (isec->gc_mark
13245                    && (isec->flags & SEC_ALLOC) != 0
13246                    && elf_section_type (isec) != SHT_NOTE)
13247             some_kept = TRUE;
13248
13249           if (!debug_frag_seen
13250               && (isec->flags & SEC_DEBUGGING)
13251               && CONST_STRNEQ (isec->name, ".debug_line."))
13252             debug_frag_seen = TRUE;
13253         }
13254
13255       /* If no non-note alloc section in this file will be kept, then
13256          we can toss out the debug and special sections.  */
13257       if (!some_kept)
13258         continue;
13259
13260       /* Keep debug and special sections like .comment when they are
13261          not part of a group.  Also keep section groups that contain
13262          just debug sections or special sections.  */
13263       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13264         {
13265           if ((isec->flags & SEC_GROUP) != 0)
13266             _bfd_elf_gc_mark_debug_special_section_group (isec);
13267           else if (((isec->flags & SEC_DEBUGGING) != 0
13268                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
13269                    && elf_next_in_group (isec) == NULL)
13270             isec->gc_mark = 1;
13271           if (isec->gc_mark && (isec->flags & SEC_DEBUGGING) != 0)
13272             has_kept_debug_info = TRUE;
13273         }
13274
13275       /* Look for CODE sections which are going to be discarded,
13276          and find and discard any fragmented debug sections which
13277          are associated with that code section.  */
13278       if (debug_frag_seen)
13279         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13280           if ((isec->flags & SEC_CODE) != 0
13281               && isec->gc_mark == 0)
13282             {
13283               unsigned int ilen;
13284               asection *dsec;
13285
13286               ilen = strlen (isec->name);
13287
13288               /* Association is determined by the name of the debug
13289                  section containing the name of the code section as
13290                  a suffix.  For example .debug_line.text.foo is a
13291                  debug section associated with .text.foo.  */
13292               for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
13293                 {
13294                   unsigned int dlen;
13295
13296                   if (dsec->gc_mark == 0
13297                       || (dsec->flags & SEC_DEBUGGING) == 0)
13298                     continue;
13299
13300                   dlen = strlen (dsec->name);
13301
13302                   if (dlen > ilen
13303                       && strncmp (dsec->name + (dlen - ilen),
13304                                   isec->name, ilen) == 0)
13305                     dsec->gc_mark = 0;
13306                 }
13307           }
13308
13309       /* Mark debug sections referenced by kept debug sections.  */
13310       if (has_kept_debug_info)
13311         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13312           if (isec->gc_mark
13313               && (isec->flags & SEC_DEBUGGING) != 0)
13314             if (!_bfd_elf_gc_mark (info, isec,
13315                                    elf_gc_mark_debug_section))
13316               return FALSE;
13317     }
13318   return TRUE;
13319 }
13320
13321 static bfd_boolean
13322 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
13323 {
13324   bfd *sub;
13325   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13326
13327   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13328     {
13329       asection *o;
13330
13331       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13332           || elf_object_id (sub) != elf_hash_table_id (elf_hash_table (info))
13333           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13334         continue;
13335       o = sub->sections;
13336       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13337         continue;
13338
13339       for (o = sub->sections; o != NULL; o = o->next)
13340         {
13341           /* When any section in a section group is kept, we keep all
13342              sections in the section group.  If the first member of
13343              the section group is excluded, we will also exclude the
13344              group section.  */
13345           if (o->flags & SEC_GROUP)
13346             {
13347               asection *first = elf_next_in_group (o);
13348               o->gc_mark = first->gc_mark;
13349             }
13350
13351           if (o->gc_mark)
13352             continue;
13353
13354           /* Skip sweeping sections already excluded.  */
13355           if (o->flags & SEC_EXCLUDE)
13356             continue;
13357
13358           /* Since this is early in the link process, it is simple
13359              to remove a section from the output.  */
13360           o->flags |= SEC_EXCLUDE;
13361
13362           if (info->print_gc_sections && o->size != 0)
13363             /* xgettext:c-format */
13364             _bfd_error_handler (_("removing unused section '%pA' in file '%pB'"),
13365                                 o, sub);
13366         }
13367     }
13368
13369   return TRUE;
13370 }
13371
13372 /* Propagate collected vtable information.  This is called through
13373    elf_link_hash_traverse.  */
13374
13375 static bfd_boolean
13376 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
13377 {
13378   /* Those that are not vtables.  */
13379   if (h->start_stop
13380       || h->u2.vtable == NULL
13381       || h->u2.vtable->parent == NULL)
13382     return TRUE;
13383
13384   /* Those vtables that do not have parents, we cannot merge.  */
13385   if (h->u2.vtable->parent == (struct elf_link_hash_entry *) -1)
13386     return TRUE;
13387
13388   /* If we've already been done, exit.  */
13389   if (h->u2.vtable->used && h->u2.vtable->used[-1])
13390     return TRUE;
13391
13392   /* Make sure the parent's table is up to date.  */
13393   elf_gc_propagate_vtable_entries_used (h->u2.vtable->parent, okp);
13394
13395   if (h->u2.vtable->used == NULL)
13396     {
13397       /* None of this table's entries were referenced.  Re-use the
13398          parent's table.  */
13399       h->u2.vtable->used = h->u2.vtable->parent->u2.vtable->used;
13400       h->u2.vtable->size = h->u2.vtable->parent->u2.vtable->size;
13401     }
13402   else
13403     {
13404       size_t n;
13405       bfd_boolean *cu, *pu;
13406
13407       /* Or the parent's entries into ours.  */
13408       cu = h->u2.vtable->used;
13409       cu[-1] = TRUE;
13410       pu = h->u2.vtable->parent->u2.vtable->used;
13411       if (pu != NULL)
13412         {
13413           const struct elf_backend_data *bed;
13414           unsigned int log_file_align;
13415
13416           bed = get_elf_backend_data (h->root.u.def.section->owner);
13417           log_file_align = bed->s->log_file_align;
13418           n = h->u2.vtable->parent->u2.vtable->size >> log_file_align;
13419           while (n--)
13420             {
13421               if (*pu)
13422                 *cu = TRUE;
13423               pu++;
13424               cu++;
13425             }
13426         }
13427     }
13428
13429   return TRUE;
13430 }
13431
13432 static bfd_boolean
13433 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
13434 {
13435   asection *sec;
13436   bfd_vma hstart, hend;
13437   Elf_Internal_Rela *relstart, *relend, *rel;
13438   const struct elf_backend_data *bed;
13439   unsigned int log_file_align;
13440
13441   /* Take care of both those symbols that do not describe vtables as
13442      well as those that are not loaded.  */
13443   if (h->start_stop
13444       || h->u2.vtable == NULL
13445       || h->u2.vtable->parent == NULL)
13446     return TRUE;
13447
13448   BFD_ASSERT (h->root.type == bfd_link_hash_defined
13449               || h->root.type == bfd_link_hash_defweak);
13450
13451   sec = h->root.u.def.section;
13452   hstart = h->root.u.def.value;
13453   hend = hstart + h->size;
13454
13455   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
13456   if (!relstart)
13457     return *(bfd_boolean *) okp = FALSE;
13458   bed = get_elf_backend_data (sec->owner);
13459   log_file_align = bed->s->log_file_align;
13460
13461   relend = relstart + sec->reloc_count;
13462
13463   for (rel = relstart; rel < relend; ++rel)
13464     if (rel->r_offset >= hstart && rel->r_offset < hend)
13465       {
13466         /* If the entry is in use, do nothing.  */
13467         if (h->u2.vtable->used
13468             && (rel->r_offset - hstart) < h->u2.vtable->size)
13469           {
13470             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
13471             if (h->u2.vtable->used[entry])
13472               continue;
13473           }
13474         /* Otherwise, kill it.  */
13475         rel->r_offset = rel->r_info = rel->r_addend = 0;
13476       }
13477
13478   return TRUE;
13479 }
13480
13481 /* Mark sections containing dynamically referenced symbols.  When
13482    building shared libraries, we must assume that any visible symbol is
13483    referenced.  */
13484
13485 bfd_boolean
13486 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
13487 {
13488   struct bfd_link_info *info = (struct bfd_link_info *) inf;
13489   struct bfd_elf_dynamic_list *d = info->dynamic_list;
13490
13491   if ((h->root.type == bfd_link_hash_defined
13492        || h->root.type == bfd_link_hash_defweak)
13493       && ((h->ref_dynamic && !h->forced_local)
13494           || ((h->def_regular || ELF_COMMON_DEF_P (h))
13495               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
13496               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
13497               && (!bfd_link_executable (info)
13498                   || info->gc_keep_exported
13499                   || info->export_dynamic
13500                   || (h->dynamic
13501                       && d != NULL
13502                       && (*d->match) (&d->head, NULL, h->root.root.string)))
13503               && (h->versioned >= versioned
13504                   || !bfd_hide_sym_by_version (info->version_info,
13505                                                h->root.root.string)))))
13506     h->root.u.def.section->flags |= SEC_KEEP;
13507
13508   return TRUE;
13509 }
13510
13511 /* Keep all sections containing symbols undefined on the command-line,
13512    and the section containing the entry symbol.  */
13513
13514 void
13515 _bfd_elf_gc_keep (struct bfd_link_info *info)
13516 {
13517   struct bfd_sym_chain *sym;
13518
13519   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
13520     {
13521       struct elf_link_hash_entry *h;
13522
13523       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
13524                                 FALSE, FALSE, FALSE);
13525
13526       if (h != NULL
13527           && (h->root.type == bfd_link_hash_defined
13528               || h->root.type == bfd_link_hash_defweak)
13529           && !bfd_is_abs_section (h->root.u.def.section)
13530           && !bfd_is_und_section (h->root.u.def.section))
13531         h->root.u.def.section->flags |= SEC_KEEP;
13532     }
13533 }
13534
13535 bfd_boolean
13536 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
13537                                 struct bfd_link_info *info)
13538 {
13539   bfd *ibfd = info->input_bfds;
13540
13541   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13542     {
13543       asection *sec;
13544       struct elf_reloc_cookie cookie;
13545
13546       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13547         continue;
13548       sec = ibfd->sections;
13549       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13550         continue;
13551
13552       if (!init_reloc_cookie (&cookie, info, ibfd))
13553         return FALSE;
13554
13555       for (sec = ibfd->sections; sec; sec = sec->next)
13556         {
13557           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
13558               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
13559             {
13560               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
13561               fini_reloc_cookie_rels (&cookie, sec);
13562             }
13563         }
13564     }
13565   return TRUE;
13566 }
13567
13568 /* Do mark and sweep of unused sections.  */
13569
13570 bfd_boolean
13571 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
13572 {
13573   bfd_boolean ok = TRUE;
13574   bfd *sub;
13575   elf_gc_mark_hook_fn gc_mark_hook;
13576   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13577   struct elf_link_hash_table *htab;
13578
13579   if (!bed->can_gc_sections
13580       || !is_elf_hash_table (info->hash))
13581     {
13582       _bfd_error_handler(_("warning: gc-sections option ignored"));
13583       return TRUE;
13584     }
13585
13586   bed->gc_keep (info);
13587   htab = elf_hash_table (info);
13588
13589   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
13590      at the .eh_frame section if we can mark the FDEs individually.  */
13591   for (sub = info->input_bfds;
13592        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
13593        sub = sub->link.next)
13594     {
13595       asection *sec;
13596       struct elf_reloc_cookie cookie;
13597
13598       sec = sub->sections;
13599       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13600         continue;
13601       sec = bfd_get_section_by_name (sub, ".eh_frame");
13602       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
13603         {
13604           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
13605           if (elf_section_data (sec)->sec_info
13606               && (sec->flags & SEC_LINKER_CREATED) == 0)
13607             elf_eh_frame_section (sub) = sec;
13608           fini_reloc_cookie_for_section (&cookie, sec);
13609           sec = bfd_get_next_section_by_name (NULL, sec);
13610         }
13611     }
13612
13613   /* Apply transitive closure to the vtable entry usage info.  */
13614   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
13615   if (!ok)
13616     return FALSE;
13617
13618   /* Kill the vtable relocations that were not used.  */
13619   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
13620   if (!ok)
13621     return FALSE;
13622
13623   /* Mark dynamically referenced symbols.  */
13624   if (htab->dynamic_sections_created || info->gc_keep_exported)
13625     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
13626
13627   /* Grovel through relocs to find out who stays ...  */
13628   gc_mark_hook = bed->gc_mark_hook;
13629   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13630     {
13631       asection *o;
13632
13633       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13634           || elf_object_id (sub) != elf_hash_table_id (htab)
13635           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13636         continue;
13637
13638       o = sub->sections;
13639       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13640         continue;
13641
13642       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
13643          Also treat note sections as a root, if the section is not part
13644          of a group.  We must keep all PREINIT_ARRAY, INIT_ARRAY as
13645          well as FINI_ARRAY sections for ld -r.  */
13646       for (o = sub->sections; o != NULL; o = o->next)
13647         if (!o->gc_mark
13648             && (o->flags & SEC_EXCLUDE) == 0
13649             && ((o->flags & SEC_KEEP) != 0
13650                 || (bfd_link_relocatable (info)
13651                     && ((elf_section_data (o)->this_hdr.sh_type
13652                          == SHT_PREINIT_ARRAY)
13653                         || (elf_section_data (o)->this_hdr.sh_type
13654                             == SHT_INIT_ARRAY)
13655                         || (elf_section_data (o)->this_hdr.sh_type
13656                             == SHT_FINI_ARRAY)))
13657                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
13658                     && elf_next_in_group (o) == NULL )))
13659           {
13660             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
13661               return FALSE;
13662           }
13663     }
13664
13665   /* Allow the backend to mark additional target specific sections.  */
13666   bed->gc_mark_extra_sections (info, gc_mark_hook);
13667
13668   /* ... and mark SEC_EXCLUDE for those that go.  */
13669   return elf_gc_sweep (abfd, info);
13670 }
13671 \f
13672 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
13673
13674 bfd_boolean
13675 bfd_elf_gc_record_vtinherit (bfd *abfd,
13676                              asection *sec,
13677                              struct elf_link_hash_entry *h,
13678                              bfd_vma offset)
13679 {
13680   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
13681   struct elf_link_hash_entry **search, *child;
13682   size_t extsymcount;
13683   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13684
13685   /* The sh_info field of the symtab header tells us where the
13686      external symbols start.  We don't care about the local symbols at
13687      this point.  */
13688   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
13689   if (!elf_bad_symtab (abfd))
13690     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
13691
13692   sym_hashes = elf_sym_hashes (abfd);
13693   sym_hashes_end = sym_hashes + extsymcount;
13694
13695   /* Hunt down the child symbol, which is in this section at the same
13696      offset as the relocation.  */
13697   for (search = sym_hashes; search != sym_hashes_end; ++search)
13698     {
13699       if ((child = *search) != NULL
13700           && (child->root.type == bfd_link_hash_defined
13701               || child->root.type == bfd_link_hash_defweak)
13702           && child->root.u.def.section == sec
13703           && child->root.u.def.value == offset)
13704         goto win;
13705     }
13706
13707   /* xgettext:c-format */
13708   _bfd_error_handler (_("%pB: %pA+%#" PRIx64 ": no symbol found for INHERIT"),
13709                       abfd, sec, (uint64_t) offset);
13710   bfd_set_error (bfd_error_invalid_operation);
13711   return FALSE;
13712
13713  win:
13714   if (!child->u2.vtable)
13715     {
13716       child->u2.vtable = ((struct elf_link_virtual_table_entry *)
13717                           bfd_zalloc (abfd, sizeof (*child->u2.vtable)));
13718       if (!child->u2.vtable)
13719         return FALSE;
13720     }
13721   if (!h)
13722     {
13723       /* This *should* only be the absolute section.  It could potentially
13724          be that someone has defined a non-global vtable though, which
13725          would be bad.  It isn't worth paging in the local symbols to be
13726          sure though; that case should simply be handled by the assembler.  */
13727
13728       child->u2.vtable->parent = (struct elf_link_hash_entry *) -1;
13729     }
13730   else
13731     child->u2.vtable->parent = h;
13732
13733   return TRUE;
13734 }
13735
13736 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
13737
13738 bfd_boolean
13739 bfd_elf_gc_record_vtentry (bfd *abfd, asection *sec,
13740                            struct elf_link_hash_entry *h,
13741                            bfd_vma addend)
13742 {
13743   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13744   unsigned int log_file_align = bed->s->log_file_align;
13745
13746   if (!h)
13747     {
13748       /* xgettext:c-format */
13749       _bfd_error_handler (_("%pB: section '%pA': corrupt VTENTRY entry"),
13750                           abfd, sec);
13751       bfd_set_error (bfd_error_bad_value);
13752       return FALSE;
13753     }
13754
13755   if (!h->u2.vtable)
13756     {
13757       h->u2.vtable = ((struct elf_link_virtual_table_entry *)
13758                       bfd_zalloc (abfd, sizeof (*h->u2.vtable)));
13759       if (!h->u2.vtable)
13760         return FALSE;
13761     }
13762
13763   if (addend >= h->u2.vtable->size)
13764     {
13765       size_t size, bytes, file_align;
13766       bfd_boolean *ptr = h->u2.vtable->used;
13767
13768       /* While the symbol is undefined, we have to be prepared to handle
13769          a zero size.  */
13770       file_align = 1 << log_file_align;
13771       if (h->root.type == bfd_link_hash_undefined)
13772         size = addend + file_align;
13773       else
13774         {
13775           size = h->size;
13776           if (addend >= size)
13777             {
13778               /* Oops!  We've got a reference past the defined end of
13779                  the table.  This is probably a bug -- shall we warn?  */
13780               size = addend + file_align;
13781             }
13782         }
13783       size = (size + file_align - 1) & -file_align;
13784
13785       /* Allocate one extra entry for use as a "done" flag for the
13786          consolidation pass.  */
13787       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
13788
13789       if (ptr)
13790         {
13791           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
13792
13793           if (ptr != NULL)
13794             {
13795               size_t oldbytes;
13796
13797               oldbytes = (((h->u2.vtable->size >> log_file_align) + 1)
13798                           * sizeof (bfd_boolean));
13799               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
13800             }
13801         }
13802       else
13803         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
13804
13805       if (ptr == NULL)
13806         return FALSE;
13807
13808       /* And arrange for that done flag to be at index -1.  */
13809       h->u2.vtable->used = ptr + 1;
13810       h->u2.vtable->size = size;
13811     }
13812
13813   h->u2.vtable->used[addend >> log_file_align] = TRUE;
13814
13815   return TRUE;
13816 }
13817
13818 /* Map an ELF section header flag to its corresponding string.  */
13819 typedef struct
13820 {
13821   char *flag_name;
13822   flagword flag_value;
13823 } elf_flags_to_name_table;
13824
13825 static elf_flags_to_name_table elf_flags_to_names [] =
13826 {
13827   { "SHF_WRITE", SHF_WRITE },
13828   { "SHF_ALLOC", SHF_ALLOC },
13829   { "SHF_EXECINSTR", SHF_EXECINSTR },
13830   { "SHF_MERGE", SHF_MERGE },
13831   { "SHF_STRINGS", SHF_STRINGS },
13832   { "SHF_INFO_LINK", SHF_INFO_LINK},
13833   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
13834   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
13835   { "SHF_GROUP", SHF_GROUP },
13836   { "SHF_TLS", SHF_TLS },
13837   { "SHF_MASKOS", SHF_MASKOS },
13838   { "SHF_EXCLUDE", SHF_EXCLUDE },
13839 };
13840
13841 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
13842 bfd_boolean
13843 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
13844                               struct flag_info *flaginfo,
13845                               asection *section)
13846 {
13847   const bfd_vma sh_flags = elf_section_flags (section);
13848
13849   if (!flaginfo->flags_initialized)
13850     {
13851       bfd *obfd = info->output_bfd;
13852       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13853       struct flag_info_list *tf = flaginfo->flag_list;
13854       int with_hex = 0;
13855       int without_hex = 0;
13856
13857       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
13858         {
13859           unsigned i;
13860           flagword (*lookup) (char *);
13861
13862           lookup = bed->elf_backend_lookup_section_flags_hook;
13863           if (lookup != NULL)
13864             {
13865               flagword hexval = (*lookup) ((char *) tf->name);
13866
13867               if (hexval != 0)
13868                 {
13869                   if (tf->with == with_flags)
13870                     with_hex |= hexval;
13871                   else if (tf->with == without_flags)
13872                     without_hex |= hexval;
13873                   tf->valid = TRUE;
13874                   continue;
13875                 }
13876             }
13877           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
13878             {
13879               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
13880                 {
13881                   if (tf->with == with_flags)
13882                     with_hex |= elf_flags_to_names[i].flag_value;
13883                   else if (tf->with == without_flags)
13884                     without_hex |= elf_flags_to_names[i].flag_value;
13885                   tf->valid = TRUE;
13886                   break;
13887                 }
13888             }
13889           if (!tf->valid)
13890             {
13891               info->callbacks->einfo
13892                 (_("unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
13893               return FALSE;
13894             }
13895         }
13896       flaginfo->flags_initialized = TRUE;
13897       flaginfo->only_with_flags |= with_hex;
13898       flaginfo->not_with_flags |= without_hex;
13899     }
13900
13901   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
13902     return FALSE;
13903
13904   if ((flaginfo->not_with_flags & sh_flags) != 0)
13905     return FALSE;
13906
13907   return TRUE;
13908 }
13909
13910 struct alloc_got_off_arg {
13911   bfd_vma gotoff;
13912   struct bfd_link_info *info;
13913 };
13914
13915 /* We need a special top-level link routine to convert got reference counts
13916    to real got offsets.  */
13917
13918 static bfd_boolean
13919 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
13920 {
13921   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
13922   bfd *obfd = gofarg->info->output_bfd;
13923   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13924
13925   if (h->got.refcount > 0)
13926     {
13927       h->got.offset = gofarg->gotoff;
13928       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
13929     }
13930   else
13931     h->got.offset = (bfd_vma) -1;
13932
13933   return TRUE;
13934 }
13935
13936 /* And an accompanying bit to work out final got entry offsets once
13937    we're done.  Should be called from final_link.  */
13938
13939 bfd_boolean
13940 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
13941                                         struct bfd_link_info *info)
13942 {
13943   bfd *i;
13944   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13945   bfd_vma gotoff;
13946   struct alloc_got_off_arg gofarg;
13947
13948   BFD_ASSERT (abfd == info->output_bfd);
13949
13950   if (! is_elf_hash_table (info->hash))
13951     return FALSE;
13952
13953   /* The GOT offset is relative to the .got section, but the GOT header is
13954      put into the .got.plt section, if the backend uses it.  */
13955   if (bed->want_got_plt)
13956     gotoff = 0;
13957   else
13958     gotoff = bed->got_header_size;
13959
13960   /* Do the local .got entries first.  */
13961   for (i = info->input_bfds; i; i = i->link.next)
13962     {
13963       bfd_signed_vma *local_got;
13964       size_t j, locsymcount;
13965       Elf_Internal_Shdr *symtab_hdr;
13966
13967       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13968         continue;
13969
13970       local_got = elf_local_got_refcounts (i);
13971       if (!local_got)
13972         continue;
13973
13974       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13975       if (elf_bad_symtab (i))
13976         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13977       else
13978         locsymcount = symtab_hdr->sh_info;
13979
13980       for (j = 0; j < locsymcount; ++j)
13981         {
13982           if (local_got[j] > 0)
13983             {
13984               local_got[j] = gotoff;
13985               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13986             }
13987           else
13988             local_got[j] = (bfd_vma) -1;
13989         }
13990     }
13991
13992   /* Then the global .got entries.  .plt refcounts are handled by
13993      adjust_dynamic_symbol  */
13994   gofarg.gotoff = gotoff;
13995   gofarg.info = info;
13996   elf_link_hash_traverse (elf_hash_table (info),
13997                           elf_gc_allocate_got_offsets,
13998                           &gofarg);
13999   return TRUE;
14000 }
14001
14002 /* Many folk need no more in the way of final link than this, once
14003    got entry reference counting is enabled.  */
14004
14005 bfd_boolean
14006 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
14007 {
14008   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
14009     return FALSE;
14010
14011   /* Invoke the regular ELF backend linker to do all the work.  */
14012   return bfd_elf_final_link (abfd, info);
14013 }
14014
14015 bfd_boolean
14016 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
14017 {
14018   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
14019
14020   if (rcookie->bad_symtab)
14021     rcookie->rel = rcookie->rels;
14022
14023   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
14024     {
14025       unsigned long r_symndx;
14026
14027       if (! rcookie->bad_symtab)
14028         if (rcookie->rel->r_offset > offset)
14029           return FALSE;
14030       if (rcookie->rel->r_offset != offset)
14031         continue;
14032
14033       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
14034       if (r_symndx == STN_UNDEF)
14035         return TRUE;
14036
14037       if (r_symndx >= rcookie->locsymcount
14038           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
14039         {
14040           struct elf_link_hash_entry *h;
14041
14042           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
14043
14044           while (h->root.type == bfd_link_hash_indirect
14045                  || h->root.type == bfd_link_hash_warning)
14046             h = (struct elf_link_hash_entry *) h->root.u.i.link;
14047
14048           if ((h->root.type == bfd_link_hash_defined
14049                || h->root.type == bfd_link_hash_defweak)
14050               && (h->root.u.def.section->owner != rcookie->abfd
14051                   || h->root.u.def.section->kept_section != NULL
14052                   || discarded_section (h->root.u.def.section)))
14053             return TRUE;
14054         }
14055       else
14056         {
14057           /* It's not a relocation against a global symbol,
14058              but it could be a relocation against a local
14059              symbol for a discarded section.  */
14060           asection *isec;
14061           Elf_Internal_Sym *isym;
14062
14063           /* Need to: get the symbol; get the section.  */
14064           isym = &rcookie->locsyms[r_symndx];
14065           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
14066           if (isec != NULL
14067               && (isec->kept_section != NULL
14068                   || discarded_section (isec)))
14069             return TRUE;
14070         }
14071       return FALSE;
14072     }
14073   return FALSE;
14074 }
14075
14076 /* Discard unneeded references to discarded sections.
14077    Returns -1 on error, 1 if any section's size was changed, 0 if
14078    nothing changed.  This function assumes that the relocations are in
14079    sorted order, which is true for all known assemblers.  */
14080
14081 int
14082 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
14083 {
14084   struct elf_reloc_cookie cookie;
14085   asection *o;
14086   bfd *abfd;
14087   int changed = 0;
14088
14089   if (info->traditional_format
14090       || !is_elf_hash_table (info->hash))
14091     return 0;
14092
14093   o = bfd_get_section_by_name (output_bfd, ".stab");
14094   if (o != NULL)
14095     {
14096       asection *i;
14097
14098       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
14099         {
14100           if (i->size == 0
14101               || i->reloc_count == 0
14102               || i->sec_info_type != SEC_INFO_TYPE_STABS)
14103             continue;
14104
14105           abfd = i->owner;
14106           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
14107             continue;
14108
14109           if (!init_reloc_cookie_for_section (&cookie, info, i))
14110             return -1;
14111
14112           if (_bfd_discard_section_stabs (abfd, i,
14113                                           elf_section_data (i)->sec_info,
14114                                           bfd_elf_reloc_symbol_deleted_p,
14115                                           &cookie))
14116             changed = 1;
14117
14118           fini_reloc_cookie_for_section (&cookie, i);
14119         }
14120     }
14121
14122   o = NULL;
14123   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
14124     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
14125   if (o != NULL)
14126     {
14127       asection *i;
14128       int eh_changed = 0;
14129       unsigned int eh_alignment;
14130
14131       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
14132         {
14133           if (i->size == 0)
14134             continue;
14135
14136           abfd = i->owner;
14137           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
14138             continue;
14139
14140           if (!init_reloc_cookie_for_section (&cookie, info, i))
14141             return -1;
14142
14143           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
14144           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
14145                                                  bfd_elf_reloc_symbol_deleted_p,
14146                                                  &cookie))
14147             {
14148               eh_changed = 1;
14149               if (i->size != i->rawsize)
14150                 changed = 1;
14151             }
14152
14153           fini_reloc_cookie_for_section (&cookie, i);
14154         }
14155
14156       eh_alignment = 1 << o->alignment_power;
14157       /* Skip over zero terminator, and prevent empty sections from
14158          adding alignment padding at the end.  */
14159       for (i = o->map_tail.s; i != NULL; i = i->map_tail.s)
14160         if (i->size == 0)
14161           i->flags |= SEC_EXCLUDE;
14162         else if (i->size > 4)
14163           break;
14164       /* The last non-empty eh_frame section doesn't need padding.  */
14165       if (i != NULL)
14166         i = i->map_tail.s;
14167       /* Any prior sections must pad the last FDE out to the output
14168          section alignment.  Otherwise we might have zero padding
14169          between sections, which would be seen as a terminator.  */
14170       for (; i != NULL; i = i->map_tail.s)
14171         if (i->size == 4)
14172           /* All but the last zero terminator should have been removed.  */
14173           BFD_FAIL ();
14174         else
14175           {
14176             bfd_size_type size
14177               = (i->size + eh_alignment - 1) & -eh_alignment;
14178             if (i->size != size)
14179               {
14180                 i->size = size;
14181                 changed = 1;
14182                 eh_changed = 1;
14183               }
14184           }
14185       if (eh_changed)
14186         elf_link_hash_traverse (elf_hash_table (info),
14187                                 _bfd_elf_adjust_eh_frame_global_symbol, NULL);
14188     }
14189
14190   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
14191     {
14192       const struct elf_backend_data *bed;
14193       asection *s;
14194
14195       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
14196         continue;
14197       s = abfd->sections;
14198       if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
14199         continue;
14200
14201       bed = get_elf_backend_data (abfd);
14202
14203       if (bed->elf_backend_discard_info != NULL)
14204         {
14205           if (!init_reloc_cookie (&cookie, info, abfd))
14206             return -1;
14207
14208           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
14209             changed = 1;
14210
14211           fini_reloc_cookie (&cookie, abfd);
14212         }
14213     }
14214
14215   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
14216     _bfd_elf_end_eh_frame_parsing (info);
14217
14218   if (info->eh_frame_hdr_type
14219       && !bfd_link_relocatable (info)
14220       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
14221     changed = 1;
14222
14223   return changed;
14224 }
14225
14226 bfd_boolean
14227 _bfd_elf_section_already_linked (bfd *abfd,
14228                                  asection *sec,
14229                                  struct bfd_link_info *info)
14230 {
14231   flagword flags;
14232   const char *name, *key;
14233   struct bfd_section_already_linked *l;
14234   struct bfd_section_already_linked_hash_entry *already_linked_list;
14235
14236   if (sec->output_section == bfd_abs_section_ptr)
14237     return FALSE;
14238
14239   flags = sec->flags;
14240
14241   /* Return if it isn't a linkonce section.  A comdat group section
14242      also has SEC_LINK_ONCE set.  */
14243   if ((flags & SEC_LINK_ONCE) == 0)
14244     return FALSE;
14245
14246   /* Don't put group member sections on our list of already linked
14247      sections.  They are handled as a group via their group section.  */
14248   if (elf_sec_group (sec) != NULL)
14249     return FALSE;
14250
14251   /* For a SHT_GROUP section, use the group signature as the key.  */
14252   name = sec->name;
14253   if ((flags & SEC_GROUP) != 0
14254       && elf_next_in_group (sec) != NULL
14255       && elf_group_name (elf_next_in_group (sec)) != NULL)
14256     key = elf_group_name (elf_next_in_group (sec));
14257   else
14258     {
14259       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
14260       if (CONST_STRNEQ (name, ".gnu.linkonce.")
14261           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
14262         key++;
14263       else
14264         /* Must be a user linkonce section that doesn't follow gcc's
14265            naming convention.  In this case we won't be matching
14266            single member groups.  */
14267         key = name;
14268     }
14269
14270   already_linked_list = bfd_section_already_linked_table_lookup (key);
14271
14272   for (l = already_linked_list->entry; l != NULL; l = l->next)
14273     {
14274       /* We may have 2 different types of sections on the list: group
14275          sections with a signature of <key> (<key> is some string),
14276          and linkonce sections named .gnu.linkonce.<type>.<key>.
14277          Match like sections.  LTO plugin sections are an exception.
14278          They are always named .gnu.linkonce.t.<key> and match either
14279          type of section.  */
14280       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
14281            && ((flags & SEC_GROUP) != 0
14282                || strcmp (name, l->sec->name) == 0))
14283           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
14284         {
14285           /* The section has already been linked.  See if we should
14286              issue a warning.  */
14287           if (!_bfd_handle_already_linked (sec, l, info))
14288             return FALSE;
14289
14290           if (flags & SEC_GROUP)
14291             {
14292               asection *first = elf_next_in_group (sec);
14293               asection *s = first;
14294
14295               while (s != NULL)
14296                 {
14297                   s->output_section = bfd_abs_section_ptr;
14298                   /* Record which group discards it.  */
14299                   s->kept_section = l->sec;
14300                   s = elf_next_in_group (s);
14301                   /* These lists are circular.  */
14302                   if (s == first)
14303                     break;
14304                 }
14305             }
14306
14307           return TRUE;
14308         }
14309     }
14310
14311   /* A single member comdat group section may be discarded by a
14312      linkonce section and vice versa.  */
14313   if ((flags & SEC_GROUP) != 0)
14314     {
14315       asection *first = elf_next_in_group (sec);
14316
14317       if (first != NULL && elf_next_in_group (first) == first)
14318         /* Check this single member group against linkonce sections.  */
14319         for (l = already_linked_list->entry; l != NULL; l = l->next)
14320           if ((l->sec->flags & SEC_GROUP) == 0
14321               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
14322             {
14323               first->output_section = bfd_abs_section_ptr;
14324               first->kept_section = l->sec;
14325               sec->output_section = bfd_abs_section_ptr;
14326               break;
14327             }
14328     }
14329   else
14330     /* Check this linkonce section against single member groups.  */
14331     for (l = already_linked_list->entry; l != NULL; l = l->next)
14332       if (l->sec->flags & SEC_GROUP)
14333         {
14334           asection *first = elf_next_in_group (l->sec);
14335
14336           if (first != NULL
14337               && elf_next_in_group (first) == first
14338               && bfd_elf_match_symbols_in_sections (first, sec, info))
14339             {
14340               sec->output_section = bfd_abs_section_ptr;
14341               sec->kept_section = first;
14342               break;
14343             }
14344         }
14345
14346   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
14347      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
14348      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
14349      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
14350      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
14351      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
14352      `.gnu.linkonce.t.F' section from a different bfd not requiring any
14353      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
14354      The reverse order cannot happen as there is never a bfd with only the
14355      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
14356      matter as here were are looking only for cross-bfd sections.  */
14357
14358   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
14359     for (l = already_linked_list->entry; l != NULL; l = l->next)
14360       if ((l->sec->flags & SEC_GROUP) == 0
14361           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
14362         {
14363           if (abfd != l->sec->owner)
14364             sec->output_section = bfd_abs_section_ptr;
14365           break;
14366         }
14367
14368   /* This is the first section with this name.  Record it.  */
14369   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
14370     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
14371   return sec->output_section == bfd_abs_section_ptr;
14372 }
14373
14374 bfd_boolean
14375 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
14376 {
14377   return sym->st_shndx == SHN_COMMON;
14378 }
14379
14380 unsigned int
14381 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
14382 {
14383   return SHN_COMMON;
14384 }
14385
14386 asection *
14387 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
14388 {
14389   return bfd_com_section_ptr;
14390 }
14391
14392 bfd_vma
14393 _bfd_elf_default_got_elt_size (bfd *abfd,
14394                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
14395                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
14396                                bfd *ibfd ATTRIBUTE_UNUSED,
14397                                unsigned long symndx ATTRIBUTE_UNUSED)
14398 {
14399   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14400   return bed->s->arch_size / 8;
14401 }
14402
14403 /* Routines to support the creation of dynamic relocs.  */
14404
14405 /* Returns the name of the dynamic reloc section associated with SEC.  */
14406
14407 static const char *
14408 get_dynamic_reloc_section_name (bfd *       abfd,
14409                                 asection *  sec,
14410                                 bfd_boolean is_rela)
14411 {
14412   char *name;
14413   const char *old_name = bfd_get_section_name (NULL, sec);
14414   const char *prefix = is_rela ? ".rela" : ".rel";
14415
14416   if (old_name == NULL)
14417     return NULL;
14418
14419   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
14420   sprintf (name, "%s%s", prefix, old_name);
14421
14422   return name;
14423 }
14424
14425 /* Returns the dynamic reloc section associated with SEC.
14426    If necessary compute the name of the dynamic reloc section based
14427    on SEC's name (looked up in ABFD's string table) and the setting
14428    of IS_RELA.  */
14429
14430 asection *
14431 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
14432                                     asection *  sec,
14433                                     bfd_boolean is_rela)
14434 {
14435   asection * reloc_sec = elf_section_data (sec)->sreloc;
14436
14437   if (reloc_sec == NULL)
14438     {
14439       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14440
14441       if (name != NULL)
14442         {
14443           reloc_sec = bfd_get_linker_section (abfd, name);
14444
14445           if (reloc_sec != NULL)
14446             elf_section_data (sec)->sreloc = reloc_sec;
14447         }
14448     }
14449
14450   return reloc_sec;
14451 }
14452
14453 /* Returns the dynamic reloc section associated with SEC.  If the
14454    section does not exist it is created and attached to the DYNOBJ
14455    bfd and stored in the SRELOC field of SEC's elf_section_data
14456    structure.
14457
14458    ALIGNMENT is the alignment for the newly created section and
14459    IS_RELA defines whether the name should be .rela.<SEC's name>
14460    or .rel.<SEC's name>.  The section name is looked up in the
14461    string table associated with ABFD.  */
14462
14463 asection *
14464 _bfd_elf_make_dynamic_reloc_section (asection *sec,
14465                                      bfd *dynobj,
14466                                      unsigned int alignment,
14467                                      bfd *abfd,
14468                                      bfd_boolean is_rela)
14469 {
14470   asection * reloc_sec = elf_section_data (sec)->sreloc;
14471
14472   if (reloc_sec == NULL)
14473     {
14474       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14475
14476       if (name == NULL)
14477         return NULL;
14478
14479       reloc_sec = bfd_get_linker_section (dynobj, name);
14480
14481       if (reloc_sec == NULL)
14482         {
14483           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
14484                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
14485           if ((sec->flags & SEC_ALLOC) != 0)
14486             flags |= SEC_ALLOC | SEC_LOAD;
14487
14488           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
14489           if (reloc_sec != NULL)
14490             {
14491               /* _bfd_elf_get_sec_type_attr chooses a section type by
14492                  name.  Override as it may be wrong, eg. for a user
14493                  section named "auto" we'll get ".relauto" which is
14494                  seen to be a .rela section.  */
14495               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
14496               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
14497                 reloc_sec = NULL;
14498             }
14499         }
14500
14501       elf_section_data (sec)->sreloc = reloc_sec;
14502     }
14503
14504   return reloc_sec;
14505 }
14506
14507 /* Copy the ELF symbol type and other attributes for a linker script
14508    assignment from HSRC to HDEST.  Generally this should be treated as
14509    if we found a strong non-dynamic definition for HDEST (except that
14510    ld ignores multiple definition errors).  */
14511 void
14512 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
14513                                      struct bfd_link_hash_entry *hdest,
14514                                      struct bfd_link_hash_entry *hsrc)
14515 {
14516   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
14517   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
14518   Elf_Internal_Sym isym;
14519
14520   ehdest->type = ehsrc->type;
14521   ehdest->target_internal = ehsrc->target_internal;
14522
14523   isym.st_other = ehsrc->other;
14524   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
14525 }
14526
14527 /* Append a RELA relocation REL to section S in BFD.  */
14528
14529 void
14530 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14531 {
14532   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14533   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
14534   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
14535   bed->s->swap_reloca_out (abfd, rel, loc);
14536 }
14537
14538 /* Append a REL relocation REL to section S in BFD.  */
14539
14540 void
14541 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14542 {
14543   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14544   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
14545   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
14546   bed->s->swap_reloc_out (abfd, rel, loc);
14547 }
14548
14549 /* Define __start, __stop, .startof. or .sizeof. symbol.  */
14550
14551 struct bfd_link_hash_entry *
14552 bfd_elf_define_start_stop (struct bfd_link_info *info,
14553                            const char *symbol, asection *sec)
14554 {
14555   struct elf_link_hash_entry *h;
14556
14557   h = elf_link_hash_lookup (elf_hash_table (info), symbol,
14558                             FALSE, FALSE, TRUE);
14559   if (h != NULL
14560       && (h->root.type == bfd_link_hash_undefined
14561           || h->root.type == bfd_link_hash_undefweak
14562           || ((h->ref_regular || h->def_dynamic) && !h->def_regular)))
14563     {
14564       bfd_boolean was_dynamic = h->ref_dynamic || h->def_dynamic;
14565       h->root.type = bfd_link_hash_defined;
14566       h->root.u.def.section = sec;
14567       h->root.u.def.value = 0;
14568       h->def_regular = 1;
14569       h->def_dynamic = 0;
14570       h->start_stop = 1;
14571       h->u2.start_stop_section = sec;
14572       if (symbol[0] == '.')
14573         {
14574           /* .startof. and .sizeof. symbols are local.  */
14575           const struct elf_backend_data *bed;
14576           bed = get_elf_backend_data (info->output_bfd);
14577           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
14578         }
14579       else
14580         {
14581           if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
14582             h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_PROTECTED;
14583           if (was_dynamic)
14584             bfd_elf_link_record_dynamic_symbol (info, h);
14585         }
14586       return &h->root;
14587     }
14588   return NULL;
14589 }