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