PR24857, ld: error adding symbols: bad value
[external/binutils.git] / bfd / elflink.c
1 /* ELF linking support for BFD.
2    Copyright (C) 1995-2019 Free Software Foundation, Inc.
3
4    This file is part of BFD, the Binary File Descriptor library.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
19    MA 02110-1301, USA.  */
20
21 #include "sysdep.h"
22 #include "bfd.h"
23 #include "bfdlink.h"
24 #include "libbfd.h"
25 #define ARCH_SIZE 0
26 #include "elf-bfd.h"
27 #include "safe-ctype.h"
28 #include "libiberty.h"
29 #include "objalloc.h"
30 #if BFD_SUPPORTS_PLUGINS
31 #include "plugin-api.h"
32 #include "plugin.h"
33 #endif
34
35 /* This struct is used to pass information to routines called via
36    elf_link_hash_traverse which must return failure.  */
37
38 struct elf_info_failed
39 {
40   struct bfd_link_info *info;
41   bfd_boolean failed;
42 };
43
44 /* This structure is used to pass information to
45    _bfd_elf_link_find_version_dependencies.  */
46
47 struct elf_find_verdep_info
48 {
49   /* General link information.  */
50   struct bfd_link_info *info;
51   /* The number of dependencies.  */
52   unsigned int vers;
53   /* Whether we had a failure.  */
54   bfd_boolean failed;
55 };
56
57 static bfd_boolean _bfd_elf_fix_symbol_flags
58   (struct elf_link_hash_entry *, struct elf_info_failed *);
59
60 asection *
61 _bfd_elf_section_for_symbol (struct elf_reloc_cookie *cookie,
62                              unsigned long r_symndx,
63                              bfd_boolean discard)
64 {
65   if (r_symndx >= cookie->locsymcount
66       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
67     {
68       struct elf_link_hash_entry *h;
69
70       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
71
72       while (h->root.type == bfd_link_hash_indirect
73              || h->root.type == bfd_link_hash_warning)
74         h = (struct elf_link_hash_entry *) h->root.u.i.link;
75
76       if ((h->root.type == bfd_link_hash_defined
77            || h->root.type == bfd_link_hash_defweak)
78            && discarded_section (h->root.u.def.section))
79         return h->root.u.def.section;
80       else
81         return NULL;
82     }
83   else
84     {
85       /* It's not a relocation against a global symbol,
86          but it could be a relocation against a local
87          symbol for a discarded section.  */
88       asection *isec;
89       Elf_Internal_Sym *isym;
90
91       /* Need to: get the symbol; get the section.  */
92       isym = &cookie->locsyms[r_symndx];
93       isec = bfd_section_from_elf_index (cookie->abfd, isym->st_shndx);
94       if (isec != NULL
95           && discard ? discarded_section (isec) : 1)
96         return isec;
97      }
98   return NULL;
99 }
100
101 /* Define a symbol in a dynamic linkage section.  */
102
103 struct elf_link_hash_entry *
104 _bfd_elf_define_linkage_sym (bfd *abfd,
105                              struct bfd_link_info *info,
106                              asection *sec,
107                              const char *name)
108 {
109   struct elf_link_hash_entry *h;
110   struct bfd_link_hash_entry *bh;
111   const struct elf_backend_data *bed;
112
113   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
114   if (h != NULL)
115     {
116       /* Zap symbol defined in an as-needed lib that wasn't linked.
117          This is a symptom of a larger problem:  Absolute symbols
118          defined in shared libraries can't be overridden, because we
119          lose the link to the bfd which is via the symbol section.  */
120       h->root.type = bfd_link_hash_new;
121       bh = &h->root;
122     }
123   else
124     bh = NULL;
125
126   bed = get_elf_backend_data (abfd);
127   if (!_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL,
128                                          sec, 0, NULL, FALSE, bed->collect,
129                                          &bh))
130     return NULL;
131   h = (struct elf_link_hash_entry *) bh;
132   BFD_ASSERT (h != NULL);
133   h->def_regular = 1;
134   h->non_elf = 0;
135   h->root.linker_def = 1;
136   h->type = STT_OBJECT;
137   if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
138     h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
139
140   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
141   return h;
142 }
143
144 bfd_boolean
145 _bfd_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
146 {
147   flagword flags;
148   asection *s;
149   struct elf_link_hash_entry *h;
150   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
151   struct elf_link_hash_table *htab = elf_hash_table (info);
152
153   /* This function may be called more than once.  */
154   if (htab->sgot != NULL)
155     return TRUE;
156
157   flags = bed->dynamic_sec_flags;
158
159   s = bfd_make_section_anyway_with_flags (abfd,
160                                           (bed->rela_plts_and_copies_p
161                                            ? ".rela.got" : ".rel.got"),
162                                           (bed->dynamic_sec_flags
163                                            | SEC_READONLY));
164   if (s == NULL
165       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
166     return FALSE;
167   htab->srelgot = s;
168
169   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
170   if (s == NULL
171       || !bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
172     return FALSE;
173   htab->sgot = s;
174
175   if (bed->want_got_plt)
176     {
177       s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
178       if (s == NULL
179           || !bfd_set_section_alignment (abfd, s,
180                                          bed->s->log_file_align))
181         return FALSE;
182       htab->sgotplt = s;
183     }
184
185   /* The first bit of the global offset table is the header.  */
186   s->size += bed->got_header_size;
187
188   if (bed->want_got_sym)
189     {
190       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
191          (or .got.plt) section.  We don't do this in the linker script
192          because we don't want to define the symbol if we are not creating
193          a global offset table.  */
194       h = _bfd_elf_define_linkage_sym (abfd, info, s,
195                                        "_GLOBAL_OFFSET_TABLE_");
196       elf_hash_table (info)->hgot = h;
197       if (h == NULL)
198         return FALSE;
199     }
200
201   return TRUE;
202 }
203 \f
204 /* Create a strtab to hold the dynamic symbol names.  */
205 static bfd_boolean
206 _bfd_elf_link_create_dynstrtab (bfd *abfd, struct bfd_link_info *info)
207 {
208   struct elf_link_hash_table *hash_table;
209
210   hash_table = elf_hash_table (info);
211   if (hash_table->dynobj == NULL)
212     {
213       /* We may not set dynobj, an input file holding linker created
214          dynamic sections to abfd, which may be a dynamic object with
215          its own dynamic sections.  We need to find a normal input file
216          to hold linker created sections if possible.  */
217       if ((abfd->flags & (DYNAMIC | BFD_PLUGIN)) != 0)
218         {
219           bfd *ibfd;
220           asection *s;
221           for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link.next)
222             if ((ibfd->flags
223                  & (DYNAMIC | BFD_LINKER_CREATED | BFD_PLUGIN)) == 0
224                 && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
225                 && elf_object_id (ibfd) == elf_hash_table_id (hash_table)
226                 && !((s = ibfd->sections) != NULL
227                      && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS))
228               {
229                 abfd = ibfd;
230                 break;
231               }
232         }
233       hash_table->dynobj = abfd;
234     }
235
236   if (hash_table->dynstr == NULL)
237     {
238       hash_table->dynstr = _bfd_elf_strtab_init ();
239       if (hash_table->dynstr == NULL)
240         return FALSE;
241     }
242   return TRUE;
243 }
244
245 /* Create some sections which will be filled in with dynamic linking
246    information.  ABFD is an input file which requires dynamic sections
247    to be created.  The dynamic sections take up virtual memory space
248    when the final executable is run, so we need to create them before
249    addresses are assigned to the output sections.  We work out the
250    actual contents and size of these sections later.  */
251
252 bfd_boolean
253 _bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
254 {
255   flagword flags;
256   asection *s;
257   const struct elf_backend_data *bed;
258   struct elf_link_hash_entry *h;
259
260   if (! is_elf_hash_table (info->hash))
261     return FALSE;
262
263   if (elf_hash_table (info)->dynamic_sections_created)
264     return TRUE;
265
266   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
267     return FALSE;
268
269   abfd = elf_hash_table (info)->dynobj;
270   bed = get_elf_backend_data (abfd);
271
272   flags = bed->dynamic_sec_flags;
273
274   /* A dynamically linked executable has a .interp section, but a
275      shared library does not.  */
276   if (bfd_link_executable (info) && !info->nointerp)
277     {
278       s = bfd_make_section_anyway_with_flags (abfd, ".interp",
279                                               flags | SEC_READONLY);
280       if (s == NULL)
281         return FALSE;
282     }
283
284   /* Create sections to hold version informations.  These are removed
285      if they are not needed.  */
286   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_d",
287                                           flags | SEC_READONLY);
288   if (s == NULL
289       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
290     return FALSE;
291
292   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version",
293                                           flags | SEC_READONLY);
294   if (s == NULL
295       || ! bfd_set_section_alignment (abfd, s, 1))
296     return FALSE;
297
298   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_r",
299                                           flags | SEC_READONLY);
300   if (s == NULL
301       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
302     return FALSE;
303
304   s = bfd_make_section_anyway_with_flags (abfd, ".dynsym",
305                                           flags | SEC_READONLY);
306   if (s == NULL
307       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
308     return FALSE;
309   elf_hash_table (info)->dynsym = s;
310
311   s = bfd_make_section_anyway_with_flags (abfd, ".dynstr",
312                                           flags | SEC_READONLY);
313   if (s == NULL)
314     return FALSE;
315
316   s = bfd_make_section_anyway_with_flags (abfd, ".dynamic", flags);
317   if (s == NULL
318       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
319     return FALSE;
320
321   /* The special symbol _DYNAMIC is always set to the start of the
322      .dynamic section.  We could set _DYNAMIC in a linker script, but we
323      only want to define it if we are, in fact, creating a .dynamic
324      section.  We don't want to define it if there is no .dynamic
325      section, since on some ELF platforms the start up code examines it
326      to decide how to initialize the process.  */
327   h = _bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC");
328   elf_hash_table (info)->hdynamic = h;
329   if (h == NULL)
330     return FALSE;
331
332   if (info->emit_hash)
333     {
334       s = bfd_make_section_anyway_with_flags (abfd, ".hash",
335                                               flags | SEC_READONLY);
336       if (s == NULL
337           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
338         return FALSE;
339       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
340     }
341
342   if (info->emit_gnu_hash)
343     {
344       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
345                                               flags | SEC_READONLY);
346       if (s == NULL
347           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
348         return FALSE;
349       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
350          4 32-bit words followed by variable count of 64-bit words, then
351          variable count of 32-bit words.  */
352       if (bed->s->arch_size == 64)
353         elf_section_data (s)->this_hdr.sh_entsize = 0;
354       else
355         elf_section_data (s)->this_hdr.sh_entsize = 4;
356     }
357
358   /* Let the backend create the rest of the sections.  This lets the
359      backend set the right flags.  The backend will normally create
360      the .got and .plt sections.  */
361   if (bed->elf_backend_create_dynamic_sections == NULL
362       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
363     return FALSE;
364
365   elf_hash_table (info)->dynamic_sections_created = TRUE;
366
367   return TRUE;
368 }
369
370 /* Create dynamic sections when linking against a dynamic object.  */
371
372 bfd_boolean
373 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
374 {
375   flagword flags, pltflags;
376   struct elf_link_hash_entry *h;
377   asection *s;
378   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
379   struct elf_link_hash_table *htab = elf_hash_table (info);
380
381   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
382      .rel[a].bss sections.  */
383   flags = bed->dynamic_sec_flags;
384
385   pltflags = flags;
386   if (bed->plt_not_loaded)
387     /* We do not clear SEC_ALLOC here because we still want the OS to
388        allocate space for the section; it's just that there's nothing
389        to read in from the object file.  */
390     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
391   else
392     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
393   if (bed->plt_readonly)
394     pltflags |= SEC_READONLY;
395
396   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
397   if (s == NULL
398       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
399     return FALSE;
400   htab->splt = s;
401
402   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
403      .plt section.  */
404   if (bed->want_plt_sym)
405     {
406       h = _bfd_elf_define_linkage_sym (abfd, info, s,
407                                        "_PROCEDURE_LINKAGE_TABLE_");
408       elf_hash_table (info)->hplt = h;
409       if (h == NULL)
410         return FALSE;
411     }
412
413   s = bfd_make_section_anyway_with_flags (abfd,
414                                           (bed->rela_plts_and_copies_p
415                                            ? ".rela.plt" : ".rel.plt"),
416                                           flags | SEC_READONLY);
417   if (s == NULL
418       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
419     return FALSE;
420   htab->srelplt = s;
421
422   if (! _bfd_elf_create_got_section (abfd, info))
423     return FALSE;
424
425   if (bed->want_dynbss)
426     {
427       /* The .dynbss section is a place to put symbols which are defined
428          by dynamic objects, are referenced by regular objects, and are
429          not functions.  We must allocate space for them in the process
430          image and use a R_*_COPY reloc to tell the dynamic linker to
431          initialize them at run time.  The linker script puts the .dynbss
432          section into the .bss section of the final image.  */
433       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
434                                               SEC_ALLOC | SEC_LINKER_CREATED);
435       if (s == NULL)
436         return FALSE;
437       htab->sdynbss = s;
438
439       if (bed->want_dynrelro)
440         {
441           /* Similarly, but for symbols that were originally in read-only
442              sections.  This section doesn't really need to have contents,
443              but make it like other .data.rel.ro sections.  */
444           s = bfd_make_section_anyway_with_flags (abfd, ".data.rel.ro",
445                                                   flags);
446           if (s == NULL)
447             return FALSE;
448           htab->sdynrelro = s;
449         }
450
451       /* The .rel[a].bss section holds copy relocs.  This section is not
452          normally needed.  We need to create it here, though, so that the
453          linker will map it to an output section.  We can't just create it
454          only if we need it, because we will not know whether we need it
455          until we have seen all the input files, and the first time the
456          main linker code calls BFD after examining all the input files
457          (size_dynamic_sections) the input sections have already been
458          mapped to the output sections.  If the section turns out not to
459          be needed, we can discard it later.  We will never need this
460          section when generating a shared object, since they do not use
461          copy relocs.  */
462       if (bfd_link_executable (info))
463         {
464           s = bfd_make_section_anyway_with_flags (abfd,
465                                                   (bed->rela_plts_and_copies_p
466                                                    ? ".rela.bss" : ".rel.bss"),
467                                                   flags | SEC_READONLY);
468           if (s == NULL
469               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
470             return FALSE;
471           htab->srelbss = s;
472
473           if (bed->want_dynrelro)
474             {
475               s = (bfd_make_section_anyway_with_flags
476                    (abfd, (bed->rela_plts_and_copies_p
477                            ? ".rela.data.rel.ro" : ".rel.data.rel.ro"),
478                     flags | SEC_READONLY));
479               if (s == NULL
480                   || ! bfd_set_section_alignment (abfd, s,
481                                                   bed->s->log_file_align))
482                 return FALSE;
483               htab->sreldynrelro = s;
484             }
485         }
486     }
487
488   return TRUE;
489 }
490 \f
491 /* Record a new dynamic symbol.  We record the dynamic symbols as we
492    read the input files, since we need to have a list of all of them
493    before we can determine the final sizes of the output sections.
494    Note that we may actually call this function even though we are not
495    going to output any dynamic symbols; in some cases we know that a
496    symbol should be in the dynamic symbol table, but only if there is
497    one.  */
498
499 bfd_boolean
500 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
501                                     struct elf_link_hash_entry *h)
502 {
503   if (h->dynindx == -1)
504     {
505       struct elf_strtab_hash *dynstr;
506       char *p;
507       const char *name;
508       size_t indx;
509
510       /* XXX: The ABI draft says the linker must turn hidden and
511          internal symbols into STB_LOCAL symbols when producing the
512          DSO. However, if ld.so honors st_other in the dynamic table,
513          this would not be necessary.  */
514       switch (ELF_ST_VISIBILITY (h->other))
515         {
516         case STV_INTERNAL:
517         case STV_HIDDEN:
518           if (h->root.type != bfd_link_hash_undefined
519               && h->root.type != bfd_link_hash_undefweak)
520             {
521               h->forced_local = 1;
522               if (!elf_hash_table (info)->is_relocatable_executable)
523                 return TRUE;
524             }
525
526         default:
527           break;
528         }
529
530       h->dynindx = elf_hash_table (info)->dynsymcount;
531       ++elf_hash_table (info)->dynsymcount;
532
533       dynstr = elf_hash_table (info)->dynstr;
534       if (dynstr == NULL)
535         {
536           /* Create a strtab to hold the dynamic symbol names.  */
537           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
538           if (dynstr == NULL)
539             return FALSE;
540         }
541
542       /* We don't put any version information in the dynamic string
543          table.  */
544       name = h->root.root.string;
545       p = strchr (name, ELF_VER_CHR);
546       if (p != NULL)
547         /* We know that the p points into writable memory.  In fact,
548            there are only a few symbols that have read-only names, being
549            those like _GLOBAL_OFFSET_TABLE_ that are created specially
550            by the backends.  Most symbols will have names pointing into
551            an ELF string table read from a file, or to objalloc memory.  */
552         *p = 0;
553
554       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
555
556       if (p != NULL)
557         *p = ELF_VER_CHR;
558
559       if (indx == (size_t) -1)
560         return FALSE;
561       h->dynstr_index = indx;
562     }
563
564   return TRUE;
565 }
566 \f
567 /* Mark a symbol dynamic.  */
568
569 static void
570 bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
571                                   struct elf_link_hash_entry *h,
572                                   Elf_Internal_Sym *sym)
573 {
574   struct bfd_elf_dynamic_list *d = info->dynamic_list;
575
576   /* It may be called more than once on the same H.  */
577   if(h->dynamic || bfd_link_relocatable (info))
578     return;
579
580   if ((info->dynamic_data
581        && (h->type == STT_OBJECT
582            || h->type == STT_COMMON
583            || (sym != NULL
584                && (ELF_ST_TYPE (sym->st_info) == STT_OBJECT
585                    || ELF_ST_TYPE (sym->st_info) == STT_COMMON))))
586       || (d != NULL
587           && h->non_elf
588           && (*d->match) (&d->head, NULL, h->root.root.string)))
589     {
590       h->dynamic = 1;
591       /* NB: If a symbol is made dynamic by --dynamic-list, it has
592          non-IR reference.  */
593       h->root.non_ir_ref_dynamic = 1;
594     }
595 }
596
597 /* Record an assignment to a symbol made by a linker script.  We need
598    this in case some dynamic object refers to this symbol.  */
599
600 bfd_boolean
601 bfd_elf_record_link_assignment (bfd *output_bfd,
602                                 struct bfd_link_info *info,
603                                 const char *name,
604                                 bfd_boolean provide,
605                                 bfd_boolean hidden)
606 {
607   struct elf_link_hash_entry *h, *hv;
608   struct elf_link_hash_table *htab;
609   const struct elf_backend_data *bed;
610
611   if (!is_elf_hash_table (info->hash))
612     return TRUE;
613
614   htab = elf_hash_table (info);
615   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
616   if (h == NULL)
617     return provide;
618
619   if (h->root.type == bfd_link_hash_warning)
620     h = (struct elf_link_hash_entry *) h->root.u.i.link;
621
622   if (h->versioned == unknown)
623     {
624       /* Set versioned if symbol version is unknown.  */
625       char *version = strrchr (name, ELF_VER_CHR);
626       if (version)
627         {
628           if (version > name && version[-1] != ELF_VER_CHR)
629             h->versioned = versioned_hidden;
630           else
631             h->versioned = versioned;
632         }
633     }
634
635   /* Symbols defined in a linker script but not referenced anywhere
636      else will have non_elf set.  */
637   if (h->non_elf)
638     {
639       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
640       h->non_elf = 0;
641     }
642
643   switch (h->root.type)
644     {
645     case bfd_link_hash_defined:
646     case bfd_link_hash_defweak:
647     case bfd_link_hash_common:
648       break;
649     case bfd_link_hash_undefweak:
650     case bfd_link_hash_undefined:
651       /* Since we're defining the symbol, don't let it seem to have not
652          been defined.  record_dynamic_symbol and size_dynamic_sections
653          may depend on this.  */
654       h->root.type = bfd_link_hash_new;
655       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
656         bfd_link_repair_undef_list (&htab->root);
657       break;
658     case bfd_link_hash_new:
659       break;
660     case bfd_link_hash_indirect:
661       /* We had a versioned symbol in a dynamic library.  We make the
662          the versioned symbol point to this one.  */
663       bed = get_elf_backend_data (output_bfd);
664       hv = h;
665       while (hv->root.type == bfd_link_hash_indirect
666              || hv->root.type == bfd_link_hash_warning)
667         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
668       /* We don't need to update h->root.u since linker will set them
669          later.  */
670       h->root.type = bfd_link_hash_undefined;
671       hv->root.type = bfd_link_hash_indirect;
672       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
673       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
674       break;
675     default:
676       BFD_FAIL ();
677       return FALSE;
678     }
679
680   /* If this symbol is being provided by the linker script, and it is
681      currently defined by a dynamic object, but not by a regular
682      object, then mark it as undefined so that the generic linker will
683      force the correct value.  */
684   if (provide
685       && h->def_dynamic
686       && !h->def_regular)
687     h->root.type = bfd_link_hash_undefined;
688
689   /* If this symbol is currently defined by a dynamic object, but not
690      by a regular object, then clear out any version information because
691      the symbol will not be associated with the dynamic object any
692      more.  */
693   if (h->def_dynamic && !h->def_regular)
694     h->verinfo.verdef = NULL;
695
696   /* Make sure this symbol is not garbage collected.  */
697   h->mark = 1;
698
699   h->def_regular = 1;
700
701   if (hidden)
702     {
703       bed = get_elf_backend_data (output_bfd);
704       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
705         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
706       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
707     }
708
709   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
710      and executables.  */
711   if (!bfd_link_relocatable (info)
712       && h->dynindx != -1
713       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
714           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
715     h->forced_local = 1;
716
717   if ((h->def_dynamic
718        || h->ref_dynamic
719        || bfd_link_dll (info)
720        || elf_hash_table (info)->is_relocatable_executable)
721       && !h->forced_local
722       && h->dynindx == -1)
723     {
724       if (! bfd_elf_link_record_dynamic_symbol (info, h))
725         return FALSE;
726
727       /* If this is a weak defined symbol, and we know a corresponding
728          real symbol from the same dynamic object, make sure the real
729          symbol is also made into a dynamic symbol.  */
730       if (h->is_weakalias)
731         {
732           struct elf_link_hash_entry *def = weakdef (h);
733
734           if (def->dynindx == -1
735               && !bfd_elf_link_record_dynamic_symbol (info, def))
736             return FALSE;
737         }
738     }
739
740   return TRUE;
741 }
742
743 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
744    success, and 2 on a failure caused by attempting to record a symbol
745    in a discarded section, eg. a discarded link-once section symbol.  */
746
747 int
748 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
749                                           bfd *input_bfd,
750                                           long input_indx)
751 {
752   bfd_size_type amt;
753   struct elf_link_local_dynamic_entry *entry;
754   struct elf_link_hash_table *eht;
755   struct elf_strtab_hash *dynstr;
756   size_t dynstr_index;
757   char *name;
758   Elf_External_Sym_Shndx eshndx;
759   char esym[sizeof (Elf64_External_Sym)];
760
761   if (! is_elf_hash_table (info->hash))
762     return 0;
763
764   /* See if the entry exists already.  */
765   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
766     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
767       return 1;
768
769   amt = sizeof (*entry);
770   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
771   if (entry == NULL)
772     return 0;
773
774   /* Go find the symbol, so that we can find it's name.  */
775   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
776                              1, input_indx, &entry->isym, esym, &eshndx))
777     {
778       bfd_release (input_bfd, entry);
779       return 0;
780     }
781
782   if (entry->isym.st_shndx != SHN_UNDEF
783       && entry->isym.st_shndx < SHN_LORESERVE)
784     {
785       asection *s;
786
787       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
788       if (s == NULL || bfd_is_abs_section (s->output_section))
789         {
790           /* We can still bfd_release here as nothing has done another
791              bfd_alloc.  We can't do this later in this function.  */
792           bfd_release (input_bfd, entry);
793           return 2;
794         }
795     }
796
797   name = (bfd_elf_string_from_elf_section
798           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
799            entry->isym.st_name));
800
801   dynstr = elf_hash_table (info)->dynstr;
802   if (dynstr == NULL)
803     {
804       /* Create a strtab to hold the dynamic symbol names.  */
805       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
806       if (dynstr == NULL)
807         return 0;
808     }
809
810   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
811   if (dynstr_index == (size_t) -1)
812     return 0;
813   entry->isym.st_name = dynstr_index;
814
815   eht = elf_hash_table (info);
816
817   entry->next = eht->dynlocal;
818   eht->dynlocal = entry;
819   entry->input_bfd = input_bfd;
820   entry->input_indx = input_indx;
821   eht->dynsymcount++;
822
823   /* Whatever binding the symbol had before, it's now local.  */
824   entry->isym.st_info
825     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
826
827   /* The dynindx will be set at the end of size_dynamic_sections.  */
828
829   return 1;
830 }
831
832 /* Return the dynindex of a local dynamic symbol.  */
833
834 long
835 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
836                                     bfd *input_bfd,
837                                     long input_indx)
838 {
839   struct elf_link_local_dynamic_entry *e;
840
841   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
842     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
843       return e->dynindx;
844   return -1;
845 }
846
847 /* This function is used to renumber the dynamic symbols, if some of
848    them are removed because they are marked as local.  This is called
849    via elf_link_hash_traverse.  */
850
851 static bfd_boolean
852 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
853                                       void *data)
854 {
855   size_t *count = (size_t *) data;
856
857   if (h->forced_local)
858     return TRUE;
859
860   if (h->dynindx != -1)
861     h->dynindx = ++(*count);
862
863   return TRUE;
864 }
865
866
867 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
868    STB_LOCAL binding.  */
869
870 static bfd_boolean
871 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
872                                             void *data)
873 {
874   size_t *count = (size_t *) data;
875
876   if (!h->forced_local)
877     return TRUE;
878
879   if (h->dynindx != -1)
880     h->dynindx = ++(*count);
881
882   return TRUE;
883 }
884
885 /* Return true if the dynamic symbol for a given section should be
886    omitted when creating a shared library.  */
887 bfd_boolean
888 _bfd_elf_omit_section_dynsym_default (bfd *output_bfd ATTRIBUTE_UNUSED,
889                                       struct bfd_link_info *info,
890                                       asection *p)
891 {
892   struct elf_link_hash_table *htab;
893   asection *ip;
894
895   switch (elf_section_data (p)->this_hdr.sh_type)
896     {
897     case SHT_PROGBITS:
898     case SHT_NOBITS:
899       /* If sh_type is yet undecided, assume it could be
900          SHT_PROGBITS/SHT_NOBITS.  */
901     case SHT_NULL:
902       htab = elf_hash_table (info);
903       if (htab->text_index_section != NULL)
904         return p != htab->text_index_section && p != htab->data_index_section;
905
906       return (htab->dynobj != NULL
907               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
908               && ip->output_section == p);
909
910       /* There shouldn't be section relative relocations
911          against any other section.  */
912     default:
913       return TRUE;
914     }
915 }
916
917 bfd_boolean
918 _bfd_elf_omit_section_dynsym_all
919     (bfd *output_bfd ATTRIBUTE_UNUSED,
920      struct bfd_link_info *info ATTRIBUTE_UNUSED,
921      asection *p ATTRIBUTE_UNUSED)
922 {
923   return TRUE;
924 }
925
926 /* Assign dynsym indices.  In a shared library we generate a section
927    symbol for each output section, which come first.  Next come symbols
928    which have been forced to local binding.  Then all of the back-end
929    allocated local dynamic syms, followed by the rest of the global
930    symbols.  If SECTION_SYM_COUNT is NULL, section dynindx is not set.
931    (This prevents the early call before elf_backend_init_index_section
932    and strip_excluded_output_sections setting dynindx for sections
933    that are stripped.)  */
934
935 static unsigned long
936 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
937                                 struct bfd_link_info *info,
938                                 unsigned long *section_sym_count)
939 {
940   unsigned long dynsymcount = 0;
941   bfd_boolean do_sec = section_sym_count != NULL;
942
943   if (bfd_link_pic (info)
944       || elf_hash_table (info)->is_relocatable_executable)
945     {
946       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
947       asection *p;
948       for (p = output_bfd->sections; p ; p = p->next)
949         if ((p->flags & SEC_EXCLUDE) == 0
950             && (p->flags & SEC_ALLOC) != 0
951             && elf_hash_table (info)->dynamic_relocs
952             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
953           {
954             ++dynsymcount;
955             if (do_sec)
956               elf_section_data (p)->dynindx = dynsymcount;
957           }
958         else if (do_sec)
959           elf_section_data (p)->dynindx = 0;
960     }
961   if (do_sec)
962     *section_sym_count = dynsymcount;
963
964   elf_link_hash_traverse (elf_hash_table (info),
965                           elf_link_renumber_local_hash_table_dynsyms,
966                           &dynsymcount);
967
968   if (elf_hash_table (info)->dynlocal)
969     {
970       struct elf_link_local_dynamic_entry *p;
971       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
972         p->dynindx = ++dynsymcount;
973     }
974   elf_hash_table (info)->local_dynsymcount = dynsymcount;
975
976   elf_link_hash_traverse (elf_hash_table (info),
977                           elf_link_renumber_hash_table_dynsyms,
978                           &dynsymcount);
979
980   /* There is an unused NULL entry at the head of the table which we
981      must account for in our count even if the table is empty since it
982      is intended for the mandatory DT_SYMTAB tag (.dynsym section) in
983      .dynamic section.  */
984   dynsymcount++;
985
986   elf_hash_table (info)->dynsymcount = dynsymcount;
987   return dynsymcount;
988 }
989
990 /* Merge st_other field.  */
991
992 static void
993 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
994                     const Elf_Internal_Sym *isym, asection *sec,
995                     bfd_boolean definition, bfd_boolean dynamic)
996 {
997   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
998
999   /* If st_other has a processor-specific meaning, specific
1000      code might be needed here.  */
1001   if (bed->elf_backend_merge_symbol_attribute)
1002     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
1003                                                 dynamic);
1004
1005   if (!dynamic)
1006     {
1007       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
1008       unsigned hvis = ELF_ST_VISIBILITY (h->other);
1009
1010       /* Keep the most constraining visibility.  Leave the remainder
1011          of the st_other field to elf_backend_merge_symbol_attribute.  */
1012       if (symvis - 1 < hvis - 1)
1013         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
1014     }
1015   else if (definition
1016            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
1017            && (sec->flags & SEC_READONLY) == 0)
1018     h->protected_def = 1;
1019 }
1020
1021 /* This function is called when we want to merge a new symbol with an
1022    existing symbol.  It handles the various cases which arise when we
1023    find a definition in a dynamic object, or when there is already a
1024    definition in a dynamic object.  The new symbol is described by
1025    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
1026    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
1027    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
1028    of an old common symbol.  We set OVERRIDE if the old symbol is
1029    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
1030    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
1031    to change.  By OK to change, we mean that we shouldn't warn if the
1032    type or size does change.  */
1033
1034 static bfd_boolean
1035 _bfd_elf_merge_symbol (bfd *abfd,
1036                        struct bfd_link_info *info,
1037                        const char *name,
1038                        Elf_Internal_Sym *sym,
1039                        asection **psec,
1040                        bfd_vma *pvalue,
1041                        struct elf_link_hash_entry **sym_hash,
1042                        bfd **poldbfd,
1043                        bfd_boolean *pold_weak,
1044                        unsigned int *pold_alignment,
1045                        bfd_boolean *skip,
1046                        bfd_boolean *override,
1047                        bfd_boolean *type_change_ok,
1048                        bfd_boolean *size_change_ok,
1049                        bfd_boolean *matched)
1050 {
1051   asection *sec, *oldsec;
1052   struct elf_link_hash_entry *h;
1053   struct elf_link_hash_entry *hi;
1054   struct elf_link_hash_entry *flip;
1055   int bind;
1056   bfd *oldbfd;
1057   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
1058   bfd_boolean newweak, oldweak, newfunc, oldfunc;
1059   const struct elf_backend_data *bed;
1060   char *new_version;
1061   bfd_boolean default_sym = *matched;
1062
1063   *skip = FALSE;
1064   *override = FALSE;
1065
1066   sec = *psec;
1067   bind = ELF_ST_BIND (sym->st_info);
1068
1069   if (! bfd_is_und_section (sec))
1070     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
1071   else
1072     h = ((struct elf_link_hash_entry *)
1073          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
1074   if (h == NULL)
1075     return FALSE;
1076   *sym_hash = h;
1077
1078   bed = get_elf_backend_data (abfd);
1079
1080   /* NEW_VERSION is the symbol version of the new symbol.  */
1081   if (h->versioned != unversioned)
1082     {
1083       /* Symbol version is unknown or versioned.  */
1084       new_version = strrchr (name, ELF_VER_CHR);
1085       if (new_version)
1086         {
1087           if (h->versioned == unknown)
1088             {
1089               if (new_version > name && new_version[-1] != ELF_VER_CHR)
1090                 h->versioned = versioned_hidden;
1091               else
1092                 h->versioned = versioned;
1093             }
1094           new_version += 1;
1095           if (new_version[0] == '\0')
1096             new_version = NULL;
1097         }
1098       else
1099         h->versioned = unversioned;
1100     }
1101   else
1102     new_version = NULL;
1103
1104   /* For merging, we only care about real symbols.  But we need to make
1105      sure that indirect symbol dynamic flags are updated.  */
1106   hi = h;
1107   while (h->root.type == bfd_link_hash_indirect
1108          || h->root.type == bfd_link_hash_warning)
1109     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1110
1111   if (!*matched)
1112     {
1113       if (hi == h || h->root.type == bfd_link_hash_new)
1114         *matched = TRUE;
1115       else
1116         {
1117           /* OLD_HIDDEN is true if the existing symbol is only visible
1118              to the symbol with the same symbol version.  NEW_HIDDEN is
1119              true if the new symbol is only visible to the symbol with
1120              the same symbol version.  */
1121           bfd_boolean old_hidden = h->versioned == versioned_hidden;
1122           bfd_boolean new_hidden = hi->versioned == versioned_hidden;
1123           if (!old_hidden && !new_hidden)
1124             /* The new symbol matches the existing symbol if both
1125                aren't hidden.  */
1126             *matched = TRUE;
1127           else
1128             {
1129               /* OLD_VERSION is the symbol version of the existing
1130                  symbol. */
1131               char *old_version;
1132
1133               if (h->versioned >= versioned)
1134                 old_version = strrchr (h->root.root.string,
1135                                        ELF_VER_CHR) + 1;
1136               else
1137                  old_version = NULL;
1138
1139               /* The new symbol matches the existing symbol if they
1140                  have the same symbol version.  */
1141               *matched = (old_version == new_version
1142                           || (old_version != NULL
1143                               && new_version != NULL
1144                               && strcmp (old_version, new_version) == 0));
1145             }
1146         }
1147     }
1148
1149   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
1150      existing symbol.  */
1151
1152   oldbfd = NULL;
1153   oldsec = NULL;
1154   switch (h->root.type)
1155     {
1156     default:
1157       break;
1158
1159     case bfd_link_hash_undefined:
1160     case bfd_link_hash_undefweak:
1161       oldbfd = h->root.u.undef.abfd;
1162       break;
1163
1164     case bfd_link_hash_defined:
1165     case bfd_link_hash_defweak:
1166       oldbfd = h->root.u.def.section->owner;
1167       oldsec = h->root.u.def.section;
1168       break;
1169
1170     case bfd_link_hash_common:
1171       oldbfd = h->root.u.c.p->section->owner;
1172       oldsec = h->root.u.c.p->section;
1173       if (pold_alignment)
1174         *pold_alignment = h->root.u.c.p->alignment_power;
1175       break;
1176     }
1177   if (poldbfd && *poldbfd == NULL)
1178     *poldbfd = oldbfd;
1179
1180   /* Differentiate strong and weak symbols.  */
1181   newweak = bind == STB_WEAK;
1182   oldweak = (h->root.type == bfd_link_hash_defweak
1183              || h->root.type == bfd_link_hash_undefweak);
1184   if (pold_weak)
1185     *pold_weak = oldweak;
1186
1187   /* We have to check it for every instance since the first few may be
1188      references and not all compilers emit symbol type for undefined
1189      symbols.  */
1190   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
1191
1192   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1193      respectively, is from a dynamic object.  */
1194
1195   newdyn = (abfd->flags & DYNAMIC) != 0;
1196
1197   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
1198      syms and defined syms in dynamic libraries respectively.
1199      ref_dynamic on the other hand can be set for a symbol defined in
1200      a dynamic library, and def_dynamic may not be set;  When the
1201      definition in a dynamic lib is overridden by a definition in the
1202      executable use of the symbol in the dynamic lib becomes a
1203      reference to the executable symbol.  */
1204   if (newdyn)
1205     {
1206       if (bfd_is_und_section (sec))
1207         {
1208           if (bind != STB_WEAK)
1209             {
1210               h->ref_dynamic_nonweak = 1;
1211               hi->ref_dynamic_nonweak = 1;
1212             }
1213         }
1214       else
1215         {
1216           /* Update the existing symbol only if they match. */
1217           if (*matched)
1218             h->dynamic_def = 1;
1219           hi->dynamic_def = 1;
1220         }
1221     }
1222
1223   /* If we just created the symbol, mark it as being an ELF symbol.
1224      Other than that, there is nothing to do--there is no merge issue
1225      with a newly defined symbol--so we just return.  */
1226
1227   if (h->root.type == bfd_link_hash_new)
1228     {
1229       h->non_elf = 0;
1230       return TRUE;
1231     }
1232
1233   /* In cases involving weak versioned symbols, we may wind up trying
1234      to merge a symbol with itself.  Catch that here, to avoid the
1235      confusion that results if we try to override a symbol with
1236      itself.  The additional tests catch cases like
1237      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1238      dynamic object, which we do want to handle here.  */
1239   if (abfd == oldbfd
1240       && (newweak || oldweak)
1241       && ((abfd->flags & DYNAMIC) == 0
1242           || !h->def_regular))
1243     return TRUE;
1244
1245   olddyn = FALSE;
1246   if (oldbfd != NULL)
1247     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1248   else if (oldsec != NULL)
1249     {
1250       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1251          indices used by MIPS ELF.  */
1252       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1253     }
1254
1255   /* Handle a case where plugin_notice won't be called and thus won't
1256      set the non_ir_ref flags on the first pass over symbols.  */
1257   if (oldbfd != NULL
1258       && (oldbfd->flags & BFD_PLUGIN) != (abfd->flags & BFD_PLUGIN)
1259       && newdyn != olddyn)
1260     {
1261       h->root.non_ir_ref_dynamic = TRUE;
1262       hi->root.non_ir_ref_dynamic = TRUE;
1263     }
1264
1265   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1266      respectively, appear to be a definition rather than reference.  */
1267
1268   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1269
1270   olddef = (h->root.type != bfd_link_hash_undefined
1271             && h->root.type != bfd_link_hash_undefweak
1272             && h->root.type != bfd_link_hash_common);
1273
1274   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1275      respectively, appear to be a function.  */
1276
1277   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1278              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1279
1280   oldfunc = (h->type != STT_NOTYPE
1281              && bed->is_function_type (h->type));
1282
1283   if (!(newfunc && oldfunc)
1284       && ELF_ST_TYPE (sym->st_info) != h->type
1285       && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1286       && h->type != STT_NOTYPE
1287       && (newdef || bfd_is_com_section (sec))
1288       && (olddef || h->root.type == bfd_link_hash_common))
1289     {
1290       /* If creating a default indirect symbol ("foo" or "foo@") from
1291          a dynamic versioned definition ("foo@@") skip doing so if
1292          there is an existing regular definition with a different
1293          type.  We don't want, for example, a "time" variable in the
1294          executable overriding a "time" function in a shared library.  */
1295       if (newdyn
1296           && !olddyn)
1297         {
1298           *skip = TRUE;
1299           return TRUE;
1300         }
1301
1302       /* When adding a symbol from a regular object file after we have
1303          created indirect symbols, undo the indirection and any
1304          dynamic state.  */
1305       if (hi != h
1306           && !newdyn
1307           && olddyn)
1308         {
1309           h = hi;
1310           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1311           h->forced_local = 0;
1312           h->ref_dynamic = 0;
1313           h->def_dynamic = 0;
1314           h->dynamic_def = 0;
1315           if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1316             {
1317               h->root.type = bfd_link_hash_undefined;
1318               h->root.u.undef.abfd = abfd;
1319             }
1320           else
1321             {
1322               h->root.type = bfd_link_hash_new;
1323               h->root.u.undef.abfd = NULL;
1324             }
1325           return TRUE;
1326         }
1327     }
1328
1329   /* Check TLS symbols.  We don't check undefined symbols introduced
1330      by "ld -u" which have no type (and oldbfd NULL), and we don't
1331      check symbols from plugins because they also have no type.  */
1332   if (oldbfd != NULL
1333       && (oldbfd->flags & BFD_PLUGIN) == 0
1334       && (abfd->flags & BFD_PLUGIN) == 0
1335       && ELF_ST_TYPE (sym->st_info) != h->type
1336       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1337     {
1338       bfd *ntbfd, *tbfd;
1339       bfd_boolean ntdef, tdef;
1340       asection *ntsec, *tsec;
1341
1342       if (h->type == STT_TLS)
1343         {
1344           ntbfd = abfd;
1345           ntsec = sec;
1346           ntdef = newdef;
1347           tbfd = oldbfd;
1348           tsec = oldsec;
1349           tdef = olddef;
1350         }
1351       else
1352         {
1353           ntbfd = oldbfd;
1354           ntsec = oldsec;
1355           ntdef = olddef;
1356           tbfd = abfd;
1357           tsec = sec;
1358           tdef = newdef;
1359         }
1360
1361       if (tdef && ntdef)
1362         _bfd_error_handler
1363           /* xgettext:c-format */
1364           (_("%s: TLS definition in %pB section %pA "
1365              "mismatches non-TLS definition in %pB section %pA"),
1366            h->root.root.string, tbfd, tsec, ntbfd, ntsec);
1367       else if (!tdef && !ntdef)
1368         _bfd_error_handler
1369           /* xgettext:c-format */
1370           (_("%s: TLS reference in %pB "
1371              "mismatches non-TLS reference in %pB"),
1372            h->root.root.string, tbfd, ntbfd);
1373       else if (tdef)
1374         _bfd_error_handler
1375           /* xgettext:c-format */
1376           (_("%s: TLS definition in %pB section %pA "
1377              "mismatches non-TLS reference in %pB"),
1378            h->root.root.string, tbfd, tsec, ntbfd);
1379       else
1380         _bfd_error_handler
1381           /* xgettext:c-format */
1382           (_("%s: TLS reference in %pB "
1383              "mismatches non-TLS definition in %pB section %pA"),
1384            h->root.root.string, tbfd, ntbfd, ntsec);
1385
1386       bfd_set_error (bfd_error_bad_value);
1387       return FALSE;
1388     }
1389
1390   /* If the old symbol has non-default visibility, we ignore the new
1391      definition from a dynamic object.  */
1392   if (newdyn
1393       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1394       && !bfd_is_und_section (sec))
1395     {
1396       *skip = TRUE;
1397       /* Make sure this symbol is dynamic.  */
1398       h->ref_dynamic = 1;
1399       hi->ref_dynamic = 1;
1400       /* A protected symbol has external availability. Make sure it is
1401          recorded as dynamic.
1402
1403          FIXME: Should we check type and size for protected symbol?  */
1404       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1405         return bfd_elf_link_record_dynamic_symbol (info, h);
1406       else
1407         return TRUE;
1408     }
1409   else if (!newdyn
1410            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1411            && h->def_dynamic)
1412     {
1413       /* If the new symbol with non-default visibility comes from a
1414          relocatable file and the old definition comes from a dynamic
1415          object, we remove the old definition.  */
1416       if (hi->root.type == bfd_link_hash_indirect)
1417         {
1418           /* Handle the case where the old dynamic definition is
1419              default versioned.  We need to copy the symbol info from
1420              the symbol with default version to the normal one if it
1421              was referenced before.  */
1422           if (h->ref_regular)
1423             {
1424               hi->root.type = h->root.type;
1425               h->root.type = bfd_link_hash_indirect;
1426               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1427
1428               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1429               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1430                 {
1431                   /* If the new symbol is hidden or internal, completely undo
1432                      any dynamic link state.  */
1433                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1434                   h->forced_local = 0;
1435                   h->ref_dynamic = 0;
1436                 }
1437               else
1438                 h->ref_dynamic = 1;
1439
1440               h->def_dynamic = 0;
1441               /* FIXME: Should we check type and size for protected symbol?  */
1442               h->size = 0;
1443               h->type = 0;
1444
1445               h = hi;
1446             }
1447           else
1448             h = hi;
1449         }
1450
1451       /* If the old symbol was undefined before, then it will still be
1452          on the undefs list.  If the new symbol is undefined or
1453          common, we can't make it bfd_link_hash_new here, because new
1454          undefined or common symbols will be added to the undefs list
1455          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1456          added twice to the undefs list.  Also, if the new symbol is
1457          undefweak then we don't want to lose the strong undef.  */
1458       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1459         {
1460           h->root.type = bfd_link_hash_undefined;
1461           h->root.u.undef.abfd = abfd;
1462         }
1463       else
1464         {
1465           h->root.type = bfd_link_hash_new;
1466           h->root.u.undef.abfd = NULL;
1467         }
1468
1469       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1470         {
1471           /* If the new symbol is hidden or internal, completely undo
1472              any dynamic link state.  */
1473           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1474           h->forced_local = 0;
1475           h->ref_dynamic = 0;
1476         }
1477       else
1478         h->ref_dynamic = 1;
1479       h->def_dynamic = 0;
1480       /* FIXME: Should we check type and size for protected symbol?  */
1481       h->size = 0;
1482       h->type = 0;
1483       return TRUE;
1484     }
1485
1486   /* If a new weak symbol definition comes from a regular file and the
1487      old symbol comes from a dynamic library, we treat the new one as
1488      strong.  Similarly, an old weak symbol definition from a regular
1489      file is treated as strong when the new symbol comes from a dynamic
1490      library.  Further, an old weak symbol from a dynamic library is
1491      treated as strong if the new symbol is from a dynamic library.
1492      This reflects the way glibc's ld.so works.
1493
1494      Also allow a weak symbol to override a linker script symbol
1495      defined by an early pass over the script.  This is done so the
1496      linker knows the symbol is defined in an object file, for the
1497      DEFINED script function.
1498
1499      Do this before setting *type_change_ok or *size_change_ok so that
1500      we warn properly when dynamic library symbols are overridden.  */
1501
1502   if (newdef && !newdyn && (olddyn || h->root.ldscript_def))
1503     newweak = FALSE;
1504   if (olddef && newdyn)
1505     oldweak = FALSE;
1506
1507   /* Allow changes between different types of function symbol.  */
1508   if (newfunc && oldfunc)
1509     *type_change_ok = TRUE;
1510
1511   /* It's OK to change the type if either the existing symbol or the
1512      new symbol is weak.  A type change is also OK if the old symbol
1513      is undefined and the new symbol is defined.  */
1514
1515   if (oldweak
1516       || newweak
1517       || (newdef
1518           && h->root.type == bfd_link_hash_undefined))
1519     *type_change_ok = TRUE;
1520
1521   /* It's OK to change the size if either the existing symbol or the
1522      new symbol is weak, or if the old symbol is undefined.  */
1523
1524   if (*type_change_ok
1525       || h->root.type == bfd_link_hash_undefined)
1526     *size_change_ok = TRUE;
1527
1528   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1529      symbol, respectively, appears to be a common symbol in a dynamic
1530      object.  If a symbol appears in an uninitialized section, and is
1531      not weak, and is not a function, then it may be a common symbol
1532      which was resolved when the dynamic object was created.  We want
1533      to treat such symbols specially, because they raise special
1534      considerations when setting the symbol size: if the symbol
1535      appears as a common symbol in a regular object, and the size in
1536      the regular object is larger, we must make sure that we use the
1537      larger size.  This problematic case can always be avoided in C,
1538      but it must be handled correctly when using Fortran shared
1539      libraries.
1540
1541      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1542      likewise for OLDDYNCOMMON and OLDDEF.
1543
1544      Note that this test is just a heuristic, and that it is quite
1545      possible to have an uninitialized symbol in a shared object which
1546      is really a definition, rather than a common symbol.  This could
1547      lead to some minor confusion when the symbol really is a common
1548      symbol in some regular object.  However, I think it will be
1549      harmless.  */
1550
1551   if (newdyn
1552       && newdef
1553       && !newweak
1554       && (sec->flags & SEC_ALLOC) != 0
1555       && (sec->flags & SEC_LOAD) == 0
1556       && sym->st_size > 0
1557       && !newfunc)
1558     newdyncommon = TRUE;
1559   else
1560     newdyncommon = FALSE;
1561
1562   if (olddyn
1563       && olddef
1564       && h->root.type == bfd_link_hash_defined
1565       && h->def_dynamic
1566       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1567       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1568       && h->size > 0
1569       && !oldfunc)
1570     olddyncommon = TRUE;
1571   else
1572     olddyncommon = FALSE;
1573
1574   /* We now know everything about the old and new symbols.  We ask the
1575      backend to check if we can merge them.  */
1576   if (bed->merge_symbol != NULL)
1577     {
1578       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1579         return FALSE;
1580       sec = *psec;
1581     }
1582
1583   /* There are multiple definitions of a normal symbol.  Skip the
1584      default symbol as well as definition from an IR object.  */
1585   if (olddef && !olddyn && !oldweak && newdef && !newdyn && !newweak
1586       && !default_sym && h->def_regular
1587       && !(oldbfd != NULL
1588            && (oldbfd->flags & BFD_PLUGIN) != 0
1589            && (abfd->flags & BFD_PLUGIN) == 0))
1590     {
1591       /* Handle a multiple definition.  */
1592       (*info->callbacks->multiple_definition) (info, &h->root,
1593                                                abfd, sec, *pvalue);
1594       *skip = TRUE;
1595       return TRUE;
1596     }
1597
1598   /* If both the old and the new symbols look like common symbols in a
1599      dynamic object, set the size of the symbol to the larger of the
1600      two.  */
1601
1602   if (olddyncommon
1603       && newdyncommon
1604       && sym->st_size != h->size)
1605     {
1606       /* Since we think we have two common symbols, issue a multiple
1607          common warning if desired.  Note that we only warn if the
1608          size is different.  If the size is the same, we simply let
1609          the old symbol override the new one as normally happens with
1610          symbols defined in dynamic objects.  */
1611
1612       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1613                                            bfd_link_hash_common, sym->st_size);
1614       if (sym->st_size > h->size)
1615         h->size = sym->st_size;
1616
1617       *size_change_ok = TRUE;
1618     }
1619
1620   /* If we are looking at a dynamic object, and we have found a
1621      definition, we need to see if the symbol was already defined by
1622      some other object.  If so, we want to use the existing
1623      definition, and we do not want to report a multiple symbol
1624      definition error; we do this by clobbering *PSEC to be
1625      bfd_und_section_ptr.
1626
1627      We treat a common symbol as a definition if the symbol in the
1628      shared library is a function, since common symbols always
1629      represent variables; this can cause confusion in principle, but
1630      any such confusion would seem to indicate an erroneous program or
1631      shared library.  We also permit a common symbol in a regular
1632      object to override a weak symbol in a shared object.  */
1633
1634   if (newdyn
1635       && newdef
1636       && (olddef
1637           || (h->root.type == bfd_link_hash_common
1638               && (newweak || newfunc))))
1639     {
1640       *override = TRUE;
1641       newdef = FALSE;
1642       newdyncommon = FALSE;
1643
1644       *psec = sec = bfd_und_section_ptr;
1645       *size_change_ok = TRUE;
1646
1647       /* If we get here when the old symbol is a common symbol, then
1648          we are explicitly letting it override a weak symbol or
1649          function in a dynamic object, and we don't want to warn about
1650          a type change.  If the old symbol is a defined symbol, a type
1651          change warning may still be appropriate.  */
1652
1653       if (h->root.type == bfd_link_hash_common)
1654         *type_change_ok = TRUE;
1655     }
1656
1657   /* Handle the special case of an old common symbol merging with a
1658      new symbol which looks like a common symbol in a shared object.
1659      We change *PSEC and *PVALUE to make the new symbol look like a
1660      common symbol, and let _bfd_generic_link_add_one_symbol do the
1661      right thing.  */
1662
1663   if (newdyncommon
1664       && h->root.type == bfd_link_hash_common)
1665     {
1666       *override = TRUE;
1667       newdef = FALSE;
1668       newdyncommon = FALSE;
1669       *pvalue = sym->st_size;
1670       *psec = sec = bed->common_section (oldsec);
1671       *size_change_ok = TRUE;
1672     }
1673
1674   /* Skip weak definitions of symbols that are already defined.  */
1675   if (newdef && olddef && newweak)
1676     {
1677       /* Don't skip new non-IR weak syms.  */
1678       if (!(oldbfd != NULL
1679             && (oldbfd->flags & BFD_PLUGIN) != 0
1680             && (abfd->flags & BFD_PLUGIN) == 0))
1681         {
1682           newdef = FALSE;
1683           *skip = TRUE;
1684         }
1685
1686       /* Merge st_other.  If the symbol already has a dynamic index,
1687          but visibility says it should not be visible, turn it into a
1688          local symbol.  */
1689       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1690       if (h->dynindx != -1)
1691         switch (ELF_ST_VISIBILITY (h->other))
1692           {
1693           case STV_INTERNAL:
1694           case STV_HIDDEN:
1695             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1696             break;
1697           }
1698     }
1699
1700   /* If the old symbol is from a dynamic object, and the new symbol is
1701      a definition which is not from a dynamic object, then the new
1702      symbol overrides the old symbol.  Symbols from regular files
1703      always take precedence over symbols from dynamic objects, even if
1704      they are defined after the dynamic object in the link.
1705
1706      As above, we again permit a common symbol in a regular object to
1707      override a definition in a shared object if the shared object
1708      symbol is a function or is weak.  */
1709
1710   flip = NULL;
1711   if (!newdyn
1712       && (newdef
1713           || (bfd_is_com_section (sec)
1714               && (oldweak || oldfunc)))
1715       && olddyn
1716       && olddef
1717       && h->def_dynamic)
1718     {
1719       /* Change the hash table entry to undefined, and let
1720          _bfd_generic_link_add_one_symbol do the right thing with the
1721          new definition.  */
1722
1723       h->root.type = bfd_link_hash_undefined;
1724       h->root.u.undef.abfd = h->root.u.def.section->owner;
1725       *size_change_ok = TRUE;
1726
1727       olddef = FALSE;
1728       olddyncommon = FALSE;
1729
1730       /* We again permit a type change when a common symbol may be
1731          overriding a function.  */
1732
1733       if (bfd_is_com_section (sec))
1734         {
1735           if (oldfunc)
1736             {
1737               /* If a common symbol overrides a function, make sure
1738                  that it isn't defined dynamically nor has type
1739                  function.  */
1740               h->def_dynamic = 0;
1741               h->type = STT_NOTYPE;
1742             }
1743           *type_change_ok = TRUE;
1744         }
1745
1746       if (hi->root.type == bfd_link_hash_indirect)
1747         flip = hi;
1748       else
1749         /* This union may have been set to be non-NULL when this symbol
1750            was seen in a dynamic object.  We must force the union to be
1751            NULL, so that it is correct for a regular symbol.  */
1752         h->verinfo.vertree = NULL;
1753     }
1754
1755   /* Handle the special case of a new common symbol merging with an
1756      old symbol that looks like it might be a common symbol defined in
1757      a shared object.  Note that we have already handled the case in
1758      which a new common symbol should simply override the definition
1759      in the shared library.  */
1760
1761   if (! newdyn
1762       && bfd_is_com_section (sec)
1763       && olddyncommon)
1764     {
1765       /* It would be best if we could set the hash table entry to a
1766          common symbol, but we don't know what to use for the section
1767          or the alignment.  */
1768       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1769                                            bfd_link_hash_common, sym->st_size);
1770
1771       /* If the presumed common symbol in the dynamic object is
1772          larger, pretend that the new symbol has its size.  */
1773
1774       if (h->size > *pvalue)
1775         *pvalue = h->size;
1776
1777       /* We need to remember the alignment required by the symbol
1778          in the dynamic object.  */
1779       BFD_ASSERT (pold_alignment);
1780       *pold_alignment = h->root.u.def.section->alignment_power;
1781
1782       olddef = FALSE;
1783       olddyncommon = FALSE;
1784
1785       h->root.type = bfd_link_hash_undefined;
1786       h->root.u.undef.abfd = h->root.u.def.section->owner;
1787
1788       *size_change_ok = TRUE;
1789       *type_change_ok = TRUE;
1790
1791       if (hi->root.type == bfd_link_hash_indirect)
1792         flip = hi;
1793       else
1794         h->verinfo.vertree = NULL;
1795     }
1796
1797   if (flip != NULL)
1798     {
1799       /* Handle the case where we had a versioned symbol in a dynamic
1800          library and now find a definition in a normal object.  In this
1801          case, we make the versioned symbol point to the normal one.  */
1802       flip->root.type = h->root.type;
1803       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1804       h->root.type = bfd_link_hash_indirect;
1805       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1806       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1807       if (h->def_dynamic)
1808         {
1809           h->def_dynamic = 0;
1810           flip->ref_dynamic = 1;
1811         }
1812     }
1813
1814   return TRUE;
1815 }
1816
1817 /* This function is called to create an indirect symbol from the
1818    default for the symbol with the default version if needed. The
1819    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1820    set DYNSYM if the new indirect symbol is dynamic.  */
1821
1822 static bfd_boolean
1823 _bfd_elf_add_default_symbol (bfd *abfd,
1824                              struct bfd_link_info *info,
1825                              struct elf_link_hash_entry *h,
1826                              const char *name,
1827                              Elf_Internal_Sym *sym,
1828                              asection *sec,
1829                              bfd_vma value,
1830                              bfd **poldbfd,
1831                              bfd_boolean *dynsym)
1832 {
1833   bfd_boolean type_change_ok;
1834   bfd_boolean size_change_ok;
1835   bfd_boolean skip;
1836   char *shortname;
1837   struct elf_link_hash_entry *hi;
1838   struct bfd_link_hash_entry *bh;
1839   const struct elf_backend_data *bed;
1840   bfd_boolean collect;
1841   bfd_boolean dynamic;
1842   bfd_boolean override;
1843   char *p;
1844   size_t len, shortlen;
1845   asection *tmp_sec;
1846   bfd_boolean matched;
1847
1848   if (h->versioned == unversioned || h->versioned == versioned_hidden)
1849     return TRUE;
1850
1851   /* If this symbol has a version, and it is the default version, we
1852      create an indirect symbol from the default name to the fully
1853      decorated name.  This will cause external references which do not
1854      specify a version to be bound to this version of the symbol.  */
1855   p = strchr (name, ELF_VER_CHR);
1856   if (h->versioned == unknown)
1857     {
1858       if (p == NULL)
1859         {
1860           h->versioned = unversioned;
1861           return TRUE;
1862         }
1863       else
1864         {
1865           if (p[1] != ELF_VER_CHR)
1866             {
1867               h->versioned = versioned_hidden;
1868               return TRUE;
1869             }
1870           else
1871             h->versioned = versioned;
1872         }
1873     }
1874   else
1875     {
1876       /* PR ld/19073: We may see an unversioned definition after the
1877          default version.  */
1878       if (p == NULL)
1879         return TRUE;
1880     }
1881
1882   bed = get_elf_backend_data (abfd);
1883   collect = bed->collect;
1884   dynamic = (abfd->flags & DYNAMIC) != 0;
1885
1886   shortlen = p - name;
1887   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1888   if (shortname == NULL)
1889     return FALSE;
1890   memcpy (shortname, name, shortlen);
1891   shortname[shortlen] = '\0';
1892
1893   /* We are going to create a new symbol.  Merge it with any existing
1894      symbol with this name.  For the purposes of the merge, act as
1895      though we were defining the symbol we just defined, although we
1896      actually going to define an indirect symbol.  */
1897   type_change_ok = FALSE;
1898   size_change_ok = FALSE;
1899   matched = TRUE;
1900   tmp_sec = sec;
1901   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1902                               &hi, poldbfd, NULL, NULL, &skip, &override,
1903                               &type_change_ok, &size_change_ok, &matched))
1904     return FALSE;
1905
1906   if (skip)
1907     goto nondefault;
1908
1909   if (hi->def_regular)
1910     {
1911       /* If the undecorated symbol will have a version added by a
1912          script different to H, then don't indirect to/from the
1913          undecorated symbol.  This isn't ideal because we may not yet
1914          have seen symbol versions, if given by a script on the
1915          command line rather than via --version-script.  */
1916       if (hi->verinfo.vertree == NULL && info->version_info != NULL)
1917         {
1918           bfd_boolean hide;
1919
1920           hi->verinfo.vertree
1921             = bfd_find_version_for_sym (info->version_info,
1922                                         hi->root.root.string, &hide);
1923           if (hi->verinfo.vertree != NULL && hide)
1924             {
1925               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
1926               goto nondefault;
1927             }
1928         }
1929       if (hi->verinfo.vertree != NULL
1930           && strcmp (p + 1 + (p[1] == '@'), hi->verinfo.vertree->name) != 0)
1931         goto nondefault;
1932     }
1933
1934   if (! override)
1935     {
1936       /* Add the default symbol if not performing a relocatable link.  */
1937       if (! bfd_link_relocatable (info))
1938         {
1939           bh = &hi->root;
1940           if (bh->type == bfd_link_hash_defined
1941               && bh->u.def.section->owner != NULL
1942               && (bh->u.def.section->owner->flags & BFD_PLUGIN) != 0)
1943             {
1944               /* Mark the previous definition from IR object as
1945                  undefined so that the generic linker will override
1946                  it.  */
1947               bh->type = bfd_link_hash_undefined;
1948               bh->u.undef.abfd = bh->u.def.section->owner;
1949             }
1950           if (! (_bfd_generic_link_add_one_symbol
1951                  (info, abfd, shortname, BSF_INDIRECT,
1952                   bfd_ind_section_ptr,
1953                   0, name, FALSE, collect, &bh)))
1954             return FALSE;
1955           hi = (struct elf_link_hash_entry *) bh;
1956         }
1957     }
1958   else
1959     {
1960       /* In this case the symbol named SHORTNAME is overriding the
1961          indirect symbol we want to add.  We were planning on making
1962          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1963          is the name without a version.  NAME is the fully versioned
1964          name, and it is the default version.
1965
1966          Overriding means that we already saw a definition for the
1967          symbol SHORTNAME in a regular object, and it is overriding
1968          the symbol defined in the dynamic object.
1969
1970          When this happens, we actually want to change NAME, the
1971          symbol we just added, to refer to SHORTNAME.  This will cause
1972          references to NAME in the shared object to become references
1973          to SHORTNAME in the regular object.  This is what we expect
1974          when we override a function in a shared object: that the
1975          references in the shared object will be mapped to the
1976          definition in the regular object.  */
1977
1978       while (hi->root.type == bfd_link_hash_indirect
1979              || hi->root.type == bfd_link_hash_warning)
1980         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1981
1982       h->root.type = bfd_link_hash_indirect;
1983       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1984       if (h->def_dynamic)
1985         {
1986           h->def_dynamic = 0;
1987           hi->ref_dynamic = 1;
1988           if (hi->ref_regular
1989               || hi->def_regular)
1990             {
1991               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1992                 return FALSE;
1993             }
1994         }
1995
1996       /* Now set HI to H, so that the following code will set the
1997          other fields correctly.  */
1998       hi = h;
1999     }
2000
2001   /* Check if HI is a warning symbol.  */
2002   if (hi->root.type == bfd_link_hash_warning)
2003     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
2004
2005   /* If there is a duplicate definition somewhere, then HI may not
2006      point to an indirect symbol.  We will have reported an error to
2007      the user in that case.  */
2008
2009   if (hi->root.type == bfd_link_hash_indirect)
2010     {
2011       struct elf_link_hash_entry *ht;
2012
2013       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
2014       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
2015
2016       /* A reference to the SHORTNAME symbol from a dynamic library
2017          will be satisfied by the versioned symbol at runtime.  In
2018          effect, we have a reference to the versioned symbol.  */
2019       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
2020       hi->dynamic_def |= ht->dynamic_def;
2021
2022       /* See if the new flags lead us to realize that the symbol must
2023          be dynamic.  */
2024       if (! *dynsym)
2025         {
2026           if (! dynamic)
2027             {
2028               if (! bfd_link_executable (info)
2029                   || hi->def_dynamic
2030                   || hi->ref_dynamic)
2031                 *dynsym = TRUE;
2032             }
2033           else
2034             {
2035               if (hi->ref_regular)
2036                 *dynsym = TRUE;
2037             }
2038         }
2039     }
2040
2041   /* We also need to define an indirection from the nondefault version
2042      of the symbol.  */
2043
2044 nondefault:
2045   len = strlen (name);
2046   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
2047   if (shortname == NULL)
2048     return FALSE;
2049   memcpy (shortname, name, shortlen);
2050   memcpy (shortname + shortlen, p + 1, len - shortlen);
2051
2052   /* Once again, merge with any existing symbol.  */
2053   type_change_ok = FALSE;
2054   size_change_ok = FALSE;
2055   tmp_sec = sec;
2056   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
2057                               &hi, poldbfd, NULL, NULL, &skip, &override,
2058                               &type_change_ok, &size_change_ok, &matched))
2059     return FALSE;
2060
2061   if (skip)
2062     return TRUE;
2063
2064   if (override)
2065     {
2066       /* Here SHORTNAME is a versioned name, so we don't expect to see
2067          the type of override we do in the case above unless it is
2068          overridden by a versioned definition.  */
2069       if (hi->root.type != bfd_link_hash_defined
2070           && hi->root.type != bfd_link_hash_defweak)
2071         _bfd_error_handler
2072           /* xgettext:c-format */
2073           (_("%pB: unexpected redefinition of indirect versioned symbol `%s'"),
2074            abfd, shortname);
2075     }
2076   else
2077     {
2078       bh = &hi->root;
2079       if (! (_bfd_generic_link_add_one_symbol
2080              (info, abfd, shortname, BSF_INDIRECT,
2081               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
2082         return FALSE;
2083       hi = (struct elf_link_hash_entry *) bh;
2084
2085       /* If there is a duplicate definition somewhere, then HI may not
2086          point to an indirect symbol.  We will have reported an error
2087          to the user in that case.  */
2088
2089       if (hi->root.type == bfd_link_hash_indirect)
2090         {
2091           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
2092           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
2093           hi->dynamic_def |= h->dynamic_def;
2094
2095           /* See if the new flags lead us to realize that the symbol
2096              must be dynamic.  */
2097           if (! *dynsym)
2098             {
2099               if (! dynamic)
2100                 {
2101                   if (! bfd_link_executable (info)
2102                       || hi->ref_dynamic)
2103                     *dynsym = TRUE;
2104                 }
2105               else
2106                 {
2107                   if (hi->ref_regular)
2108                     *dynsym = TRUE;
2109                 }
2110             }
2111         }
2112     }
2113
2114   return TRUE;
2115 }
2116 \f
2117 /* This routine is used to export all defined symbols into the dynamic
2118    symbol table.  It is called via elf_link_hash_traverse.  */
2119
2120 static bfd_boolean
2121 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
2122 {
2123   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2124
2125   /* Ignore indirect symbols.  These are added by the versioning code.  */
2126   if (h->root.type == bfd_link_hash_indirect)
2127     return TRUE;
2128
2129   /* Ignore this if we won't export it.  */
2130   if (!eif->info->export_dynamic && !h->dynamic)
2131     return TRUE;
2132
2133   if (h->dynindx == -1
2134       && (h->def_regular || h->ref_regular)
2135       && ! bfd_hide_sym_by_version (eif->info->version_info,
2136                                     h->root.root.string))
2137     {
2138       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2139         {
2140           eif->failed = TRUE;
2141           return FALSE;
2142         }
2143     }
2144
2145   return TRUE;
2146 }
2147 \f
2148 /* Look through the symbols which are defined in other shared
2149    libraries and referenced here.  Update the list of version
2150    dependencies.  This will be put into the .gnu.version_r section.
2151    This function is called via elf_link_hash_traverse.  */
2152
2153 static bfd_boolean
2154 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
2155                                          void *data)
2156 {
2157   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
2158   Elf_Internal_Verneed *t;
2159   Elf_Internal_Vernaux *a;
2160   bfd_size_type amt;
2161
2162   /* We only care about symbols defined in shared objects with version
2163      information.  */
2164   if (!h->def_dynamic
2165       || h->def_regular
2166       || h->dynindx == -1
2167       || h->verinfo.verdef == NULL
2168       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
2169           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
2170     return TRUE;
2171
2172   /* See if we already know about this version.  */
2173   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
2174        t != NULL;
2175        t = t->vn_nextref)
2176     {
2177       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
2178         continue;
2179
2180       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
2181         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
2182           return TRUE;
2183
2184       break;
2185     }
2186
2187   /* This is a new version.  Add it to tree we are building.  */
2188
2189   if (t == NULL)
2190     {
2191       amt = sizeof *t;
2192       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
2193       if (t == NULL)
2194         {
2195           rinfo->failed = TRUE;
2196           return FALSE;
2197         }
2198
2199       t->vn_bfd = h->verinfo.verdef->vd_bfd;
2200       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
2201       elf_tdata (rinfo->info->output_bfd)->verref = t;
2202     }
2203
2204   amt = sizeof *a;
2205   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
2206   if (a == NULL)
2207     {
2208       rinfo->failed = TRUE;
2209       return FALSE;
2210     }
2211
2212   /* Note that we are copying a string pointer here, and testing it
2213      above.  If bfd_elf_string_from_elf_section is ever changed to
2214      discard the string data when low in memory, this will have to be
2215      fixed.  */
2216   a->vna_nodename = h->verinfo.verdef->vd_nodename;
2217
2218   a->vna_flags = h->verinfo.verdef->vd_flags;
2219   a->vna_nextptr = t->vn_auxptr;
2220
2221   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
2222   ++rinfo->vers;
2223
2224   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
2225
2226   t->vn_auxptr = a;
2227
2228   return TRUE;
2229 }
2230
2231 /* Return TRUE and set *HIDE to TRUE if the versioned symbol is
2232    hidden.  Set *T_P to NULL if there is no match.  */
2233
2234 static bfd_boolean
2235 _bfd_elf_link_hide_versioned_symbol (struct bfd_link_info *info,
2236                                      struct elf_link_hash_entry *h,
2237                                      const char *version_p,
2238                                      struct bfd_elf_version_tree **t_p,
2239                                      bfd_boolean *hide)
2240 {
2241   struct bfd_elf_version_tree *t;
2242
2243   /* Look for the version.  If we find it, it is no longer weak.  */
2244   for (t = info->version_info; t != NULL; t = t->next)
2245     {
2246       if (strcmp (t->name, version_p) == 0)
2247         {
2248           size_t len;
2249           char *alc;
2250           struct bfd_elf_version_expr *d;
2251
2252           len = version_p - h->root.root.string;
2253           alc = (char *) bfd_malloc (len);
2254           if (alc == NULL)
2255             return FALSE;
2256           memcpy (alc, h->root.root.string, len - 1);
2257           alc[len - 1] = '\0';
2258           if (alc[len - 2] == ELF_VER_CHR)
2259             alc[len - 2] = '\0';
2260
2261           h->verinfo.vertree = t;
2262           t->used = TRUE;
2263           d = NULL;
2264
2265           if (t->globals.list != NULL)
2266             d = (*t->match) (&t->globals, NULL, alc);
2267
2268           /* See if there is anything to force this symbol to
2269              local scope.  */
2270           if (d == NULL && t->locals.list != NULL)
2271             {
2272               d = (*t->match) (&t->locals, NULL, alc);
2273               if (d != NULL
2274                   && h->dynindx != -1
2275                   && ! info->export_dynamic)
2276                 *hide = TRUE;
2277             }
2278
2279           free (alc);
2280           break;
2281         }
2282     }
2283
2284   *t_p = t;
2285
2286   return TRUE;
2287 }
2288
2289 /* Return TRUE if the symbol H is hidden by version script.  */
2290
2291 bfd_boolean
2292 _bfd_elf_link_hide_sym_by_version (struct bfd_link_info *info,
2293                                    struct elf_link_hash_entry *h)
2294 {
2295   const char *p;
2296   bfd_boolean hide = FALSE;
2297   const struct elf_backend_data *bed
2298     = get_elf_backend_data (info->output_bfd);
2299
2300   /* Version script only hides symbols defined in regular objects.  */
2301   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
2302     return TRUE;
2303
2304   p = strchr (h->root.root.string, ELF_VER_CHR);
2305   if (p != NULL && h->verinfo.vertree == NULL)
2306     {
2307       struct bfd_elf_version_tree *t;
2308
2309       ++p;
2310       if (*p == ELF_VER_CHR)
2311         ++p;
2312
2313       if (*p != '\0'
2314           && _bfd_elf_link_hide_versioned_symbol (info, h, p, &t, &hide)
2315           && hide)
2316         {
2317           if (hide)
2318             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2319           return TRUE;
2320         }
2321     }
2322
2323   /* If we don't have a version for this symbol, see if we can find
2324      something.  */
2325   if (h->verinfo.vertree == NULL && info->version_info != NULL)
2326     {
2327       h->verinfo.vertree
2328         = bfd_find_version_for_sym (info->version_info,
2329                                     h->root.root.string, &hide);
2330       if (h->verinfo.vertree != NULL && hide)
2331         {
2332           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2333           return TRUE;
2334         }
2335     }
2336
2337   return FALSE;
2338 }
2339
2340 /* Figure out appropriate versions for all the symbols.  We may not
2341    have the version number script until we have read all of the input
2342    files, so until that point we don't know which symbols should be
2343    local.  This function is called via elf_link_hash_traverse.  */
2344
2345 static bfd_boolean
2346 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2347 {
2348   struct elf_info_failed *sinfo;
2349   struct bfd_link_info *info;
2350   const struct elf_backend_data *bed;
2351   struct elf_info_failed eif;
2352   char *p;
2353   bfd_boolean hide;
2354
2355   sinfo = (struct elf_info_failed *) data;
2356   info = sinfo->info;
2357
2358   /* Fix the symbol flags.  */
2359   eif.failed = FALSE;
2360   eif.info = info;
2361   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2362     {
2363       if (eif.failed)
2364         sinfo->failed = TRUE;
2365       return FALSE;
2366     }
2367
2368   bed = get_elf_backend_data (info->output_bfd);
2369
2370   /* We only need version numbers for symbols defined in regular
2371      objects.  */
2372   if (!h->def_regular)
2373     {
2374       /* Hide symbols defined in discarded input sections.  */
2375       if ((h->root.type == bfd_link_hash_defined
2376            || h->root.type == bfd_link_hash_defweak)
2377           && discarded_section (h->root.u.def.section))
2378         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2379       return TRUE;
2380     }
2381
2382   hide = FALSE;
2383   p = strchr (h->root.root.string, ELF_VER_CHR);
2384   if (p != NULL && h->verinfo.vertree == NULL)
2385     {
2386       struct bfd_elf_version_tree *t;
2387
2388       ++p;
2389       if (*p == ELF_VER_CHR)
2390         ++p;
2391
2392       /* If there is no version string, we can just return out.  */
2393       if (*p == '\0')
2394         return TRUE;
2395
2396       if (!_bfd_elf_link_hide_versioned_symbol (info, h, p, &t, &hide))
2397         {
2398           sinfo->failed = TRUE;
2399           return FALSE;
2400         }
2401
2402       if (hide)
2403         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2404
2405       /* If we are building an application, we need to create a
2406          version node for this version.  */
2407       if (t == NULL && bfd_link_executable (info))
2408         {
2409           struct bfd_elf_version_tree **pp;
2410           int version_index;
2411
2412           /* If we aren't going to export this symbol, we don't need
2413              to worry about it.  */
2414           if (h->dynindx == -1)
2415             return TRUE;
2416
2417           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd,
2418                                                           sizeof *t);
2419           if (t == NULL)
2420             {
2421               sinfo->failed = TRUE;
2422               return FALSE;
2423             }
2424
2425           t->name = p;
2426           t->name_indx = (unsigned int) -1;
2427           t->used = TRUE;
2428
2429           version_index = 1;
2430           /* Don't count anonymous version tag.  */
2431           if (sinfo->info->version_info != NULL
2432               && sinfo->info->version_info->vernum == 0)
2433             version_index = 0;
2434           for (pp = &sinfo->info->version_info;
2435                *pp != NULL;
2436                pp = &(*pp)->next)
2437             ++version_index;
2438           t->vernum = version_index;
2439
2440           *pp = t;
2441
2442           h->verinfo.vertree = t;
2443         }
2444       else if (t == NULL)
2445         {
2446           /* We could not find the version for a symbol when
2447              generating a shared archive.  Return an error.  */
2448           _bfd_error_handler
2449             /* xgettext:c-format */
2450             (_("%pB: version node not found for symbol %s"),
2451              info->output_bfd, h->root.root.string);
2452           bfd_set_error (bfd_error_bad_value);
2453           sinfo->failed = TRUE;
2454           return FALSE;
2455         }
2456     }
2457
2458   /* If we don't have a version for this symbol, see if we can find
2459      something.  */
2460   if (!hide
2461       && h->verinfo.vertree == NULL
2462       && sinfo->info->version_info != NULL)
2463     {
2464       h->verinfo.vertree
2465         = bfd_find_version_for_sym (sinfo->info->version_info,
2466                                     h->root.root.string, &hide);
2467       if (h->verinfo.vertree != NULL && hide)
2468         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2469     }
2470
2471   return TRUE;
2472 }
2473 \f
2474 /* Read and swap the relocs from the section indicated by SHDR.  This
2475    may be either a REL or a RELA section.  The relocations are
2476    translated into RELA relocations and stored in INTERNAL_RELOCS,
2477    which should have already been allocated to contain enough space.
2478    The EXTERNAL_RELOCS are a buffer where the external form of the
2479    relocations should be stored.
2480
2481    Returns FALSE if something goes wrong.  */
2482
2483 static bfd_boolean
2484 elf_link_read_relocs_from_section (bfd *abfd,
2485                                    asection *sec,
2486                                    Elf_Internal_Shdr *shdr,
2487                                    void *external_relocs,
2488                                    Elf_Internal_Rela *internal_relocs)
2489 {
2490   const struct elf_backend_data *bed;
2491   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2492   const bfd_byte *erela;
2493   const bfd_byte *erelaend;
2494   Elf_Internal_Rela *irela;
2495   Elf_Internal_Shdr *symtab_hdr;
2496   size_t nsyms;
2497
2498   /* Position ourselves at the start of the section.  */
2499   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2500     return FALSE;
2501
2502   /* Read the relocations.  */
2503   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2504     return FALSE;
2505
2506   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2507   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2508
2509   bed = get_elf_backend_data (abfd);
2510
2511   /* Convert the external relocations to the internal format.  */
2512   if (shdr->sh_entsize == bed->s->sizeof_rel)
2513     swap_in = bed->s->swap_reloc_in;
2514   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2515     swap_in = bed->s->swap_reloca_in;
2516   else
2517     {
2518       bfd_set_error (bfd_error_wrong_format);
2519       return FALSE;
2520     }
2521
2522   erela = (const bfd_byte *) external_relocs;
2523   /* Setting erelaend like this and comparing with <= handles case of
2524      a fuzzed object with sh_size not a multiple of sh_entsize.  */
2525   erelaend = erela + shdr->sh_size - shdr->sh_entsize;
2526   irela = internal_relocs;
2527   while (erela <= erelaend)
2528     {
2529       bfd_vma r_symndx;
2530
2531       (*swap_in) (abfd, erela, irela);
2532       r_symndx = ELF32_R_SYM (irela->r_info);
2533       if (bed->s->arch_size == 64)
2534         r_symndx >>= 24;
2535       if (nsyms > 0)
2536         {
2537           if ((size_t) r_symndx >= nsyms)
2538             {
2539               _bfd_error_handler
2540                 /* xgettext:c-format */
2541                 (_("%pB: bad reloc symbol index (%#" PRIx64 " >= %#lx)"
2542                    " for offset %#" PRIx64 " in section `%pA'"),
2543                  abfd, (uint64_t) r_symndx, (unsigned long) nsyms,
2544                  (uint64_t) irela->r_offset, sec);
2545               bfd_set_error (bfd_error_bad_value);
2546               return FALSE;
2547             }
2548         }
2549       else if (r_symndx != STN_UNDEF)
2550         {
2551           _bfd_error_handler
2552             /* xgettext:c-format */
2553             (_("%pB: non-zero symbol index (%#" PRIx64 ")"
2554                " for offset %#" PRIx64 " in section `%pA'"
2555                " when the object file has no symbol table"),
2556              abfd, (uint64_t) r_symndx,
2557              (uint64_t) irela->r_offset, sec);
2558           bfd_set_error (bfd_error_bad_value);
2559           return FALSE;
2560         }
2561       irela += bed->s->int_rels_per_ext_rel;
2562       erela += shdr->sh_entsize;
2563     }
2564
2565   return TRUE;
2566 }
2567
2568 /* Read and swap the relocs for a section O.  They may have been
2569    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2570    not NULL, they are used as buffers to read into.  They are known to
2571    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2572    the return value is allocated using either malloc or bfd_alloc,
2573    according to the KEEP_MEMORY argument.  If O has two relocation
2574    sections (both REL and RELA relocations), then the REL_HDR
2575    relocations will appear first in INTERNAL_RELOCS, followed by the
2576    RELA_HDR relocations.  */
2577
2578 Elf_Internal_Rela *
2579 _bfd_elf_link_read_relocs (bfd *abfd,
2580                            asection *o,
2581                            void *external_relocs,
2582                            Elf_Internal_Rela *internal_relocs,
2583                            bfd_boolean keep_memory)
2584 {
2585   void *alloc1 = NULL;
2586   Elf_Internal_Rela *alloc2 = NULL;
2587   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2588   struct bfd_elf_section_data *esdo = elf_section_data (o);
2589   Elf_Internal_Rela *internal_rela_relocs;
2590
2591   if (esdo->relocs != NULL)
2592     return esdo->relocs;
2593
2594   if (o->reloc_count == 0)
2595     return NULL;
2596
2597   if (internal_relocs == NULL)
2598     {
2599       bfd_size_type size;
2600
2601       size = (bfd_size_type) o->reloc_count * sizeof (Elf_Internal_Rela);
2602       if (keep_memory)
2603         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2604       else
2605         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2606       if (internal_relocs == NULL)
2607         goto error_return;
2608     }
2609
2610   if (external_relocs == NULL)
2611     {
2612       bfd_size_type size = 0;
2613
2614       if (esdo->rel.hdr)
2615         size += esdo->rel.hdr->sh_size;
2616       if (esdo->rela.hdr)
2617         size += esdo->rela.hdr->sh_size;
2618
2619       alloc1 = bfd_malloc (size);
2620       if (alloc1 == NULL)
2621         goto error_return;
2622       external_relocs = alloc1;
2623     }
2624
2625   internal_rela_relocs = internal_relocs;
2626   if (esdo->rel.hdr)
2627     {
2628       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2629                                               external_relocs,
2630                                               internal_relocs))
2631         goto error_return;
2632       external_relocs = (((bfd_byte *) external_relocs)
2633                          + esdo->rel.hdr->sh_size);
2634       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2635                                * bed->s->int_rels_per_ext_rel);
2636     }
2637
2638   if (esdo->rela.hdr
2639       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2640                                               external_relocs,
2641                                               internal_rela_relocs)))
2642     goto error_return;
2643
2644   /* Cache the results for next time, if we can.  */
2645   if (keep_memory)
2646     esdo->relocs = internal_relocs;
2647
2648   if (alloc1 != NULL)
2649     free (alloc1);
2650
2651   /* Don't free alloc2, since if it was allocated we are passing it
2652      back (under the name of internal_relocs).  */
2653
2654   return internal_relocs;
2655
2656  error_return:
2657   if (alloc1 != NULL)
2658     free (alloc1);
2659   if (alloc2 != NULL)
2660     {
2661       if (keep_memory)
2662         bfd_release (abfd, alloc2);
2663       else
2664         free (alloc2);
2665     }
2666   return NULL;
2667 }
2668
2669 /* Compute the size of, and allocate space for, REL_HDR which is the
2670    section header for a section containing relocations for O.  */
2671
2672 static bfd_boolean
2673 _bfd_elf_link_size_reloc_section (bfd *abfd,
2674                                   struct bfd_elf_section_reloc_data *reldata)
2675 {
2676   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2677
2678   /* That allows us to calculate the size of the section.  */
2679   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2680
2681   /* The contents field must last into write_object_contents, so we
2682      allocate it with bfd_alloc rather than malloc.  Also since we
2683      cannot be sure that the contents will actually be filled in,
2684      we zero the allocated space.  */
2685   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2686   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2687     return FALSE;
2688
2689   if (reldata->hashes == NULL && reldata->count)
2690     {
2691       struct elf_link_hash_entry **p;
2692
2693       p = ((struct elf_link_hash_entry **)
2694            bfd_zmalloc (reldata->count * sizeof (*p)));
2695       if (p == NULL)
2696         return FALSE;
2697
2698       reldata->hashes = p;
2699     }
2700
2701   return TRUE;
2702 }
2703
2704 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2705    originated from the section given by INPUT_REL_HDR) to the
2706    OUTPUT_BFD.  */
2707
2708 bfd_boolean
2709 _bfd_elf_link_output_relocs (bfd *output_bfd,
2710                              asection *input_section,
2711                              Elf_Internal_Shdr *input_rel_hdr,
2712                              Elf_Internal_Rela *internal_relocs,
2713                              struct elf_link_hash_entry **rel_hash
2714                                ATTRIBUTE_UNUSED)
2715 {
2716   Elf_Internal_Rela *irela;
2717   Elf_Internal_Rela *irelaend;
2718   bfd_byte *erel;
2719   struct bfd_elf_section_reloc_data *output_reldata;
2720   asection *output_section;
2721   const struct elf_backend_data *bed;
2722   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2723   struct bfd_elf_section_data *esdo;
2724
2725   output_section = input_section->output_section;
2726
2727   bed = get_elf_backend_data (output_bfd);
2728   esdo = elf_section_data (output_section);
2729   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2730     {
2731       output_reldata = &esdo->rel;
2732       swap_out = bed->s->swap_reloc_out;
2733     }
2734   else if (esdo->rela.hdr
2735            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2736     {
2737       output_reldata = &esdo->rela;
2738       swap_out = bed->s->swap_reloca_out;
2739     }
2740   else
2741     {
2742       _bfd_error_handler
2743         /* xgettext:c-format */
2744         (_("%pB: relocation size mismatch in %pB section %pA"),
2745          output_bfd, input_section->owner, input_section);
2746       bfd_set_error (bfd_error_wrong_format);
2747       return FALSE;
2748     }
2749
2750   erel = output_reldata->hdr->contents;
2751   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2752   irela = internal_relocs;
2753   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2754                       * bed->s->int_rels_per_ext_rel);
2755   while (irela < irelaend)
2756     {
2757       (*swap_out) (output_bfd, irela, erel);
2758       irela += bed->s->int_rels_per_ext_rel;
2759       erel += input_rel_hdr->sh_entsize;
2760     }
2761
2762   /* Bump the counter, so that we know where to add the next set of
2763      relocations.  */
2764   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2765
2766   return TRUE;
2767 }
2768 \f
2769 /* Make weak undefined symbols in PIE dynamic.  */
2770
2771 bfd_boolean
2772 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2773                                  struct elf_link_hash_entry *h)
2774 {
2775   if (bfd_link_pie (info)
2776       && h->dynindx == -1
2777       && h->root.type == bfd_link_hash_undefweak)
2778     return bfd_elf_link_record_dynamic_symbol (info, h);
2779
2780   return TRUE;
2781 }
2782
2783 /* Fix up the flags for a symbol.  This handles various cases which
2784    can only be fixed after all the input files are seen.  This is
2785    currently called by both adjust_dynamic_symbol and
2786    assign_sym_version, which is unnecessary but perhaps more robust in
2787    the face of future changes.  */
2788
2789 static bfd_boolean
2790 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2791                            struct elf_info_failed *eif)
2792 {
2793   const struct elf_backend_data *bed;
2794
2795   /* If this symbol was mentioned in a non-ELF file, try to set
2796      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2797      permit a non-ELF file to correctly refer to a symbol defined in
2798      an ELF dynamic object.  */
2799   if (h->non_elf)
2800     {
2801       while (h->root.type == bfd_link_hash_indirect)
2802         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2803
2804       if (h->root.type != bfd_link_hash_defined
2805           && h->root.type != bfd_link_hash_defweak)
2806         {
2807           h->ref_regular = 1;
2808           h->ref_regular_nonweak = 1;
2809         }
2810       else
2811         {
2812           if (h->root.u.def.section->owner != NULL
2813               && (bfd_get_flavour (h->root.u.def.section->owner)
2814                   == bfd_target_elf_flavour))
2815             {
2816               h->ref_regular = 1;
2817               h->ref_regular_nonweak = 1;
2818             }
2819           else
2820             h->def_regular = 1;
2821         }
2822
2823       if (h->dynindx == -1
2824           && (h->def_dynamic
2825               || h->ref_dynamic))
2826         {
2827           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2828             {
2829               eif->failed = TRUE;
2830               return FALSE;
2831             }
2832         }
2833     }
2834   else
2835     {
2836       /* Unfortunately, NON_ELF is only correct if the symbol
2837          was first seen in a non-ELF file.  Fortunately, if the symbol
2838          was first seen in an ELF file, we're probably OK unless the
2839          symbol was defined in a non-ELF file.  Catch that case here.
2840          FIXME: We're still in trouble if the symbol was first seen in
2841          a dynamic object, and then later in a non-ELF regular object.  */
2842       if ((h->root.type == bfd_link_hash_defined
2843            || h->root.type == bfd_link_hash_defweak)
2844           && !h->def_regular
2845           && (h->root.u.def.section->owner != NULL
2846               ? (bfd_get_flavour (h->root.u.def.section->owner)
2847                  != bfd_target_elf_flavour)
2848               : (bfd_is_abs_section (h->root.u.def.section)
2849                  && !h->def_dynamic)))
2850         h->def_regular = 1;
2851     }
2852
2853   /* Backend specific symbol fixup.  */
2854   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2855   if (bed->elf_backend_fixup_symbol
2856       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2857     return FALSE;
2858
2859   /* If this is a final link, and the symbol was defined as a common
2860      symbol in a regular object file, and there was no definition in
2861      any dynamic object, then the linker will have allocated space for
2862      the symbol in a common section but the DEF_REGULAR
2863      flag will not have been set.  */
2864   if (h->root.type == bfd_link_hash_defined
2865       && !h->def_regular
2866       && h->ref_regular
2867       && !h->def_dynamic
2868       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2869     h->def_regular = 1;
2870
2871   /* Symbols defined in discarded sections shouldn't be dynamic.  */
2872   if (h->root.type == bfd_link_hash_undefined && h->indx == -3)
2873     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2874
2875   /* If a weak undefined symbol has non-default visibility, we also
2876      hide it from the dynamic linker.  */
2877   else if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2878            && h->root.type == bfd_link_hash_undefweak)
2879     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2880
2881   /* A hidden versioned symbol in executable should be forced local if
2882      it is is locally defined, not referenced by shared library and not
2883      exported.  */
2884   else if (bfd_link_executable (eif->info)
2885            && h->versioned == versioned_hidden
2886            && !eif->info->export_dynamic
2887            && !h->dynamic
2888            && !h->ref_dynamic
2889            && h->def_regular)
2890     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2891
2892   /* If -Bsymbolic was used (which means to bind references to global
2893      symbols to the definition within the shared object), and this
2894      symbol was defined in a regular object, then it actually doesn't
2895      need a PLT entry.  Likewise, if the symbol has non-default
2896      visibility.  If the symbol has hidden or internal visibility, we
2897      will force it local.  */
2898   else if (h->needs_plt
2899            && bfd_link_pic (eif->info)
2900            && is_elf_hash_table (eif->info->hash)
2901            && (SYMBOLIC_BIND (eif->info, h)
2902                || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2903            && h->def_regular)
2904     {
2905       bfd_boolean force_local;
2906
2907       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2908                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2909       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2910     }
2911
2912   /* If this is a weak defined symbol in a dynamic object, and we know
2913      the real definition in the dynamic object, copy interesting flags
2914      over to the real definition.  */
2915   if (h->is_weakalias)
2916     {
2917       struct elf_link_hash_entry *def = weakdef (h);
2918
2919       /* If the real definition is defined by a regular object file,
2920          don't do anything special.  See the longer description in
2921          _bfd_elf_adjust_dynamic_symbol, below.  If the def is not
2922          bfd_link_hash_defined as it was when put on the alias list
2923          then it must have originally been a versioned symbol (for
2924          which a non-versioned indirect symbol is created) and later
2925          a definition for the non-versioned symbol is found.  In that
2926          case the indirection is flipped with the versioned symbol
2927          becoming an indirect pointing at the non-versioned symbol.
2928          Thus, not an alias any more.  */
2929       if (def->def_regular
2930           || def->root.type != bfd_link_hash_defined)
2931         {
2932           h = def;
2933           while ((h = h->u.alias) != def)
2934             h->is_weakalias = 0;
2935         }
2936       else
2937         {
2938           while (h->root.type == bfd_link_hash_indirect)
2939             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2940           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2941                       || h->root.type == bfd_link_hash_defweak);
2942           BFD_ASSERT (def->def_dynamic);
2943           (*bed->elf_backend_copy_indirect_symbol) (eif->info, def, h);
2944         }
2945     }
2946
2947   return TRUE;
2948 }
2949
2950 /* Make the backend pick a good value for a dynamic symbol.  This is
2951    called via elf_link_hash_traverse, and also calls itself
2952    recursively.  */
2953
2954 static bfd_boolean
2955 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2956 {
2957   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2958   struct elf_link_hash_table *htab;
2959   const struct elf_backend_data *bed;
2960
2961   if (! is_elf_hash_table (eif->info->hash))
2962     return FALSE;
2963
2964   /* Ignore indirect symbols.  These are added by the versioning code.  */
2965   if (h->root.type == bfd_link_hash_indirect)
2966     return TRUE;
2967
2968   /* Fix the symbol flags.  */
2969   if (! _bfd_elf_fix_symbol_flags (h, eif))
2970     return FALSE;
2971
2972   htab = elf_hash_table (eif->info);
2973   bed = get_elf_backend_data (htab->dynobj);
2974
2975   if (h->root.type == bfd_link_hash_undefweak)
2976     {
2977       if (eif->info->dynamic_undefined_weak == 0)
2978         (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2979       else if (eif->info->dynamic_undefined_weak > 0
2980                && h->ref_regular
2981                && ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2982                && !bfd_hide_sym_by_version (eif->info->version_info,
2983                                             h->root.root.string))
2984         {
2985           if (!bfd_elf_link_record_dynamic_symbol (eif->info, h))
2986             {
2987               eif->failed = TRUE;
2988               return FALSE;
2989             }
2990         }
2991     }
2992
2993   /* If this symbol does not require a PLT entry, and it is not
2994      defined by a dynamic object, or is not referenced by a regular
2995      object, ignore it.  We do have to handle a weak defined symbol,
2996      even if no regular object refers to it, if we decided to add it
2997      to the dynamic symbol table.  FIXME: Do we normally need to worry
2998      about symbols which are defined by one dynamic object and
2999      referenced by another one?  */
3000   if (!h->needs_plt
3001       && h->type != STT_GNU_IFUNC
3002       && (h->def_regular
3003           || !h->def_dynamic
3004           || (!h->ref_regular
3005               && (!h->is_weakalias || weakdef (h)->dynindx == -1))))
3006     {
3007       h->plt = elf_hash_table (eif->info)->init_plt_offset;
3008       return TRUE;
3009     }
3010
3011   /* If we've already adjusted this symbol, don't do it again.  This
3012      can happen via a recursive call.  */
3013   if (h->dynamic_adjusted)
3014     return TRUE;
3015
3016   /* Don't look at this symbol again.  Note that we must set this
3017      after checking the above conditions, because we may look at a
3018      symbol once, decide not to do anything, and then get called
3019      recursively later after REF_REGULAR is set below.  */
3020   h->dynamic_adjusted = 1;
3021
3022   /* If this is a weak definition, and we know a real definition, and
3023      the real symbol is not itself defined by a regular object file,
3024      then get a good value for the real definition.  We handle the
3025      real symbol first, for the convenience of the backend routine.
3026
3027      Note that there is a confusing case here.  If the real definition
3028      is defined by a regular object file, we don't get the real symbol
3029      from the dynamic object, but we do get the weak symbol.  If the
3030      processor backend uses a COPY reloc, then if some routine in the
3031      dynamic object changes the real symbol, we will not see that
3032      change in the corresponding weak symbol.  This is the way other
3033      ELF linkers work as well, and seems to be a result of the shared
3034      library model.
3035
3036      I will clarify this issue.  Most SVR4 shared libraries define the
3037      variable _timezone and define timezone as a weak synonym.  The
3038      tzset call changes _timezone.  If you write
3039        extern int timezone;
3040        int _timezone = 5;
3041        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
3042      you might expect that, since timezone is a synonym for _timezone,
3043      the same number will print both times.  However, if the processor
3044      backend uses a COPY reloc, then actually timezone will be copied
3045      into your process image, and, since you define _timezone
3046      yourself, _timezone will not.  Thus timezone and _timezone will
3047      wind up at different memory locations.  The tzset call will set
3048      _timezone, leaving timezone unchanged.  */
3049
3050   if (h->is_weakalias)
3051     {
3052       struct elf_link_hash_entry *def = weakdef (h);
3053
3054       /* If we get to this point, there is an implicit reference to
3055          the alias by a regular object file via the weak symbol H.  */
3056       def->ref_regular = 1;
3057
3058       /* Ensure that the backend adjust_dynamic_symbol function sees
3059          the strong alias before H by recursively calling ourselves.  */
3060       if (!_bfd_elf_adjust_dynamic_symbol (def, eif))
3061         return FALSE;
3062     }
3063
3064   /* If a symbol has no type and no size and does not require a PLT
3065      entry, then we are probably about to do the wrong thing here: we
3066      are probably going to create a COPY reloc for an empty object.
3067      This case can arise when a shared object is built with assembly
3068      code, and the assembly code fails to set the symbol type.  */
3069   if (h->size == 0
3070       && h->type == STT_NOTYPE
3071       && !h->needs_plt)
3072     _bfd_error_handler
3073       (_("warning: type and size of dynamic symbol `%s' are not defined"),
3074        h->root.root.string);
3075
3076   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
3077     {
3078       eif->failed = TRUE;
3079       return FALSE;
3080     }
3081
3082   return TRUE;
3083 }
3084
3085 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
3086    DYNBSS.  */
3087
3088 bfd_boolean
3089 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
3090                               struct elf_link_hash_entry *h,
3091                               asection *dynbss)
3092 {
3093   unsigned int power_of_two;
3094   bfd_vma mask;
3095   asection *sec = h->root.u.def.section;
3096
3097   /* The section alignment of the definition is the maximum alignment
3098      requirement of symbols defined in the section.  Since we don't
3099      know the symbol alignment requirement, we start with the
3100      maximum alignment and check low bits of the symbol address
3101      for the minimum alignment.  */
3102   power_of_two = bfd_get_section_alignment (sec->owner, sec);
3103   mask = ((bfd_vma) 1 << power_of_two) - 1;
3104   while ((h->root.u.def.value & mask) != 0)
3105     {
3106        mask >>= 1;
3107        --power_of_two;
3108     }
3109
3110   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
3111                                                 dynbss))
3112     {
3113       /* Adjust the section alignment if needed.  */
3114       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
3115                                        power_of_two))
3116         return FALSE;
3117     }
3118
3119   /* We make sure that the symbol will be aligned properly.  */
3120   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
3121
3122   /* Define the symbol as being at this point in DYNBSS.  */
3123   h->root.u.def.section = dynbss;
3124   h->root.u.def.value = dynbss->size;
3125
3126   /* Increment the size of DYNBSS to make room for the symbol.  */
3127   dynbss->size += h->size;
3128
3129   /* No error if extern_protected_data is true.  */
3130   if (h->protected_def
3131       && (!info->extern_protected_data
3132           || (info->extern_protected_data < 0
3133               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
3134     info->callbacks->einfo
3135       (_("%P: copy reloc against protected `%pT' is dangerous\n"),
3136        h->root.root.string);
3137
3138   return TRUE;
3139 }
3140
3141 /* Adjust all external symbols pointing into SEC_MERGE sections
3142    to reflect the object merging within the sections.  */
3143
3144 static bfd_boolean
3145 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
3146 {
3147   asection *sec;
3148
3149   if ((h->root.type == bfd_link_hash_defined
3150        || h->root.type == bfd_link_hash_defweak)
3151       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
3152       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
3153     {
3154       bfd *output_bfd = (bfd *) data;
3155
3156       h->root.u.def.value =
3157         _bfd_merged_section_offset (output_bfd,
3158                                     &h->root.u.def.section,
3159                                     elf_section_data (sec)->sec_info,
3160                                     h->root.u.def.value);
3161     }
3162
3163   return TRUE;
3164 }
3165
3166 /* Returns false if the symbol referred to by H should be considered
3167    to resolve local to the current module, and true if it should be
3168    considered to bind dynamically.  */
3169
3170 bfd_boolean
3171 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
3172                            struct bfd_link_info *info,
3173                            bfd_boolean not_local_protected)
3174 {
3175   bfd_boolean binding_stays_local_p;
3176   const struct elf_backend_data *bed;
3177   struct elf_link_hash_table *hash_table;
3178
3179   if (h == NULL)
3180     return FALSE;
3181
3182   while (h->root.type == bfd_link_hash_indirect
3183          || h->root.type == bfd_link_hash_warning)
3184     h = (struct elf_link_hash_entry *) h->root.u.i.link;
3185
3186   /* If it was forced local, then clearly it's not dynamic.  */
3187   if (h->dynindx == -1)
3188     return FALSE;
3189   if (h->forced_local)
3190     return FALSE;
3191
3192   /* Identify the cases where name binding rules say that a
3193      visible symbol resolves locally.  */
3194   binding_stays_local_p = (bfd_link_executable (info)
3195                            || SYMBOLIC_BIND (info, h));
3196
3197   switch (ELF_ST_VISIBILITY (h->other))
3198     {
3199     case STV_INTERNAL:
3200     case STV_HIDDEN:
3201       return FALSE;
3202
3203     case STV_PROTECTED:
3204       hash_table = elf_hash_table (info);
3205       if (!is_elf_hash_table (hash_table))
3206         return FALSE;
3207
3208       bed = get_elf_backend_data (hash_table->dynobj);
3209
3210       /* Proper resolution for function pointer equality may require
3211          that these symbols perhaps be resolved dynamically, even though
3212          we should be resolving them to the current module.  */
3213       if (!not_local_protected || !bed->is_function_type (h->type))
3214         binding_stays_local_p = TRUE;
3215       break;
3216
3217     default:
3218       break;
3219     }
3220
3221   /* If it isn't defined locally, then clearly it's dynamic.  */
3222   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
3223     return TRUE;
3224
3225   /* Otherwise, the symbol is dynamic if binding rules don't tell
3226      us that it remains local.  */
3227   return !binding_stays_local_p;
3228 }
3229
3230 /* Return true if the symbol referred to by H should be considered
3231    to resolve local to the current module, and false otherwise.  Differs
3232    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
3233    undefined symbols.  The two functions are virtually identical except
3234    for the place where dynindx == -1 is tested.  If that test is true,
3235    _bfd_elf_dynamic_symbol_p will say the symbol is local, while
3236    _bfd_elf_symbol_refs_local_p will say the symbol is local only for
3237    defined symbols.
3238    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
3239    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
3240    treatment of undefined weak symbols.  For those that do not make
3241    undefined weak symbols dynamic, both functions may return false.  */
3242
3243 bfd_boolean
3244 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
3245                               struct bfd_link_info *info,
3246                               bfd_boolean local_protected)
3247 {
3248   const struct elf_backend_data *bed;
3249   struct elf_link_hash_table *hash_table;
3250
3251   /* If it's a local sym, of course we resolve locally.  */
3252   if (h == NULL)
3253     return TRUE;
3254
3255   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
3256   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
3257       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
3258     return TRUE;
3259
3260   /* Forced local symbols resolve locally.  */
3261   if (h->forced_local)
3262     return TRUE;
3263
3264   /* Common symbols that become definitions don't get the DEF_REGULAR
3265      flag set, so test it first, and don't bail out.  */
3266   if (ELF_COMMON_DEF_P (h))
3267     /* Do nothing.  */;
3268   /* If we don't have a definition in a regular file, then we can't
3269      resolve locally.  The sym is either undefined or dynamic.  */
3270   else if (!h->def_regular)
3271     return FALSE;
3272
3273   /* Non-dynamic symbols resolve locally.  */
3274   if (h->dynindx == -1)
3275     return TRUE;
3276
3277   /* At this point, we know the symbol is defined and dynamic.  In an
3278      executable it must resolve locally, likewise when building symbolic
3279      shared libraries.  */
3280   if (bfd_link_executable (info) || SYMBOLIC_BIND (info, h))
3281     return TRUE;
3282
3283   /* Now deal with defined dynamic symbols in shared libraries.  Ones
3284      with default visibility might not resolve locally.  */
3285   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
3286     return FALSE;
3287
3288   hash_table = elf_hash_table (info);
3289   if (!is_elf_hash_table (hash_table))
3290     return TRUE;
3291
3292   bed = get_elf_backend_data (hash_table->dynobj);
3293
3294   /* If extern_protected_data is false, STV_PROTECTED non-function
3295      symbols are local.  */
3296   if ((!info->extern_protected_data
3297        || (info->extern_protected_data < 0
3298            && !bed->extern_protected_data))
3299       && !bed->is_function_type (h->type))
3300     return TRUE;
3301
3302   /* Function pointer equality tests may require that STV_PROTECTED
3303      symbols be treated as dynamic symbols.  If the address of a
3304      function not defined in an executable is set to that function's
3305      plt entry in the executable, then the address of the function in
3306      a shared library must also be the plt entry in the executable.  */
3307   return local_protected;
3308 }
3309
3310 /* Caches some TLS segment info, and ensures that the TLS segment vma is
3311    aligned.  Returns the first TLS output section.  */
3312
3313 struct bfd_section *
3314 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
3315 {
3316   struct bfd_section *sec, *tls;
3317   unsigned int align = 0;
3318
3319   for (sec = obfd->sections; sec != NULL; sec = sec->next)
3320     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
3321       break;
3322   tls = sec;
3323
3324   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
3325     if (sec->alignment_power > align)
3326       align = sec->alignment_power;
3327
3328   elf_hash_table (info)->tls_sec = tls;
3329
3330   /* Ensure the alignment of the first section is the largest alignment,
3331      so that the tls segment starts aligned.  */
3332   if (tls != NULL)
3333     tls->alignment_power = align;
3334
3335   return tls;
3336 }
3337
3338 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
3339 static bfd_boolean
3340 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
3341                                   Elf_Internal_Sym *sym)
3342 {
3343   const struct elf_backend_data *bed;
3344
3345   /* Local symbols do not count, but target specific ones might.  */
3346   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
3347       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
3348     return FALSE;
3349
3350   bed = get_elf_backend_data (abfd);
3351   /* Function symbols do not count.  */
3352   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
3353     return FALSE;
3354
3355   /* If the section is undefined, then so is the symbol.  */
3356   if (sym->st_shndx == SHN_UNDEF)
3357     return FALSE;
3358
3359   /* If the symbol is defined in the common section, then
3360      it is a common definition and so does not count.  */
3361   if (bed->common_definition (sym))
3362     return FALSE;
3363
3364   /* If the symbol is in a target specific section then we
3365      must rely upon the backend to tell us what it is.  */
3366   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3367     /* FIXME - this function is not coded yet:
3368
3369        return _bfd_is_global_symbol_definition (abfd, sym);
3370
3371        Instead for now assume that the definition is not global,
3372        Even if this is wrong, at least the linker will behave
3373        in the same way that it used to do.  */
3374     return FALSE;
3375
3376   return TRUE;
3377 }
3378
3379 /* Search the symbol table of the archive element of the archive ABFD
3380    whose archive map contains a mention of SYMDEF, and determine if
3381    the symbol is defined in this element.  */
3382 static bfd_boolean
3383 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3384 {
3385   Elf_Internal_Shdr * hdr;
3386   size_t symcount;
3387   size_t extsymcount;
3388   size_t extsymoff;
3389   Elf_Internal_Sym *isymbuf;
3390   Elf_Internal_Sym *isym;
3391   Elf_Internal_Sym *isymend;
3392   bfd_boolean result;
3393
3394   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3395   if (abfd == NULL)
3396     return FALSE;
3397
3398   if (! bfd_check_format (abfd, bfd_object))
3399     return FALSE;
3400
3401   /* Select the appropriate symbol table.  If we don't know if the
3402      object file is an IR object, give linker LTO plugin a chance to
3403      get the correct symbol table.  */
3404   if (abfd->plugin_format == bfd_plugin_yes
3405 #if BFD_SUPPORTS_PLUGINS
3406       || (abfd->plugin_format == bfd_plugin_unknown
3407           && bfd_link_plugin_object_p (abfd))
3408 #endif
3409       )
3410     {
3411       /* Use the IR symbol table if the object has been claimed by
3412          plugin.  */
3413       abfd = abfd->plugin_dummy_bfd;
3414       hdr = &elf_tdata (abfd)->symtab_hdr;
3415     }
3416   else if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3417     hdr = &elf_tdata (abfd)->symtab_hdr;
3418   else
3419     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3420
3421   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3422
3423   /* The sh_info field of the symtab header tells us where the
3424      external symbols start.  We don't care about the local symbols.  */
3425   if (elf_bad_symtab (abfd))
3426     {
3427       extsymcount = symcount;
3428       extsymoff = 0;
3429     }
3430   else
3431     {
3432       extsymcount = symcount - hdr->sh_info;
3433       extsymoff = hdr->sh_info;
3434     }
3435
3436   if (extsymcount == 0)
3437     return FALSE;
3438
3439   /* Read in the symbol table.  */
3440   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3441                                   NULL, NULL, NULL);
3442   if (isymbuf == NULL)
3443     return FALSE;
3444
3445   /* Scan the symbol table looking for SYMDEF.  */
3446   result = FALSE;
3447   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3448     {
3449       const char *name;
3450
3451       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3452                                               isym->st_name);
3453       if (name == NULL)
3454         break;
3455
3456       if (strcmp (name, symdef->name) == 0)
3457         {
3458           result = is_global_data_symbol_definition (abfd, isym);
3459           break;
3460         }
3461     }
3462
3463   free (isymbuf);
3464
3465   return result;
3466 }
3467 \f
3468 /* Add an entry to the .dynamic table.  */
3469
3470 bfd_boolean
3471 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3472                             bfd_vma tag,
3473                             bfd_vma val)
3474 {
3475   struct elf_link_hash_table *hash_table;
3476   const struct elf_backend_data *bed;
3477   asection *s;
3478   bfd_size_type newsize;
3479   bfd_byte *newcontents;
3480   Elf_Internal_Dyn dyn;
3481
3482   hash_table = elf_hash_table (info);
3483   if (! is_elf_hash_table (hash_table))
3484     return FALSE;
3485
3486   if (tag == DT_RELA || tag == DT_REL)
3487     hash_table->dynamic_relocs = TRUE;
3488
3489   bed = get_elf_backend_data (hash_table->dynobj);
3490   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3491   BFD_ASSERT (s != NULL);
3492
3493   newsize = s->size + bed->s->sizeof_dyn;
3494   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3495   if (newcontents == NULL)
3496     return FALSE;
3497
3498   dyn.d_tag = tag;
3499   dyn.d_un.d_val = val;
3500   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3501
3502   s->size = newsize;
3503   s->contents = newcontents;
3504
3505   return TRUE;
3506 }
3507
3508 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3509    otherwise just check whether one already exists.  Returns -1 on error,
3510    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3511
3512 static int
3513 elf_add_dt_needed_tag (bfd *abfd,
3514                        struct bfd_link_info *info,
3515                        const char *soname,
3516                        bfd_boolean do_it)
3517 {
3518   struct elf_link_hash_table *hash_table;
3519   size_t strindex;
3520
3521   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3522     return -1;
3523
3524   hash_table = elf_hash_table (info);
3525   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3526   if (strindex == (size_t) -1)
3527     return -1;
3528
3529   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3530     {
3531       asection *sdyn;
3532       const struct elf_backend_data *bed;
3533       bfd_byte *extdyn;
3534
3535       bed = get_elf_backend_data (hash_table->dynobj);
3536       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3537       if (sdyn != NULL)
3538         for (extdyn = sdyn->contents;
3539              extdyn < sdyn->contents + sdyn->size;
3540              extdyn += bed->s->sizeof_dyn)
3541           {
3542             Elf_Internal_Dyn dyn;
3543
3544             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3545             if (dyn.d_tag == DT_NEEDED
3546                 && dyn.d_un.d_val == strindex)
3547               {
3548                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3549                 return 1;
3550               }
3551           }
3552     }
3553
3554   if (do_it)
3555     {
3556       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3557         return -1;
3558
3559       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3560         return -1;
3561     }
3562   else
3563     /* We were just checking for existence of the tag.  */
3564     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3565
3566   return 0;
3567 }
3568
3569 /* Return true if SONAME is on the needed list between NEEDED and STOP
3570    (or the end of list if STOP is NULL), and needed by a library that
3571    will be loaded.  */
3572
3573 static bfd_boolean
3574 on_needed_list (const char *soname,
3575                 struct bfd_link_needed_list *needed,
3576                 struct bfd_link_needed_list *stop)
3577 {
3578   struct bfd_link_needed_list *look;
3579   for (look = needed; look != stop; look = look->next)
3580     if (strcmp (soname, look->name) == 0
3581         && ((elf_dyn_lib_class (look->by) & DYN_AS_NEEDED) == 0
3582             /* If needed by a library that itself is not directly
3583                needed, recursively check whether that library is
3584                indirectly needed.  Since we add DT_NEEDED entries to
3585                the end of the list, library dependencies appear after
3586                the library.  Therefore search prior to the current
3587                LOOK, preventing possible infinite recursion.  */
3588             || on_needed_list (elf_dt_name (look->by), needed, look)))
3589       return TRUE;
3590
3591   return FALSE;
3592 }
3593
3594 /* Sort symbol by value, section, and size.  */
3595 static int
3596 elf_sort_symbol (const void *arg1, const void *arg2)
3597 {
3598   const struct elf_link_hash_entry *h1;
3599   const struct elf_link_hash_entry *h2;
3600   bfd_signed_vma vdiff;
3601
3602   h1 = *(const struct elf_link_hash_entry **) arg1;
3603   h2 = *(const struct elf_link_hash_entry **) arg2;
3604   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3605   if (vdiff != 0)
3606     return vdiff > 0 ? 1 : -1;
3607   else
3608     {
3609       int sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3610       if (sdiff != 0)
3611         return sdiff > 0 ? 1 : -1;
3612     }
3613   vdiff = h1->size - h2->size;
3614   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3615 }
3616
3617 /* This function is used to adjust offsets into .dynstr for
3618    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3619
3620 static bfd_boolean
3621 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3622 {
3623   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3624
3625   if (h->dynindx != -1)
3626     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3627   return TRUE;
3628 }
3629
3630 /* Assign string offsets in .dynstr, update all structures referencing
3631    them.  */
3632
3633 static bfd_boolean
3634 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3635 {
3636   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3637   struct elf_link_local_dynamic_entry *entry;
3638   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3639   bfd *dynobj = hash_table->dynobj;
3640   asection *sdyn;
3641   bfd_size_type size;
3642   const struct elf_backend_data *bed;
3643   bfd_byte *extdyn;
3644
3645   _bfd_elf_strtab_finalize (dynstr);
3646   size = _bfd_elf_strtab_size (dynstr);
3647
3648   bed = get_elf_backend_data (dynobj);
3649   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3650   BFD_ASSERT (sdyn != NULL);
3651
3652   /* Update all .dynamic entries referencing .dynstr strings.  */
3653   for (extdyn = sdyn->contents;
3654        extdyn < sdyn->contents + sdyn->size;
3655        extdyn += bed->s->sizeof_dyn)
3656     {
3657       Elf_Internal_Dyn dyn;
3658
3659       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3660       switch (dyn.d_tag)
3661         {
3662         case DT_STRSZ:
3663           dyn.d_un.d_val = size;
3664           break;
3665         case DT_NEEDED:
3666         case DT_SONAME:
3667         case DT_RPATH:
3668         case DT_RUNPATH:
3669         case DT_FILTER:
3670         case DT_AUXILIARY:
3671         case DT_AUDIT:
3672         case DT_DEPAUDIT:
3673           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3674           break;
3675         default:
3676           continue;
3677         }
3678       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3679     }
3680
3681   /* Now update local dynamic symbols.  */
3682   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3683     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3684                                                   entry->isym.st_name);
3685
3686   /* And the rest of dynamic symbols.  */
3687   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3688
3689   /* Adjust version definitions.  */
3690   if (elf_tdata (output_bfd)->cverdefs)
3691     {
3692       asection *s;
3693       bfd_byte *p;
3694       size_t i;
3695       Elf_Internal_Verdef def;
3696       Elf_Internal_Verdaux defaux;
3697
3698       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3699       p = s->contents;
3700       do
3701         {
3702           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3703                                    &def);
3704           p += sizeof (Elf_External_Verdef);
3705           if (def.vd_aux != sizeof (Elf_External_Verdef))
3706             continue;
3707           for (i = 0; i < def.vd_cnt; ++i)
3708             {
3709               _bfd_elf_swap_verdaux_in (output_bfd,
3710                                         (Elf_External_Verdaux *) p, &defaux);
3711               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3712                                                         defaux.vda_name);
3713               _bfd_elf_swap_verdaux_out (output_bfd,
3714                                          &defaux, (Elf_External_Verdaux *) p);
3715               p += sizeof (Elf_External_Verdaux);
3716             }
3717         }
3718       while (def.vd_next);
3719     }
3720
3721   /* Adjust version references.  */
3722   if (elf_tdata (output_bfd)->verref)
3723     {
3724       asection *s;
3725       bfd_byte *p;
3726       size_t i;
3727       Elf_Internal_Verneed need;
3728       Elf_Internal_Vernaux needaux;
3729
3730       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3731       p = s->contents;
3732       do
3733         {
3734           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3735                                     &need);
3736           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3737           _bfd_elf_swap_verneed_out (output_bfd, &need,
3738                                      (Elf_External_Verneed *) p);
3739           p += sizeof (Elf_External_Verneed);
3740           for (i = 0; i < need.vn_cnt; ++i)
3741             {
3742               _bfd_elf_swap_vernaux_in (output_bfd,
3743                                         (Elf_External_Vernaux *) p, &needaux);
3744               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3745                                                          needaux.vna_name);
3746               _bfd_elf_swap_vernaux_out (output_bfd,
3747                                          &needaux,
3748                                          (Elf_External_Vernaux *) p);
3749               p += sizeof (Elf_External_Vernaux);
3750             }
3751         }
3752       while (need.vn_next);
3753     }
3754
3755   return TRUE;
3756 }
3757 \f
3758 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3759    The default is to only match when the INPUT and OUTPUT are exactly
3760    the same target.  */
3761
3762 bfd_boolean
3763 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3764                                     const bfd_target *output)
3765 {
3766   return input == output;
3767 }
3768
3769 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3770    This version is used when different targets for the same architecture
3771    are virtually identical.  */
3772
3773 bfd_boolean
3774 _bfd_elf_relocs_compatible (const bfd_target *input,
3775                             const bfd_target *output)
3776 {
3777   const struct elf_backend_data *obed, *ibed;
3778
3779   if (input == output)
3780     return TRUE;
3781
3782   ibed = xvec_get_elf_backend_data (input);
3783   obed = xvec_get_elf_backend_data (output);
3784
3785   if (ibed->arch != obed->arch)
3786     return FALSE;
3787
3788   /* If both backends are using this function, deem them compatible.  */
3789   return ibed->relocs_compatible == obed->relocs_compatible;
3790 }
3791
3792 /* Make a special call to the linker "notice" function to tell it that
3793    we are about to handle an as-needed lib, or have finished
3794    processing the lib.  */
3795
3796 bfd_boolean
3797 _bfd_elf_notice_as_needed (bfd *ibfd,
3798                            struct bfd_link_info *info,
3799                            enum notice_asneeded_action act)
3800 {
3801   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3802 }
3803
3804 /* Check relocations an ELF object file.  */
3805
3806 bfd_boolean
3807 _bfd_elf_link_check_relocs (bfd *abfd, struct bfd_link_info *info)
3808 {
3809   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3810   struct elf_link_hash_table *htab = elf_hash_table (info);
3811
3812   /* If this object is the same format as the output object, and it is
3813      not a shared library, then let the backend look through the
3814      relocs.
3815
3816      This is required to build global offset table entries and to
3817      arrange for dynamic relocs.  It is not required for the
3818      particular common case of linking non PIC code, even when linking
3819      against shared libraries, but unfortunately there is no way of
3820      knowing whether an object file has been compiled PIC or not.
3821      Looking through the relocs is not particularly time consuming.
3822      The problem is that we must either (1) keep the relocs in memory,
3823      which causes the linker to require additional runtime memory or
3824      (2) read the relocs twice from the input file, which wastes time.
3825      This would be a good case for using mmap.
3826
3827      I have no idea how to handle linking PIC code into a file of a
3828      different format.  It probably can't be done.  */
3829   if ((abfd->flags & DYNAMIC) == 0
3830       && is_elf_hash_table (htab)
3831       && bed->check_relocs != NULL
3832       && elf_object_id (abfd) == elf_hash_table_id (htab)
3833       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
3834     {
3835       asection *o;
3836
3837       for (o = abfd->sections; o != NULL; o = o->next)
3838         {
3839           Elf_Internal_Rela *internal_relocs;
3840           bfd_boolean ok;
3841
3842           /* Don't check relocations in excluded sections.  */
3843           if ((o->flags & SEC_RELOC) == 0
3844               || (o->flags & SEC_EXCLUDE) != 0
3845               || o->reloc_count == 0
3846               || ((info->strip == strip_all || info->strip == strip_debugger)
3847                   && (o->flags & SEC_DEBUGGING) != 0)
3848               || bfd_is_abs_section (o->output_section))
3849             continue;
3850
3851           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
3852                                                        info->keep_memory);
3853           if (internal_relocs == NULL)
3854             return FALSE;
3855
3856           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
3857
3858           if (elf_section_data (o)->relocs != internal_relocs)
3859             free (internal_relocs);
3860
3861           if (! ok)
3862             return FALSE;
3863         }
3864     }
3865
3866   return TRUE;
3867 }
3868
3869 /* Add symbols from an ELF object file to the linker hash table.  */
3870
3871 static bfd_boolean
3872 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3873 {
3874   Elf_Internal_Ehdr *ehdr;
3875   Elf_Internal_Shdr *hdr;
3876   size_t symcount;
3877   size_t extsymcount;
3878   size_t extsymoff;
3879   struct elf_link_hash_entry **sym_hash;
3880   bfd_boolean dynamic;
3881   Elf_External_Versym *extversym = NULL;
3882   Elf_External_Versym *extversym_end = NULL;
3883   Elf_External_Versym *ever;
3884   struct elf_link_hash_entry *weaks;
3885   struct elf_link_hash_entry **nondeflt_vers = NULL;
3886   size_t nondeflt_vers_cnt = 0;
3887   Elf_Internal_Sym *isymbuf = NULL;
3888   Elf_Internal_Sym *isym;
3889   Elf_Internal_Sym *isymend;
3890   const struct elf_backend_data *bed;
3891   bfd_boolean add_needed;
3892   struct elf_link_hash_table *htab;
3893   bfd_size_type amt;
3894   void *alloc_mark = NULL;
3895   struct bfd_hash_entry **old_table = NULL;
3896   unsigned int old_size = 0;
3897   unsigned int old_count = 0;
3898   void *old_tab = NULL;
3899   void *old_ent;
3900   struct bfd_link_hash_entry *old_undefs = NULL;
3901   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3902   void *old_strtab = NULL;
3903   size_t tabsize = 0;
3904   asection *s;
3905   bfd_boolean just_syms;
3906
3907   htab = elf_hash_table (info);
3908   bed = get_elf_backend_data (abfd);
3909
3910   if ((abfd->flags & DYNAMIC) == 0)
3911     dynamic = FALSE;
3912   else
3913     {
3914       dynamic = TRUE;
3915
3916       /* You can't use -r against a dynamic object.  Also, there's no
3917          hope of using a dynamic object which does not exactly match
3918          the format of the output file.  */
3919       if (bfd_link_relocatable (info)
3920           || !is_elf_hash_table (htab)
3921           || info->output_bfd->xvec != abfd->xvec)
3922         {
3923           if (bfd_link_relocatable (info))
3924             bfd_set_error (bfd_error_invalid_operation);
3925           else
3926             bfd_set_error (bfd_error_wrong_format);
3927           goto error_return;
3928         }
3929     }
3930
3931   ehdr = elf_elfheader (abfd);
3932   if (info->warn_alternate_em
3933       && bed->elf_machine_code != ehdr->e_machine
3934       && ((bed->elf_machine_alt1 != 0
3935            && ehdr->e_machine == bed->elf_machine_alt1)
3936           || (bed->elf_machine_alt2 != 0
3937               && ehdr->e_machine == bed->elf_machine_alt2)))
3938     _bfd_error_handler
3939       /* xgettext:c-format */
3940       (_("alternate ELF machine code found (%d) in %pB, expecting %d"),
3941        ehdr->e_machine, abfd, bed->elf_machine_code);
3942
3943   /* As a GNU extension, any input sections which are named
3944      .gnu.warning.SYMBOL are treated as warning symbols for the given
3945      symbol.  This differs from .gnu.warning sections, which generate
3946      warnings when they are included in an output file.  */
3947   /* PR 12761: Also generate this warning when building shared libraries.  */
3948   for (s = abfd->sections; s != NULL; s = s->next)
3949     {
3950       const char *name;
3951
3952       name = bfd_get_section_name (abfd, s);
3953       if (CONST_STRNEQ (name, ".gnu.warning."))
3954         {
3955           char *msg;
3956           bfd_size_type sz;
3957
3958           name += sizeof ".gnu.warning." - 1;
3959
3960           /* If this is a shared object, then look up the symbol
3961              in the hash table.  If it is there, and it is already
3962              been defined, then we will not be using the entry
3963              from this shared object, so we don't need to warn.
3964              FIXME: If we see the definition in a regular object
3965              later on, we will warn, but we shouldn't.  The only
3966              fix is to keep track of what warnings we are supposed
3967              to emit, and then handle them all at the end of the
3968              link.  */
3969           if (dynamic)
3970             {
3971               struct elf_link_hash_entry *h;
3972
3973               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3974
3975               /* FIXME: What about bfd_link_hash_common?  */
3976               if (h != NULL
3977                   && (h->root.type == bfd_link_hash_defined
3978                       || h->root.type == bfd_link_hash_defweak))
3979                 continue;
3980             }
3981
3982           sz = s->size;
3983           msg = (char *) bfd_alloc (abfd, sz + 1);
3984           if (msg == NULL)
3985             goto error_return;
3986
3987           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3988             goto error_return;
3989
3990           msg[sz] = '\0';
3991
3992           if (! (_bfd_generic_link_add_one_symbol
3993                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3994                   FALSE, bed->collect, NULL)))
3995             goto error_return;
3996
3997           if (bfd_link_executable (info))
3998             {
3999               /* Clobber the section size so that the warning does
4000                  not get copied into the output file.  */
4001               s->size = 0;
4002
4003               /* Also set SEC_EXCLUDE, so that symbols defined in
4004                  the warning section don't get copied to the output.  */
4005               s->flags |= SEC_EXCLUDE;
4006             }
4007         }
4008     }
4009
4010   just_syms = ((s = abfd->sections) != NULL
4011                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
4012
4013   add_needed = TRUE;
4014   if (! dynamic)
4015     {
4016       /* If we are creating a shared library, create all the dynamic
4017          sections immediately.  We need to attach them to something,
4018          so we attach them to this BFD, provided it is the right
4019          format and is not from ld --just-symbols.  Always create the
4020          dynamic sections for -E/--dynamic-list.  FIXME: If there
4021          are no input BFD's of the same format as the output, we can't
4022          make a shared library.  */
4023       if (!just_syms
4024           && (bfd_link_pic (info)
4025               || (!bfd_link_relocatable (info)
4026                   && info->nointerp
4027                   && (info->export_dynamic || info->dynamic)))
4028           && is_elf_hash_table (htab)
4029           && info->output_bfd->xvec == abfd->xvec
4030           && !htab->dynamic_sections_created)
4031         {
4032           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
4033             goto error_return;
4034         }
4035     }
4036   else if (!is_elf_hash_table (htab))
4037     goto error_return;
4038   else
4039     {
4040       const char *soname = NULL;
4041       char *audit = NULL;
4042       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
4043       const Elf_Internal_Phdr *phdr;
4044       int ret;
4045
4046       /* ld --just-symbols and dynamic objects don't mix very well.
4047          ld shouldn't allow it.  */
4048       if (just_syms)
4049         abort ();
4050
4051       /* If this dynamic lib was specified on the command line with
4052          --as-needed in effect, then we don't want to add a DT_NEEDED
4053          tag unless the lib is actually used.  Similary for libs brought
4054          in by another lib's DT_NEEDED.  When --no-add-needed is used
4055          on a dynamic lib, we don't want to add a DT_NEEDED entry for
4056          any dynamic library in DT_NEEDED tags in the dynamic lib at
4057          all.  */
4058       add_needed = (elf_dyn_lib_class (abfd)
4059                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
4060                        | DYN_NO_NEEDED)) == 0;
4061
4062       s = bfd_get_section_by_name (abfd, ".dynamic");
4063       if (s != NULL)
4064         {
4065           bfd_byte *dynbuf;
4066           bfd_byte *extdyn;
4067           unsigned int elfsec;
4068           unsigned long shlink;
4069
4070           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
4071             {
4072 error_free_dyn:
4073               free (dynbuf);
4074               goto error_return;
4075             }
4076
4077           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
4078           if (elfsec == SHN_BAD)
4079             goto error_free_dyn;
4080           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
4081
4082           for (extdyn = dynbuf;
4083                extdyn <= dynbuf + s->size - bed->s->sizeof_dyn;
4084                extdyn += bed->s->sizeof_dyn)
4085             {
4086               Elf_Internal_Dyn dyn;
4087
4088               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
4089               if (dyn.d_tag == DT_SONAME)
4090                 {
4091                   unsigned int tagv = dyn.d_un.d_val;
4092                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4093                   if (soname == NULL)
4094                     goto error_free_dyn;
4095                 }
4096               if (dyn.d_tag == DT_NEEDED)
4097                 {
4098                   struct bfd_link_needed_list *n, **pn;
4099                   char *fnm, *anm;
4100                   unsigned int tagv = dyn.d_un.d_val;
4101
4102                   amt = sizeof (struct bfd_link_needed_list);
4103                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
4104                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4105                   if (n == NULL || fnm == NULL)
4106                     goto error_free_dyn;
4107                   amt = strlen (fnm) + 1;
4108                   anm = (char *) bfd_alloc (abfd, amt);
4109                   if (anm == NULL)
4110                     goto error_free_dyn;
4111                   memcpy (anm, fnm, amt);
4112                   n->name = anm;
4113                   n->by = abfd;
4114                   n->next = NULL;
4115                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
4116                     ;
4117                   *pn = n;
4118                 }
4119               if (dyn.d_tag == DT_RUNPATH)
4120                 {
4121                   struct bfd_link_needed_list *n, **pn;
4122                   char *fnm, *anm;
4123                   unsigned int tagv = dyn.d_un.d_val;
4124
4125                   amt = sizeof (struct bfd_link_needed_list);
4126                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
4127                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4128                   if (n == NULL || fnm == NULL)
4129                     goto error_free_dyn;
4130                   amt = strlen (fnm) + 1;
4131                   anm = (char *) bfd_alloc (abfd, amt);
4132                   if (anm == NULL)
4133                     goto error_free_dyn;
4134                   memcpy (anm, fnm, amt);
4135                   n->name = anm;
4136                   n->by = abfd;
4137                   n->next = NULL;
4138                   for (pn = & runpath;
4139                        *pn != NULL;
4140                        pn = &(*pn)->next)
4141                     ;
4142                   *pn = n;
4143                 }
4144               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
4145               if (!runpath && dyn.d_tag == DT_RPATH)
4146                 {
4147                   struct bfd_link_needed_list *n, **pn;
4148                   char *fnm, *anm;
4149                   unsigned int tagv = dyn.d_un.d_val;
4150
4151                   amt = sizeof (struct bfd_link_needed_list);
4152                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
4153                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4154                   if (n == NULL || fnm == NULL)
4155                     goto error_free_dyn;
4156                   amt = strlen (fnm) + 1;
4157                   anm = (char *) bfd_alloc (abfd, amt);
4158                   if (anm == NULL)
4159                     goto error_free_dyn;
4160                   memcpy (anm, fnm, amt);
4161                   n->name = anm;
4162                   n->by = abfd;
4163                   n->next = NULL;
4164                   for (pn = & rpath;
4165                        *pn != NULL;
4166                        pn = &(*pn)->next)
4167                     ;
4168                   *pn = n;
4169                 }
4170               if (dyn.d_tag == DT_AUDIT)
4171                 {
4172                   unsigned int tagv = dyn.d_un.d_val;
4173                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4174                 }
4175             }
4176
4177           free (dynbuf);
4178         }
4179
4180       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
4181          frees all more recently bfd_alloc'd blocks as well.  */
4182       if (runpath)
4183         rpath = runpath;
4184
4185       if (rpath)
4186         {
4187           struct bfd_link_needed_list **pn;
4188           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
4189             ;
4190           *pn = rpath;
4191         }
4192
4193       /* If we have a PT_GNU_RELRO program header, mark as read-only
4194          all sections contained fully therein.  This makes relro
4195          shared library sections appear as they will at run-time.  */
4196       phdr = elf_tdata (abfd)->phdr + elf_elfheader (abfd)->e_phnum;
4197       while (phdr-- > elf_tdata (abfd)->phdr)
4198         if (phdr->p_type == PT_GNU_RELRO)
4199           {
4200             for (s = abfd->sections; s != NULL; s = s->next)
4201               if ((s->flags & SEC_ALLOC) != 0
4202                   && s->vma >= phdr->p_vaddr
4203                   && s->vma + s->size <= phdr->p_vaddr + phdr->p_memsz)
4204                 s->flags |= SEC_READONLY;
4205             break;
4206           }
4207
4208       /* We do not want to include any of the sections in a dynamic
4209          object in the output file.  We hack by simply clobbering the
4210          list of sections in the BFD.  This could be handled more
4211          cleanly by, say, a new section flag; the existing
4212          SEC_NEVER_LOAD flag is not the one we want, because that one
4213          still implies that the section takes up space in the output
4214          file.  */
4215       bfd_section_list_clear (abfd);
4216
4217       /* Find the name to use in a DT_NEEDED entry that refers to this
4218          object.  If the object has a DT_SONAME entry, we use it.
4219          Otherwise, if the generic linker stuck something in
4220          elf_dt_name, we use that.  Otherwise, we just use the file
4221          name.  */
4222       if (soname == NULL || *soname == '\0')
4223         {
4224           soname = elf_dt_name (abfd);
4225           if (soname == NULL || *soname == '\0')
4226             soname = bfd_get_filename (abfd);
4227         }
4228
4229       /* Save the SONAME because sometimes the linker emulation code
4230          will need to know it.  */
4231       elf_dt_name (abfd) = soname;
4232
4233       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4234       if (ret < 0)
4235         goto error_return;
4236
4237       /* If we have already included this dynamic object in the
4238          link, just ignore it.  There is no reason to include a
4239          particular dynamic object more than once.  */
4240       if (ret > 0)
4241         return TRUE;
4242
4243       /* Save the DT_AUDIT entry for the linker emulation code. */
4244       elf_dt_audit (abfd) = audit;
4245     }
4246
4247   /* If this is a dynamic object, we always link against the .dynsym
4248      symbol table, not the .symtab symbol table.  The dynamic linker
4249      will only see the .dynsym symbol table, so there is no reason to
4250      look at .symtab for a dynamic object.  */
4251
4252   if (! dynamic || elf_dynsymtab (abfd) == 0)
4253     hdr = &elf_tdata (abfd)->symtab_hdr;
4254   else
4255     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
4256
4257   symcount = hdr->sh_size / bed->s->sizeof_sym;
4258
4259   /* The sh_info field of the symtab header tells us where the
4260      external symbols start.  We don't care about the local symbols at
4261      this point.  */
4262   if (elf_bad_symtab (abfd))
4263     {
4264       extsymcount = symcount;
4265       extsymoff = 0;
4266     }
4267   else
4268     {
4269       extsymcount = symcount - hdr->sh_info;
4270       extsymoff = hdr->sh_info;
4271     }
4272
4273   sym_hash = elf_sym_hashes (abfd);
4274   if (extsymcount != 0)
4275     {
4276       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
4277                                       NULL, NULL, NULL);
4278       if (isymbuf == NULL)
4279         goto error_return;
4280
4281       if (sym_hash == NULL)
4282         {
4283           /* We store a pointer to the hash table entry for each
4284              external symbol.  */
4285           amt = extsymcount;
4286           amt *= sizeof (struct elf_link_hash_entry *);
4287           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
4288           if (sym_hash == NULL)
4289             goto error_free_sym;
4290           elf_sym_hashes (abfd) = sym_hash;
4291         }
4292     }
4293
4294   if (dynamic)
4295     {
4296       /* Read in any version definitions.  */
4297       if (!_bfd_elf_slurp_version_tables (abfd,
4298                                           info->default_imported_symver))
4299         goto error_free_sym;
4300
4301       /* Read in the symbol versions, but don't bother to convert them
4302          to internal format.  */
4303       if (elf_dynversym (abfd) != 0)
4304         {
4305           Elf_Internal_Shdr *versymhdr;
4306
4307           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
4308           amt = versymhdr->sh_size;
4309           extversym = (Elf_External_Versym *) bfd_malloc (amt);
4310           if (extversym == NULL)
4311             goto error_free_sym;
4312           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
4313               || bfd_bread (extversym, amt, abfd) != amt)
4314             goto error_free_vers;
4315           extversym_end = extversym + (amt / sizeof (* extversym));
4316         }
4317     }
4318
4319   /* If we are loading an as-needed shared lib, save the symbol table
4320      state before we start adding symbols.  If the lib turns out
4321      to be unneeded, restore the state.  */
4322   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4323     {
4324       unsigned int i;
4325       size_t entsize;
4326
4327       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
4328         {
4329           struct bfd_hash_entry *p;
4330           struct elf_link_hash_entry *h;
4331
4332           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4333             {
4334               h = (struct elf_link_hash_entry *) p;
4335               entsize += htab->root.table.entsize;
4336               if (h->root.type == bfd_link_hash_warning)
4337                 entsize += htab->root.table.entsize;
4338             }
4339         }
4340
4341       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
4342       old_tab = bfd_malloc (tabsize + entsize);
4343       if (old_tab == NULL)
4344         goto error_free_vers;
4345
4346       /* Remember the current objalloc pointer, so that all mem for
4347          symbols added can later be reclaimed.  */
4348       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
4349       if (alloc_mark == NULL)
4350         goto error_free_vers;
4351
4352       /* Make a special call to the linker "notice" function to
4353          tell it that we are about to handle an as-needed lib.  */
4354       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
4355         goto error_free_vers;
4356
4357       /* Clone the symbol table.  Remember some pointers into the
4358          symbol table, and dynamic symbol count.  */
4359       old_ent = (char *) old_tab + tabsize;
4360       memcpy (old_tab, htab->root.table.table, tabsize);
4361       old_undefs = htab->root.undefs;
4362       old_undefs_tail = htab->root.undefs_tail;
4363       old_table = htab->root.table.table;
4364       old_size = htab->root.table.size;
4365       old_count = htab->root.table.count;
4366       old_strtab = _bfd_elf_strtab_save (htab->dynstr);
4367       if (old_strtab == NULL)
4368         goto error_free_vers;
4369
4370       for (i = 0; i < htab->root.table.size; i++)
4371         {
4372           struct bfd_hash_entry *p;
4373           struct elf_link_hash_entry *h;
4374
4375           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4376             {
4377               memcpy (old_ent, p, htab->root.table.entsize);
4378               old_ent = (char *) old_ent + htab->root.table.entsize;
4379               h = (struct elf_link_hash_entry *) p;
4380               if (h->root.type == bfd_link_hash_warning)
4381                 {
4382                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
4383                   old_ent = (char *) old_ent + htab->root.table.entsize;
4384                 }
4385             }
4386         }
4387     }
4388
4389   weaks = NULL;
4390   if (extversym == NULL)
4391     ever = NULL;
4392   else if (extversym + extsymoff < extversym_end)
4393     ever = extversym + extsymoff;
4394   else
4395     {
4396       /* xgettext:c-format */
4397       _bfd_error_handler (_("%pB: invalid version offset %lx (max %lx)"),
4398                           abfd, (long) extsymoff,
4399                           (long) (extversym_end - extversym) / sizeof (* extversym));
4400       bfd_set_error (bfd_error_bad_value);
4401       goto error_free_vers;
4402     }
4403
4404   for (isym = isymbuf, isymend = isymbuf + extsymcount;
4405        isym < isymend;
4406        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
4407     {
4408       int bind;
4409       bfd_vma value;
4410       asection *sec, *new_sec;
4411       flagword flags;
4412       const char *name;
4413       struct elf_link_hash_entry *h;
4414       struct elf_link_hash_entry *hi;
4415       bfd_boolean definition;
4416       bfd_boolean size_change_ok;
4417       bfd_boolean type_change_ok;
4418       bfd_boolean new_weak;
4419       bfd_boolean old_weak;
4420       bfd_boolean override;
4421       bfd_boolean common;
4422       bfd_boolean discarded;
4423       unsigned int old_alignment;
4424       unsigned int shindex;
4425       bfd *old_bfd;
4426       bfd_boolean matched;
4427
4428       override = FALSE;
4429
4430       flags = BSF_NO_FLAGS;
4431       sec = NULL;
4432       value = isym->st_value;
4433       common = bed->common_definition (isym);
4434       if (common && info->inhibit_common_definition)
4435         {
4436           /* Treat common symbol as undefined for --no-define-common.  */
4437           isym->st_shndx = SHN_UNDEF;
4438           common = FALSE;
4439         }
4440       discarded = FALSE;
4441
4442       bind = ELF_ST_BIND (isym->st_info);
4443       switch (bind)
4444         {
4445         case STB_LOCAL:
4446           /* This should be impossible, since ELF requires that all
4447              global symbols follow all local symbols, and that sh_info
4448              point to the first global symbol.  Unfortunately, Irix 5
4449              screws this up.  */
4450           if (elf_bad_symtab (abfd))
4451             continue;
4452
4453           /* If we aren't prepared to handle locals within the globals
4454              then we'll likely segfault on a NULL symbol hash if the
4455              symbol is ever referenced in relocations.  */
4456           shindex = elf_elfheader (abfd)->e_shstrndx;
4457           name = bfd_elf_string_from_elf_section (abfd, shindex, hdr->sh_name);
4458           _bfd_error_handler (_("%pB: %s local symbol at index %lu"
4459                                 " (>= sh_info of %lu)"),
4460                               abfd, name, (long) (isym - isymbuf + extsymoff),
4461                               (long) extsymoff);
4462
4463           /* Dynamic object relocations are not processed by ld, so
4464              ld won't run into the problem mentioned above.  */
4465           if (dynamic)
4466             continue;
4467           bfd_set_error (bfd_error_bad_value);
4468           goto error_free_vers;
4469
4470         case STB_GLOBAL:
4471           if (isym->st_shndx != SHN_UNDEF && !common)
4472             flags = BSF_GLOBAL;
4473           break;
4474
4475         case STB_WEAK:
4476           flags = BSF_WEAK;
4477           break;
4478
4479         case STB_GNU_UNIQUE:
4480           flags = BSF_GNU_UNIQUE;
4481           break;
4482
4483         default:
4484           /* Leave it up to the processor backend.  */
4485           break;
4486         }
4487
4488       if (isym->st_shndx == SHN_UNDEF)
4489         sec = bfd_und_section_ptr;
4490       else if (isym->st_shndx == SHN_ABS)
4491         sec = bfd_abs_section_ptr;
4492       else if (isym->st_shndx == SHN_COMMON)
4493         {
4494           sec = bfd_com_section_ptr;
4495           /* What ELF calls the size we call the value.  What ELF
4496              calls the value we call the alignment.  */
4497           value = isym->st_size;
4498         }
4499       else
4500         {
4501           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
4502           if (sec == NULL)
4503             sec = bfd_abs_section_ptr;
4504           else if (discarded_section (sec))
4505             {
4506               /* Symbols from discarded section are undefined.  We keep
4507                  its visibility.  */
4508               sec = bfd_und_section_ptr;
4509               discarded = TRUE;
4510               isym->st_shndx = SHN_UNDEF;
4511             }
4512           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
4513             value -= sec->vma;
4514         }
4515
4516       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4517                                               isym->st_name);
4518       if (name == NULL)
4519         goto error_free_vers;
4520
4521       if (isym->st_shndx == SHN_COMMON
4522           && (abfd->flags & BFD_PLUGIN) != 0)
4523         {
4524           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4525
4526           if (xc == NULL)
4527             {
4528               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4529                                  | SEC_EXCLUDE);
4530               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4531               if (xc == NULL)
4532                 goto error_free_vers;
4533             }
4534           sec = xc;
4535         }
4536       else if (isym->st_shndx == SHN_COMMON
4537                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4538                && !bfd_link_relocatable (info))
4539         {
4540           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4541
4542           if (tcomm == NULL)
4543             {
4544               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4545                                  | SEC_LINKER_CREATED);
4546               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4547               if (tcomm == NULL)
4548                 goto error_free_vers;
4549             }
4550           sec = tcomm;
4551         }
4552       else if (bed->elf_add_symbol_hook)
4553         {
4554           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4555                                              &sec, &value))
4556             goto error_free_vers;
4557
4558           /* The hook function sets the name to NULL if this symbol
4559              should be skipped for some reason.  */
4560           if (name == NULL)
4561             continue;
4562         }
4563
4564       /* Sanity check that all possibilities were handled.  */
4565       if (sec == NULL)
4566         abort ();
4567
4568       /* Silently discard TLS symbols from --just-syms.  There's
4569          no way to combine a static TLS block with a new TLS block
4570          for this executable.  */
4571       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4572           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4573         continue;
4574
4575       if (bfd_is_und_section (sec)
4576           || bfd_is_com_section (sec))
4577         definition = FALSE;
4578       else
4579         definition = TRUE;
4580
4581       size_change_ok = FALSE;
4582       type_change_ok = bed->type_change_ok;
4583       old_weak = FALSE;
4584       matched = FALSE;
4585       old_alignment = 0;
4586       old_bfd = NULL;
4587       new_sec = sec;
4588
4589       if (is_elf_hash_table (htab))
4590         {
4591           Elf_Internal_Versym iver;
4592           unsigned int vernum = 0;
4593           bfd_boolean skip;
4594
4595           if (ever == NULL)
4596             {
4597               if (info->default_imported_symver)
4598                 /* Use the default symbol version created earlier.  */
4599                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4600               else
4601                 iver.vs_vers = 0;
4602             }
4603           else if (ever >= extversym_end)
4604             {
4605               /* xgettext:c-format */
4606               _bfd_error_handler (_("%pB: not enough version information"),
4607                                   abfd);
4608               bfd_set_error (bfd_error_bad_value);
4609               goto error_free_vers;
4610             }
4611           else
4612             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4613
4614           vernum = iver.vs_vers & VERSYM_VERSION;
4615
4616           /* If this is a hidden symbol, or if it is not version
4617              1, we append the version name to the symbol name.
4618              However, we do not modify a non-hidden absolute symbol
4619              if it is not a function, because it might be the version
4620              symbol itself.  FIXME: What if it isn't?  */
4621           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4622               || (vernum > 1
4623                   && (!bfd_is_abs_section (sec)
4624                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4625             {
4626               const char *verstr;
4627               size_t namelen, verlen, newlen;
4628               char *newname, *p;
4629
4630               if (isym->st_shndx != SHN_UNDEF)
4631                 {
4632                   if (vernum > elf_tdata (abfd)->cverdefs)
4633                     verstr = NULL;
4634                   else if (vernum > 1)
4635                     verstr =
4636                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4637                   else
4638                     verstr = "";
4639
4640                   if (verstr == NULL)
4641                     {
4642                       _bfd_error_handler
4643                         /* xgettext:c-format */
4644                         (_("%pB: %s: invalid version %u (max %d)"),
4645                          abfd, name, vernum,
4646                          elf_tdata (abfd)->cverdefs);
4647                       bfd_set_error (bfd_error_bad_value);
4648                       goto error_free_vers;
4649                     }
4650                 }
4651               else
4652                 {
4653                   /* We cannot simply test for the number of
4654                      entries in the VERNEED section since the
4655                      numbers for the needed versions do not start
4656                      at 0.  */
4657                   Elf_Internal_Verneed *t;
4658
4659                   verstr = NULL;
4660                   for (t = elf_tdata (abfd)->verref;
4661                        t != NULL;
4662                        t = t->vn_nextref)
4663                     {
4664                       Elf_Internal_Vernaux *a;
4665
4666                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4667                         {
4668                           if (a->vna_other == vernum)
4669                             {
4670                               verstr = a->vna_nodename;
4671                               break;
4672                             }
4673                         }
4674                       if (a != NULL)
4675                         break;
4676                     }
4677                   if (verstr == NULL)
4678                     {
4679                       _bfd_error_handler
4680                         /* xgettext:c-format */
4681                         (_("%pB: %s: invalid needed version %d"),
4682                          abfd, name, vernum);
4683                       bfd_set_error (bfd_error_bad_value);
4684                       goto error_free_vers;
4685                     }
4686                 }
4687
4688               namelen = strlen (name);
4689               verlen = strlen (verstr);
4690               newlen = namelen + verlen + 2;
4691               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4692                   && isym->st_shndx != SHN_UNDEF)
4693                 ++newlen;
4694
4695               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4696               if (newname == NULL)
4697                 goto error_free_vers;
4698               memcpy (newname, name, namelen);
4699               p = newname + namelen;
4700               *p++ = ELF_VER_CHR;
4701               /* If this is a defined non-hidden version symbol,
4702                  we add another @ to the name.  This indicates the
4703                  default version of the symbol.  */
4704               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4705                   && isym->st_shndx != SHN_UNDEF)
4706                 *p++ = ELF_VER_CHR;
4707               memcpy (p, verstr, verlen + 1);
4708
4709               name = newname;
4710             }
4711
4712           /* If this symbol has default visibility and the user has
4713              requested we not re-export it, then mark it as hidden.  */
4714           if (!bfd_is_und_section (sec)
4715               && !dynamic
4716               && abfd->no_export
4717               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4718             isym->st_other = (STV_HIDDEN
4719                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4720
4721           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4722                                       sym_hash, &old_bfd, &old_weak,
4723                                       &old_alignment, &skip, &override,
4724                                       &type_change_ok, &size_change_ok,
4725                                       &matched))
4726             goto error_free_vers;
4727
4728           if (skip)
4729             continue;
4730
4731           /* Override a definition only if the new symbol matches the
4732              existing one.  */
4733           if (override && matched)
4734             definition = FALSE;
4735
4736           h = *sym_hash;
4737           while (h->root.type == bfd_link_hash_indirect
4738                  || h->root.type == bfd_link_hash_warning)
4739             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4740
4741           if (elf_tdata (abfd)->verdef != NULL
4742               && vernum > 1
4743               && definition)
4744             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4745         }
4746
4747       if (! (_bfd_generic_link_add_one_symbol
4748              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4749               (struct bfd_link_hash_entry **) sym_hash)))
4750         goto error_free_vers;
4751
4752       h = *sym_hash;
4753       /* We need to make sure that indirect symbol dynamic flags are
4754          updated.  */
4755       hi = h;
4756       while (h->root.type == bfd_link_hash_indirect
4757              || h->root.type == bfd_link_hash_warning)
4758         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4759
4760       /* Setting the index to -3 tells elf_link_output_extsym that
4761          this symbol is defined in a discarded section.  */
4762       if (discarded)
4763         h->indx = -3;
4764
4765       *sym_hash = h;
4766
4767       new_weak = (flags & BSF_WEAK) != 0;
4768       if (dynamic
4769           && definition
4770           && new_weak
4771           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4772           && is_elf_hash_table (htab)
4773           && h->u.alias == NULL)
4774         {
4775           /* Keep a list of all weak defined non function symbols from
4776              a dynamic object, using the alias field.  Later in this
4777              function we will set the alias field to the correct
4778              value.  We only put non-function symbols from dynamic
4779              objects on this list, because that happens to be the only
4780              time we need to know the normal symbol corresponding to a
4781              weak symbol, and the information is time consuming to
4782              figure out.  If the alias field is not already NULL,
4783              then this symbol was already defined by some previous
4784              dynamic object, and we will be using that previous
4785              definition anyhow.  */
4786
4787           h->u.alias = weaks;
4788           weaks = h;
4789         }
4790
4791       /* Set the alignment of a common symbol.  */
4792       if ((common || bfd_is_com_section (sec))
4793           && h->root.type == bfd_link_hash_common)
4794         {
4795           unsigned int align;
4796
4797           if (common)
4798             align = bfd_log2 (isym->st_value);
4799           else
4800             {
4801               /* The new symbol is a common symbol in a shared object.
4802                  We need to get the alignment from the section.  */
4803               align = new_sec->alignment_power;
4804             }
4805           if (align > old_alignment)
4806             h->root.u.c.p->alignment_power = align;
4807           else
4808             h->root.u.c.p->alignment_power = old_alignment;
4809         }
4810
4811       if (is_elf_hash_table (htab))
4812         {
4813           /* Set a flag in the hash table entry indicating the type of
4814              reference or definition we just found.  A dynamic symbol
4815              is one which is referenced or defined by both a regular
4816              object and a shared object.  */
4817           bfd_boolean dynsym = FALSE;
4818
4819           /* Plugin symbols aren't normal.  Don't set def_regular or
4820              ref_regular for them, or make them dynamic.  */
4821           if ((abfd->flags & BFD_PLUGIN) != 0)
4822             ;
4823           else if (! dynamic)
4824             {
4825               if (! definition)
4826                 {
4827                   h->ref_regular = 1;
4828                   if (bind != STB_WEAK)
4829                     h->ref_regular_nonweak = 1;
4830                 }
4831               else
4832                 {
4833                   h->def_regular = 1;
4834                   if (h->def_dynamic)
4835                     {
4836                       h->def_dynamic = 0;
4837                       h->ref_dynamic = 1;
4838                     }
4839                 }
4840
4841               /* If the indirect symbol has been forced local, don't
4842                  make the real symbol dynamic.  */
4843               if ((h == hi || !hi->forced_local)
4844                   && (bfd_link_dll (info)
4845                       || h->def_dynamic
4846                       || h->ref_dynamic))
4847                 dynsym = TRUE;
4848             }
4849           else
4850             {
4851               if (! definition)
4852                 {
4853                   h->ref_dynamic = 1;
4854                   hi->ref_dynamic = 1;
4855                 }
4856               else
4857                 {
4858                   h->def_dynamic = 1;
4859                   hi->def_dynamic = 1;
4860                 }
4861
4862               /* If the indirect symbol has been forced local, don't
4863                  make the real symbol dynamic.  */
4864               if ((h == hi || !hi->forced_local)
4865                   && (h->def_regular
4866                       || h->ref_regular
4867                       || (h->is_weakalias
4868                           && weakdef (h)->dynindx != -1)))
4869                 dynsym = TRUE;
4870             }
4871
4872           /* Check to see if we need to add an indirect symbol for
4873              the default name.  */
4874           if (definition
4875               || (!override && h->root.type == bfd_link_hash_common))
4876             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4877                                               sec, value, &old_bfd, &dynsym))
4878               goto error_free_vers;
4879
4880           /* Check the alignment when a common symbol is involved. This
4881              can change when a common symbol is overridden by a normal
4882              definition or a common symbol is ignored due to the old
4883              normal definition. We need to make sure the maximum
4884              alignment is maintained.  */
4885           if ((old_alignment || common)
4886               && h->root.type != bfd_link_hash_common)
4887             {
4888               unsigned int common_align;
4889               unsigned int normal_align;
4890               unsigned int symbol_align;
4891               bfd *normal_bfd;
4892               bfd *common_bfd;
4893
4894               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4895                           || h->root.type == bfd_link_hash_defweak);
4896
4897               symbol_align = ffs (h->root.u.def.value) - 1;
4898               if (h->root.u.def.section->owner != NULL
4899                   && (h->root.u.def.section->owner->flags
4900                        & (DYNAMIC | BFD_PLUGIN)) == 0)
4901                 {
4902                   normal_align = h->root.u.def.section->alignment_power;
4903                   if (normal_align > symbol_align)
4904                     normal_align = symbol_align;
4905                 }
4906               else
4907                 normal_align = symbol_align;
4908
4909               if (old_alignment)
4910                 {
4911                   common_align = old_alignment;
4912                   common_bfd = old_bfd;
4913                   normal_bfd = abfd;
4914                 }
4915               else
4916                 {
4917                   common_align = bfd_log2 (isym->st_value);
4918                   common_bfd = abfd;
4919                   normal_bfd = old_bfd;
4920                 }
4921
4922               if (normal_align < common_align)
4923                 {
4924                   /* PR binutils/2735 */
4925                   if (normal_bfd == NULL)
4926                     _bfd_error_handler
4927                       /* xgettext:c-format */
4928                       (_("warning: alignment %u of common symbol `%s' in %pB is"
4929                          " greater than the alignment (%u) of its section %pA"),
4930                        1 << common_align, name, common_bfd,
4931                        1 << normal_align, h->root.u.def.section);
4932                   else
4933                     _bfd_error_handler
4934                       /* xgettext:c-format */
4935                       (_("warning: alignment %u of symbol `%s' in %pB"
4936                          " is smaller than %u in %pB"),
4937                        1 << normal_align, name, normal_bfd,
4938                        1 << common_align, common_bfd);
4939                 }
4940             }
4941
4942           /* Remember the symbol size if it isn't undefined.  */
4943           if (isym->st_size != 0
4944               && isym->st_shndx != SHN_UNDEF
4945               && (definition || h->size == 0))
4946             {
4947               if (h->size != 0
4948                   && h->size != isym->st_size
4949                   && ! size_change_ok)
4950                 _bfd_error_handler
4951                   /* xgettext:c-format */
4952                   (_("warning: size of symbol `%s' changed"
4953                      " from %" PRIu64 " in %pB to %" PRIu64 " in %pB"),
4954                    name, (uint64_t) h->size, old_bfd,
4955                    (uint64_t) isym->st_size, abfd);
4956
4957               h->size = isym->st_size;
4958             }
4959
4960           /* If this is a common symbol, then we always want H->SIZE
4961              to be the size of the common symbol.  The code just above
4962              won't fix the size if a common symbol becomes larger.  We
4963              don't warn about a size change here, because that is
4964              covered by --warn-common.  Allow changes between different
4965              function types.  */
4966           if (h->root.type == bfd_link_hash_common)
4967             h->size = h->root.u.c.size;
4968
4969           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4970               && ((definition && !new_weak)
4971                   || (old_weak && h->root.type == bfd_link_hash_common)
4972                   || h->type == STT_NOTYPE))
4973             {
4974               unsigned int type = ELF_ST_TYPE (isym->st_info);
4975
4976               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4977                  symbol.  */
4978               if (type == STT_GNU_IFUNC
4979                   && (abfd->flags & DYNAMIC) != 0)
4980                 type = STT_FUNC;
4981
4982               if (h->type != type)
4983                 {
4984                   if (h->type != STT_NOTYPE && ! type_change_ok)
4985                     /* xgettext:c-format */
4986                     _bfd_error_handler
4987                       (_("warning: type of symbol `%s' changed"
4988                          " from %d to %d in %pB"),
4989                        name, h->type, type, abfd);
4990
4991                   h->type = type;
4992                 }
4993             }
4994
4995           /* Merge st_other field.  */
4996           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4997
4998           /* We don't want to make debug symbol dynamic.  */
4999           if (definition
5000               && (sec->flags & SEC_DEBUGGING)
5001               && !bfd_link_relocatable (info))
5002             dynsym = FALSE;
5003
5004           /* Nor should we make plugin symbols dynamic.  */
5005           if ((abfd->flags & BFD_PLUGIN) != 0)
5006             dynsym = FALSE;
5007
5008           if (definition)
5009             {
5010               h->target_internal = isym->st_target_internal;
5011               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
5012             }
5013
5014           if (definition && !dynamic)
5015             {
5016               char *p = strchr (name, ELF_VER_CHR);
5017               if (p != NULL && p[1] != ELF_VER_CHR)
5018                 {
5019                   /* Queue non-default versions so that .symver x, x@FOO
5020                      aliases can be checked.  */
5021                   if (!nondeflt_vers)
5022                     {
5023                       amt = ((isymend - isym + 1)
5024                              * sizeof (struct elf_link_hash_entry *));
5025                       nondeflt_vers
5026                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
5027                       if (!nondeflt_vers)
5028                         goto error_free_vers;
5029                     }
5030                   nondeflt_vers[nondeflt_vers_cnt++] = h;
5031                 }
5032             }
5033
5034           if (dynsym && h->dynindx == -1)
5035             {
5036               if (! bfd_elf_link_record_dynamic_symbol (info, h))
5037                 goto error_free_vers;
5038               if (h->is_weakalias
5039                   && weakdef (h)->dynindx == -1)
5040                 {
5041                   if (!bfd_elf_link_record_dynamic_symbol (info, weakdef (h)))
5042                     goto error_free_vers;
5043                 }
5044             }
5045           else if (h->dynindx != -1)
5046             /* If the symbol already has a dynamic index, but
5047                visibility says it should not be visible, turn it into
5048                a local symbol.  */
5049             switch (ELF_ST_VISIBILITY (h->other))
5050               {
5051               case STV_INTERNAL:
5052               case STV_HIDDEN:
5053                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
5054                 dynsym = FALSE;
5055                 break;
5056               }
5057
5058           /* Don't add DT_NEEDED for references from the dummy bfd nor
5059              for unmatched symbol.  */
5060           if (!add_needed
5061               && matched
5062               && definition
5063               && ((dynsym
5064                    && h->ref_regular_nonweak
5065                    && (old_bfd == NULL
5066                        || (old_bfd->flags & BFD_PLUGIN) == 0))
5067                   || (h->ref_dynamic_nonweak
5068                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
5069                       && !on_needed_list (elf_dt_name (abfd),
5070                                           htab->needed, NULL))))
5071             {
5072               int ret;
5073               const char *soname = elf_dt_name (abfd);
5074
5075               info->callbacks->minfo ("%!", soname, old_bfd,
5076                                       h->root.root.string);
5077
5078               /* A symbol from a library loaded via DT_NEEDED of some
5079                  other library is referenced by a regular object.
5080                  Add a DT_NEEDED entry for it.  Issue an error if
5081                  --no-add-needed is used and the reference was not
5082                  a weak one.  */
5083               if (old_bfd != NULL
5084                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
5085                 {
5086                   _bfd_error_handler
5087                     /* xgettext:c-format */
5088                     (_("%pB: undefined reference to symbol '%s'"),
5089                      old_bfd, name);
5090                   bfd_set_error (bfd_error_missing_dso);
5091                   goto error_free_vers;
5092                 }
5093
5094               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
5095                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
5096
5097               add_needed = TRUE;
5098               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
5099               if (ret < 0)
5100                 goto error_free_vers;
5101
5102               BFD_ASSERT (ret == 0);
5103             }
5104         }
5105     }
5106
5107   if (info->lto_plugin_active
5108       && !bfd_link_relocatable (info)
5109       && (abfd->flags & BFD_PLUGIN) == 0
5110       && !just_syms
5111       && extsymcount)
5112     {
5113       int r_sym_shift;
5114
5115       if (bed->s->arch_size == 32)
5116         r_sym_shift = 8;
5117       else
5118         r_sym_shift = 32;
5119
5120       /* If linker plugin is enabled, set non_ir_ref_regular on symbols
5121          referenced in regular objects so that linker plugin will get
5122          the correct symbol resolution.  */
5123
5124       sym_hash = elf_sym_hashes (abfd);
5125       for (s = abfd->sections; s != NULL; s = s->next)
5126         {
5127           Elf_Internal_Rela *internal_relocs;
5128           Elf_Internal_Rela *rel, *relend;
5129
5130           /* Don't check relocations in excluded sections.  */
5131           if ((s->flags & SEC_RELOC) == 0
5132               || s->reloc_count == 0
5133               || (s->flags & SEC_EXCLUDE) != 0
5134               || ((info->strip == strip_all
5135                    || info->strip == strip_debugger)
5136                   && (s->flags & SEC_DEBUGGING) != 0))
5137             continue;
5138
5139           internal_relocs = _bfd_elf_link_read_relocs (abfd, s, NULL,
5140                                                        NULL,
5141                                                        info->keep_memory);
5142           if (internal_relocs == NULL)
5143             goto error_free_vers;
5144
5145           rel = internal_relocs;
5146           relend = rel + s->reloc_count;
5147           for ( ; rel < relend; rel++)
5148             {
5149               unsigned long r_symndx = rel->r_info >> r_sym_shift;
5150               struct elf_link_hash_entry *h;
5151
5152               /* Skip local symbols.  */
5153               if (r_symndx < extsymoff)
5154                 continue;
5155
5156               h = sym_hash[r_symndx - extsymoff];
5157               if (h != NULL)
5158                 h->root.non_ir_ref_regular = 1;
5159             }
5160
5161           if (elf_section_data (s)->relocs != internal_relocs)
5162             free (internal_relocs);
5163         }
5164     }
5165
5166   if (extversym != NULL)
5167     {
5168       free (extversym);
5169       extversym = NULL;
5170     }
5171
5172   if (isymbuf != NULL)
5173     {
5174       free (isymbuf);
5175       isymbuf = NULL;
5176     }
5177
5178   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
5179     {
5180       unsigned int i;
5181
5182       /* Restore the symbol table.  */
5183       old_ent = (char *) old_tab + tabsize;
5184       memset (elf_sym_hashes (abfd), 0,
5185               extsymcount * sizeof (struct elf_link_hash_entry *));
5186       htab->root.table.table = old_table;
5187       htab->root.table.size = old_size;
5188       htab->root.table.count = old_count;
5189       memcpy (htab->root.table.table, old_tab, tabsize);
5190       htab->root.undefs = old_undefs;
5191       htab->root.undefs_tail = old_undefs_tail;
5192       _bfd_elf_strtab_restore (htab->dynstr, old_strtab);
5193       free (old_strtab);
5194       old_strtab = NULL;
5195       for (i = 0; i < htab->root.table.size; i++)
5196         {
5197           struct bfd_hash_entry *p;
5198           struct elf_link_hash_entry *h;
5199           bfd_size_type size;
5200           unsigned int alignment_power;
5201           unsigned int non_ir_ref_dynamic;
5202
5203           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
5204             {
5205               h = (struct elf_link_hash_entry *) p;
5206               if (h->root.type == bfd_link_hash_warning)
5207                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
5208
5209               /* Preserve the maximum alignment and size for common
5210                  symbols even if this dynamic lib isn't on DT_NEEDED
5211                  since it can still be loaded at run time by another
5212                  dynamic lib.  */
5213               if (h->root.type == bfd_link_hash_common)
5214                 {
5215                   size = h->root.u.c.size;
5216                   alignment_power = h->root.u.c.p->alignment_power;
5217                 }
5218               else
5219                 {
5220                   size = 0;
5221                   alignment_power = 0;
5222                 }
5223               /* Preserve non_ir_ref_dynamic so that this symbol
5224                  will be exported when the dynamic lib becomes needed
5225                  in the second pass.  */
5226               non_ir_ref_dynamic = h->root.non_ir_ref_dynamic;
5227               memcpy (p, old_ent, htab->root.table.entsize);
5228               old_ent = (char *) old_ent + htab->root.table.entsize;
5229               h = (struct elf_link_hash_entry *) p;
5230               if (h->root.type == bfd_link_hash_warning)
5231                 {
5232                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
5233                   old_ent = (char *) old_ent + htab->root.table.entsize;
5234                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
5235                 }
5236               if (h->root.type == bfd_link_hash_common)
5237                 {
5238                   if (size > h->root.u.c.size)
5239                     h->root.u.c.size = size;
5240                   if (alignment_power > h->root.u.c.p->alignment_power)
5241                     h->root.u.c.p->alignment_power = alignment_power;
5242                 }
5243               h->root.non_ir_ref_dynamic = non_ir_ref_dynamic;
5244             }
5245         }
5246
5247       /* Make a special call to the linker "notice" function to
5248          tell it that symbols added for crefs may need to be removed.  */
5249       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
5250         goto error_free_vers;
5251
5252       free (old_tab);
5253       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
5254                            alloc_mark);
5255       if (nondeflt_vers != NULL)
5256         free (nondeflt_vers);
5257       return TRUE;
5258     }
5259
5260   if (old_tab != NULL)
5261     {
5262       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
5263         goto error_free_vers;
5264       free (old_tab);
5265       old_tab = NULL;
5266     }
5267
5268   /* Now that all the symbols from this input file are created, if
5269      not performing a relocatable link, handle .symver foo, foo@BAR
5270      such that any relocs against foo become foo@BAR.  */
5271   if (!bfd_link_relocatable (info) && nondeflt_vers != NULL)
5272     {
5273       size_t cnt, symidx;
5274
5275       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
5276         {
5277           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
5278           char *shortname, *p;
5279
5280           p = strchr (h->root.root.string, ELF_VER_CHR);
5281           if (p == NULL
5282               || (h->root.type != bfd_link_hash_defined
5283                   && h->root.type != bfd_link_hash_defweak))
5284             continue;
5285
5286           amt = p - h->root.root.string;
5287           shortname = (char *) bfd_malloc (amt + 1);
5288           if (!shortname)
5289             goto error_free_vers;
5290           memcpy (shortname, h->root.root.string, amt);
5291           shortname[amt] = '\0';
5292
5293           hi = (struct elf_link_hash_entry *)
5294                bfd_link_hash_lookup (&htab->root, shortname,
5295                                      FALSE, FALSE, FALSE);
5296           if (hi != NULL
5297               && hi->root.type == h->root.type
5298               && hi->root.u.def.value == h->root.u.def.value
5299               && hi->root.u.def.section == h->root.u.def.section)
5300             {
5301               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
5302               hi->root.type = bfd_link_hash_indirect;
5303               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
5304               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
5305               sym_hash = elf_sym_hashes (abfd);
5306               if (sym_hash)
5307                 for (symidx = 0; symidx < extsymcount; ++symidx)
5308                   if (sym_hash[symidx] == hi)
5309                     {
5310                       sym_hash[symidx] = h;
5311                       break;
5312                     }
5313             }
5314           free (shortname);
5315         }
5316       free (nondeflt_vers);
5317       nondeflt_vers = NULL;
5318     }
5319
5320   /* Now set the alias field correctly for all the weak defined
5321      symbols we found.  The only way to do this is to search all the
5322      symbols.  Since we only need the information for non functions in
5323      dynamic objects, that's the only time we actually put anything on
5324      the list WEAKS.  We need this information so that if a regular
5325      object refers to a symbol defined weakly in a dynamic object, the
5326      real symbol in the dynamic object is also put in the dynamic
5327      symbols; we also must arrange for both symbols to point to the
5328      same memory location.  We could handle the general case of symbol
5329      aliasing, but a general symbol alias can only be generated in
5330      assembler code, handling it correctly would be very time
5331      consuming, and other ELF linkers don't handle general aliasing
5332      either.  */
5333   if (weaks != NULL)
5334     {
5335       struct elf_link_hash_entry **hpp;
5336       struct elf_link_hash_entry **hppend;
5337       struct elf_link_hash_entry **sorted_sym_hash;
5338       struct elf_link_hash_entry *h;
5339       size_t sym_count;
5340
5341       /* Since we have to search the whole symbol list for each weak
5342          defined symbol, search time for N weak defined symbols will be
5343          O(N^2). Binary search will cut it down to O(NlogN).  */
5344       amt = extsymcount;
5345       amt *= sizeof (struct elf_link_hash_entry *);
5346       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
5347       if (sorted_sym_hash == NULL)
5348         goto error_return;
5349       sym_hash = sorted_sym_hash;
5350       hpp = elf_sym_hashes (abfd);
5351       hppend = hpp + extsymcount;
5352       sym_count = 0;
5353       for (; hpp < hppend; hpp++)
5354         {
5355           h = *hpp;
5356           if (h != NULL
5357               && h->root.type == bfd_link_hash_defined
5358               && !bed->is_function_type (h->type))
5359             {
5360               *sym_hash = h;
5361               sym_hash++;
5362               sym_count++;
5363             }
5364         }
5365
5366       qsort (sorted_sym_hash, sym_count,
5367              sizeof (struct elf_link_hash_entry *),
5368              elf_sort_symbol);
5369
5370       while (weaks != NULL)
5371         {
5372           struct elf_link_hash_entry *hlook;
5373           asection *slook;
5374           bfd_vma vlook;
5375           size_t i, j, idx = 0;
5376
5377           hlook = weaks;
5378           weaks = hlook->u.alias;
5379           hlook->u.alias = NULL;
5380
5381           if (hlook->root.type != bfd_link_hash_defined
5382               && hlook->root.type != bfd_link_hash_defweak)
5383             continue;
5384
5385           slook = hlook->root.u.def.section;
5386           vlook = hlook->root.u.def.value;
5387
5388           i = 0;
5389           j = sym_count;
5390           while (i != j)
5391             {
5392               bfd_signed_vma vdiff;
5393               idx = (i + j) / 2;
5394               h = sorted_sym_hash[idx];
5395               vdiff = vlook - h->root.u.def.value;
5396               if (vdiff < 0)
5397                 j = idx;
5398               else if (vdiff > 0)
5399                 i = idx + 1;
5400               else
5401                 {
5402                   int sdiff = slook->id - h->root.u.def.section->id;
5403                   if (sdiff < 0)
5404                     j = idx;
5405                   else if (sdiff > 0)
5406                     i = idx + 1;
5407                   else
5408                     break;
5409                 }
5410             }
5411
5412           /* We didn't find a value/section match.  */
5413           if (i == j)
5414             continue;
5415
5416           /* With multiple aliases, or when the weak symbol is already
5417              strongly defined, we have multiple matching symbols and
5418              the binary search above may land on any of them.  Step
5419              one past the matching symbol(s).  */
5420           while (++idx != j)
5421             {
5422               h = sorted_sym_hash[idx];
5423               if (h->root.u.def.section != slook
5424                   || h->root.u.def.value != vlook)
5425                 break;
5426             }
5427
5428           /* Now look back over the aliases.  Since we sorted by size
5429              as well as value and section, we'll choose the one with
5430              the largest size.  */
5431           while (idx-- != i)
5432             {
5433               h = sorted_sym_hash[idx];
5434
5435               /* Stop if value or section doesn't match.  */
5436               if (h->root.u.def.section != slook
5437                   || h->root.u.def.value != vlook)
5438                 break;
5439               else if (h != hlook)
5440                 {
5441                   struct elf_link_hash_entry *t;
5442
5443                   hlook->u.alias = h;
5444                   hlook->is_weakalias = 1;
5445                   t = h;
5446                   if (t->u.alias != NULL)
5447                     while (t->u.alias != h)
5448                       t = t->u.alias;
5449                   t->u.alias = hlook;
5450
5451                   /* If the weak definition is in the list of dynamic
5452                      symbols, make sure the real definition is put
5453                      there as well.  */
5454                   if (hlook->dynindx != -1 && h->dynindx == -1)
5455                     {
5456                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
5457                         {
5458                         err_free_sym_hash:
5459                           free (sorted_sym_hash);
5460                           goto error_return;
5461                         }
5462                     }
5463
5464                   /* If the real definition is in the list of dynamic
5465                      symbols, make sure the weak definition is put
5466                      there as well.  If we don't do this, then the
5467                      dynamic loader might not merge the entries for the
5468                      real definition and the weak definition.  */
5469                   if (h->dynindx != -1 && hlook->dynindx == -1)
5470                     {
5471                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
5472                         goto err_free_sym_hash;
5473                     }
5474                   break;
5475                 }
5476             }
5477         }
5478
5479       free (sorted_sym_hash);
5480     }
5481
5482   if (bed->check_directives
5483       && !(*bed->check_directives) (abfd, info))
5484     return FALSE;
5485
5486   /* If this is a non-traditional link, try to optimize the handling
5487      of the .stab/.stabstr sections.  */
5488   if (! dynamic
5489       && ! info->traditional_format
5490       && is_elf_hash_table (htab)
5491       && (info->strip != strip_all && info->strip != strip_debugger))
5492     {
5493       asection *stabstr;
5494
5495       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
5496       if (stabstr != NULL)
5497         {
5498           bfd_size_type string_offset = 0;
5499           asection *stab;
5500
5501           for (stab = abfd->sections; stab; stab = stab->next)
5502             if (CONST_STRNEQ (stab->name, ".stab")
5503                 && (!stab->name[5] ||
5504                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
5505                 && (stab->flags & SEC_MERGE) == 0
5506                 && !bfd_is_abs_section (stab->output_section))
5507               {
5508                 struct bfd_elf_section_data *secdata;
5509
5510                 secdata = elf_section_data (stab);
5511                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
5512                                                stabstr, &secdata->sec_info,
5513                                                &string_offset))
5514                   goto error_return;
5515                 if (secdata->sec_info)
5516                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
5517             }
5518         }
5519     }
5520
5521   if (is_elf_hash_table (htab) && add_needed)
5522     {
5523       /* Add this bfd to the loaded list.  */
5524       struct elf_link_loaded_list *n;
5525
5526       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
5527       if (n == NULL)
5528         goto error_return;
5529       n->abfd = abfd;
5530       n->next = htab->loaded;
5531       htab->loaded = n;
5532     }
5533
5534   return TRUE;
5535
5536  error_free_vers:
5537   if (old_tab != NULL)
5538     free (old_tab);
5539   if (old_strtab != NULL)
5540     free (old_strtab);
5541   if (nondeflt_vers != NULL)
5542     free (nondeflt_vers);
5543   if (extversym != NULL)
5544     free (extversym);
5545  error_free_sym:
5546   if (isymbuf != NULL)
5547     free (isymbuf);
5548  error_return:
5549   return FALSE;
5550 }
5551
5552 /* Return the linker hash table entry of a symbol that might be
5553    satisfied by an archive symbol.  Return -1 on error.  */
5554
5555 struct elf_link_hash_entry *
5556 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5557                                 struct bfd_link_info *info,
5558                                 const char *name)
5559 {
5560   struct elf_link_hash_entry *h;
5561   char *p, *copy;
5562   size_t len, first;
5563
5564   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5565   if (h != NULL)
5566     return h;
5567
5568   /* If this is a default version (the name contains @@), look up the
5569      symbol again with only one `@' as well as without the version.
5570      The effect is that references to the symbol with and without the
5571      version will be matched by the default symbol in the archive.  */
5572
5573   p = strchr (name, ELF_VER_CHR);
5574   if (p == NULL || p[1] != ELF_VER_CHR)
5575     return h;
5576
5577   /* First check with only one `@'.  */
5578   len = strlen (name);
5579   copy = (char *) bfd_alloc (abfd, len);
5580   if (copy == NULL)
5581     return (struct elf_link_hash_entry *) -1;
5582
5583   first = p - name + 1;
5584   memcpy (copy, name, first);
5585   memcpy (copy + first, name + first + 1, len - first);
5586
5587   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5588   if (h == NULL)
5589     {
5590       /* We also need to check references to the symbol without the
5591          version.  */
5592       copy[first - 1] = '\0';
5593       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5594                                 FALSE, FALSE, TRUE);
5595     }
5596
5597   bfd_release (abfd, copy);
5598   return h;
5599 }
5600
5601 /* Add symbols from an ELF archive file to the linker hash table.  We
5602    don't use _bfd_generic_link_add_archive_symbols because we need to
5603    handle versioned symbols.
5604
5605    Fortunately, ELF archive handling is simpler than that done by
5606    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5607    oddities.  In ELF, if we find a symbol in the archive map, and the
5608    symbol is currently undefined, we know that we must pull in that
5609    object file.
5610
5611    Unfortunately, we do have to make multiple passes over the symbol
5612    table until nothing further is resolved.  */
5613
5614 static bfd_boolean
5615 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5616 {
5617   symindex c;
5618   unsigned char *included = NULL;
5619   carsym *symdefs;
5620   bfd_boolean loop;
5621   bfd_size_type amt;
5622   const struct elf_backend_data *bed;
5623   struct elf_link_hash_entry * (*archive_symbol_lookup)
5624     (bfd *, struct bfd_link_info *, const char *);
5625
5626   if (! bfd_has_map (abfd))
5627     {
5628       /* An empty archive is a special case.  */
5629       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5630         return TRUE;
5631       bfd_set_error (bfd_error_no_armap);
5632       return FALSE;
5633     }
5634
5635   /* Keep track of all symbols we know to be already defined, and all
5636      files we know to be already included.  This is to speed up the
5637      second and subsequent passes.  */
5638   c = bfd_ardata (abfd)->symdef_count;
5639   if (c == 0)
5640     return TRUE;
5641   amt = c;
5642   amt *= sizeof (*included);
5643   included = (unsigned char *) bfd_zmalloc (amt);
5644   if (included == NULL)
5645     return FALSE;
5646
5647   symdefs = bfd_ardata (abfd)->symdefs;
5648   bed = get_elf_backend_data (abfd);
5649   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5650
5651   do
5652     {
5653       file_ptr last;
5654       symindex i;
5655       carsym *symdef;
5656       carsym *symdefend;
5657
5658       loop = FALSE;
5659       last = -1;
5660
5661       symdef = symdefs;
5662       symdefend = symdef + c;
5663       for (i = 0; symdef < symdefend; symdef++, i++)
5664         {
5665           struct elf_link_hash_entry *h;
5666           bfd *element;
5667           struct bfd_link_hash_entry *undefs_tail;
5668           symindex mark;
5669
5670           if (included[i])
5671             continue;
5672           if (symdef->file_offset == last)
5673             {
5674               included[i] = TRUE;
5675               continue;
5676             }
5677
5678           h = archive_symbol_lookup (abfd, info, symdef->name);
5679           if (h == (struct elf_link_hash_entry *) -1)
5680             goto error_return;
5681
5682           if (h == NULL)
5683             continue;
5684
5685           if (h->root.type == bfd_link_hash_common)
5686             {
5687               /* We currently have a common symbol.  The archive map contains
5688                  a reference to this symbol, so we may want to include it.  We
5689                  only want to include it however, if this archive element
5690                  contains a definition of the symbol, not just another common
5691                  declaration of it.
5692
5693                  Unfortunately some archivers (including GNU ar) will put
5694                  declarations of common symbols into their archive maps, as
5695                  well as real definitions, so we cannot just go by the archive
5696                  map alone.  Instead we must read in the element's symbol
5697                  table and check that to see what kind of symbol definition
5698                  this is.  */
5699               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5700                 continue;
5701             }
5702           else if (h->root.type != bfd_link_hash_undefined)
5703             {
5704               if (h->root.type != bfd_link_hash_undefweak)
5705                 /* Symbol must be defined.  Don't check it again.  */
5706                 included[i] = TRUE;
5707               continue;
5708             }
5709
5710           /* We need to include this archive member.  */
5711           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5712           if (element == NULL)
5713             goto error_return;
5714
5715           if (! bfd_check_format (element, bfd_object))
5716             goto error_return;
5717
5718           undefs_tail = info->hash->undefs_tail;
5719
5720           if (!(*info->callbacks
5721                 ->add_archive_element) (info, element, symdef->name, &element))
5722             continue;
5723           if (!bfd_link_add_symbols (element, info))
5724             goto error_return;
5725
5726           /* If there are any new undefined symbols, we need to make
5727              another pass through the archive in order to see whether
5728              they can be defined.  FIXME: This isn't perfect, because
5729              common symbols wind up on undefs_tail and because an
5730              undefined symbol which is defined later on in this pass
5731              does not require another pass.  This isn't a bug, but it
5732              does make the code less efficient than it could be.  */
5733           if (undefs_tail != info->hash->undefs_tail)
5734             loop = TRUE;
5735
5736           /* Look backward to mark all symbols from this object file
5737              which we have already seen in this pass.  */
5738           mark = i;
5739           do
5740             {
5741               included[mark] = TRUE;
5742               if (mark == 0)
5743                 break;
5744               --mark;
5745             }
5746           while (symdefs[mark].file_offset == symdef->file_offset);
5747
5748           /* We mark subsequent symbols from this object file as we go
5749              on through the loop.  */
5750           last = symdef->file_offset;
5751         }
5752     }
5753   while (loop);
5754
5755   free (included);
5756
5757   return TRUE;
5758
5759  error_return:
5760   if (included != NULL)
5761     free (included);
5762   return FALSE;
5763 }
5764
5765 /* Given an ELF BFD, add symbols to the global hash table as
5766    appropriate.  */
5767
5768 bfd_boolean
5769 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5770 {
5771   switch (bfd_get_format (abfd))
5772     {
5773     case bfd_object:
5774       return elf_link_add_object_symbols (abfd, info);
5775     case bfd_archive:
5776       return elf_link_add_archive_symbols (abfd, info);
5777     default:
5778       bfd_set_error (bfd_error_wrong_format);
5779       return FALSE;
5780     }
5781 }
5782 \f
5783 struct hash_codes_info
5784 {
5785   unsigned long *hashcodes;
5786   bfd_boolean error;
5787 };
5788
5789 /* This function will be called though elf_link_hash_traverse to store
5790    all hash value of the exported symbols in an array.  */
5791
5792 static bfd_boolean
5793 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5794 {
5795   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5796   const char *name;
5797   unsigned long ha;
5798   char *alc = NULL;
5799
5800   /* Ignore indirect symbols.  These are added by the versioning code.  */
5801   if (h->dynindx == -1)
5802     return TRUE;
5803
5804   name = h->root.root.string;
5805   if (h->versioned >= versioned)
5806     {
5807       char *p = strchr (name, ELF_VER_CHR);
5808       if (p != NULL)
5809         {
5810           alc = (char *) bfd_malloc (p - name + 1);
5811           if (alc == NULL)
5812             {
5813               inf->error = TRUE;
5814               return FALSE;
5815             }
5816           memcpy (alc, name, p - name);
5817           alc[p - name] = '\0';
5818           name = alc;
5819         }
5820     }
5821
5822   /* Compute the hash value.  */
5823   ha = bfd_elf_hash (name);
5824
5825   /* Store the found hash value in the array given as the argument.  */
5826   *(inf->hashcodes)++ = ha;
5827
5828   /* And store it in the struct so that we can put it in the hash table
5829      later.  */
5830   h->u.elf_hash_value = ha;
5831
5832   if (alc != NULL)
5833     free (alc);
5834
5835   return TRUE;
5836 }
5837
5838 struct collect_gnu_hash_codes
5839 {
5840   bfd *output_bfd;
5841   const struct elf_backend_data *bed;
5842   unsigned long int nsyms;
5843   unsigned long int maskbits;
5844   unsigned long int *hashcodes;
5845   unsigned long int *hashval;
5846   unsigned long int *indx;
5847   unsigned long int *counts;
5848   bfd_vma *bitmask;
5849   bfd_byte *contents;
5850   long int min_dynindx;
5851   unsigned long int bucketcount;
5852   unsigned long int symindx;
5853   long int local_indx;
5854   long int shift1, shift2;
5855   unsigned long int mask;
5856   bfd_boolean error;
5857 };
5858
5859 /* This function will be called though elf_link_hash_traverse to store
5860    all hash value of the exported symbols in an array.  */
5861
5862 static bfd_boolean
5863 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5864 {
5865   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5866   const char *name;
5867   unsigned long ha;
5868   char *alc = NULL;
5869
5870   /* Ignore indirect symbols.  These are added by the versioning code.  */
5871   if (h->dynindx == -1)
5872     return TRUE;
5873
5874   /* Ignore also local symbols and undefined symbols.  */
5875   if (! (*s->bed->elf_hash_symbol) (h))
5876     return TRUE;
5877
5878   name = h->root.root.string;
5879   if (h->versioned >= versioned)
5880     {
5881       char *p = strchr (name, ELF_VER_CHR);
5882       if (p != NULL)
5883         {
5884           alc = (char *) bfd_malloc (p - name + 1);
5885           if (alc == NULL)
5886             {
5887               s->error = TRUE;
5888               return FALSE;
5889             }
5890           memcpy (alc, name, p - name);
5891           alc[p - name] = '\0';
5892           name = alc;
5893         }
5894     }
5895
5896   /* Compute the hash value.  */
5897   ha = bfd_elf_gnu_hash (name);
5898
5899   /* Store the found hash value in the array for compute_bucket_count,
5900      and also for .dynsym reordering purposes.  */
5901   s->hashcodes[s->nsyms] = ha;
5902   s->hashval[h->dynindx] = ha;
5903   ++s->nsyms;
5904   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5905     s->min_dynindx = h->dynindx;
5906
5907   if (alc != NULL)
5908     free (alc);
5909
5910   return TRUE;
5911 }
5912
5913 /* This function will be called though elf_link_hash_traverse to do
5914    final dynaminc symbol renumbering.  */
5915
5916 static bfd_boolean
5917 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5918 {
5919   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5920   unsigned long int bucket;
5921   unsigned long int val;
5922
5923   /* Ignore indirect symbols.  */
5924   if (h->dynindx == -1)
5925     return TRUE;
5926
5927   /* Ignore also local symbols and undefined symbols.  */
5928   if (! (*s->bed->elf_hash_symbol) (h))
5929     {
5930       if (h->dynindx >= s->min_dynindx)
5931         h->dynindx = s->local_indx++;
5932       return TRUE;
5933     }
5934
5935   bucket = s->hashval[h->dynindx] % s->bucketcount;
5936   val = (s->hashval[h->dynindx] >> s->shift1)
5937         & ((s->maskbits >> s->shift1) - 1);
5938   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5939   s->bitmask[val]
5940     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5941   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5942   if (s->counts[bucket] == 1)
5943     /* Last element terminates the chain.  */
5944     val |= 1;
5945   bfd_put_32 (s->output_bfd, val,
5946               s->contents + (s->indx[bucket] - s->symindx) * 4);
5947   --s->counts[bucket];
5948   h->dynindx = s->indx[bucket]++;
5949   return TRUE;
5950 }
5951
5952 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5953
5954 bfd_boolean
5955 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5956 {
5957   return !(h->forced_local
5958            || h->root.type == bfd_link_hash_undefined
5959            || h->root.type == bfd_link_hash_undefweak
5960            || ((h->root.type == bfd_link_hash_defined
5961                 || h->root.type == bfd_link_hash_defweak)
5962                && h->root.u.def.section->output_section == NULL));
5963 }
5964
5965 /* Array used to determine the number of hash table buckets to use
5966    based on the number of symbols there are.  If there are fewer than
5967    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5968    fewer than 37 we use 17 buckets, and so forth.  We never use more
5969    than 32771 buckets.  */
5970
5971 static const size_t elf_buckets[] =
5972 {
5973   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5974   16411, 32771, 0
5975 };
5976
5977 /* Compute bucket count for hashing table.  We do not use a static set
5978    of possible tables sizes anymore.  Instead we determine for all
5979    possible reasonable sizes of the table the outcome (i.e., the
5980    number of collisions etc) and choose the best solution.  The
5981    weighting functions are not too simple to allow the table to grow
5982    without bounds.  Instead one of the weighting factors is the size.
5983    Therefore the result is always a good payoff between few collisions
5984    (= short chain lengths) and table size.  */
5985 static size_t
5986 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5987                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5988                       unsigned long int nsyms,
5989                       int gnu_hash)
5990 {
5991   size_t best_size = 0;
5992   unsigned long int i;
5993
5994   /* We have a problem here.  The following code to optimize the table
5995      size requires an integer type with more the 32 bits.  If
5996      BFD_HOST_U_64_BIT is set we know about such a type.  */
5997 #ifdef BFD_HOST_U_64_BIT
5998   if (info->optimize)
5999     {
6000       size_t minsize;
6001       size_t maxsize;
6002       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
6003       bfd *dynobj = elf_hash_table (info)->dynobj;
6004       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
6005       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
6006       unsigned long int *counts;
6007       bfd_size_type amt;
6008       unsigned int no_improvement_count = 0;
6009
6010       /* Possible optimization parameters: if we have NSYMS symbols we say
6011          that the hashing table must at least have NSYMS/4 and at most
6012          2*NSYMS buckets.  */
6013       minsize = nsyms / 4;
6014       if (minsize == 0)
6015         minsize = 1;
6016       best_size = maxsize = nsyms * 2;
6017       if (gnu_hash)
6018         {
6019           if (minsize < 2)
6020             minsize = 2;
6021           if ((best_size & 31) == 0)
6022             ++best_size;
6023         }
6024
6025       /* Create array where we count the collisions in.  We must use bfd_malloc
6026          since the size could be large.  */
6027       amt = maxsize;
6028       amt *= sizeof (unsigned long int);
6029       counts = (unsigned long int *) bfd_malloc (amt);
6030       if (counts == NULL)
6031         return 0;
6032
6033       /* Compute the "optimal" size for the hash table.  The criteria is a
6034          minimal chain length.  The minor criteria is (of course) the size
6035          of the table.  */
6036       for (i = minsize; i < maxsize; ++i)
6037         {
6038           /* Walk through the array of hashcodes and count the collisions.  */
6039           BFD_HOST_U_64_BIT max;
6040           unsigned long int j;
6041           unsigned long int fact;
6042
6043           if (gnu_hash && (i & 31) == 0)
6044             continue;
6045
6046           memset (counts, '\0', i * sizeof (unsigned long int));
6047
6048           /* Determine how often each hash bucket is used.  */
6049           for (j = 0; j < nsyms; ++j)
6050             ++counts[hashcodes[j] % i];
6051
6052           /* For the weight function we need some information about the
6053              pagesize on the target.  This is information need not be 100%
6054              accurate.  Since this information is not available (so far) we
6055              define it here to a reasonable default value.  If it is crucial
6056              to have a better value some day simply define this value.  */
6057 # ifndef BFD_TARGET_PAGESIZE
6058 #  define BFD_TARGET_PAGESIZE   (4096)
6059 # endif
6060
6061           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
6062              and the chains.  */
6063           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
6064
6065 # if 1
6066           /* Variant 1: optimize for short chains.  We add the squares
6067              of all the chain lengths (which favors many small chain
6068              over a few long chains).  */
6069           for (j = 0; j < i; ++j)
6070             max += counts[j] * counts[j];
6071
6072           /* This adds penalties for the overall size of the table.  */
6073           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
6074           max *= fact * fact;
6075 # else
6076           /* Variant 2: Optimize a lot more for small table.  Here we
6077              also add squares of the size but we also add penalties for
6078              empty slots (the +1 term).  */
6079           for (j = 0; j < i; ++j)
6080             max += (1 + counts[j]) * (1 + counts[j]);
6081
6082           /* The overall size of the table is considered, but not as
6083              strong as in variant 1, where it is squared.  */
6084           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
6085           max *= fact;
6086 # endif
6087
6088           /* Compare with current best results.  */
6089           if (max < best_chlen)
6090             {
6091               best_chlen = max;
6092               best_size = i;
6093               no_improvement_count = 0;
6094             }
6095           /* PR 11843: Avoid futile long searches for the best bucket size
6096              when there are a large number of symbols.  */
6097           else if (++no_improvement_count == 100)
6098             break;
6099         }
6100
6101       free (counts);
6102     }
6103   else
6104 #endif /* defined (BFD_HOST_U_64_BIT) */
6105     {
6106       /* This is the fallback solution if no 64bit type is available or if we
6107          are not supposed to spend much time on optimizations.  We select the
6108          bucket count using a fixed set of numbers.  */
6109       for (i = 0; elf_buckets[i] != 0; i++)
6110         {
6111           best_size = elf_buckets[i];
6112           if (nsyms < elf_buckets[i + 1])
6113             break;
6114         }
6115       if (gnu_hash && best_size < 2)
6116         best_size = 2;
6117     }
6118
6119   return best_size;
6120 }
6121
6122 /* Size any SHT_GROUP section for ld -r.  */
6123
6124 bfd_boolean
6125 _bfd_elf_size_group_sections (struct bfd_link_info *info)
6126 {
6127   bfd *ibfd;
6128   asection *s;
6129
6130   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
6131     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
6132         && (s = ibfd->sections) != NULL
6133         && s->sec_info_type != SEC_INFO_TYPE_JUST_SYMS
6134         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
6135       return FALSE;
6136   return TRUE;
6137 }
6138
6139 /* Set a default stack segment size.  The value in INFO wins.  If it
6140    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
6141    undefined it is initialized.  */
6142
6143 bfd_boolean
6144 bfd_elf_stack_segment_size (bfd *output_bfd,
6145                             struct bfd_link_info *info,
6146                             const char *legacy_symbol,
6147                             bfd_vma default_size)
6148 {
6149   struct elf_link_hash_entry *h = NULL;
6150
6151   /* Look for legacy symbol.  */
6152   if (legacy_symbol)
6153     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
6154                               FALSE, FALSE, FALSE);
6155   if (h && (h->root.type == bfd_link_hash_defined
6156             || h->root.type == bfd_link_hash_defweak)
6157       && h->def_regular
6158       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
6159     {
6160       /* The symbol has no type if specified on the command line.  */
6161       h->type = STT_OBJECT;
6162       if (info->stacksize)
6163         /* xgettext:c-format */
6164         _bfd_error_handler (_("%pB: stack size specified and %s set"),
6165                             output_bfd, legacy_symbol);
6166       else if (h->root.u.def.section != bfd_abs_section_ptr)
6167         /* xgettext:c-format */
6168         _bfd_error_handler (_("%pB: %s not absolute"),
6169                             output_bfd, legacy_symbol);
6170       else
6171         info->stacksize = h->root.u.def.value;
6172     }
6173
6174   if (!info->stacksize)
6175     /* If the user didn't set a size, or explicitly inhibit the
6176        size, set it now.  */
6177     info->stacksize = default_size;
6178
6179   /* Provide the legacy symbol, if it is referenced.  */
6180   if (h && (h->root.type == bfd_link_hash_undefined
6181             || h->root.type == bfd_link_hash_undefweak))
6182     {
6183       struct bfd_link_hash_entry *bh = NULL;
6184
6185       if (!(_bfd_generic_link_add_one_symbol
6186             (info, output_bfd, legacy_symbol,
6187              BSF_GLOBAL, bfd_abs_section_ptr,
6188              info->stacksize >= 0 ? info->stacksize : 0,
6189              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
6190         return FALSE;
6191
6192       h = (struct elf_link_hash_entry *) bh;
6193       h->def_regular = 1;
6194       h->type = STT_OBJECT;
6195     }
6196
6197   return TRUE;
6198 }
6199
6200 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
6201
6202 struct elf_gc_sweep_symbol_info
6203 {
6204   struct bfd_link_info *info;
6205   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
6206                        bfd_boolean);
6207 };
6208
6209 static bfd_boolean
6210 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
6211 {
6212   if (!h->mark
6213       && (((h->root.type == bfd_link_hash_defined
6214             || h->root.type == bfd_link_hash_defweak)
6215            && !((h->def_regular || ELF_COMMON_DEF_P (h))
6216                 && h->root.u.def.section->gc_mark))
6217           || h->root.type == bfd_link_hash_undefined
6218           || h->root.type == bfd_link_hash_undefweak))
6219     {
6220       struct elf_gc_sweep_symbol_info *inf;
6221
6222       inf = (struct elf_gc_sweep_symbol_info *) data;
6223       (*inf->hide_symbol) (inf->info, h, TRUE);
6224       h->def_regular = 0;
6225       h->ref_regular = 0;
6226       h->ref_regular_nonweak = 0;
6227     }
6228
6229   return TRUE;
6230 }
6231
6232 /* Set up the sizes and contents of the ELF dynamic sections.  This is
6233    called by the ELF linker emulation before_allocation routine.  We
6234    must set the sizes of the sections before the linker sets the
6235    addresses of the various sections.  */
6236
6237 bfd_boolean
6238 bfd_elf_size_dynamic_sections (bfd *output_bfd,
6239                                const char *soname,
6240                                const char *rpath,
6241                                const char *filter_shlib,
6242                                const char *audit,
6243                                const char *depaudit,
6244                                const char * const *auxiliary_filters,
6245                                struct bfd_link_info *info,
6246                                asection **sinterpptr)
6247 {
6248   bfd *dynobj;
6249   const struct elf_backend_data *bed;
6250
6251   *sinterpptr = NULL;
6252
6253   if (!is_elf_hash_table (info->hash))
6254     return TRUE;
6255
6256   dynobj = elf_hash_table (info)->dynobj;
6257
6258   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6259     {
6260       struct bfd_elf_version_tree *verdefs;
6261       struct elf_info_failed asvinfo;
6262       struct bfd_elf_version_tree *t;
6263       struct bfd_elf_version_expr *d;
6264       asection *s;
6265       size_t soname_indx;
6266
6267       /* If we are supposed to export all symbols into the dynamic symbol
6268          table (this is not the normal case), then do so.  */
6269       if (info->export_dynamic
6270           || (bfd_link_executable (info) && info->dynamic))
6271         {
6272           struct elf_info_failed eif;
6273
6274           eif.info = info;
6275           eif.failed = FALSE;
6276           elf_link_hash_traverse (elf_hash_table (info),
6277                                   _bfd_elf_export_symbol,
6278                                   &eif);
6279           if (eif.failed)
6280             return FALSE;
6281         }
6282
6283       if (soname != NULL)
6284         {
6285           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6286                                              soname, TRUE);
6287           if (soname_indx == (size_t) -1
6288               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
6289             return FALSE;
6290         }
6291       else
6292         soname_indx = (size_t) -1;
6293
6294       /* Make all global versions with definition.  */
6295       for (t = info->version_info; t != NULL; t = t->next)
6296         for (d = t->globals.list; d != NULL; d = d->next)
6297           if (!d->symver && d->literal)
6298             {
6299               const char *verstr, *name;
6300               size_t namelen, verlen, newlen;
6301               char *newname, *p, leading_char;
6302               struct elf_link_hash_entry *newh;
6303
6304               leading_char = bfd_get_symbol_leading_char (output_bfd);
6305               name = d->pattern;
6306               namelen = strlen (name) + (leading_char != '\0');
6307               verstr = t->name;
6308               verlen = strlen (verstr);
6309               newlen = namelen + verlen + 3;
6310
6311               newname = (char *) bfd_malloc (newlen);
6312               if (newname == NULL)
6313                 return FALSE;
6314               newname[0] = leading_char;
6315               memcpy (newname + (leading_char != '\0'), name, namelen);
6316
6317               /* Check the hidden versioned definition.  */
6318               p = newname + namelen;
6319               *p++ = ELF_VER_CHR;
6320               memcpy (p, verstr, verlen + 1);
6321               newh = elf_link_hash_lookup (elf_hash_table (info),
6322                                            newname, FALSE, FALSE,
6323                                            FALSE);
6324               if (newh == NULL
6325                   || (newh->root.type != bfd_link_hash_defined
6326                       && newh->root.type != bfd_link_hash_defweak))
6327                 {
6328                   /* Check the default versioned definition.  */
6329                   *p++ = ELF_VER_CHR;
6330                   memcpy (p, verstr, verlen + 1);
6331                   newh = elf_link_hash_lookup (elf_hash_table (info),
6332                                                newname, FALSE, FALSE,
6333                                                FALSE);
6334                 }
6335               free (newname);
6336
6337               /* Mark this version if there is a definition and it is
6338                  not defined in a shared object.  */
6339               if (newh != NULL
6340                   && !newh->def_dynamic
6341                   && (newh->root.type == bfd_link_hash_defined
6342                       || newh->root.type == bfd_link_hash_defweak))
6343                 d->symver = 1;
6344             }
6345
6346       /* Attach all the symbols to their version information.  */
6347       asvinfo.info = info;
6348       asvinfo.failed = FALSE;
6349
6350       elf_link_hash_traverse (elf_hash_table (info),
6351                               _bfd_elf_link_assign_sym_version,
6352                               &asvinfo);
6353       if (asvinfo.failed)
6354         return FALSE;
6355
6356       if (!info->allow_undefined_version)
6357         {
6358           /* Check if all global versions have a definition.  */
6359           bfd_boolean all_defined = TRUE;
6360           for (t = info->version_info; t != NULL; t = t->next)
6361             for (d = t->globals.list; d != NULL; d = d->next)
6362               if (d->literal && !d->symver && !d->script)
6363                 {
6364                   _bfd_error_handler
6365                     (_("%s: undefined version: %s"),
6366                      d->pattern, t->name);
6367                   all_defined = FALSE;
6368                 }
6369
6370           if (!all_defined)
6371             {
6372               bfd_set_error (bfd_error_bad_value);
6373               return FALSE;
6374             }
6375         }
6376
6377       /* Set up the version definition section.  */
6378       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6379       BFD_ASSERT (s != NULL);
6380
6381       /* We may have created additional version definitions if we are
6382          just linking a regular application.  */
6383       verdefs = info->version_info;
6384
6385       /* Skip anonymous version tag.  */
6386       if (verdefs != NULL && verdefs->vernum == 0)
6387         verdefs = verdefs->next;
6388
6389       if (verdefs == NULL && !info->create_default_symver)
6390         s->flags |= SEC_EXCLUDE;
6391       else
6392         {
6393           unsigned int cdefs;
6394           bfd_size_type size;
6395           bfd_byte *p;
6396           Elf_Internal_Verdef def;
6397           Elf_Internal_Verdaux defaux;
6398           struct bfd_link_hash_entry *bh;
6399           struct elf_link_hash_entry *h;
6400           const char *name;
6401
6402           cdefs = 0;
6403           size = 0;
6404
6405           /* Make space for the base version.  */
6406           size += sizeof (Elf_External_Verdef);
6407           size += sizeof (Elf_External_Verdaux);
6408           ++cdefs;
6409
6410           /* Make space for the default version.  */
6411           if (info->create_default_symver)
6412             {
6413               size += sizeof (Elf_External_Verdef);
6414               ++cdefs;
6415             }
6416
6417           for (t = verdefs; t != NULL; t = t->next)
6418             {
6419               struct bfd_elf_version_deps *n;
6420
6421               /* Don't emit base version twice.  */
6422               if (t->vernum == 0)
6423                 continue;
6424
6425               size += sizeof (Elf_External_Verdef);
6426               size += sizeof (Elf_External_Verdaux);
6427               ++cdefs;
6428
6429               for (n = t->deps; n != NULL; n = n->next)
6430                 size += sizeof (Elf_External_Verdaux);
6431             }
6432
6433           s->size = size;
6434           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6435           if (s->contents == NULL && s->size != 0)
6436             return FALSE;
6437
6438           /* Fill in the version definition section.  */
6439
6440           p = s->contents;
6441
6442           def.vd_version = VER_DEF_CURRENT;
6443           def.vd_flags = VER_FLG_BASE;
6444           def.vd_ndx = 1;
6445           def.vd_cnt = 1;
6446           if (info->create_default_symver)
6447             {
6448               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6449               def.vd_next = sizeof (Elf_External_Verdef);
6450             }
6451           else
6452             {
6453               def.vd_aux = sizeof (Elf_External_Verdef);
6454               def.vd_next = (sizeof (Elf_External_Verdef)
6455                              + sizeof (Elf_External_Verdaux));
6456             }
6457
6458           if (soname_indx != (size_t) -1)
6459             {
6460               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6461                                       soname_indx);
6462               def.vd_hash = bfd_elf_hash (soname);
6463               defaux.vda_name = soname_indx;
6464               name = soname;
6465             }
6466           else
6467             {
6468               size_t indx;
6469
6470               name = lbasename (output_bfd->filename);
6471               def.vd_hash = bfd_elf_hash (name);
6472               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6473                                           name, FALSE);
6474               if (indx == (size_t) -1)
6475                 return FALSE;
6476               defaux.vda_name = indx;
6477             }
6478           defaux.vda_next = 0;
6479
6480           _bfd_elf_swap_verdef_out (output_bfd, &def,
6481                                     (Elf_External_Verdef *) p);
6482           p += sizeof (Elf_External_Verdef);
6483           if (info->create_default_symver)
6484             {
6485               /* Add a symbol representing this version.  */
6486               bh = NULL;
6487               if (! (_bfd_generic_link_add_one_symbol
6488                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6489                       0, NULL, FALSE,
6490                       get_elf_backend_data (dynobj)->collect, &bh)))
6491                 return FALSE;
6492               h = (struct elf_link_hash_entry *) bh;
6493               h->non_elf = 0;
6494               h->def_regular = 1;
6495               h->type = STT_OBJECT;
6496               h->verinfo.vertree = NULL;
6497
6498               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6499                 return FALSE;
6500
6501               /* Create a duplicate of the base version with the same
6502                  aux block, but different flags.  */
6503               def.vd_flags = 0;
6504               def.vd_ndx = 2;
6505               def.vd_aux = sizeof (Elf_External_Verdef);
6506               if (verdefs)
6507                 def.vd_next = (sizeof (Elf_External_Verdef)
6508                                + sizeof (Elf_External_Verdaux));
6509               else
6510                 def.vd_next = 0;
6511               _bfd_elf_swap_verdef_out (output_bfd, &def,
6512                                         (Elf_External_Verdef *) p);
6513               p += sizeof (Elf_External_Verdef);
6514             }
6515           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6516                                      (Elf_External_Verdaux *) p);
6517           p += sizeof (Elf_External_Verdaux);
6518
6519           for (t = verdefs; t != NULL; t = t->next)
6520             {
6521               unsigned int cdeps;
6522               struct bfd_elf_version_deps *n;
6523
6524               /* Don't emit the base version twice.  */
6525               if (t->vernum == 0)
6526                 continue;
6527
6528               cdeps = 0;
6529               for (n = t->deps; n != NULL; n = n->next)
6530                 ++cdeps;
6531
6532               /* Add a symbol representing this version.  */
6533               bh = NULL;
6534               if (! (_bfd_generic_link_add_one_symbol
6535                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6536                       0, NULL, FALSE,
6537                       get_elf_backend_data (dynobj)->collect, &bh)))
6538                 return FALSE;
6539               h = (struct elf_link_hash_entry *) bh;
6540               h->non_elf = 0;
6541               h->def_regular = 1;
6542               h->type = STT_OBJECT;
6543               h->verinfo.vertree = t;
6544
6545               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6546                 return FALSE;
6547
6548               def.vd_version = VER_DEF_CURRENT;
6549               def.vd_flags = 0;
6550               if (t->globals.list == NULL
6551                   && t->locals.list == NULL
6552                   && ! t->used)
6553                 def.vd_flags |= VER_FLG_WEAK;
6554               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6555               def.vd_cnt = cdeps + 1;
6556               def.vd_hash = bfd_elf_hash (t->name);
6557               def.vd_aux = sizeof (Elf_External_Verdef);
6558               def.vd_next = 0;
6559
6560               /* If a basever node is next, it *must* be the last node in
6561                  the chain, otherwise Verdef construction breaks.  */
6562               if (t->next != NULL && t->next->vernum == 0)
6563                 BFD_ASSERT (t->next->next == NULL);
6564
6565               if (t->next != NULL && t->next->vernum != 0)
6566                 def.vd_next = (sizeof (Elf_External_Verdef)
6567                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6568
6569               _bfd_elf_swap_verdef_out (output_bfd, &def,
6570                                         (Elf_External_Verdef *) p);
6571               p += sizeof (Elf_External_Verdef);
6572
6573               defaux.vda_name = h->dynstr_index;
6574               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6575                                       h->dynstr_index);
6576               defaux.vda_next = 0;
6577               if (t->deps != NULL)
6578                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6579               t->name_indx = defaux.vda_name;
6580
6581               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6582                                          (Elf_External_Verdaux *) p);
6583               p += sizeof (Elf_External_Verdaux);
6584
6585               for (n = t->deps; n != NULL; n = n->next)
6586                 {
6587                   if (n->version_needed == NULL)
6588                     {
6589                       /* This can happen if there was an error in the
6590                          version script.  */
6591                       defaux.vda_name = 0;
6592                     }
6593                   else
6594                     {
6595                       defaux.vda_name = n->version_needed->name_indx;
6596                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6597                                               defaux.vda_name);
6598                     }
6599                   if (n->next == NULL)
6600                     defaux.vda_next = 0;
6601                   else
6602                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6603
6604                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6605                                              (Elf_External_Verdaux *) p);
6606                   p += sizeof (Elf_External_Verdaux);
6607                 }
6608             }
6609
6610           elf_tdata (output_bfd)->cverdefs = cdefs;
6611         }
6612     }
6613
6614   bed = get_elf_backend_data (output_bfd);
6615
6616   if (info->gc_sections && bed->can_gc_sections)
6617     {
6618       struct elf_gc_sweep_symbol_info sweep_info;
6619
6620       /* Remove the symbols that were in the swept sections from the
6621          dynamic symbol table.  */
6622       sweep_info.info = info;
6623       sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
6624       elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
6625                               &sweep_info);
6626     }
6627
6628   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6629     {
6630       asection *s;
6631       struct elf_find_verdep_info sinfo;
6632
6633       /* Work out the size of the version reference section.  */
6634
6635       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6636       BFD_ASSERT (s != NULL);
6637
6638       sinfo.info = info;
6639       sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6640       if (sinfo.vers == 0)
6641         sinfo.vers = 1;
6642       sinfo.failed = FALSE;
6643
6644       elf_link_hash_traverse (elf_hash_table (info),
6645                               _bfd_elf_link_find_version_dependencies,
6646                               &sinfo);
6647       if (sinfo.failed)
6648         return FALSE;
6649
6650       if (elf_tdata (output_bfd)->verref == NULL)
6651         s->flags |= SEC_EXCLUDE;
6652       else
6653         {
6654           Elf_Internal_Verneed *vn;
6655           unsigned int size;
6656           unsigned int crefs;
6657           bfd_byte *p;
6658
6659           /* Build the version dependency section.  */
6660           size = 0;
6661           crefs = 0;
6662           for (vn = elf_tdata (output_bfd)->verref;
6663                vn != NULL;
6664                vn = vn->vn_nextref)
6665             {
6666               Elf_Internal_Vernaux *a;
6667
6668               size += sizeof (Elf_External_Verneed);
6669               ++crefs;
6670               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6671                 size += sizeof (Elf_External_Vernaux);
6672             }
6673
6674           s->size = size;
6675           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6676           if (s->contents == NULL)
6677             return FALSE;
6678
6679           p = s->contents;
6680           for (vn = elf_tdata (output_bfd)->verref;
6681                vn != NULL;
6682                vn = vn->vn_nextref)
6683             {
6684               unsigned int caux;
6685               Elf_Internal_Vernaux *a;
6686               size_t indx;
6687
6688               caux = 0;
6689               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6690                 ++caux;
6691
6692               vn->vn_version = VER_NEED_CURRENT;
6693               vn->vn_cnt = caux;
6694               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6695                                           elf_dt_name (vn->vn_bfd) != NULL
6696                                           ? elf_dt_name (vn->vn_bfd)
6697                                           : lbasename (vn->vn_bfd->filename),
6698                                           FALSE);
6699               if (indx == (size_t) -1)
6700                 return FALSE;
6701               vn->vn_file = indx;
6702               vn->vn_aux = sizeof (Elf_External_Verneed);
6703               if (vn->vn_nextref == NULL)
6704                 vn->vn_next = 0;
6705               else
6706                 vn->vn_next = (sizeof (Elf_External_Verneed)
6707                                + caux * sizeof (Elf_External_Vernaux));
6708
6709               _bfd_elf_swap_verneed_out (output_bfd, vn,
6710                                          (Elf_External_Verneed *) p);
6711               p += sizeof (Elf_External_Verneed);
6712
6713               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6714                 {
6715                   a->vna_hash = bfd_elf_hash (a->vna_nodename);
6716                   indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6717                                               a->vna_nodename, FALSE);
6718                   if (indx == (size_t) -1)
6719                     return FALSE;
6720                   a->vna_name = indx;
6721                   if (a->vna_nextptr == NULL)
6722                     a->vna_next = 0;
6723                   else
6724                     a->vna_next = sizeof (Elf_External_Vernaux);
6725
6726                   _bfd_elf_swap_vernaux_out (output_bfd, a,
6727                                              (Elf_External_Vernaux *) p);
6728                   p += sizeof (Elf_External_Vernaux);
6729                 }
6730             }
6731
6732           elf_tdata (output_bfd)->cverrefs = crefs;
6733         }
6734     }
6735
6736   /* Any syms created from now on start with -1 in
6737      got.refcount/offset and plt.refcount/offset.  */
6738   elf_hash_table (info)->init_got_refcount
6739     = elf_hash_table (info)->init_got_offset;
6740   elf_hash_table (info)->init_plt_refcount
6741     = elf_hash_table (info)->init_plt_offset;
6742
6743   if (bfd_link_relocatable (info)
6744       && !_bfd_elf_size_group_sections (info))
6745     return FALSE;
6746
6747   /* The backend may have to create some sections regardless of whether
6748      we're dynamic or not.  */
6749   if (bed->elf_backend_always_size_sections
6750       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
6751     return FALSE;
6752
6753   /* Determine any GNU_STACK segment requirements, after the backend
6754      has had a chance to set a default segment size.  */
6755   if (info->execstack)
6756     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
6757   else if (info->noexecstack)
6758     elf_stack_flags (output_bfd) = PF_R | PF_W;
6759   else
6760     {
6761       bfd *inputobj;
6762       asection *notesec = NULL;
6763       int exec = 0;
6764
6765       for (inputobj = info->input_bfds;
6766            inputobj;
6767            inputobj = inputobj->link.next)
6768         {
6769           asection *s;
6770
6771           if (inputobj->flags
6772               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
6773             continue;
6774           s = inputobj->sections;
6775           if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
6776             continue;
6777
6778           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
6779           if (s)
6780             {
6781               if (s->flags & SEC_CODE)
6782                 exec = PF_X;
6783               notesec = s;
6784             }
6785           else if (bed->default_execstack)
6786             exec = PF_X;
6787         }
6788       if (notesec || info->stacksize > 0)
6789         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
6790       if (notesec && exec && bfd_link_relocatable (info)
6791           && notesec->output_section != bfd_abs_section_ptr)
6792         notesec->output_section->flags |= SEC_CODE;
6793     }
6794
6795   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6796     {
6797       struct elf_info_failed eif;
6798       struct elf_link_hash_entry *h;
6799       asection *dynstr;
6800       asection *s;
6801
6802       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
6803       BFD_ASSERT (*sinterpptr != NULL || !bfd_link_executable (info) || info->nointerp);
6804
6805       if (info->symbolic)
6806         {
6807           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
6808             return FALSE;
6809           info->flags |= DF_SYMBOLIC;
6810         }
6811
6812       if (rpath != NULL)
6813         {
6814           size_t indx;
6815           bfd_vma tag;
6816
6817           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
6818                                       TRUE);
6819           if (indx == (size_t) -1)
6820             return FALSE;
6821
6822           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
6823           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
6824             return FALSE;
6825         }
6826
6827       if (filter_shlib != NULL)
6828         {
6829           size_t indx;
6830
6831           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6832                                       filter_shlib, TRUE);
6833           if (indx == (size_t) -1
6834               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
6835             return FALSE;
6836         }
6837
6838       if (auxiliary_filters != NULL)
6839         {
6840           const char * const *p;
6841
6842           for (p = auxiliary_filters; *p != NULL; p++)
6843             {
6844               size_t indx;
6845
6846               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6847                                           *p, TRUE);
6848               if (indx == (size_t) -1
6849                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
6850                 return FALSE;
6851             }
6852         }
6853
6854       if (audit != NULL)
6855         {
6856           size_t indx;
6857
6858           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
6859                                       TRUE);
6860           if (indx == (size_t) -1
6861               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
6862             return FALSE;
6863         }
6864
6865       if (depaudit != NULL)
6866         {
6867           size_t indx;
6868
6869           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
6870                                       TRUE);
6871           if (indx == (size_t) -1
6872               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
6873             return FALSE;
6874         }
6875
6876       eif.info = info;
6877       eif.failed = FALSE;
6878
6879       /* Find all symbols which were defined in a dynamic object and make
6880          the backend pick a reasonable value for them.  */
6881       elf_link_hash_traverse (elf_hash_table (info),
6882                               _bfd_elf_adjust_dynamic_symbol,
6883                               &eif);
6884       if (eif.failed)
6885         return FALSE;
6886
6887       /* Add some entries to the .dynamic section.  We fill in some of the
6888          values later, in bfd_elf_final_link, but we must add the entries
6889          now so that we know the final size of the .dynamic section.  */
6890
6891       /* If there are initialization and/or finalization functions to
6892          call then add the corresponding DT_INIT/DT_FINI entries.  */
6893       h = (info->init_function
6894            ? elf_link_hash_lookup (elf_hash_table (info),
6895                                    info->init_function, FALSE,
6896                                    FALSE, FALSE)
6897            : NULL);
6898       if (h != NULL
6899           && (h->ref_regular
6900               || h->def_regular))
6901         {
6902           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
6903             return FALSE;
6904         }
6905       h = (info->fini_function
6906            ? elf_link_hash_lookup (elf_hash_table (info),
6907                                    info->fini_function, FALSE,
6908                                    FALSE, FALSE)
6909            : NULL);
6910       if (h != NULL
6911           && (h->ref_regular
6912               || h->def_regular))
6913         {
6914           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
6915             return FALSE;
6916         }
6917
6918       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
6919       if (s != NULL && s->linker_has_input)
6920         {
6921           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
6922           if (! bfd_link_executable (info))
6923             {
6924               bfd *sub;
6925               asection *o;
6926
6927               for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
6928                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour
6929                     && (o = sub->sections) != NULL
6930                     && o->sec_info_type != SEC_INFO_TYPE_JUST_SYMS)
6931                   for (o = sub->sections; o != NULL; o = o->next)
6932                     if (elf_section_data (o)->this_hdr.sh_type
6933                         == SHT_PREINIT_ARRAY)
6934                       {
6935                         _bfd_error_handler
6936                           (_("%pB: .preinit_array section is not allowed in DSO"),
6937                            sub);
6938                         break;
6939                       }
6940
6941               bfd_set_error (bfd_error_nonrepresentable_section);
6942               return FALSE;
6943             }
6944
6945           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6946               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6947             return FALSE;
6948         }
6949       s = bfd_get_section_by_name (output_bfd, ".init_array");
6950       if (s != NULL && s->linker_has_input)
6951         {
6952           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6953               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6954             return FALSE;
6955         }
6956       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6957       if (s != NULL && s->linker_has_input)
6958         {
6959           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6960               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6961             return FALSE;
6962         }
6963
6964       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6965       /* If .dynstr is excluded from the link, we don't want any of
6966          these tags.  Strictly, we should be checking each section
6967          individually;  This quick check covers for the case where
6968          someone does a /DISCARD/ : { *(*) }.  */
6969       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6970         {
6971           bfd_size_type strsize;
6972
6973           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6974           if ((info->emit_hash
6975                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6976               || (info->emit_gnu_hash
6977                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6978               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6979               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6980               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6981               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6982                                               bed->s->sizeof_sym))
6983             return FALSE;
6984         }
6985     }
6986
6987   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6988     return FALSE;
6989
6990   /* The backend must work out the sizes of all the other dynamic
6991      sections.  */
6992   if (dynobj != NULL
6993       && bed->elf_backend_size_dynamic_sections != NULL
6994       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6995     return FALSE;
6996
6997   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6998     {
6999       if (elf_tdata (output_bfd)->cverdefs)
7000         {
7001           unsigned int crefs = elf_tdata (output_bfd)->cverdefs;
7002
7003           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
7004               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, crefs))
7005             return FALSE;
7006         }
7007
7008       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
7009         {
7010           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
7011             return FALSE;
7012         }
7013       else if (info->flags & DF_BIND_NOW)
7014         {
7015           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
7016             return FALSE;
7017         }
7018
7019       if (info->flags_1)
7020         {
7021           if (bfd_link_executable (info))
7022             info->flags_1 &= ~ (DF_1_INITFIRST
7023                                 | DF_1_NODELETE
7024                                 | DF_1_NOOPEN);
7025           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
7026             return FALSE;
7027         }
7028
7029       if (elf_tdata (output_bfd)->cverrefs)
7030         {
7031           unsigned int crefs = elf_tdata (output_bfd)->cverrefs;
7032
7033           if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
7034               || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
7035             return FALSE;
7036         }
7037
7038       if ((elf_tdata (output_bfd)->cverrefs == 0
7039            && elf_tdata (output_bfd)->cverdefs == 0)
7040           || _bfd_elf_link_renumber_dynsyms (output_bfd, info, NULL) <= 1)
7041         {
7042           asection *s;
7043
7044           s = bfd_get_linker_section (dynobj, ".gnu.version");
7045           s->flags |= SEC_EXCLUDE;
7046         }
7047     }
7048   return TRUE;
7049 }
7050
7051 /* Find the first non-excluded output section.  We'll use its
7052    section symbol for some emitted relocs.  */
7053 void
7054 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
7055 {
7056   asection *s;
7057   asection *found = NULL;
7058
7059   for (s = output_bfd->sections; s != NULL; s = s->next)
7060     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
7061         && !_bfd_elf_omit_section_dynsym_default (output_bfd, info, s))
7062       {
7063         found = s;
7064         if ((s->flags & SEC_THREAD_LOCAL) == 0)
7065           break;
7066       }
7067   elf_hash_table (info)->text_index_section = found;
7068 }
7069
7070 /* Find two non-excluded output sections, one for code, one for data.
7071    We'll use their section symbols for some emitted relocs.  */
7072 void
7073 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
7074 {
7075   asection *s;
7076   asection *found = NULL;
7077
7078   /* Data first, since setting text_index_section changes
7079      _bfd_elf_omit_section_dynsym_default.  */
7080   for (s = output_bfd->sections; s != NULL; s = s->next)
7081     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
7082         && !(s->flags & SEC_READONLY)
7083         && !_bfd_elf_omit_section_dynsym_default (output_bfd, info, s))
7084       {
7085         found = s;
7086         if ((s->flags & SEC_THREAD_LOCAL) == 0)
7087           break;
7088       }
7089   elf_hash_table (info)->data_index_section = found;
7090
7091   for (s = output_bfd->sections; s != NULL; s = s->next)
7092     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
7093         && (s->flags & SEC_READONLY)
7094         && !_bfd_elf_omit_section_dynsym_default (output_bfd, info, s))
7095       {
7096         found = s;
7097         break;
7098       }
7099   elf_hash_table (info)->text_index_section = found;
7100 }
7101
7102 bfd_boolean
7103 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
7104 {
7105   const struct elf_backend_data *bed;
7106   unsigned long section_sym_count;
7107   bfd_size_type dynsymcount = 0;
7108
7109   if (!is_elf_hash_table (info->hash))
7110     return TRUE;
7111
7112   bed = get_elf_backend_data (output_bfd);
7113   (*bed->elf_backend_init_index_section) (output_bfd, info);
7114
7115   /* Assign dynsym indices.  In a shared library we generate a section
7116      symbol for each output section, which come first.  Next come all
7117      of the back-end allocated local dynamic syms, followed by the rest
7118      of the global symbols.
7119
7120      This is usually not needed for static binaries, however backends
7121      can request to always do it, e.g. the MIPS backend uses dynamic
7122      symbol counts to lay out GOT, which will be produced in the
7123      presence of GOT relocations even in static binaries (holding fixed
7124      data in that case, to satisfy those relocations).  */
7125
7126   if (elf_hash_table (info)->dynamic_sections_created
7127       || bed->always_renumber_dynsyms)
7128     dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
7129                                                   &section_sym_count);
7130
7131   if (elf_hash_table (info)->dynamic_sections_created)
7132     {
7133       bfd *dynobj;
7134       asection *s;
7135       unsigned int dtagcount;
7136
7137       dynobj = elf_hash_table (info)->dynobj;
7138
7139       /* Work out the size of the symbol version section.  */
7140       s = bfd_get_linker_section (dynobj, ".gnu.version");
7141       BFD_ASSERT (s != NULL);
7142       if ((s->flags & SEC_EXCLUDE) == 0)
7143         {
7144           s->size = dynsymcount * sizeof (Elf_External_Versym);
7145           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7146           if (s->contents == NULL)
7147             return FALSE;
7148
7149           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
7150             return FALSE;
7151         }
7152
7153       /* Set the size of the .dynsym and .hash sections.  We counted
7154          the number of dynamic symbols in elf_link_add_object_symbols.
7155          We will build the contents of .dynsym and .hash when we build
7156          the final symbol table, because until then we do not know the
7157          correct value to give the symbols.  We built the .dynstr
7158          section as we went along in elf_link_add_object_symbols.  */
7159       s = elf_hash_table (info)->dynsym;
7160       BFD_ASSERT (s != NULL);
7161       s->size = dynsymcount * bed->s->sizeof_sym;
7162
7163       s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
7164       if (s->contents == NULL)
7165         return FALSE;
7166
7167       /* The first entry in .dynsym is a dummy symbol.  Clear all the
7168          section syms, in case we don't output them all.  */
7169       ++section_sym_count;
7170       memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
7171
7172       elf_hash_table (info)->bucketcount = 0;
7173
7174       /* Compute the size of the hashing table.  As a side effect this
7175          computes the hash values for all the names we export.  */
7176       if (info->emit_hash)
7177         {
7178           unsigned long int *hashcodes;
7179           struct hash_codes_info hashinf;
7180           bfd_size_type amt;
7181           unsigned long int nsyms;
7182           size_t bucketcount;
7183           size_t hash_entry_size;
7184
7185           /* Compute the hash values for all exported symbols.  At the same
7186              time store the values in an array so that we could use them for
7187              optimizations.  */
7188           amt = dynsymcount * sizeof (unsigned long int);
7189           hashcodes = (unsigned long int *) bfd_malloc (amt);
7190           if (hashcodes == NULL)
7191             return FALSE;
7192           hashinf.hashcodes = hashcodes;
7193           hashinf.error = FALSE;
7194
7195           /* Put all hash values in HASHCODES.  */
7196           elf_link_hash_traverse (elf_hash_table (info),
7197                                   elf_collect_hash_codes, &hashinf);
7198           if (hashinf.error)
7199             {
7200               free (hashcodes);
7201               return FALSE;
7202             }
7203
7204           nsyms = hashinf.hashcodes - hashcodes;
7205           bucketcount
7206             = compute_bucket_count (info, hashcodes, nsyms, 0);
7207           free (hashcodes);
7208
7209           if (bucketcount == 0 && nsyms > 0)
7210             return FALSE;
7211
7212           elf_hash_table (info)->bucketcount = bucketcount;
7213
7214           s = bfd_get_linker_section (dynobj, ".hash");
7215           BFD_ASSERT (s != NULL);
7216           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
7217           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
7218           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7219           if (s->contents == NULL)
7220             return FALSE;
7221
7222           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
7223           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
7224                    s->contents + hash_entry_size);
7225         }
7226
7227       if (info->emit_gnu_hash)
7228         {
7229           size_t i, cnt;
7230           unsigned char *contents;
7231           struct collect_gnu_hash_codes cinfo;
7232           bfd_size_type amt;
7233           size_t bucketcount;
7234
7235           memset (&cinfo, 0, sizeof (cinfo));
7236
7237           /* Compute the hash values for all exported symbols.  At the same
7238              time store the values in an array so that we could use them for
7239              optimizations.  */
7240           amt = dynsymcount * 2 * sizeof (unsigned long int);
7241           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
7242           if (cinfo.hashcodes == NULL)
7243             return FALSE;
7244
7245           cinfo.hashval = cinfo.hashcodes + dynsymcount;
7246           cinfo.min_dynindx = -1;
7247           cinfo.output_bfd = output_bfd;
7248           cinfo.bed = bed;
7249
7250           /* Put all hash values in HASHCODES.  */
7251           elf_link_hash_traverse (elf_hash_table (info),
7252                                   elf_collect_gnu_hash_codes, &cinfo);
7253           if (cinfo.error)
7254             {
7255               free (cinfo.hashcodes);
7256               return FALSE;
7257             }
7258
7259           bucketcount
7260             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
7261
7262           if (bucketcount == 0)
7263             {
7264               free (cinfo.hashcodes);
7265               return FALSE;
7266             }
7267
7268           s = bfd_get_linker_section (dynobj, ".gnu.hash");
7269           BFD_ASSERT (s != NULL);
7270
7271           if (cinfo.nsyms == 0)
7272             {
7273               /* Empty .gnu.hash section is special.  */
7274               BFD_ASSERT (cinfo.min_dynindx == -1);
7275               free (cinfo.hashcodes);
7276               s->size = 5 * 4 + bed->s->arch_size / 8;
7277               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7278               if (contents == NULL)
7279                 return FALSE;
7280               s->contents = contents;
7281               /* 1 empty bucket.  */
7282               bfd_put_32 (output_bfd, 1, contents);
7283               /* SYMIDX above the special symbol 0.  */
7284               bfd_put_32 (output_bfd, 1, contents + 4);
7285               /* Just one word for bitmask.  */
7286               bfd_put_32 (output_bfd, 1, contents + 8);
7287               /* Only hash fn bloom filter.  */
7288               bfd_put_32 (output_bfd, 0, contents + 12);
7289               /* No hashes are valid - empty bitmask.  */
7290               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
7291               /* No hashes in the only bucket.  */
7292               bfd_put_32 (output_bfd, 0,
7293                           contents + 16 + bed->s->arch_size / 8);
7294             }
7295           else
7296             {
7297               unsigned long int maskwords, maskbitslog2, x;
7298               BFD_ASSERT (cinfo.min_dynindx != -1);
7299
7300               x = cinfo.nsyms;
7301               maskbitslog2 = 1;
7302               while ((x >>= 1) != 0)
7303                 ++maskbitslog2;
7304               if (maskbitslog2 < 3)
7305                 maskbitslog2 = 5;
7306               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
7307                 maskbitslog2 = maskbitslog2 + 3;
7308               else
7309                 maskbitslog2 = maskbitslog2 + 2;
7310               if (bed->s->arch_size == 64)
7311                 {
7312                   if (maskbitslog2 == 5)
7313                     maskbitslog2 = 6;
7314                   cinfo.shift1 = 6;
7315                 }
7316               else
7317                 cinfo.shift1 = 5;
7318               cinfo.mask = (1 << cinfo.shift1) - 1;
7319               cinfo.shift2 = maskbitslog2;
7320               cinfo.maskbits = 1 << maskbitslog2;
7321               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
7322               amt = bucketcount * sizeof (unsigned long int) * 2;
7323               amt += maskwords * sizeof (bfd_vma);
7324               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
7325               if (cinfo.bitmask == NULL)
7326                 {
7327                   free (cinfo.hashcodes);
7328                   return FALSE;
7329                 }
7330
7331               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
7332               cinfo.indx = cinfo.counts + bucketcount;
7333               cinfo.symindx = dynsymcount - cinfo.nsyms;
7334               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
7335
7336               /* Determine how often each hash bucket is used.  */
7337               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
7338               for (i = 0; i < cinfo.nsyms; ++i)
7339                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
7340
7341               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
7342                 if (cinfo.counts[i] != 0)
7343                   {
7344                     cinfo.indx[i] = cnt;
7345                     cnt += cinfo.counts[i];
7346                   }
7347               BFD_ASSERT (cnt == dynsymcount);
7348               cinfo.bucketcount = bucketcount;
7349               cinfo.local_indx = cinfo.min_dynindx;
7350
7351               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
7352               s->size += cinfo.maskbits / 8;
7353               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7354               if (contents == NULL)
7355                 {
7356                   free (cinfo.bitmask);
7357                   free (cinfo.hashcodes);
7358                   return FALSE;
7359                 }
7360
7361               s->contents = contents;
7362               bfd_put_32 (output_bfd, bucketcount, contents);
7363               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
7364               bfd_put_32 (output_bfd, maskwords, contents + 8);
7365               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
7366               contents += 16 + cinfo.maskbits / 8;
7367
7368               for (i = 0; i < bucketcount; ++i)
7369                 {
7370                   if (cinfo.counts[i] == 0)
7371                     bfd_put_32 (output_bfd, 0, contents);
7372                   else
7373                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
7374                   contents += 4;
7375                 }
7376
7377               cinfo.contents = contents;
7378
7379               /* Renumber dynamic symbols, populate .gnu.hash section.  */
7380               elf_link_hash_traverse (elf_hash_table (info),
7381                                       elf_renumber_gnu_hash_syms, &cinfo);
7382
7383               contents = s->contents + 16;
7384               for (i = 0; i < maskwords; ++i)
7385                 {
7386                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
7387                            contents);
7388                   contents += bed->s->arch_size / 8;
7389                 }
7390
7391               free (cinfo.bitmask);
7392               free (cinfo.hashcodes);
7393             }
7394         }
7395
7396       s = bfd_get_linker_section (dynobj, ".dynstr");
7397       BFD_ASSERT (s != NULL);
7398
7399       elf_finalize_dynstr (output_bfd, info);
7400
7401       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
7402
7403       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
7404         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
7405           return FALSE;
7406     }
7407
7408   return TRUE;
7409 }
7410 \f
7411 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
7412
7413 static void
7414 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
7415                             asection *sec)
7416 {
7417   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
7418   sec->sec_info_type = SEC_INFO_TYPE_NONE;
7419 }
7420
7421 /* Finish SHF_MERGE section merging.  */
7422
7423 bfd_boolean
7424 _bfd_elf_merge_sections (bfd *obfd, struct bfd_link_info *info)
7425 {
7426   bfd *ibfd;
7427   asection *sec;
7428
7429   if (!is_elf_hash_table (info->hash))
7430     return FALSE;
7431
7432   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
7433     if ((ibfd->flags & DYNAMIC) == 0
7434         && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
7435         && (elf_elfheader (ibfd)->e_ident[EI_CLASS]
7436             == get_elf_backend_data (obfd)->s->elfclass))
7437       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
7438         if ((sec->flags & SEC_MERGE) != 0
7439             && !bfd_is_abs_section (sec->output_section))
7440           {
7441             struct bfd_elf_section_data *secdata;
7442
7443             secdata = elf_section_data (sec);
7444             if (! _bfd_add_merge_section (obfd,
7445                                           &elf_hash_table (info)->merge_info,
7446                                           sec, &secdata->sec_info))
7447               return FALSE;
7448             else if (secdata->sec_info)
7449               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
7450           }
7451
7452   if (elf_hash_table (info)->merge_info != NULL)
7453     _bfd_merge_sections (obfd, info, elf_hash_table (info)->merge_info,
7454                          merge_sections_remove_hook);
7455   return TRUE;
7456 }
7457
7458 /* Create an entry in an ELF linker hash table.  */
7459
7460 struct bfd_hash_entry *
7461 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
7462                             struct bfd_hash_table *table,
7463                             const char *string)
7464 {
7465   /* Allocate the structure if it has not already been allocated by a
7466      subclass.  */
7467   if (entry == NULL)
7468     {
7469       entry = (struct bfd_hash_entry *)
7470         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
7471       if (entry == NULL)
7472         return entry;
7473     }
7474
7475   /* Call the allocation method of the superclass.  */
7476   entry = _bfd_link_hash_newfunc (entry, table, string);
7477   if (entry != NULL)
7478     {
7479       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
7480       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
7481
7482       /* Set local fields.  */
7483       ret->indx = -1;
7484       ret->dynindx = -1;
7485       ret->got = htab->init_got_refcount;
7486       ret->plt = htab->init_plt_refcount;
7487       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
7488                               - offsetof (struct elf_link_hash_entry, size)));
7489       /* Assume that we have been called by a non-ELF symbol reader.
7490          This flag is then reset by the code which reads an ELF input
7491          file.  This ensures that a symbol created by a non-ELF symbol
7492          reader will have the flag set correctly.  */
7493       ret->non_elf = 1;
7494     }
7495
7496   return entry;
7497 }
7498
7499 /* Copy data from an indirect symbol to its direct symbol, hiding the
7500    old indirect symbol.  Also used for copying flags to a weakdef.  */
7501
7502 void
7503 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
7504                                   struct elf_link_hash_entry *dir,
7505                                   struct elf_link_hash_entry *ind)
7506 {
7507   struct elf_link_hash_table *htab;
7508
7509   /* Copy down any references that we may have already seen to the
7510      symbol which just became indirect.  */
7511
7512   if (dir->versioned != versioned_hidden)
7513     dir->ref_dynamic |= ind->ref_dynamic;
7514   dir->ref_regular |= ind->ref_regular;
7515   dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
7516   dir->non_got_ref |= ind->non_got_ref;
7517   dir->needs_plt |= ind->needs_plt;
7518   dir->pointer_equality_needed |= ind->pointer_equality_needed;
7519
7520   if (ind->root.type != bfd_link_hash_indirect)
7521     return;
7522
7523   /* Copy over the global and procedure linkage table refcount entries.
7524      These may have been already set up by a check_relocs routine.  */
7525   htab = elf_hash_table (info);
7526   if (ind->got.refcount > htab->init_got_refcount.refcount)
7527     {
7528       if (dir->got.refcount < 0)
7529         dir->got.refcount = 0;
7530       dir->got.refcount += ind->got.refcount;
7531       ind->got.refcount = htab->init_got_refcount.refcount;
7532     }
7533
7534   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
7535     {
7536       if (dir->plt.refcount < 0)
7537         dir->plt.refcount = 0;
7538       dir->plt.refcount += ind->plt.refcount;
7539       ind->plt.refcount = htab->init_plt_refcount.refcount;
7540     }
7541
7542   if (ind->dynindx != -1)
7543     {
7544       if (dir->dynindx != -1)
7545         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
7546       dir->dynindx = ind->dynindx;
7547       dir->dynstr_index = ind->dynstr_index;
7548       ind->dynindx = -1;
7549       ind->dynstr_index = 0;
7550     }
7551 }
7552
7553 void
7554 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
7555                                 struct elf_link_hash_entry *h,
7556                                 bfd_boolean force_local)
7557 {
7558   /* STT_GNU_IFUNC symbol must go through PLT.  */
7559   if (h->type != STT_GNU_IFUNC)
7560     {
7561       h->plt = elf_hash_table (info)->init_plt_offset;
7562       h->needs_plt = 0;
7563     }
7564   if (force_local)
7565     {
7566       h->forced_local = 1;
7567       if (h->dynindx != -1)
7568         {
7569           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
7570                                   h->dynstr_index);
7571           h->dynindx = -1;
7572           h->dynstr_index = 0;
7573         }
7574     }
7575 }
7576
7577 /* Hide a symbol. */
7578
7579 void
7580 _bfd_elf_link_hide_symbol (bfd *output_bfd,
7581                            struct bfd_link_info *info,
7582                            struct bfd_link_hash_entry *h)
7583 {
7584   if (is_elf_hash_table (info->hash))
7585     {
7586       const struct elf_backend_data *bed
7587         = get_elf_backend_data (output_bfd);
7588       struct elf_link_hash_entry *eh
7589         = (struct elf_link_hash_entry *) h;
7590       bed->elf_backend_hide_symbol (info, eh, TRUE);
7591       eh->def_dynamic = 0;
7592       eh->ref_dynamic = 0;
7593       eh->dynamic_def = 0;
7594     }
7595 }
7596
7597 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
7598    caller.  */
7599
7600 bfd_boolean
7601 _bfd_elf_link_hash_table_init
7602   (struct elf_link_hash_table *table,
7603    bfd *abfd,
7604    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
7605                                       struct bfd_hash_table *,
7606                                       const char *),
7607    unsigned int entsize,
7608    enum elf_target_id target_id)
7609 {
7610   bfd_boolean ret;
7611   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
7612
7613   table->init_got_refcount.refcount = can_refcount - 1;
7614   table->init_plt_refcount.refcount = can_refcount - 1;
7615   table->init_got_offset.offset = -(bfd_vma) 1;
7616   table->init_plt_offset.offset = -(bfd_vma) 1;
7617   /* The first dynamic symbol is a dummy.  */
7618   table->dynsymcount = 1;
7619
7620   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
7621
7622   table->root.type = bfd_link_elf_hash_table;
7623   table->hash_table_id = target_id;
7624
7625   return ret;
7626 }
7627
7628 /* Create an ELF linker hash table.  */
7629
7630 struct bfd_link_hash_table *
7631 _bfd_elf_link_hash_table_create (bfd *abfd)
7632 {
7633   struct elf_link_hash_table *ret;
7634   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7635
7636   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7637   if (ret == NULL)
7638     return NULL;
7639
7640   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7641                                        sizeof (struct elf_link_hash_entry),
7642                                        GENERIC_ELF_DATA))
7643     {
7644       free (ret);
7645       return NULL;
7646     }
7647   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7648
7649   return &ret->root;
7650 }
7651
7652 /* Destroy an ELF linker hash table.  */
7653
7654 void
7655 _bfd_elf_link_hash_table_free (bfd *obfd)
7656 {
7657   struct elf_link_hash_table *htab;
7658
7659   htab = (struct elf_link_hash_table *) obfd->link.hash;
7660   if (htab->dynstr != NULL)
7661     _bfd_elf_strtab_free (htab->dynstr);
7662   _bfd_merge_sections_free (htab->merge_info);
7663   _bfd_generic_link_hash_table_free (obfd);
7664 }
7665
7666 /* This is a hook for the ELF emulation code in the generic linker to
7667    tell the backend linker what file name to use for the DT_NEEDED
7668    entry for a dynamic object.  */
7669
7670 void
7671 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7672 {
7673   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7674       && bfd_get_format (abfd) == bfd_object)
7675     elf_dt_name (abfd) = name;
7676 }
7677
7678 int
7679 bfd_elf_get_dyn_lib_class (bfd *abfd)
7680 {
7681   int lib_class;
7682   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7683       && bfd_get_format (abfd) == bfd_object)
7684     lib_class = elf_dyn_lib_class (abfd);
7685   else
7686     lib_class = 0;
7687   return lib_class;
7688 }
7689
7690 void
7691 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7692 {
7693   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7694       && bfd_get_format (abfd) == bfd_object)
7695     elf_dyn_lib_class (abfd) = lib_class;
7696 }
7697
7698 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7699    the linker ELF emulation code.  */
7700
7701 struct bfd_link_needed_list *
7702 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7703                          struct bfd_link_info *info)
7704 {
7705   if (! is_elf_hash_table (info->hash))
7706     return NULL;
7707   return elf_hash_table (info)->needed;
7708 }
7709
7710 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7711    hook for the linker ELF emulation code.  */
7712
7713 struct bfd_link_needed_list *
7714 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7715                           struct bfd_link_info *info)
7716 {
7717   if (! is_elf_hash_table (info->hash))
7718     return NULL;
7719   return elf_hash_table (info)->runpath;
7720 }
7721
7722 /* Get the name actually used for a dynamic object for a link.  This
7723    is the SONAME entry if there is one.  Otherwise, it is the string
7724    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7725
7726 const char *
7727 bfd_elf_get_dt_soname (bfd *abfd)
7728 {
7729   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7730       && bfd_get_format (abfd) == bfd_object)
7731     return elf_dt_name (abfd);
7732   return NULL;
7733 }
7734
7735 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7736    the ELF linker emulation code.  */
7737
7738 bfd_boolean
7739 bfd_elf_get_bfd_needed_list (bfd *abfd,
7740                              struct bfd_link_needed_list **pneeded)
7741 {
7742   asection *s;
7743   bfd_byte *dynbuf = NULL;
7744   unsigned int elfsec;
7745   unsigned long shlink;
7746   bfd_byte *extdyn, *extdynend;
7747   size_t extdynsize;
7748   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7749
7750   *pneeded = NULL;
7751
7752   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7753       || bfd_get_format (abfd) != bfd_object)
7754     return TRUE;
7755
7756   s = bfd_get_section_by_name (abfd, ".dynamic");
7757   if (s == NULL || s->size == 0)
7758     return TRUE;
7759
7760   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7761     goto error_return;
7762
7763   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7764   if (elfsec == SHN_BAD)
7765     goto error_return;
7766
7767   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7768
7769   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7770   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7771
7772   extdyn = dynbuf;
7773   extdynend = extdyn + s->size;
7774   for (; extdyn < extdynend; extdyn += extdynsize)
7775     {
7776       Elf_Internal_Dyn dyn;
7777
7778       (*swap_dyn_in) (abfd, extdyn, &dyn);
7779
7780       if (dyn.d_tag == DT_NULL)
7781         break;
7782
7783       if (dyn.d_tag == DT_NEEDED)
7784         {
7785           const char *string;
7786           struct bfd_link_needed_list *l;
7787           unsigned int tagv = dyn.d_un.d_val;
7788           bfd_size_type amt;
7789
7790           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7791           if (string == NULL)
7792             goto error_return;
7793
7794           amt = sizeof *l;
7795           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7796           if (l == NULL)
7797             goto error_return;
7798
7799           l->by = abfd;
7800           l->name = string;
7801           l->next = *pneeded;
7802           *pneeded = l;
7803         }
7804     }
7805
7806   free (dynbuf);
7807
7808   return TRUE;
7809
7810  error_return:
7811   if (dynbuf != NULL)
7812     free (dynbuf);
7813   return FALSE;
7814 }
7815
7816 struct elf_symbuf_symbol
7817 {
7818   unsigned long st_name;        /* Symbol name, index in string tbl */
7819   unsigned char st_info;        /* Type and binding attributes */
7820   unsigned char st_other;       /* Visibilty, and target specific */
7821 };
7822
7823 struct elf_symbuf_head
7824 {
7825   struct elf_symbuf_symbol *ssym;
7826   size_t count;
7827   unsigned int st_shndx;
7828 };
7829
7830 struct elf_symbol
7831 {
7832   union
7833     {
7834       Elf_Internal_Sym *isym;
7835       struct elf_symbuf_symbol *ssym;
7836     } u;
7837   const char *name;
7838 };
7839
7840 /* Sort references to symbols by ascending section number.  */
7841
7842 static int
7843 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7844 {
7845   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7846   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7847
7848   return s1->st_shndx - s2->st_shndx;
7849 }
7850
7851 static int
7852 elf_sym_name_compare (const void *arg1, const void *arg2)
7853 {
7854   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7855   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7856   return strcmp (s1->name, s2->name);
7857 }
7858
7859 static struct elf_symbuf_head *
7860 elf_create_symbuf (size_t symcount, Elf_Internal_Sym *isymbuf)
7861 {
7862   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7863   struct elf_symbuf_symbol *ssym;
7864   struct elf_symbuf_head *ssymbuf, *ssymhead;
7865   size_t i, shndx_count, total_size;
7866
7867   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7868   if (indbuf == NULL)
7869     return NULL;
7870
7871   for (ind = indbuf, i = 0; i < symcount; i++)
7872     if (isymbuf[i].st_shndx != SHN_UNDEF)
7873       *ind++ = &isymbuf[i];
7874   indbufend = ind;
7875
7876   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7877          elf_sort_elf_symbol);
7878
7879   shndx_count = 0;
7880   if (indbufend > indbuf)
7881     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7882       if (ind[0]->st_shndx != ind[1]->st_shndx)
7883         shndx_count++;
7884
7885   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7886                 + (indbufend - indbuf) * sizeof (*ssym));
7887   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7888   if (ssymbuf == NULL)
7889     {
7890       free (indbuf);
7891       return NULL;
7892     }
7893
7894   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7895   ssymbuf->ssym = NULL;
7896   ssymbuf->count = shndx_count;
7897   ssymbuf->st_shndx = 0;
7898   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7899     {
7900       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7901         {
7902           ssymhead++;
7903           ssymhead->ssym = ssym;
7904           ssymhead->count = 0;
7905           ssymhead->st_shndx = (*ind)->st_shndx;
7906         }
7907       ssym->st_name = (*ind)->st_name;
7908       ssym->st_info = (*ind)->st_info;
7909       ssym->st_other = (*ind)->st_other;
7910       ssymhead->count++;
7911     }
7912   BFD_ASSERT ((size_t) (ssymhead - ssymbuf) == shndx_count
7913               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7914                   == total_size));
7915
7916   free (indbuf);
7917   return ssymbuf;
7918 }
7919
7920 /* Check if 2 sections define the same set of local and global
7921    symbols.  */
7922
7923 static bfd_boolean
7924 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7925                                    struct bfd_link_info *info)
7926 {
7927   bfd *bfd1, *bfd2;
7928   const struct elf_backend_data *bed1, *bed2;
7929   Elf_Internal_Shdr *hdr1, *hdr2;
7930   size_t symcount1, symcount2;
7931   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7932   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7933   Elf_Internal_Sym *isym, *isymend;
7934   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7935   size_t count1, count2, i;
7936   unsigned int shndx1, shndx2;
7937   bfd_boolean result;
7938
7939   bfd1 = sec1->owner;
7940   bfd2 = sec2->owner;
7941
7942   /* Both sections have to be in ELF.  */
7943   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7944       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7945     return FALSE;
7946
7947   if (elf_section_type (sec1) != elf_section_type (sec2))
7948     return FALSE;
7949
7950   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7951   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7952   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7953     return FALSE;
7954
7955   bed1 = get_elf_backend_data (bfd1);
7956   bed2 = get_elf_backend_data (bfd2);
7957   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7958   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7959   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7960   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7961
7962   if (symcount1 == 0 || symcount2 == 0)
7963     return FALSE;
7964
7965   result = FALSE;
7966   isymbuf1 = NULL;
7967   isymbuf2 = NULL;
7968   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7969   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7970
7971   if (ssymbuf1 == NULL)
7972     {
7973       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7974                                        NULL, NULL, NULL);
7975       if (isymbuf1 == NULL)
7976         goto done;
7977
7978       if (!info->reduce_memory_overheads)
7979         elf_tdata (bfd1)->symbuf = ssymbuf1
7980           = elf_create_symbuf (symcount1, isymbuf1);
7981     }
7982
7983   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7984     {
7985       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7986                                        NULL, NULL, NULL);
7987       if (isymbuf2 == NULL)
7988         goto done;
7989
7990       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7991         elf_tdata (bfd2)->symbuf = ssymbuf2
7992           = elf_create_symbuf (symcount2, isymbuf2);
7993     }
7994
7995   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7996     {
7997       /* Optimized faster version.  */
7998       size_t lo, hi, mid;
7999       struct elf_symbol *symp;
8000       struct elf_symbuf_symbol *ssym, *ssymend;
8001
8002       lo = 0;
8003       hi = ssymbuf1->count;
8004       ssymbuf1++;
8005       count1 = 0;
8006       while (lo < hi)
8007         {
8008           mid = (lo + hi) / 2;
8009           if (shndx1 < ssymbuf1[mid].st_shndx)
8010             hi = mid;
8011           else if (shndx1 > ssymbuf1[mid].st_shndx)
8012             lo = mid + 1;
8013           else
8014             {
8015               count1 = ssymbuf1[mid].count;
8016               ssymbuf1 += mid;
8017               break;
8018             }
8019         }
8020
8021       lo = 0;
8022       hi = ssymbuf2->count;
8023       ssymbuf2++;
8024       count2 = 0;
8025       while (lo < hi)
8026         {
8027           mid = (lo + hi) / 2;
8028           if (shndx2 < ssymbuf2[mid].st_shndx)
8029             hi = mid;
8030           else if (shndx2 > ssymbuf2[mid].st_shndx)
8031             lo = mid + 1;
8032           else
8033             {
8034               count2 = ssymbuf2[mid].count;
8035               ssymbuf2 += mid;
8036               break;
8037             }
8038         }
8039
8040       if (count1 == 0 || count2 == 0 || count1 != count2)
8041         goto done;
8042
8043       symtable1
8044         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
8045       symtable2
8046         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
8047       if (symtable1 == NULL || symtable2 == NULL)
8048         goto done;
8049
8050       symp = symtable1;
8051       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
8052            ssym < ssymend; ssym++, symp++)
8053         {
8054           symp->u.ssym = ssym;
8055           symp->name = bfd_elf_string_from_elf_section (bfd1,
8056                                                         hdr1->sh_link,
8057                                                         ssym->st_name);
8058         }
8059
8060       symp = symtable2;
8061       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
8062            ssym < ssymend; ssym++, symp++)
8063         {
8064           symp->u.ssym = ssym;
8065           symp->name = bfd_elf_string_from_elf_section (bfd2,
8066                                                         hdr2->sh_link,
8067                                                         ssym->st_name);
8068         }
8069
8070       /* Sort symbol by name.  */
8071       qsort (symtable1, count1, sizeof (struct elf_symbol),
8072              elf_sym_name_compare);
8073       qsort (symtable2, count1, sizeof (struct elf_symbol),
8074              elf_sym_name_compare);
8075
8076       for (i = 0; i < count1; i++)
8077         /* Two symbols must have the same binding, type and name.  */
8078         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
8079             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
8080             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
8081           goto done;
8082
8083       result = TRUE;
8084       goto done;
8085     }
8086
8087   symtable1 = (struct elf_symbol *)
8088       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
8089   symtable2 = (struct elf_symbol *)
8090       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
8091   if (symtable1 == NULL || symtable2 == NULL)
8092     goto done;
8093
8094   /* Count definitions in the section.  */
8095   count1 = 0;
8096   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
8097     if (isym->st_shndx == shndx1)
8098       symtable1[count1++].u.isym = isym;
8099
8100   count2 = 0;
8101   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
8102     if (isym->st_shndx == shndx2)
8103       symtable2[count2++].u.isym = isym;
8104
8105   if (count1 == 0 || count2 == 0 || count1 != count2)
8106     goto done;
8107
8108   for (i = 0; i < count1; i++)
8109     symtable1[i].name
8110       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
8111                                          symtable1[i].u.isym->st_name);
8112
8113   for (i = 0; i < count2; i++)
8114     symtable2[i].name
8115       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
8116                                          symtable2[i].u.isym->st_name);
8117
8118   /* Sort symbol by name.  */
8119   qsort (symtable1, count1, sizeof (struct elf_symbol),
8120          elf_sym_name_compare);
8121   qsort (symtable2, count1, sizeof (struct elf_symbol),
8122          elf_sym_name_compare);
8123
8124   for (i = 0; i < count1; i++)
8125     /* Two symbols must have the same binding, type and name.  */
8126     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
8127         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
8128         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
8129       goto done;
8130
8131   result = TRUE;
8132
8133 done:
8134   if (symtable1)
8135     free (symtable1);
8136   if (symtable2)
8137     free (symtable2);
8138   if (isymbuf1)
8139     free (isymbuf1);
8140   if (isymbuf2)
8141     free (isymbuf2);
8142
8143   return result;
8144 }
8145
8146 /* Return TRUE if 2 section types are compatible.  */
8147
8148 bfd_boolean
8149 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
8150                                  bfd *bbfd, const asection *bsec)
8151 {
8152   if (asec == NULL
8153       || bsec == NULL
8154       || abfd->xvec->flavour != bfd_target_elf_flavour
8155       || bbfd->xvec->flavour != bfd_target_elf_flavour)
8156     return TRUE;
8157
8158   return elf_section_type (asec) == elf_section_type (bsec);
8159 }
8160 \f
8161 /* Final phase of ELF linker.  */
8162
8163 /* A structure we use to avoid passing large numbers of arguments.  */
8164
8165 struct elf_final_link_info
8166 {
8167   /* General link information.  */
8168   struct bfd_link_info *info;
8169   /* Output BFD.  */
8170   bfd *output_bfd;
8171   /* Symbol string table.  */
8172   struct elf_strtab_hash *symstrtab;
8173   /* .hash section.  */
8174   asection *hash_sec;
8175   /* symbol version section (.gnu.version).  */
8176   asection *symver_sec;
8177   /* Buffer large enough to hold contents of any section.  */
8178   bfd_byte *contents;
8179   /* Buffer large enough to hold external relocs of any section.  */
8180   void *external_relocs;
8181   /* Buffer large enough to hold internal relocs of any section.  */
8182   Elf_Internal_Rela *internal_relocs;
8183   /* Buffer large enough to hold external local symbols of any input
8184      BFD.  */
8185   bfd_byte *external_syms;
8186   /* And a buffer for symbol section indices.  */
8187   Elf_External_Sym_Shndx *locsym_shndx;
8188   /* Buffer large enough to hold internal local symbols of any input
8189      BFD.  */
8190   Elf_Internal_Sym *internal_syms;
8191   /* Array large enough to hold a symbol index for each local symbol
8192      of any input BFD.  */
8193   long *indices;
8194   /* Array large enough to hold a section pointer for each local
8195      symbol of any input BFD.  */
8196   asection **sections;
8197   /* Buffer for SHT_SYMTAB_SHNDX section.  */
8198   Elf_External_Sym_Shndx *symshndxbuf;
8199   /* Number of STT_FILE syms seen.  */
8200   size_t filesym_count;
8201 };
8202
8203 /* This struct is used to pass information to elf_link_output_extsym.  */
8204
8205 struct elf_outext_info
8206 {
8207   bfd_boolean failed;
8208   bfd_boolean localsyms;
8209   bfd_boolean file_sym_done;
8210   struct elf_final_link_info *flinfo;
8211 };
8212
8213
8214 /* Support for evaluating a complex relocation.
8215
8216    Complex relocations are generalized, self-describing relocations.  The
8217    implementation of them consists of two parts: complex symbols, and the
8218    relocations themselves.
8219
8220    The relocations are use a reserved elf-wide relocation type code (R_RELC
8221    external / BFD_RELOC_RELC internal) and an encoding of relocation field
8222    information (start bit, end bit, word width, etc) into the addend.  This
8223    information is extracted from CGEN-generated operand tables within gas.
8224
8225    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
8226    internal) representing prefix-notation expressions, including but not
8227    limited to those sorts of expressions normally encoded as addends in the
8228    addend field.  The symbol mangling format is:
8229
8230    <node> := <literal>
8231           |  <unary-operator> ':' <node>
8232           |  <binary-operator> ':' <node> ':' <node>
8233           ;
8234
8235    <literal> := 's' <digits=N> ':' <N character symbol name>
8236              |  'S' <digits=N> ':' <N character section name>
8237              |  '#' <hexdigits>
8238              ;
8239
8240    <binary-operator> := as in C
8241    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
8242
8243 static void
8244 set_symbol_value (bfd *bfd_with_globals,
8245                   Elf_Internal_Sym *isymbuf,
8246                   size_t locsymcount,
8247                   size_t symidx,
8248                   bfd_vma val)
8249 {
8250   struct elf_link_hash_entry **sym_hashes;
8251   struct elf_link_hash_entry *h;
8252   size_t extsymoff = locsymcount;
8253
8254   if (symidx < locsymcount)
8255     {
8256       Elf_Internal_Sym *sym;
8257
8258       sym = isymbuf + symidx;
8259       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
8260         {
8261           /* It is a local symbol: move it to the
8262              "absolute" section and give it a value.  */
8263           sym->st_shndx = SHN_ABS;
8264           sym->st_value = val;
8265           return;
8266         }
8267       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
8268       extsymoff = 0;
8269     }
8270
8271   /* It is a global symbol: set its link type
8272      to "defined" and give it a value.  */
8273
8274   sym_hashes = elf_sym_hashes (bfd_with_globals);
8275   h = sym_hashes [symidx - extsymoff];
8276   while (h->root.type == bfd_link_hash_indirect
8277          || h->root.type == bfd_link_hash_warning)
8278     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8279   h->root.type = bfd_link_hash_defined;
8280   h->root.u.def.value = val;
8281   h->root.u.def.section = bfd_abs_section_ptr;
8282 }
8283
8284 static bfd_boolean
8285 resolve_symbol (const char *name,
8286                 bfd *input_bfd,
8287                 struct elf_final_link_info *flinfo,
8288                 bfd_vma *result,
8289                 Elf_Internal_Sym *isymbuf,
8290                 size_t locsymcount)
8291 {
8292   Elf_Internal_Sym *sym;
8293   struct bfd_link_hash_entry *global_entry;
8294   const char *candidate = NULL;
8295   Elf_Internal_Shdr *symtab_hdr;
8296   size_t i;
8297
8298   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
8299
8300   for (i = 0; i < locsymcount; ++ i)
8301     {
8302       sym = isymbuf + i;
8303
8304       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
8305         continue;
8306
8307       candidate = bfd_elf_string_from_elf_section (input_bfd,
8308                                                    symtab_hdr->sh_link,
8309                                                    sym->st_name);
8310 #ifdef DEBUG
8311       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
8312               name, candidate, (unsigned long) sym->st_value);
8313 #endif
8314       if (candidate && strcmp (candidate, name) == 0)
8315         {
8316           asection *sec = flinfo->sections [i];
8317
8318           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
8319           *result += sec->output_offset + sec->output_section->vma;
8320 #ifdef DEBUG
8321           printf ("Found symbol with value %8.8lx\n",
8322                   (unsigned long) *result);
8323 #endif
8324           return TRUE;
8325         }
8326     }
8327
8328   /* Hmm, haven't found it yet. perhaps it is a global.  */
8329   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
8330                                        FALSE, FALSE, TRUE);
8331   if (!global_entry)
8332     return FALSE;
8333
8334   if (global_entry->type == bfd_link_hash_defined
8335       || global_entry->type == bfd_link_hash_defweak)
8336     {
8337       *result = (global_entry->u.def.value
8338                  + global_entry->u.def.section->output_section->vma
8339                  + global_entry->u.def.section->output_offset);
8340 #ifdef DEBUG
8341       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
8342               global_entry->root.string, (unsigned long) *result);
8343 #endif
8344       return TRUE;
8345     }
8346
8347   return FALSE;
8348 }
8349
8350 /* Looks up NAME in SECTIONS.  If found sets RESULT to NAME's address (in
8351    bytes) and returns TRUE, otherwise returns FALSE.  Accepts pseudo-section
8352    names like "foo.end" which is the end address of section "foo".  */
8353
8354 static bfd_boolean
8355 resolve_section (const char *name,
8356                  asection *sections,
8357                  bfd_vma *result,
8358                  bfd * abfd)
8359 {
8360   asection *curr;
8361   unsigned int len;
8362
8363   for (curr = sections; curr; curr = curr->next)
8364     if (strcmp (curr->name, name) == 0)
8365       {
8366         *result = curr->vma;
8367         return TRUE;
8368       }
8369
8370   /* Hmm. still haven't found it. try pseudo-section names.  */
8371   /* FIXME: This could be coded more efficiently...  */
8372   for (curr = sections; curr; curr = curr->next)
8373     {
8374       len = strlen (curr->name);
8375       if (len > strlen (name))
8376         continue;
8377
8378       if (strncmp (curr->name, name, len) == 0)
8379         {
8380           if (strncmp (".end", name + len, 4) == 0)
8381             {
8382               *result = curr->vma + curr->size / bfd_octets_per_byte (abfd);
8383               return TRUE;
8384             }
8385
8386           /* Insert more pseudo-section names here, if you like.  */
8387         }
8388     }
8389
8390   return FALSE;
8391 }
8392
8393 static void
8394 undefined_reference (const char *reftype, const char *name)
8395 {
8396   /* xgettext:c-format */
8397   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
8398                       reftype, name);
8399 }
8400
8401 static bfd_boolean
8402 eval_symbol (bfd_vma *result,
8403              const char **symp,
8404              bfd *input_bfd,
8405              struct elf_final_link_info *flinfo,
8406              bfd_vma dot,
8407              Elf_Internal_Sym *isymbuf,
8408              size_t locsymcount,
8409              int signed_p)
8410 {
8411   size_t len;
8412   size_t symlen;
8413   bfd_vma a;
8414   bfd_vma b;
8415   char symbuf[4096];
8416   const char *sym = *symp;
8417   const char *symend;
8418   bfd_boolean symbol_is_section = FALSE;
8419
8420   len = strlen (sym);
8421   symend = sym + len;
8422
8423   if (len < 1 || len > sizeof (symbuf))
8424     {
8425       bfd_set_error (bfd_error_invalid_operation);
8426       return FALSE;
8427     }
8428
8429   switch (* sym)
8430     {
8431     case '.':
8432       *result = dot;
8433       *symp = sym + 1;
8434       return TRUE;
8435
8436     case '#':
8437       ++sym;
8438       *result = strtoul (sym, (char **) symp, 16);
8439       return TRUE;
8440
8441     case 'S':
8442       symbol_is_section = TRUE;
8443       /* Fall through.  */
8444     case 's':
8445       ++sym;
8446       symlen = strtol (sym, (char **) symp, 10);
8447       sym = *symp + 1; /* Skip the trailing ':'.  */
8448
8449       if (symend < sym || symlen + 1 > sizeof (symbuf))
8450         {
8451           bfd_set_error (bfd_error_invalid_operation);
8452           return FALSE;
8453         }
8454
8455       memcpy (symbuf, sym, symlen);
8456       symbuf[symlen] = '\0';
8457       *symp = sym + symlen;
8458
8459       /* Is it always possible, with complex symbols, that gas "mis-guessed"
8460          the symbol as a section, or vice-versa. so we're pretty liberal in our
8461          interpretation here; section means "try section first", not "must be a
8462          section", and likewise with symbol.  */
8463
8464       if (symbol_is_section)
8465         {
8466           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result, input_bfd)
8467               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
8468                                   isymbuf, locsymcount))
8469             {
8470               undefined_reference ("section", symbuf);
8471               return FALSE;
8472             }
8473         }
8474       else
8475         {
8476           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
8477                                isymbuf, locsymcount)
8478               && !resolve_section (symbuf, flinfo->output_bfd->sections,
8479                                    result, input_bfd))
8480             {
8481               undefined_reference ("symbol", symbuf);
8482               return FALSE;
8483             }
8484         }
8485
8486       return TRUE;
8487
8488       /* All that remains are operators.  */
8489
8490 #define UNARY_OP(op)                                            \
8491   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8492     {                                                           \
8493       sym += strlen (#op);                                      \
8494       if (*sym == ':')                                          \
8495         ++sym;                                                  \
8496       *symp = sym;                                              \
8497       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8498                         isymbuf, locsymcount, signed_p))        \
8499         return FALSE;                                           \
8500       if (signed_p)                                             \
8501         *result = op ((bfd_signed_vma) a);                      \
8502       else                                                      \
8503         *result = op a;                                         \
8504       return TRUE;                                              \
8505     }
8506
8507 #define BINARY_OP(op)                                           \
8508   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8509     {                                                           \
8510       sym += strlen (#op);                                      \
8511       if (*sym == ':')                                          \
8512         ++sym;                                                  \
8513       *symp = sym;                                              \
8514       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8515                         isymbuf, locsymcount, signed_p))        \
8516         return FALSE;                                           \
8517       ++*symp;                                                  \
8518       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
8519                         isymbuf, locsymcount, signed_p))        \
8520         return FALSE;                                           \
8521       if (signed_p)                                             \
8522         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
8523       else                                                      \
8524         *result = a op b;                                       \
8525       return TRUE;                                              \
8526     }
8527
8528     default:
8529       UNARY_OP  (0-);
8530       BINARY_OP (<<);
8531       BINARY_OP (>>);
8532       BINARY_OP (==);
8533       BINARY_OP (!=);
8534       BINARY_OP (<=);
8535       BINARY_OP (>=);
8536       BINARY_OP (&&);
8537       BINARY_OP (||);
8538       UNARY_OP  (~);
8539       UNARY_OP  (!);
8540       BINARY_OP (*);
8541       BINARY_OP (/);
8542       BINARY_OP (%);
8543       BINARY_OP (^);
8544       BINARY_OP (|);
8545       BINARY_OP (&);
8546       BINARY_OP (+);
8547       BINARY_OP (-);
8548       BINARY_OP (<);
8549       BINARY_OP (>);
8550 #undef UNARY_OP
8551 #undef BINARY_OP
8552       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
8553       bfd_set_error (bfd_error_invalid_operation);
8554       return FALSE;
8555     }
8556 }
8557
8558 static void
8559 put_value (bfd_vma size,
8560            unsigned long chunksz,
8561            bfd *input_bfd,
8562            bfd_vma x,
8563            bfd_byte *location)
8564 {
8565   location += (size - chunksz);
8566
8567   for (; size; size -= chunksz, location -= chunksz)
8568     {
8569       switch (chunksz)
8570         {
8571         case 1:
8572           bfd_put_8 (input_bfd, x, location);
8573           x >>= 8;
8574           break;
8575         case 2:
8576           bfd_put_16 (input_bfd, x, location);
8577           x >>= 16;
8578           break;
8579         case 4:
8580           bfd_put_32 (input_bfd, x, location);
8581           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
8582           x >>= 16;
8583           x >>= 16;
8584           break;
8585 #ifdef BFD64
8586         case 8:
8587           bfd_put_64 (input_bfd, x, location);
8588           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
8589           x >>= 32;
8590           x >>= 32;
8591           break;
8592 #endif
8593         default:
8594           abort ();
8595           break;
8596         }
8597     }
8598 }
8599
8600 static bfd_vma
8601 get_value (bfd_vma size,
8602            unsigned long chunksz,
8603            bfd *input_bfd,
8604            bfd_byte *location)
8605 {
8606   int shift;
8607   bfd_vma x = 0;
8608
8609   /* Sanity checks.  */
8610   BFD_ASSERT (chunksz <= sizeof (x)
8611               && size >= chunksz
8612               && chunksz != 0
8613               && (size % chunksz) == 0
8614               && input_bfd != NULL
8615               && location != NULL);
8616
8617   if (chunksz == sizeof (x))
8618     {
8619       BFD_ASSERT (size == chunksz);
8620
8621       /* Make sure that we do not perform an undefined shift operation.
8622          We know that size == chunksz so there will only be one iteration
8623          of the loop below.  */
8624       shift = 0;
8625     }
8626   else
8627     shift = 8 * chunksz;
8628
8629   for (; size; size -= chunksz, location += chunksz)
8630     {
8631       switch (chunksz)
8632         {
8633         case 1:
8634           x = (x << shift) | bfd_get_8 (input_bfd, location);
8635           break;
8636         case 2:
8637           x = (x << shift) | bfd_get_16 (input_bfd, location);
8638           break;
8639         case 4:
8640           x = (x << shift) | bfd_get_32 (input_bfd, location);
8641           break;
8642 #ifdef BFD64
8643         case 8:
8644           x = (x << shift) | bfd_get_64 (input_bfd, location);
8645           break;
8646 #endif
8647         default:
8648           abort ();
8649         }
8650     }
8651   return x;
8652 }
8653
8654 static void
8655 decode_complex_addend (unsigned long *start,   /* in bits */
8656                        unsigned long *oplen,   /* in bits */
8657                        unsigned long *len,     /* in bits */
8658                        unsigned long *wordsz,  /* in bytes */
8659                        unsigned long *chunksz, /* in bytes */
8660                        unsigned long *lsb0_p,
8661                        unsigned long *signed_p,
8662                        unsigned long *trunc_p,
8663                        unsigned long encoded)
8664 {
8665   * start     =  encoded        & 0x3F;
8666   * len       = (encoded >>  6) & 0x3F;
8667   * oplen     = (encoded >> 12) & 0x3F;
8668   * wordsz    = (encoded >> 18) & 0xF;
8669   * chunksz   = (encoded >> 22) & 0xF;
8670   * lsb0_p    = (encoded >> 27) & 1;
8671   * signed_p  = (encoded >> 28) & 1;
8672   * trunc_p   = (encoded >> 29) & 1;
8673 }
8674
8675 bfd_reloc_status_type
8676 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8677                                     asection *input_section ATTRIBUTE_UNUSED,
8678                                     bfd_byte *contents,
8679                                     Elf_Internal_Rela *rel,
8680                                     bfd_vma relocation)
8681 {
8682   bfd_vma shift, x, mask;
8683   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8684   bfd_reloc_status_type r;
8685
8686   /*  Perform this reloc, since it is complex.
8687       (this is not to say that it necessarily refers to a complex
8688       symbol; merely that it is a self-describing CGEN based reloc.
8689       i.e. the addend has the complete reloc information (bit start, end,
8690       word size, etc) encoded within it.).  */
8691
8692   decode_complex_addend (&start, &oplen, &len, &wordsz,
8693                          &chunksz, &lsb0_p, &signed_p,
8694                          &trunc_p, rel->r_addend);
8695
8696   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8697
8698   if (lsb0_p)
8699     shift = (start + 1) - len;
8700   else
8701     shift = (8 * wordsz) - (start + len);
8702
8703   x = get_value (wordsz, chunksz, input_bfd,
8704                  contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8705
8706 #ifdef DEBUG
8707   printf ("Doing complex reloc: "
8708           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8709           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8710           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8711           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8712           oplen, (unsigned long) x, (unsigned long) mask,
8713           (unsigned long) relocation);
8714 #endif
8715
8716   r = bfd_reloc_ok;
8717   if (! trunc_p)
8718     /* Now do an overflow check.  */
8719     r = bfd_check_overflow ((signed_p
8720                              ? complain_overflow_signed
8721                              : complain_overflow_unsigned),
8722                             len, 0, (8 * wordsz),
8723                             relocation);
8724
8725   /* Do the deed.  */
8726   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8727
8728 #ifdef DEBUG
8729   printf ("           relocation: %8.8lx\n"
8730           "         shifted mask: %8.8lx\n"
8731           " shifted/masked reloc: %8.8lx\n"
8732           "               result: %8.8lx\n",
8733           (unsigned long) relocation, (unsigned long) (mask << shift),
8734           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8735 #endif
8736   put_value (wordsz, chunksz, input_bfd, x,
8737              contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8738   return r;
8739 }
8740
8741 /* Functions to read r_offset from external (target order) reloc
8742    entry.  Faster than bfd_getl32 et al, because we let the compiler
8743    know the value is aligned.  */
8744
8745 static bfd_vma
8746 ext32l_r_offset (const void *p)
8747 {
8748   union aligned32
8749   {
8750     uint32_t v;
8751     unsigned char c[4];
8752   };
8753   const union aligned32 *a
8754     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8755
8756   uint32_t aval = (  (uint32_t) a->c[0]
8757                    | (uint32_t) a->c[1] << 8
8758                    | (uint32_t) a->c[2] << 16
8759                    | (uint32_t) a->c[3] << 24);
8760   return aval;
8761 }
8762
8763 static bfd_vma
8764 ext32b_r_offset (const void *p)
8765 {
8766   union aligned32
8767   {
8768     uint32_t v;
8769     unsigned char c[4];
8770   };
8771   const union aligned32 *a
8772     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8773
8774   uint32_t aval = (  (uint32_t) a->c[0] << 24
8775                    | (uint32_t) a->c[1] << 16
8776                    | (uint32_t) a->c[2] << 8
8777                    | (uint32_t) a->c[3]);
8778   return aval;
8779 }
8780
8781 #ifdef BFD_HOST_64_BIT
8782 static bfd_vma
8783 ext64l_r_offset (const void *p)
8784 {
8785   union aligned64
8786   {
8787     uint64_t v;
8788     unsigned char c[8];
8789   };
8790   const union aligned64 *a
8791     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8792
8793   uint64_t aval = (  (uint64_t) a->c[0]
8794                    | (uint64_t) a->c[1] << 8
8795                    | (uint64_t) a->c[2] << 16
8796                    | (uint64_t) a->c[3] << 24
8797                    | (uint64_t) a->c[4] << 32
8798                    | (uint64_t) a->c[5] << 40
8799                    | (uint64_t) a->c[6] << 48
8800                    | (uint64_t) a->c[7] << 56);
8801   return aval;
8802 }
8803
8804 static bfd_vma
8805 ext64b_r_offset (const void *p)
8806 {
8807   union aligned64
8808   {
8809     uint64_t v;
8810     unsigned char c[8];
8811   };
8812   const union aligned64 *a
8813     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8814
8815   uint64_t aval = (  (uint64_t) a->c[0] << 56
8816                    | (uint64_t) a->c[1] << 48
8817                    | (uint64_t) a->c[2] << 40
8818                    | (uint64_t) a->c[3] << 32
8819                    | (uint64_t) a->c[4] << 24
8820                    | (uint64_t) a->c[5] << 16
8821                    | (uint64_t) a->c[6] << 8
8822                    | (uint64_t) a->c[7]);
8823   return aval;
8824 }
8825 #endif
8826
8827 /* When performing a relocatable link, the input relocations are
8828    preserved.  But, if they reference global symbols, the indices
8829    referenced must be updated.  Update all the relocations found in
8830    RELDATA.  */
8831
8832 static bfd_boolean
8833 elf_link_adjust_relocs (bfd *abfd,
8834                         asection *sec,
8835                         struct bfd_elf_section_reloc_data *reldata,
8836                         bfd_boolean sort,
8837                         struct bfd_link_info *info)
8838 {
8839   unsigned int i;
8840   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8841   bfd_byte *erela;
8842   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8843   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8844   bfd_vma r_type_mask;
8845   int r_sym_shift;
8846   unsigned int count = reldata->count;
8847   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8848
8849   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8850     {
8851       swap_in = bed->s->swap_reloc_in;
8852       swap_out = bed->s->swap_reloc_out;
8853     }
8854   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8855     {
8856       swap_in = bed->s->swap_reloca_in;
8857       swap_out = bed->s->swap_reloca_out;
8858     }
8859   else
8860     abort ();
8861
8862   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8863     abort ();
8864
8865   if (bed->s->arch_size == 32)
8866     {
8867       r_type_mask = 0xff;
8868       r_sym_shift = 8;
8869     }
8870   else
8871     {
8872       r_type_mask = 0xffffffff;
8873       r_sym_shift = 32;
8874     }
8875
8876   erela = reldata->hdr->contents;
8877   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8878     {
8879       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8880       unsigned int j;
8881
8882       if (*rel_hash == NULL)
8883         continue;
8884
8885       if ((*rel_hash)->indx == -2
8886           && info->gc_sections
8887           && ! info->gc_keep_exported)
8888         {
8889           /* PR 21524: Let the user know if a symbol was removed by garbage collection.  */
8890           _bfd_error_handler (_("%pB:%pA: error: relocation references symbol %s which was removed by garbage collection"),
8891                               abfd, sec,
8892                               (*rel_hash)->root.root.string);
8893           _bfd_error_handler (_("%pB:%pA: error: try relinking with --gc-keep-exported enabled"),
8894                               abfd, sec);
8895           bfd_set_error (bfd_error_invalid_operation);
8896           return FALSE;
8897         }
8898       BFD_ASSERT ((*rel_hash)->indx >= 0);
8899
8900       (*swap_in) (abfd, erela, irela);
8901       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8902         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8903                            | (irela[j].r_info & r_type_mask));
8904       (*swap_out) (abfd, irela, erela);
8905     }
8906
8907   if (bed->elf_backend_update_relocs)
8908     (*bed->elf_backend_update_relocs) (sec, reldata);
8909
8910   if (sort && count != 0)
8911     {
8912       bfd_vma (*ext_r_off) (const void *);
8913       bfd_vma r_off;
8914       size_t elt_size;
8915       bfd_byte *base, *end, *p, *loc;
8916       bfd_byte *buf = NULL;
8917
8918       if (bed->s->arch_size == 32)
8919         {
8920           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8921             ext_r_off = ext32l_r_offset;
8922           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8923             ext_r_off = ext32b_r_offset;
8924           else
8925             abort ();
8926         }
8927       else
8928         {
8929 #ifdef BFD_HOST_64_BIT
8930           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8931             ext_r_off = ext64l_r_offset;
8932           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8933             ext_r_off = ext64b_r_offset;
8934           else
8935 #endif
8936             abort ();
8937         }
8938
8939       /*  Must use a stable sort here.  A modified insertion sort,
8940           since the relocs are mostly sorted already.  */
8941       elt_size = reldata->hdr->sh_entsize;
8942       base = reldata->hdr->contents;
8943       end = base + count * elt_size;
8944       if (elt_size > sizeof (Elf64_External_Rela))
8945         abort ();
8946
8947       /* Ensure the first element is lowest.  This acts as a sentinel,
8948          speeding the main loop below.  */
8949       r_off = (*ext_r_off) (base);
8950       for (p = loc = base; (p += elt_size) < end; )
8951         {
8952           bfd_vma r_off2 = (*ext_r_off) (p);
8953           if (r_off > r_off2)
8954             {
8955               r_off = r_off2;
8956               loc = p;
8957             }
8958         }
8959       if (loc != base)
8960         {
8961           /* Don't just swap *base and *loc as that changes the order
8962              of the original base[0] and base[1] if they happen to
8963              have the same r_offset.  */
8964           bfd_byte onebuf[sizeof (Elf64_External_Rela)];
8965           memcpy (onebuf, loc, elt_size);
8966           memmove (base + elt_size, base, loc - base);
8967           memcpy (base, onebuf, elt_size);
8968         }
8969
8970       for (p = base + elt_size; (p += elt_size) < end; )
8971         {
8972           /* base to p is sorted, *p is next to insert.  */
8973           r_off = (*ext_r_off) (p);
8974           /* Search the sorted region for location to insert.  */
8975           loc = p - elt_size;
8976           while (r_off < (*ext_r_off) (loc))
8977             loc -= elt_size;
8978           loc += elt_size;
8979           if (loc != p)
8980             {
8981               /* Chances are there is a run of relocs to insert here,
8982                  from one of more input files.  Files are not always
8983                  linked in order due to the way elf_link_input_bfd is
8984                  called.  See pr17666.  */
8985               size_t sortlen = p - loc;
8986               bfd_vma r_off2 = (*ext_r_off) (loc);
8987               size_t runlen = elt_size;
8988               size_t buf_size = 96 * 1024;
8989               while (p + runlen < end
8990                      && (sortlen <= buf_size
8991                          || runlen + elt_size <= buf_size)
8992                      && r_off2 > (*ext_r_off) (p + runlen))
8993                 runlen += elt_size;
8994               if (buf == NULL)
8995                 {
8996                   buf = bfd_malloc (buf_size);
8997                   if (buf == NULL)
8998                     return FALSE;
8999                 }
9000               if (runlen < sortlen)
9001                 {
9002                   memcpy (buf, p, runlen);
9003                   memmove (loc + runlen, loc, sortlen);
9004                   memcpy (loc, buf, runlen);
9005                 }
9006               else
9007                 {
9008                   memcpy (buf, loc, sortlen);
9009                   memmove (loc, p, runlen);
9010                   memcpy (loc + runlen, buf, sortlen);
9011                 }
9012               p += runlen - elt_size;
9013             }
9014         }
9015       /* Hashes are no longer valid.  */
9016       free (reldata->hashes);
9017       reldata->hashes = NULL;
9018       free (buf);
9019     }
9020   return TRUE;
9021 }
9022
9023 struct elf_link_sort_rela
9024 {
9025   union {
9026     bfd_vma offset;
9027     bfd_vma sym_mask;
9028   } u;
9029   enum elf_reloc_type_class type;
9030   /* We use this as an array of size int_rels_per_ext_rel.  */
9031   Elf_Internal_Rela rela[1];
9032 };
9033
9034 static int
9035 elf_link_sort_cmp1 (const void *A, const void *B)
9036 {
9037   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
9038   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
9039   int relativea, relativeb;
9040
9041   relativea = a->type == reloc_class_relative;
9042   relativeb = b->type == reloc_class_relative;
9043
9044   if (relativea < relativeb)
9045     return 1;
9046   if (relativea > relativeb)
9047     return -1;
9048   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
9049     return -1;
9050   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
9051     return 1;
9052   if (a->rela->r_offset < b->rela->r_offset)
9053     return -1;
9054   if (a->rela->r_offset > b->rela->r_offset)
9055     return 1;
9056   return 0;
9057 }
9058
9059 static int
9060 elf_link_sort_cmp2 (const void *A, const void *B)
9061 {
9062   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
9063   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
9064
9065   if (a->type < b->type)
9066     return -1;
9067   if (a->type > b->type)
9068     return 1;
9069   if (a->u.offset < b->u.offset)
9070     return -1;
9071   if (a->u.offset > b->u.offset)
9072     return 1;
9073   if (a->rela->r_offset < b->rela->r_offset)
9074     return -1;
9075   if (a->rela->r_offset > b->rela->r_offset)
9076     return 1;
9077   return 0;
9078 }
9079
9080 static size_t
9081 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
9082 {
9083   asection *dynamic_relocs;
9084   asection *rela_dyn;
9085   asection *rel_dyn;
9086   bfd_size_type count, size;
9087   size_t i, ret, sort_elt, ext_size;
9088   bfd_byte *sort, *s_non_relative, *p;
9089   struct elf_link_sort_rela *sq;
9090   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9091   int i2e = bed->s->int_rels_per_ext_rel;
9092   unsigned int opb = bfd_octets_per_byte (abfd);
9093   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
9094   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
9095   struct bfd_link_order *lo;
9096   bfd_vma r_sym_mask;
9097   bfd_boolean use_rela;
9098
9099   /* Find a dynamic reloc section.  */
9100   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
9101   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
9102   if (rela_dyn != NULL && rela_dyn->size > 0
9103       && rel_dyn != NULL && rel_dyn->size > 0)
9104     {
9105       bfd_boolean use_rela_initialised = FALSE;
9106
9107       /* This is just here to stop gcc from complaining.
9108          Its initialization checking code is not perfect.  */
9109       use_rela = TRUE;
9110
9111       /* Both sections are present.  Examine the sizes
9112          of the indirect sections to help us choose.  */
9113       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
9114         if (lo->type == bfd_indirect_link_order)
9115           {
9116             asection *o = lo->u.indirect.section;
9117
9118             if ((o->size % bed->s->sizeof_rela) == 0)
9119               {
9120                 if ((o->size % bed->s->sizeof_rel) == 0)
9121                   /* Section size is divisible by both rel and rela sizes.
9122                      It is of no help to us.  */
9123                   ;
9124                 else
9125                   {
9126                     /* Section size is only divisible by rela.  */
9127                     if (use_rela_initialised && !use_rela)
9128                       {
9129                         _bfd_error_handler (_("%pB: unable to sort relocs - "
9130                                               "they are in more than one size"),
9131                                             abfd);
9132                         bfd_set_error (bfd_error_invalid_operation);
9133                         return 0;
9134                       }
9135                     else
9136                       {
9137                         use_rela = TRUE;
9138                         use_rela_initialised = TRUE;
9139                       }
9140                   }
9141               }
9142             else if ((o->size % bed->s->sizeof_rel) == 0)
9143               {
9144                 /* Section size is only divisible by rel.  */
9145                 if (use_rela_initialised && use_rela)
9146                   {
9147                     _bfd_error_handler (_("%pB: unable to sort relocs - "
9148                                           "they are in more than one size"),
9149                                         abfd);
9150                     bfd_set_error (bfd_error_invalid_operation);
9151                     return 0;
9152                   }
9153                 else
9154                   {
9155                     use_rela = FALSE;
9156                     use_rela_initialised = TRUE;
9157                   }
9158               }
9159             else
9160               {
9161                 /* The section size is not divisible by either -
9162                    something is wrong.  */
9163                 _bfd_error_handler (_("%pB: unable to sort relocs - "
9164                                       "they are of an unknown size"), abfd);
9165                 bfd_set_error (bfd_error_invalid_operation);
9166                 return 0;
9167               }
9168           }
9169
9170       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
9171         if (lo->type == bfd_indirect_link_order)
9172           {
9173             asection *o = lo->u.indirect.section;
9174
9175             if ((o->size % bed->s->sizeof_rela) == 0)
9176               {
9177                 if ((o->size % bed->s->sizeof_rel) == 0)
9178                   /* Section size is divisible by both rel and rela sizes.
9179                      It is of no help to us.  */
9180                   ;
9181                 else
9182                   {
9183                     /* Section size is only divisible by rela.  */
9184                     if (use_rela_initialised && !use_rela)
9185                       {
9186                         _bfd_error_handler (_("%pB: unable to sort relocs - "
9187                                               "they are in more than one size"),
9188                                             abfd);
9189                         bfd_set_error (bfd_error_invalid_operation);
9190                         return 0;
9191                       }
9192                     else
9193                       {
9194                         use_rela = TRUE;
9195                         use_rela_initialised = TRUE;
9196                       }
9197                   }
9198               }
9199             else if ((o->size % bed->s->sizeof_rel) == 0)
9200               {
9201                 /* Section size is only divisible by rel.  */
9202                 if (use_rela_initialised && use_rela)
9203                   {
9204                     _bfd_error_handler (_("%pB: unable to sort relocs - "
9205                                           "they are in more than one size"),
9206                                         abfd);
9207                     bfd_set_error (bfd_error_invalid_operation);
9208                     return 0;
9209                   }
9210                 else
9211                   {
9212                     use_rela = FALSE;
9213                     use_rela_initialised = TRUE;
9214                   }
9215               }
9216             else
9217               {
9218                 /* The section size is not divisible by either -
9219                    something is wrong.  */
9220                 _bfd_error_handler (_("%pB: unable to sort relocs - "
9221                                       "they are of an unknown size"), abfd);
9222                 bfd_set_error (bfd_error_invalid_operation);
9223                 return 0;
9224               }
9225           }
9226
9227       if (! use_rela_initialised)
9228         /* Make a guess.  */
9229         use_rela = TRUE;
9230     }
9231   else if (rela_dyn != NULL && rela_dyn->size > 0)
9232     use_rela = TRUE;
9233   else if (rel_dyn != NULL && rel_dyn->size > 0)
9234     use_rela = FALSE;
9235   else
9236     return 0;
9237
9238   if (use_rela)
9239     {
9240       dynamic_relocs = rela_dyn;
9241       ext_size = bed->s->sizeof_rela;
9242       swap_in = bed->s->swap_reloca_in;
9243       swap_out = bed->s->swap_reloca_out;
9244     }
9245   else
9246     {
9247       dynamic_relocs = rel_dyn;
9248       ext_size = bed->s->sizeof_rel;
9249       swap_in = bed->s->swap_reloc_in;
9250       swap_out = bed->s->swap_reloc_out;
9251     }
9252
9253   size = 0;
9254   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9255     if (lo->type == bfd_indirect_link_order)
9256       size += lo->u.indirect.section->size;
9257
9258   if (size != dynamic_relocs->size)
9259     return 0;
9260
9261   sort_elt = (sizeof (struct elf_link_sort_rela)
9262               + (i2e - 1) * sizeof (Elf_Internal_Rela));
9263
9264   count = dynamic_relocs->size / ext_size;
9265   if (count == 0)
9266     return 0;
9267   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
9268
9269   if (sort == NULL)
9270     {
9271       (*info->callbacks->warning)
9272         (info, _("not enough memory to sort relocations"), 0, abfd, 0, 0);
9273       return 0;
9274     }
9275
9276   if (bed->s->arch_size == 32)
9277     r_sym_mask = ~(bfd_vma) 0xff;
9278   else
9279     r_sym_mask = ~(bfd_vma) 0xffffffff;
9280
9281   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9282     if (lo->type == bfd_indirect_link_order)
9283       {
9284         bfd_byte *erel, *erelend;
9285         asection *o = lo->u.indirect.section;
9286
9287         if (o->contents == NULL && o->size != 0)
9288           {
9289             /* This is a reloc section that is being handled as a normal
9290                section.  See bfd_section_from_shdr.  We can't combine
9291                relocs in this case.  */
9292             free (sort);
9293             return 0;
9294           }
9295         erel = o->contents;
9296         erelend = o->contents + o->size;
9297         p = sort + o->output_offset * opb / ext_size * sort_elt;
9298
9299         while (erel < erelend)
9300           {
9301             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9302
9303             (*swap_in) (abfd, erel, s->rela);
9304             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
9305             s->u.sym_mask = r_sym_mask;
9306             p += sort_elt;
9307             erel += ext_size;
9308           }
9309       }
9310
9311   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
9312
9313   for (i = 0, p = sort; i < count; i++, p += sort_elt)
9314     {
9315       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9316       if (s->type != reloc_class_relative)
9317         break;
9318     }
9319   ret = i;
9320   s_non_relative = p;
9321
9322   sq = (struct elf_link_sort_rela *) s_non_relative;
9323   for (; i < count; i++, p += sort_elt)
9324     {
9325       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
9326       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
9327         sq = sp;
9328       sp->u.offset = sq->rela->r_offset;
9329     }
9330
9331   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
9332
9333   struct elf_link_hash_table *htab = elf_hash_table (info);
9334   if (htab->srelplt && htab->srelplt->output_section == dynamic_relocs)
9335     {
9336       /* We have plt relocs in .rela.dyn.  */
9337       sq = (struct elf_link_sort_rela *) sort;
9338       for (i = 0; i < count; i++)
9339         if (sq[count - i - 1].type != reloc_class_plt)
9340           break;
9341       if (i != 0 && htab->srelplt->size == i * ext_size)
9342         {
9343           struct bfd_link_order **plo;
9344           /* Put srelplt link_order last.  This is so the output_offset
9345              set in the next loop is correct for DT_JMPREL.  */
9346           for (plo = &dynamic_relocs->map_head.link_order; *plo != NULL; )
9347             if ((*plo)->type == bfd_indirect_link_order
9348                 && (*plo)->u.indirect.section == htab->srelplt)
9349               {
9350                 lo = *plo;
9351                 *plo = lo->next;
9352               }
9353             else
9354               plo = &(*plo)->next;
9355           *plo = lo;
9356           lo->next = NULL;
9357           dynamic_relocs->map_tail.link_order = lo;
9358         }
9359     }
9360
9361   p = sort;
9362   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9363     if (lo->type == bfd_indirect_link_order)
9364       {
9365         bfd_byte *erel, *erelend;
9366         asection *o = lo->u.indirect.section;
9367
9368         erel = o->contents;
9369         erelend = o->contents + o->size;
9370         o->output_offset = (p - sort) / sort_elt * ext_size / opb;
9371         while (erel < erelend)
9372           {
9373             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9374             (*swap_out) (abfd, s->rela, erel);
9375             p += sort_elt;
9376             erel += ext_size;
9377           }
9378       }
9379
9380   free (sort);
9381   *psec = dynamic_relocs;
9382   return ret;
9383 }
9384
9385 /* Add a symbol to the output symbol string table.  */
9386
9387 static int
9388 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
9389                            const char *name,
9390                            Elf_Internal_Sym *elfsym,
9391                            asection *input_sec,
9392                            struct elf_link_hash_entry *h)
9393 {
9394   int (*output_symbol_hook)
9395     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
9396      struct elf_link_hash_entry *);
9397   struct elf_link_hash_table *hash_table;
9398   const struct elf_backend_data *bed;
9399   bfd_size_type strtabsize;
9400
9401   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9402
9403   bed = get_elf_backend_data (flinfo->output_bfd);
9404   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
9405   if (output_symbol_hook != NULL)
9406     {
9407       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
9408       if (ret != 1)
9409         return ret;
9410     }
9411
9412   if (ELF_ST_TYPE (elfsym->st_info) == STT_GNU_IFUNC)
9413     elf_tdata (flinfo->output_bfd)->has_gnu_osabi |= elf_gnu_osabi_ifunc;
9414   if (ELF_ST_BIND (elfsym->st_info) == STB_GNU_UNIQUE)
9415     elf_tdata (flinfo->output_bfd)->has_gnu_osabi |= elf_gnu_osabi_unique;
9416
9417   if (name == NULL
9418       || *name == '\0'
9419       || (input_sec->flags & SEC_EXCLUDE))
9420     elfsym->st_name = (unsigned long) -1;
9421   else
9422     {
9423       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
9424          to get the final offset for st_name.  */
9425       elfsym->st_name
9426         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
9427                                                name, FALSE);
9428       if (elfsym->st_name == (unsigned long) -1)
9429         return 0;
9430     }
9431
9432   hash_table = elf_hash_table (flinfo->info);
9433   strtabsize = hash_table->strtabsize;
9434   if (strtabsize <= hash_table->strtabcount)
9435     {
9436       strtabsize += strtabsize;
9437       hash_table->strtabsize = strtabsize;
9438       strtabsize *= sizeof (*hash_table->strtab);
9439       hash_table->strtab
9440         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
9441                                                  strtabsize);
9442       if (hash_table->strtab == NULL)
9443         return 0;
9444     }
9445   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
9446   hash_table->strtab[hash_table->strtabcount].dest_index
9447     = hash_table->strtabcount;
9448   hash_table->strtab[hash_table->strtabcount].destshndx_index
9449     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
9450
9451   bfd_get_symcount (flinfo->output_bfd) += 1;
9452   hash_table->strtabcount += 1;
9453
9454   return 1;
9455 }
9456
9457 /* Swap symbols out to the symbol table and flush the output symbols to
9458    the file.  */
9459
9460 static bfd_boolean
9461 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
9462 {
9463   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
9464   bfd_size_type amt;
9465   size_t i;
9466   const struct elf_backend_data *bed;
9467   bfd_byte *symbuf;
9468   Elf_Internal_Shdr *hdr;
9469   file_ptr pos;
9470   bfd_boolean ret;
9471
9472   if (!hash_table->strtabcount)
9473     return TRUE;
9474
9475   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9476
9477   bed = get_elf_backend_data (flinfo->output_bfd);
9478
9479   amt = bed->s->sizeof_sym * hash_table->strtabcount;
9480   symbuf = (bfd_byte *) bfd_malloc (amt);
9481   if (symbuf == NULL)
9482     return FALSE;
9483
9484   if (flinfo->symshndxbuf)
9485     {
9486       amt = sizeof (Elf_External_Sym_Shndx);
9487       amt *= bfd_get_symcount (flinfo->output_bfd);
9488       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
9489       if (flinfo->symshndxbuf == NULL)
9490         {
9491           free (symbuf);
9492           return FALSE;
9493         }
9494     }
9495
9496   for (i = 0; i < hash_table->strtabcount; i++)
9497     {
9498       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
9499       if (elfsym->sym.st_name == (unsigned long) -1)
9500         elfsym->sym.st_name = 0;
9501       else
9502         elfsym->sym.st_name
9503           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
9504                                                     elfsym->sym.st_name);
9505       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
9506                                ((bfd_byte *) symbuf
9507                                 + (elfsym->dest_index
9508                                    * bed->s->sizeof_sym)),
9509                                (flinfo->symshndxbuf
9510                                 + elfsym->destshndx_index));
9511     }
9512
9513   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
9514   pos = hdr->sh_offset + hdr->sh_size;
9515   amt = hash_table->strtabcount * bed->s->sizeof_sym;
9516   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
9517       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
9518     {
9519       hdr->sh_size += amt;
9520       ret = TRUE;
9521     }
9522   else
9523     ret = FALSE;
9524
9525   free (symbuf);
9526
9527   free (hash_table->strtab);
9528   hash_table->strtab = NULL;
9529
9530   return ret;
9531 }
9532
9533 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
9534
9535 static bfd_boolean
9536 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
9537 {
9538   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
9539       && sym->st_shndx < SHN_LORESERVE)
9540     {
9541       /* The gABI doesn't support dynamic symbols in output sections
9542          beyond 64k.  */
9543       _bfd_error_handler
9544         /* xgettext:c-format */
9545         (_("%pB: too many sections: %d (>= %d)"),
9546          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
9547       bfd_set_error (bfd_error_nonrepresentable_section);
9548       return FALSE;
9549     }
9550   return TRUE;
9551 }
9552
9553 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
9554    allowing an unsatisfied unversioned symbol in the DSO to match a
9555    versioned symbol that would normally require an explicit version.
9556    We also handle the case that a DSO references a hidden symbol
9557    which may be satisfied by a versioned symbol in another DSO.  */
9558
9559 static bfd_boolean
9560 elf_link_check_versioned_symbol (struct bfd_link_info *info,
9561                                  const struct elf_backend_data *bed,
9562                                  struct elf_link_hash_entry *h)
9563 {
9564   bfd *abfd;
9565   struct elf_link_loaded_list *loaded;
9566
9567   if (!is_elf_hash_table (info->hash))
9568     return FALSE;
9569
9570   /* Check indirect symbol.  */
9571   while (h->root.type == bfd_link_hash_indirect)
9572     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9573
9574   switch (h->root.type)
9575     {
9576     default:
9577       abfd = NULL;
9578       break;
9579
9580     case bfd_link_hash_undefined:
9581     case bfd_link_hash_undefweak:
9582       abfd = h->root.u.undef.abfd;
9583       if (abfd == NULL
9584           || (abfd->flags & DYNAMIC) == 0
9585           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
9586         return FALSE;
9587       break;
9588
9589     case bfd_link_hash_defined:
9590     case bfd_link_hash_defweak:
9591       abfd = h->root.u.def.section->owner;
9592       break;
9593
9594     case bfd_link_hash_common:
9595       abfd = h->root.u.c.p->section->owner;
9596       break;
9597     }
9598   BFD_ASSERT (abfd != NULL);
9599
9600   for (loaded = elf_hash_table (info)->loaded;
9601        loaded != NULL;
9602        loaded = loaded->next)
9603     {
9604       bfd *input;
9605       Elf_Internal_Shdr *hdr;
9606       size_t symcount;
9607       size_t extsymcount;
9608       size_t extsymoff;
9609       Elf_Internal_Shdr *versymhdr;
9610       Elf_Internal_Sym *isym;
9611       Elf_Internal_Sym *isymend;
9612       Elf_Internal_Sym *isymbuf;
9613       Elf_External_Versym *ever;
9614       Elf_External_Versym *extversym;
9615
9616       input = loaded->abfd;
9617
9618       /* We check each DSO for a possible hidden versioned definition.  */
9619       if (input == abfd
9620           || (input->flags & DYNAMIC) == 0
9621           || elf_dynversym (input) == 0)
9622         continue;
9623
9624       hdr = &elf_tdata (input)->dynsymtab_hdr;
9625
9626       symcount = hdr->sh_size / bed->s->sizeof_sym;
9627       if (elf_bad_symtab (input))
9628         {
9629           extsymcount = symcount;
9630           extsymoff = 0;
9631         }
9632       else
9633         {
9634           extsymcount = symcount - hdr->sh_info;
9635           extsymoff = hdr->sh_info;
9636         }
9637
9638       if (extsymcount == 0)
9639         continue;
9640
9641       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
9642                                       NULL, NULL, NULL);
9643       if (isymbuf == NULL)
9644         return FALSE;
9645
9646       /* Read in any version definitions.  */
9647       versymhdr = &elf_tdata (input)->dynversym_hdr;
9648       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
9649       if (extversym == NULL)
9650         goto error_ret;
9651
9652       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
9653           || (bfd_bread (extversym, versymhdr->sh_size, input)
9654               != versymhdr->sh_size))
9655         {
9656           free (extversym);
9657         error_ret:
9658           free (isymbuf);
9659           return FALSE;
9660         }
9661
9662       ever = extversym + extsymoff;
9663       isymend = isymbuf + extsymcount;
9664       for (isym = isymbuf; isym < isymend; isym++, ever++)
9665         {
9666           const char *name;
9667           Elf_Internal_Versym iver;
9668           unsigned short version_index;
9669
9670           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
9671               || isym->st_shndx == SHN_UNDEF)
9672             continue;
9673
9674           name = bfd_elf_string_from_elf_section (input,
9675                                                   hdr->sh_link,
9676                                                   isym->st_name);
9677           if (strcmp (name, h->root.root.string) != 0)
9678             continue;
9679
9680           _bfd_elf_swap_versym_in (input, ever, &iver);
9681
9682           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
9683               && !(h->def_regular
9684                    && h->forced_local))
9685             {
9686               /* If we have a non-hidden versioned sym, then it should
9687                  have provided a definition for the undefined sym unless
9688                  it is defined in a non-shared object and forced local.
9689                */
9690               abort ();
9691             }
9692
9693           version_index = iver.vs_vers & VERSYM_VERSION;
9694           if (version_index == 1 || version_index == 2)
9695             {
9696               /* This is the base or first version.  We can use it.  */
9697               free (extversym);
9698               free (isymbuf);
9699               return TRUE;
9700             }
9701         }
9702
9703       free (extversym);
9704       free (isymbuf);
9705     }
9706
9707   return FALSE;
9708 }
9709
9710 /* Convert ELF common symbol TYPE.  */
9711
9712 static int
9713 elf_link_convert_common_type (struct bfd_link_info *info, int type)
9714 {
9715   /* Commom symbol can only appear in relocatable link.  */
9716   if (!bfd_link_relocatable (info))
9717     abort ();
9718   switch (info->elf_stt_common)
9719     {
9720     case unchanged:
9721       break;
9722     case elf_stt_common:
9723       type = STT_COMMON;
9724       break;
9725     case no_elf_stt_common:
9726       type = STT_OBJECT;
9727       break;
9728     }
9729   return type;
9730 }
9731
9732 /* Add an external symbol to the symbol table.  This is called from
9733    the hash table traversal routine.  When generating a shared object,
9734    we go through the symbol table twice.  The first time we output
9735    anything that might have been forced to local scope in a version
9736    script.  The second time we output the symbols that are still
9737    global symbols.  */
9738
9739 static bfd_boolean
9740 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
9741 {
9742   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
9743   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
9744   struct elf_final_link_info *flinfo = eoinfo->flinfo;
9745   bfd_boolean strip;
9746   Elf_Internal_Sym sym;
9747   asection *input_sec;
9748   const struct elf_backend_data *bed;
9749   long indx;
9750   int ret;
9751   unsigned int type;
9752
9753   if (h->root.type == bfd_link_hash_warning)
9754     {
9755       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9756       if (h->root.type == bfd_link_hash_new)
9757         return TRUE;
9758     }
9759
9760   /* Decide whether to output this symbol in this pass.  */
9761   if (eoinfo->localsyms)
9762     {
9763       if (!h->forced_local)
9764         return TRUE;
9765     }
9766   else
9767     {
9768       if (h->forced_local)
9769         return TRUE;
9770     }
9771
9772   bed = get_elf_backend_data (flinfo->output_bfd);
9773
9774   if (h->root.type == bfd_link_hash_undefined)
9775     {
9776       /* If we have an undefined symbol reference here then it must have
9777          come from a shared library that is being linked in.  (Undefined
9778          references in regular files have already been handled unless
9779          they are in unreferenced sections which are removed by garbage
9780          collection).  */
9781       bfd_boolean ignore_undef = FALSE;
9782
9783       /* Some symbols may be special in that the fact that they're
9784          undefined can be safely ignored - let backend determine that.  */
9785       if (bed->elf_backend_ignore_undef_symbol)
9786         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9787
9788       /* If we are reporting errors for this situation then do so now.  */
9789       if (!ignore_undef
9790           && h->ref_dynamic_nonweak
9791           && (!h->ref_regular || flinfo->info->gc_sections)
9792           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9793           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9794         (*flinfo->info->callbacks->undefined_symbol)
9795           (flinfo->info, h->root.root.string,
9796            h->ref_regular ? NULL : h->root.u.undef.abfd,
9797            NULL, 0,
9798            flinfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR);
9799
9800       /* Strip a global symbol defined in a discarded section.  */
9801       if (h->indx == -3)
9802         return TRUE;
9803     }
9804
9805   /* We should also warn if a forced local symbol is referenced from
9806      shared libraries.  */
9807   if (bfd_link_executable (flinfo->info)
9808       && h->forced_local
9809       && h->ref_dynamic
9810       && h->def_regular
9811       && !h->dynamic_def
9812       && h->ref_dynamic_nonweak
9813       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9814     {
9815       bfd *def_bfd;
9816       const char *msg;
9817       struct elf_link_hash_entry *hi = h;
9818
9819       /* Check indirect symbol.  */
9820       while (hi->root.type == bfd_link_hash_indirect)
9821         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9822
9823       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9824         /* xgettext:c-format */
9825         msg = _("%pB: internal symbol `%s' in %pB is referenced by DSO");
9826       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9827         /* xgettext:c-format */
9828         msg = _("%pB: hidden symbol `%s' in %pB is referenced by DSO");
9829       else
9830         /* xgettext:c-format */
9831         msg = _("%pB: local symbol `%s' in %pB is referenced by DSO");
9832       def_bfd = flinfo->output_bfd;
9833       if (hi->root.u.def.section != bfd_abs_section_ptr)
9834         def_bfd = hi->root.u.def.section->owner;
9835       _bfd_error_handler (msg, flinfo->output_bfd,
9836                           h->root.root.string, def_bfd);
9837       bfd_set_error (bfd_error_bad_value);
9838       eoinfo->failed = TRUE;
9839       return FALSE;
9840     }
9841
9842   /* We don't want to output symbols that have never been mentioned by
9843      a regular file, or that we have been told to strip.  However, if
9844      h->indx is set to -2, the symbol is used by a reloc and we must
9845      output it.  */
9846   strip = FALSE;
9847   if (h->indx == -2)
9848     ;
9849   else if ((h->def_dynamic
9850             || h->ref_dynamic
9851             || h->root.type == bfd_link_hash_new)
9852            && !h->def_regular
9853            && !h->ref_regular)
9854     strip = TRUE;
9855   else if (flinfo->info->strip == strip_all)
9856     strip = TRUE;
9857   else if (flinfo->info->strip == strip_some
9858            && bfd_hash_lookup (flinfo->info->keep_hash,
9859                                h->root.root.string, FALSE, FALSE) == NULL)
9860     strip = TRUE;
9861   else if ((h->root.type == bfd_link_hash_defined
9862             || h->root.type == bfd_link_hash_defweak)
9863            && ((flinfo->info->strip_discarded
9864                 && discarded_section (h->root.u.def.section))
9865                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9866                    && h->root.u.def.section->owner != NULL
9867                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9868     strip = TRUE;
9869   else if ((h->root.type == bfd_link_hash_undefined
9870             || h->root.type == bfd_link_hash_undefweak)
9871            && h->root.u.undef.abfd != NULL
9872            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9873     strip = TRUE;
9874
9875   type = h->type;
9876
9877   /* If we're stripping it, and it's not a dynamic symbol, there's
9878      nothing else to do.   However, if it is a forced local symbol or
9879      an ifunc symbol we need to give the backend finish_dynamic_symbol
9880      function a chance to make it dynamic.  */
9881   if (strip
9882       && h->dynindx == -1
9883       && type != STT_GNU_IFUNC
9884       && !h->forced_local)
9885     return TRUE;
9886
9887   sym.st_value = 0;
9888   sym.st_size = h->size;
9889   sym.st_other = h->other;
9890   switch (h->root.type)
9891     {
9892     default:
9893     case bfd_link_hash_new:
9894     case bfd_link_hash_warning:
9895       abort ();
9896       return FALSE;
9897
9898     case bfd_link_hash_undefined:
9899     case bfd_link_hash_undefweak:
9900       input_sec = bfd_und_section_ptr;
9901       sym.st_shndx = SHN_UNDEF;
9902       break;
9903
9904     case bfd_link_hash_defined:
9905     case bfd_link_hash_defweak:
9906       {
9907         input_sec = h->root.u.def.section;
9908         if (input_sec->output_section != NULL)
9909           {
9910             sym.st_shndx =
9911               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9912                                                  input_sec->output_section);
9913             if (sym.st_shndx == SHN_BAD)
9914               {
9915                 _bfd_error_handler
9916                   /* xgettext:c-format */
9917                   (_("%pB: could not find output section %pA for input section %pA"),
9918                    flinfo->output_bfd, input_sec->output_section, input_sec);
9919                 bfd_set_error (bfd_error_nonrepresentable_section);
9920                 eoinfo->failed = TRUE;
9921                 return FALSE;
9922               }
9923
9924             /* ELF symbols in relocatable files are section relative,
9925                but in nonrelocatable files they are virtual
9926                addresses.  */
9927             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9928             if (!bfd_link_relocatable (flinfo->info))
9929               {
9930                 sym.st_value += input_sec->output_section->vma;
9931                 if (h->type == STT_TLS)
9932                   {
9933                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9934                     if (tls_sec != NULL)
9935                       sym.st_value -= tls_sec->vma;
9936                   }
9937               }
9938           }
9939         else
9940           {
9941             BFD_ASSERT (input_sec->owner == NULL
9942                         || (input_sec->owner->flags & DYNAMIC) != 0);
9943             sym.st_shndx = SHN_UNDEF;
9944             input_sec = bfd_und_section_ptr;
9945           }
9946       }
9947       break;
9948
9949     case bfd_link_hash_common:
9950       input_sec = h->root.u.c.p->section;
9951       sym.st_shndx = bed->common_section_index (input_sec);
9952       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9953       break;
9954
9955     case bfd_link_hash_indirect:
9956       /* These symbols are created by symbol versioning.  They point
9957          to the decorated version of the name.  For example, if the
9958          symbol foo@@GNU_1.2 is the default, which should be used when
9959          foo is used with no version, then we add an indirect symbol
9960          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9961          since the indirected symbol is already in the hash table.  */
9962       return TRUE;
9963     }
9964
9965   if (type == STT_COMMON || type == STT_OBJECT)
9966     switch (h->root.type)
9967       {
9968       case bfd_link_hash_common:
9969         type = elf_link_convert_common_type (flinfo->info, type);
9970         break;
9971       case bfd_link_hash_defined:
9972       case bfd_link_hash_defweak:
9973         if (bed->common_definition (&sym))
9974           type = elf_link_convert_common_type (flinfo->info, type);
9975         else
9976           type = STT_OBJECT;
9977         break;
9978       case bfd_link_hash_undefined:
9979       case bfd_link_hash_undefweak:
9980         break;
9981       default:
9982         abort ();
9983       }
9984
9985   if (h->forced_local)
9986     {
9987       sym.st_info = ELF_ST_INFO (STB_LOCAL, type);
9988       /* Turn off visibility on local symbol.  */
9989       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9990     }
9991   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9992   else if (h->unique_global && h->def_regular)
9993     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, type);
9994   else if (h->root.type == bfd_link_hash_undefweak
9995            || h->root.type == bfd_link_hash_defweak)
9996     sym.st_info = ELF_ST_INFO (STB_WEAK, type);
9997   else
9998     sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9999   sym.st_target_internal = h->target_internal;
10000
10001   /* Give the processor backend a chance to tweak the symbol value,
10002      and also to finish up anything that needs to be done for this
10003      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
10004      forced local syms when non-shared is due to a historical quirk.
10005      STT_GNU_IFUNC symbol must go through PLT.  */
10006   if ((h->type == STT_GNU_IFUNC
10007        && h->def_regular
10008        && !bfd_link_relocatable (flinfo->info))
10009       || ((h->dynindx != -1
10010            || h->forced_local)
10011           && ((bfd_link_pic (flinfo->info)
10012                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
10013                    || h->root.type != bfd_link_hash_undefweak))
10014               || !h->forced_local)
10015           && elf_hash_table (flinfo->info)->dynamic_sections_created))
10016     {
10017       if (! ((*bed->elf_backend_finish_dynamic_symbol)
10018              (flinfo->output_bfd, flinfo->info, h, &sym)))
10019         {
10020           eoinfo->failed = TRUE;
10021           return FALSE;
10022         }
10023     }
10024
10025   /* If we are marking the symbol as undefined, and there are no
10026      non-weak references to this symbol from a regular object, then
10027      mark the symbol as weak undefined; if there are non-weak
10028      references, mark the symbol as strong.  We can't do this earlier,
10029      because it might not be marked as undefined until the
10030      finish_dynamic_symbol routine gets through with it.  */
10031   if (sym.st_shndx == SHN_UNDEF
10032       && h->ref_regular
10033       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
10034           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
10035     {
10036       int bindtype;
10037       type = ELF_ST_TYPE (sym.st_info);
10038
10039       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
10040       if (type == STT_GNU_IFUNC)
10041         type = STT_FUNC;
10042
10043       if (h->ref_regular_nonweak)
10044         bindtype = STB_GLOBAL;
10045       else
10046         bindtype = STB_WEAK;
10047       sym.st_info = ELF_ST_INFO (bindtype, type);
10048     }
10049
10050   /* If this is a symbol defined in a dynamic library, don't use the
10051      symbol size from the dynamic library.  Relinking an executable
10052      against a new library may introduce gratuitous changes in the
10053      executable's symbols if we keep the size.  */
10054   if (sym.st_shndx == SHN_UNDEF
10055       && !h->def_regular
10056       && h->def_dynamic)
10057     sym.st_size = 0;
10058
10059   /* If a non-weak symbol with non-default visibility is not defined
10060      locally, it is a fatal error.  */
10061   if (!bfd_link_relocatable (flinfo->info)
10062       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
10063       && ELF_ST_BIND (sym.st_info) != STB_WEAK
10064       && h->root.type == bfd_link_hash_undefined
10065       && !h->def_regular)
10066     {
10067       const char *msg;
10068
10069       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
10070         /* xgettext:c-format */
10071         msg = _("%pB: protected symbol `%s' isn't defined");
10072       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
10073         /* xgettext:c-format */
10074         msg = _("%pB: internal symbol `%s' isn't defined");
10075       else
10076         /* xgettext:c-format */
10077         msg = _("%pB: hidden symbol `%s' isn't defined");
10078       _bfd_error_handler (msg, flinfo->output_bfd, h->root.root.string);
10079       bfd_set_error (bfd_error_bad_value);
10080       eoinfo->failed = TRUE;
10081       return FALSE;
10082     }
10083
10084   /* If this symbol should be put in the .dynsym section, then put it
10085      there now.  We already know the symbol index.  We also fill in
10086      the entry in the .hash section.  */
10087   if (h->dynindx != -1
10088       && elf_hash_table (flinfo->info)->dynamic_sections_created
10089       && elf_hash_table (flinfo->info)->dynsym != NULL
10090       && !discarded_section (elf_hash_table (flinfo->info)->dynsym))
10091     {
10092       bfd_byte *esym;
10093
10094       /* Since there is no version information in the dynamic string,
10095          if there is no version info in symbol version section, we will
10096          have a run-time problem if not linking executable, referenced
10097          by shared library, or not bound locally.  */
10098       if (h->verinfo.verdef == NULL
10099           && (!bfd_link_executable (flinfo->info)
10100               || h->ref_dynamic
10101               || !h->def_regular))
10102         {
10103           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
10104
10105           if (p && p [1] != '\0')
10106             {
10107               _bfd_error_handler
10108                 /* xgettext:c-format */
10109                 (_("%pB: no symbol version section for versioned symbol `%s'"),
10110                  flinfo->output_bfd, h->root.root.string);
10111               eoinfo->failed = TRUE;
10112               return FALSE;
10113             }
10114         }
10115
10116       sym.st_name = h->dynstr_index;
10117       esym = (elf_hash_table (flinfo->info)->dynsym->contents
10118               + h->dynindx * bed->s->sizeof_sym);
10119       if (!check_dynsym (flinfo->output_bfd, &sym))
10120         {
10121           eoinfo->failed = TRUE;
10122           return FALSE;
10123         }
10124       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
10125
10126       if (flinfo->hash_sec != NULL)
10127         {
10128           size_t hash_entry_size;
10129           bfd_byte *bucketpos;
10130           bfd_vma chain;
10131           size_t bucketcount;
10132           size_t bucket;
10133
10134           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
10135           bucket = h->u.elf_hash_value % bucketcount;
10136
10137           hash_entry_size
10138             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
10139           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
10140                        + (bucket + 2) * hash_entry_size);
10141           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
10142           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
10143                    bucketpos);
10144           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
10145                    ((bfd_byte *) flinfo->hash_sec->contents
10146                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
10147         }
10148
10149       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
10150         {
10151           Elf_Internal_Versym iversym;
10152           Elf_External_Versym *eversym;
10153
10154           if (!h->def_regular)
10155             {
10156               if (h->verinfo.verdef == NULL
10157                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
10158                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
10159                 iversym.vs_vers = 0;
10160               else
10161                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
10162             }
10163           else
10164             {
10165               if (h->verinfo.vertree == NULL)
10166                 iversym.vs_vers = 1;
10167               else
10168                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
10169               if (flinfo->info->create_default_symver)
10170                 iversym.vs_vers++;
10171             }
10172
10173           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
10174              defined locally.  */
10175           if (h->versioned == versioned_hidden && h->def_regular)
10176             iversym.vs_vers |= VERSYM_HIDDEN;
10177
10178           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
10179           eversym += h->dynindx;
10180           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
10181         }
10182     }
10183
10184   /* If the symbol is undefined, and we didn't output it to .dynsym,
10185      strip it from .symtab too.  Obviously we can't do this for
10186      relocatable output or when needed for --emit-relocs.  */
10187   else if (input_sec == bfd_und_section_ptr
10188            && h->indx != -2
10189            /* PR 22319 Do not strip global undefined symbols marked as being needed.  */
10190            && (h->mark != 1 || ELF_ST_BIND (sym.st_info) != STB_GLOBAL)
10191            && !bfd_link_relocatable (flinfo->info))
10192     return TRUE;
10193
10194   /* Also strip others that we couldn't earlier due to dynamic symbol
10195      processing.  */
10196   if (strip)
10197     return TRUE;
10198   if ((input_sec->flags & SEC_EXCLUDE) != 0)
10199     return TRUE;
10200
10201   /* Output a FILE symbol so that following locals are not associated
10202      with the wrong input file.  We need one for forced local symbols
10203      if we've seen more than one FILE symbol or when we have exactly
10204      one FILE symbol but global symbols are present in a file other
10205      than the one with the FILE symbol.  We also need one if linker
10206      defined symbols are present.  In practice these conditions are
10207      always met, so just emit the FILE symbol unconditionally.  */
10208   if (eoinfo->localsyms
10209       && !eoinfo->file_sym_done
10210       && eoinfo->flinfo->filesym_count != 0)
10211     {
10212       Elf_Internal_Sym fsym;
10213
10214       memset (&fsym, 0, sizeof (fsym));
10215       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10216       fsym.st_shndx = SHN_ABS;
10217       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
10218                                       bfd_und_section_ptr, NULL))
10219         return FALSE;
10220
10221       eoinfo->file_sym_done = TRUE;
10222     }
10223
10224   indx = bfd_get_symcount (flinfo->output_bfd);
10225   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
10226                                    input_sec, h);
10227   if (ret == 0)
10228     {
10229       eoinfo->failed = TRUE;
10230       return FALSE;
10231     }
10232   else if (ret == 1)
10233     h->indx = indx;
10234   else if (h->indx == -2)
10235     abort();
10236
10237   return TRUE;
10238 }
10239
10240 /* Return TRUE if special handling is done for relocs in SEC against
10241    symbols defined in discarded sections.  */
10242
10243 static bfd_boolean
10244 elf_section_ignore_discarded_relocs (asection *sec)
10245 {
10246   const struct elf_backend_data *bed;
10247
10248   switch (sec->sec_info_type)
10249     {
10250     case SEC_INFO_TYPE_STABS:
10251     case SEC_INFO_TYPE_EH_FRAME:
10252     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10253       return TRUE;
10254     default:
10255       break;
10256     }
10257
10258   bed = get_elf_backend_data (sec->owner);
10259   if (bed->elf_backend_ignore_discarded_relocs != NULL
10260       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
10261     return TRUE;
10262
10263   return FALSE;
10264 }
10265
10266 /* Return a mask saying how ld should treat relocations in SEC against
10267    symbols defined in discarded sections.  If this function returns
10268    COMPLAIN set, ld will issue a warning message.  If this function
10269    returns PRETEND set, and the discarded section was link-once and the
10270    same size as the kept link-once section, ld will pretend that the
10271    symbol was actually defined in the kept section.  Otherwise ld will
10272    zero the reloc (at least that is the intent, but some cooperation by
10273    the target dependent code is needed, particularly for REL targets).  */
10274
10275 unsigned int
10276 _bfd_elf_default_action_discarded (asection *sec)
10277 {
10278   if (sec->flags & SEC_DEBUGGING)
10279     return PRETEND;
10280
10281   if (strcmp (".eh_frame", sec->name) == 0)
10282     return 0;
10283
10284   if (strcmp (".gcc_except_table", sec->name) == 0)
10285     return 0;
10286
10287   return COMPLAIN | PRETEND;
10288 }
10289
10290 /* Find a match between a section and a member of a section group.  */
10291
10292 static asection *
10293 match_group_member (asection *sec, asection *group,
10294                     struct bfd_link_info *info)
10295 {
10296   asection *first = elf_next_in_group (group);
10297   asection *s = first;
10298
10299   while (s != NULL)
10300     {
10301       if (bfd_elf_match_symbols_in_sections (s, sec, info))
10302         return s;
10303
10304       s = elf_next_in_group (s);
10305       if (s == first)
10306         break;
10307     }
10308
10309   return NULL;
10310 }
10311
10312 /* Check if the kept section of a discarded section SEC can be used
10313    to replace it.  Return the replacement if it is OK.  Otherwise return
10314    NULL.  */
10315
10316 asection *
10317 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
10318 {
10319   asection *kept;
10320
10321   kept = sec->kept_section;
10322   if (kept != NULL)
10323     {
10324       if ((kept->flags & SEC_GROUP) != 0)
10325         kept = match_group_member (sec, kept, info);
10326       if (kept != NULL
10327           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
10328               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
10329         kept = NULL;
10330       sec->kept_section = kept;
10331     }
10332   return kept;
10333 }
10334
10335 /* Link an input file into the linker output file.  This function
10336    handles all the sections and relocations of the input file at once.
10337    This is so that we only have to read the local symbols once, and
10338    don't have to keep them in memory.  */
10339
10340 static bfd_boolean
10341 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
10342 {
10343   int (*relocate_section)
10344     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
10345      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
10346   bfd *output_bfd;
10347   Elf_Internal_Shdr *symtab_hdr;
10348   size_t locsymcount;
10349   size_t extsymoff;
10350   Elf_Internal_Sym *isymbuf;
10351   Elf_Internal_Sym *isym;
10352   Elf_Internal_Sym *isymend;
10353   long *pindex;
10354   asection **ppsection;
10355   asection *o;
10356   const struct elf_backend_data *bed;
10357   struct elf_link_hash_entry **sym_hashes;
10358   bfd_size_type address_size;
10359   bfd_vma r_type_mask;
10360   int r_sym_shift;
10361   bfd_boolean have_file_sym = FALSE;
10362
10363   output_bfd = flinfo->output_bfd;
10364   bed = get_elf_backend_data (output_bfd);
10365   relocate_section = bed->elf_backend_relocate_section;
10366
10367   /* If this is a dynamic object, we don't want to do anything here:
10368      we don't want the local symbols, and we don't want the section
10369      contents.  */
10370   if ((input_bfd->flags & DYNAMIC) != 0)
10371     return TRUE;
10372
10373   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
10374   if (elf_bad_symtab (input_bfd))
10375     {
10376       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
10377       extsymoff = 0;
10378     }
10379   else
10380     {
10381       locsymcount = symtab_hdr->sh_info;
10382       extsymoff = symtab_hdr->sh_info;
10383     }
10384
10385   /* Read the local symbols.  */
10386   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
10387   if (isymbuf == NULL && locsymcount != 0)
10388     {
10389       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
10390                                       flinfo->internal_syms,
10391                                       flinfo->external_syms,
10392                                       flinfo->locsym_shndx);
10393       if (isymbuf == NULL)
10394         return FALSE;
10395     }
10396
10397   /* Find local symbol sections and adjust values of symbols in
10398      SEC_MERGE sections.  Write out those local symbols we know are
10399      going into the output file.  */
10400   isymend = isymbuf + locsymcount;
10401   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
10402        isym < isymend;
10403        isym++, pindex++, ppsection++)
10404     {
10405       asection *isec;
10406       const char *name;
10407       Elf_Internal_Sym osym;
10408       long indx;
10409       int ret;
10410
10411       *pindex = -1;
10412
10413       if (elf_bad_symtab (input_bfd))
10414         {
10415           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
10416             {
10417               *ppsection = NULL;
10418               continue;
10419             }
10420         }
10421
10422       if (isym->st_shndx == SHN_UNDEF)
10423         isec = bfd_und_section_ptr;
10424       else if (isym->st_shndx == SHN_ABS)
10425         isec = bfd_abs_section_ptr;
10426       else if (isym->st_shndx == SHN_COMMON)
10427         isec = bfd_com_section_ptr;
10428       else
10429         {
10430           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
10431           if (isec == NULL)
10432             {
10433               /* Don't attempt to output symbols with st_shnx in the
10434                  reserved range other than SHN_ABS and SHN_COMMON.  */
10435               isec = bfd_und_section_ptr;
10436             }
10437           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
10438                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
10439             isym->st_value =
10440               _bfd_merged_section_offset (output_bfd, &isec,
10441                                           elf_section_data (isec)->sec_info,
10442                                           isym->st_value);
10443         }
10444
10445       *ppsection = isec;
10446
10447       /* Don't output the first, undefined, symbol.  In fact, don't
10448          output any undefined local symbol.  */
10449       if (isec == bfd_und_section_ptr)
10450         continue;
10451
10452       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
10453         {
10454           /* We never output section symbols.  Instead, we use the
10455              section symbol of the corresponding section in the output
10456              file.  */
10457           continue;
10458         }
10459
10460       /* If we are stripping all symbols, we don't want to output this
10461          one.  */
10462       if (flinfo->info->strip == strip_all)
10463         continue;
10464
10465       /* If we are discarding all local symbols, we don't want to
10466          output this one.  If we are generating a relocatable output
10467          file, then some of the local symbols may be required by
10468          relocs; we output them below as we discover that they are
10469          needed.  */
10470       if (flinfo->info->discard == discard_all)
10471         continue;
10472
10473       /* If this symbol is defined in a section which we are
10474          discarding, we don't need to keep it.  */
10475       if (isym->st_shndx != SHN_UNDEF
10476           && isym->st_shndx < SHN_LORESERVE
10477           && bfd_section_removed_from_list (output_bfd,
10478                                             isec->output_section))
10479         continue;
10480
10481       /* Get the name of the symbol.  */
10482       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
10483                                               isym->st_name);
10484       if (name == NULL)
10485         return FALSE;
10486
10487       /* See if we are discarding symbols with this name.  */
10488       if ((flinfo->info->strip == strip_some
10489            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
10490                == NULL))
10491           || (((flinfo->info->discard == discard_sec_merge
10492                 && (isec->flags & SEC_MERGE)
10493                 && !bfd_link_relocatable (flinfo->info))
10494                || flinfo->info->discard == discard_l)
10495               && bfd_is_local_label_name (input_bfd, name)))
10496         continue;
10497
10498       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
10499         {
10500           if (input_bfd->lto_output)
10501             /* -flto puts a temp file name here.  This means builds
10502                are not reproducible.  Discard the symbol.  */
10503             continue;
10504           have_file_sym = TRUE;
10505           flinfo->filesym_count += 1;
10506         }
10507       if (!have_file_sym)
10508         {
10509           /* In the absence of debug info, bfd_find_nearest_line uses
10510              FILE symbols to determine the source file for local
10511              function symbols.  Provide a FILE symbol here if input
10512              files lack such, so that their symbols won't be
10513              associated with a previous input file.  It's not the
10514              source file, but the best we can do.  */
10515           have_file_sym = TRUE;
10516           flinfo->filesym_count += 1;
10517           memset (&osym, 0, sizeof (osym));
10518           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10519           osym.st_shndx = SHN_ABS;
10520           if (!elf_link_output_symstrtab (flinfo,
10521                                           (input_bfd->lto_output ? NULL
10522                                            : input_bfd->filename),
10523                                           &osym, bfd_abs_section_ptr,
10524                                           NULL))
10525             return FALSE;
10526         }
10527
10528       osym = *isym;
10529
10530       /* Adjust the section index for the output file.  */
10531       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10532                                                          isec->output_section);
10533       if (osym.st_shndx == SHN_BAD)
10534         return FALSE;
10535
10536       /* ELF symbols in relocatable files are section relative, but
10537          in executable files they are virtual addresses.  Note that
10538          this code assumes that all ELF sections have an associated
10539          BFD section with a reasonable value for output_offset; below
10540          we assume that they also have a reasonable value for
10541          output_section.  Any special sections must be set up to meet
10542          these requirements.  */
10543       osym.st_value += isec->output_offset;
10544       if (!bfd_link_relocatable (flinfo->info))
10545         {
10546           osym.st_value += isec->output_section->vma;
10547           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
10548             {
10549               /* STT_TLS symbols are relative to PT_TLS segment base.  */
10550               if (elf_hash_table (flinfo->info)->tls_sec != NULL)
10551                 osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
10552               else
10553                 osym.st_info = ELF_ST_INFO (ELF_ST_BIND (osym.st_info),
10554                                             STT_NOTYPE);
10555             }
10556         }
10557
10558       indx = bfd_get_symcount (output_bfd);
10559       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
10560       if (ret == 0)
10561         return FALSE;
10562       else if (ret == 1)
10563         *pindex = indx;
10564     }
10565
10566   if (bed->s->arch_size == 32)
10567     {
10568       r_type_mask = 0xff;
10569       r_sym_shift = 8;
10570       address_size = 4;
10571     }
10572   else
10573     {
10574       r_type_mask = 0xffffffff;
10575       r_sym_shift = 32;
10576       address_size = 8;
10577     }
10578
10579   /* Relocate the contents of each section.  */
10580   sym_hashes = elf_sym_hashes (input_bfd);
10581   for (o = input_bfd->sections; o != NULL; o = o->next)
10582     {
10583       bfd_byte *contents;
10584
10585       if (! o->linker_mark)
10586         {
10587           /* This section was omitted from the link.  */
10588           continue;
10589         }
10590
10591       if (!flinfo->info->resolve_section_groups
10592           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
10593         {
10594           /* Deal with the group signature symbol.  */
10595           struct bfd_elf_section_data *sec_data = elf_section_data (o);
10596           unsigned long symndx = sec_data->this_hdr.sh_info;
10597           asection *osec = o->output_section;
10598
10599           BFD_ASSERT (bfd_link_relocatable (flinfo->info));
10600           if (symndx >= locsymcount
10601               || (elf_bad_symtab (input_bfd)
10602                   && flinfo->sections[symndx] == NULL))
10603             {
10604               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
10605               while (h->root.type == bfd_link_hash_indirect
10606                      || h->root.type == bfd_link_hash_warning)
10607                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
10608               /* Arrange for symbol to be output.  */
10609               h->indx = -2;
10610               elf_section_data (osec)->this_hdr.sh_info = -2;
10611             }
10612           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
10613             {
10614               /* We'll use the output section target_index.  */
10615               asection *sec = flinfo->sections[symndx]->output_section;
10616               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
10617             }
10618           else
10619             {
10620               if (flinfo->indices[symndx] == -1)
10621                 {
10622                   /* Otherwise output the local symbol now.  */
10623                   Elf_Internal_Sym sym = isymbuf[symndx];
10624                   asection *sec = flinfo->sections[symndx]->output_section;
10625                   const char *name;
10626                   long indx;
10627                   int ret;
10628
10629                   name = bfd_elf_string_from_elf_section (input_bfd,
10630                                                           symtab_hdr->sh_link,
10631                                                           sym.st_name);
10632                   if (name == NULL)
10633                     return FALSE;
10634
10635                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10636                                                                     sec);
10637                   if (sym.st_shndx == SHN_BAD)
10638                     return FALSE;
10639
10640                   sym.st_value += o->output_offset;
10641
10642                   indx = bfd_get_symcount (output_bfd);
10643                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
10644                                                    NULL);
10645                   if (ret == 0)
10646                     return FALSE;
10647                   else if (ret == 1)
10648                     flinfo->indices[symndx] = indx;
10649                   else
10650                     abort ();
10651                 }
10652               elf_section_data (osec)->this_hdr.sh_info
10653                 = flinfo->indices[symndx];
10654             }
10655         }
10656
10657       if ((o->flags & SEC_HAS_CONTENTS) == 0
10658           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
10659         continue;
10660
10661       if ((o->flags & SEC_LINKER_CREATED) != 0)
10662         {
10663           /* Section was created by _bfd_elf_link_create_dynamic_sections
10664              or somesuch.  */
10665           continue;
10666         }
10667
10668       /* Get the contents of the section.  They have been cached by a
10669          relaxation routine.  Note that o is a section in an input
10670          file, so the contents field will not have been set by any of
10671          the routines which work on output files.  */
10672       if (elf_section_data (o)->this_hdr.contents != NULL)
10673         {
10674           contents = elf_section_data (o)->this_hdr.contents;
10675           if (bed->caches_rawsize
10676               && o->rawsize != 0
10677               && o->rawsize < o->size)
10678             {
10679               memcpy (flinfo->contents, contents, o->rawsize);
10680               contents = flinfo->contents;
10681             }
10682         }
10683       else
10684         {
10685           contents = flinfo->contents;
10686           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
10687             return FALSE;
10688         }
10689
10690       if ((o->flags & SEC_RELOC) != 0)
10691         {
10692           Elf_Internal_Rela *internal_relocs;
10693           Elf_Internal_Rela *rel, *relend;
10694           int action_discarded;
10695           int ret;
10696
10697           /* Get the swapped relocs.  */
10698           internal_relocs
10699             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
10700                                          flinfo->internal_relocs, FALSE);
10701           if (internal_relocs == NULL
10702               && o->reloc_count > 0)
10703             return FALSE;
10704
10705           /* We need to reverse-copy input .ctors/.dtors sections if
10706              they are placed in .init_array/.finit_array for output.  */
10707           if (o->size > address_size
10708               && ((strncmp (o->name, ".ctors", 6) == 0
10709                    && strcmp (o->output_section->name,
10710                               ".init_array") == 0)
10711                   || (strncmp (o->name, ".dtors", 6) == 0
10712                       && strcmp (o->output_section->name,
10713                                  ".fini_array") == 0))
10714               && (o->name[6] == 0 || o->name[6] == '.'))
10715             {
10716               if (o->size * bed->s->int_rels_per_ext_rel
10717                   != o->reloc_count * address_size)
10718                 {
10719                   _bfd_error_handler
10720                     /* xgettext:c-format */
10721                     (_("error: %pB: size of section %pA is not "
10722                        "multiple of address size"),
10723                      input_bfd, o);
10724                   bfd_set_error (bfd_error_bad_value);
10725                   return FALSE;
10726                 }
10727               o->flags |= SEC_ELF_REVERSE_COPY;
10728             }
10729
10730           action_discarded = -1;
10731           if (!elf_section_ignore_discarded_relocs (o))
10732             action_discarded = (*bed->action_discarded) (o);
10733
10734           /* Run through the relocs evaluating complex reloc symbols and
10735              looking for relocs against symbols from discarded sections
10736              or section symbols from removed link-once sections.
10737              Complain about relocs against discarded sections.  Zero
10738              relocs against removed link-once sections.  */
10739
10740           rel = internal_relocs;
10741           relend = rel + o->reloc_count;
10742           for ( ; rel < relend; rel++)
10743             {
10744               unsigned long r_symndx = rel->r_info >> r_sym_shift;
10745               unsigned int s_type;
10746               asection **ps, *sec;
10747               struct elf_link_hash_entry *h = NULL;
10748               const char *sym_name;
10749
10750               if (r_symndx == STN_UNDEF)
10751                 continue;
10752
10753               if (r_symndx >= locsymcount
10754                   || (elf_bad_symtab (input_bfd)
10755                       && flinfo->sections[r_symndx] == NULL))
10756                 {
10757                   h = sym_hashes[r_symndx - extsymoff];
10758
10759                   /* Badly formatted input files can contain relocs that
10760                      reference non-existant symbols.  Check here so that
10761                      we do not seg fault.  */
10762                   if (h == NULL)
10763                     {
10764                       _bfd_error_handler
10765                         /* xgettext:c-format */
10766                         (_("error: %pB contains a reloc (%#" PRIx64 ") for section %pA "
10767                            "that references a non-existent global symbol"),
10768                          input_bfd, (uint64_t) rel->r_info, o);
10769                       bfd_set_error (bfd_error_bad_value);
10770                       return FALSE;
10771                     }
10772
10773                   while (h->root.type == bfd_link_hash_indirect
10774                          || h->root.type == bfd_link_hash_warning)
10775                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10776
10777                   s_type = h->type;
10778
10779                   /* If a plugin symbol is referenced from a non-IR file,
10780                      mark the symbol as undefined.  Note that the
10781                      linker may attach linker created dynamic sections
10782                      to the plugin bfd.  Symbols defined in linker
10783                      created sections are not plugin symbols.  */
10784                   if ((h->root.non_ir_ref_regular
10785                        || h->root.non_ir_ref_dynamic)
10786                       && (h->root.type == bfd_link_hash_defined
10787                           || h->root.type == bfd_link_hash_defweak)
10788                       && (h->root.u.def.section->flags
10789                           & SEC_LINKER_CREATED) == 0
10790                       && h->root.u.def.section->owner != NULL
10791                       && (h->root.u.def.section->owner->flags
10792                           & BFD_PLUGIN) != 0)
10793                     {
10794                       h->root.type = bfd_link_hash_undefined;
10795                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10796                     }
10797
10798                   ps = NULL;
10799                   if (h->root.type == bfd_link_hash_defined
10800                       || h->root.type == bfd_link_hash_defweak)
10801                     ps = &h->root.u.def.section;
10802
10803                   sym_name = h->root.root.string;
10804                 }
10805               else
10806                 {
10807                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10808
10809                   s_type = ELF_ST_TYPE (sym->st_info);
10810                   ps = &flinfo->sections[r_symndx];
10811                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10812                                                sym, *ps);
10813                 }
10814
10815               if ((s_type == STT_RELC || s_type == STT_SRELC)
10816                   && !bfd_link_relocatable (flinfo->info))
10817                 {
10818                   bfd_vma val;
10819                   bfd_vma dot = (rel->r_offset
10820                                  + o->output_offset + o->output_section->vma);
10821 #ifdef DEBUG
10822                   printf ("Encountered a complex symbol!");
10823                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10824                           input_bfd->filename, o->name,
10825                           (long) (rel - internal_relocs));
10826                   printf (" symbol: idx  %8.8lx, name %s\n",
10827                           r_symndx, sym_name);
10828                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10829                           (unsigned long) rel->r_info,
10830                           (unsigned long) rel->r_offset);
10831 #endif
10832                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10833                                     isymbuf, locsymcount, s_type == STT_SRELC))
10834                     return FALSE;
10835
10836                   /* Symbol evaluated OK.  Update to absolute value.  */
10837                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10838                                     r_symndx, val);
10839                   continue;
10840                 }
10841
10842               if (action_discarded != -1 && ps != NULL)
10843                 {
10844                   /* Complain if the definition comes from a
10845                      discarded section.  */
10846                   if ((sec = *ps) != NULL && discarded_section (sec))
10847                     {
10848                       BFD_ASSERT (r_symndx != STN_UNDEF);
10849                       if (action_discarded & COMPLAIN)
10850                         (*flinfo->info->callbacks->einfo)
10851                           /* xgettext:c-format */
10852                           (_("%X`%s' referenced in section `%pA' of %pB: "
10853                              "defined in discarded section `%pA' of %pB\n"),
10854                            sym_name, o, input_bfd, sec, sec->owner);
10855
10856                       /* Try to do the best we can to support buggy old
10857                          versions of gcc.  Pretend that the symbol is
10858                          really defined in the kept linkonce section.
10859                          FIXME: This is quite broken.  Modifying the
10860                          symbol here means we will be changing all later
10861                          uses of the symbol, not just in this section.  */
10862                       if (action_discarded & PRETEND)
10863                         {
10864                           asection *kept;
10865
10866                           kept = _bfd_elf_check_kept_section (sec,
10867                                                               flinfo->info);
10868                           if (kept != NULL)
10869                             {
10870                               *ps = kept;
10871                               continue;
10872                             }
10873                         }
10874                     }
10875                 }
10876             }
10877
10878           /* Relocate the section by invoking a back end routine.
10879
10880              The back end routine is responsible for adjusting the
10881              section contents as necessary, and (if using Rela relocs
10882              and generating a relocatable output file) adjusting the
10883              reloc addend as necessary.
10884
10885              The back end routine does not have to worry about setting
10886              the reloc address or the reloc symbol index.
10887
10888              The back end routine is given a pointer to the swapped in
10889              internal symbols, and can access the hash table entries
10890              for the external symbols via elf_sym_hashes (input_bfd).
10891
10892              When generating relocatable output, the back end routine
10893              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10894              output symbol is going to be a section symbol
10895              corresponding to the output section, which will require
10896              the addend to be adjusted.  */
10897
10898           ret = (*relocate_section) (output_bfd, flinfo->info,
10899                                      input_bfd, o, contents,
10900                                      internal_relocs,
10901                                      isymbuf,
10902                                      flinfo->sections);
10903           if (!ret)
10904             return FALSE;
10905
10906           if (ret == 2
10907               || bfd_link_relocatable (flinfo->info)
10908               || flinfo->info->emitrelocations)
10909             {
10910               Elf_Internal_Rela *irela;
10911               Elf_Internal_Rela *irelaend, *irelamid;
10912               bfd_vma last_offset;
10913               struct elf_link_hash_entry **rel_hash;
10914               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10915               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10916               unsigned int next_erel;
10917               bfd_boolean rela_normal;
10918               struct bfd_elf_section_data *esdi, *esdo;
10919
10920               esdi = elf_section_data (o);
10921               esdo = elf_section_data (o->output_section);
10922               rela_normal = FALSE;
10923
10924               /* Adjust the reloc addresses and symbol indices.  */
10925
10926               irela = internal_relocs;
10927               irelaend = irela + o->reloc_count;
10928               rel_hash = esdo->rel.hashes + esdo->rel.count;
10929               /* We start processing the REL relocs, if any.  When we reach
10930                  IRELAMID in the loop, we switch to the RELA relocs.  */
10931               irelamid = irela;
10932               if (esdi->rel.hdr != NULL)
10933                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10934                              * bed->s->int_rels_per_ext_rel);
10935               rel_hash_list = rel_hash;
10936               rela_hash_list = NULL;
10937               last_offset = o->output_offset;
10938               if (!bfd_link_relocatable (flinfo->info))
10939                 last_offset += o->output_section->vma;
10940               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10941                 {
10942                   unsigned long r_symndx;
10943                   asection *sec;
10944                   Elf_Internal_Sym sym;
10945
10946                   if (next_erel == bed->s->int_rels_per_ext_rel)
10947                     {
10948                       rel_hash++;
10949                       next_erel = 0;
10950                     }
10951
10952                   if (irela == irelamid)
10953                     {
10954                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10955                       rela_hash_list = rel_hash;
10956                       rela_normal = bed->rela_normal;
10957                     }
10958
10959                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10960                                                              flinfo->info, o,
10961                                                              irela->r_offset);
10962                   if (irela->r_offset >= (bfd_vma) -2)
10963                     {
10964                       /* This is a reloc for a deleted entry or somesuch.
10965                          Turn it into an R_*_NONE reloc, at the same
10966                          offset as the last reloc.  elf_eh_frame.c and
10967                          bfd_elf_discard_info rely on reloc offsets
10968                          being ordered.  */
10969                       irela->r_offset = last_offset;
10970                       irela->r_info = 0;
10971                       irela->r_addend = 0;
10972                       continue;
10973                     }
10974
10975                   irela->r_offset += o->output_offset;
10976
10977                   /* Relocs in an executable have to be virtual addresses.  */
10978                   if (!bfd_link_relocatable (flinfo->info))
10979                     irela->r_offset += o->output_section->vma;
10980
10981                   last_offset = irela->r_offset;
10982
10983                   r_symndx = irela->r_info >> r_sym_shift;
10984                   if (r_symndx == STN_UNDEF)
10985                     continue;
10986
10987                   if (r_symndx >= locsymcount
10988                       || (elf_bad_symtab (input_bfd)
10989                           && flinfo->sections[r_symndx] == NULL))
10990                     {
10991                       struct elf_link_hash_entry *rh;
10992                       unsigned long indx;
10993
10994                       /* This is a reloc against a global symbol.  We
10995                          have not yet output all the local symbols, so
10996                          we do not know the symbol index of any global
10997                          symbol.  We set the rel_hash entry for this
10998                          reloc to point to the global hash table entry
10999                          for this symbol.  The symbol index is then
11000                          set at the end of bfd_elf_final_link.  */
11001                       indx = r_symndx - extsymoff;
11002                       rh = elf_sym_hashes (input_bfd)[indx];
11003                       while (rh->root.type == bfd_link_hash_indirect
11004                              || rh->root.type == bfd_link_hash_warning)
11005                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
11006
11007                       /* Setting the index to -2 tells
11008                          elf_link_output_extsym that this symbol is
11009                          used by a reloc.  */
11010                       BFD_ASSERT (rh->indx < 0);
11011                       rh->indx = -2;
11012                       *rel_hash = rh;
11013
11014                       continue;
11015                     }
11016
11017                   /* This is a reloc against a local symbol.  */
11018
11019                   *rel_hash = NULL;
11020                   sym = isymbuf[r_symndx];
11021                   sec = flinfo->sections[r_symndx];
11022                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
11023                     {
11024                       /* I suppose the backend ought to fill in the
11025                          section of any STT_SECTION symbol against a
11026                          processor specific section.  */
11027                       r_symndx = STN_UNDEF;
11028                       if (bfd_is_abs_section (sec))
11029                         ;
11030                       else if (sec == NULL || sec->owner == NULL)
11031                         {
11032                           bfd_set_error (bfd_error_bad_value);
11033                           return FALSE;
11034                         }
11035                       else
11036                         {
11037                           asection *osec = sec->output_section;
11038
11039                           /* If we have discarded a section, the output
11040                              section will be the absolute section.  In
11041                              case of discarded SEC_MERGE sections, use
11042                              the kept section.  relocate_section should
11043                              have already handled discarded linkonce
11044                              sections.  */
11045                           if (bfd_is_abs_section (osec)
11046                               && sec->kept_section != NULL
11047                               && sec->kept_section->output_section != NULL)
11048                             {
11049                               osec = sec->kept_section->output_section;
11050                               irela->r_addend -= osec->vma;
11051                             }
11052
11053                           if (!bfd_is_abs_section (osec))
11054                             {
11055                               r_symndx = osec->target_index;
11056                               if (r_symndx == STN_UNDEF)
11057                                 {
11058                                   irela->r_addend += osec->vma;
11059                                   osec = _bfd_nearby_section (output_bfd, osec,
11060                                                               osec->vma);
11061                                   irela->r_addend -= osec->vma;
11062                                   r_symndx = osec->target_index;
11063                                 }
11064                             }
11065                         }
11066
11067                       /* Adjust the addend according to where the
11068                          section winds up in the output section.  */
11069                       if (rela_normal)
11070                         irela->r_addend += sec->output_offset;
11071                     }
11072                   else
11073                     {
11074                       if (flinfo->indices[r_symndx] == -1)
11075                         {
11076                           unsigned long shlink;
11077                           const char *name;
11078                           asection *osec;
11079                           long indx;
11080
11081                           if (flinfo->info->strip == strip_all)
11082                             {
11083                               /* You can't do ld -r -s.  */
11084                               bfd_set_error (bfd_error_invalid_operation);
11085                               return FALSE;
11086                             }
11087
11088                           /* This symbol was skipped earlier, but
11089                              since it is needed by a reloc, we
11090                              must output it now.  */
11091                           shlink = symtab_hdr->sh_link;
11092                           name = (bfd_elf_string_from_elf_section
11093                                   (input_bfd, shlink, sym.st_name));
11094                           if (name == NULL)
11095                             return FALSE;
11096
11097                           osec = sec->output_section;
11098                           sym.st_shndx =
11099                             _bfd_elf_section_from_bfd_section (output_bfd,
11100                                                                osec);
11101                           if (sym.st_shndx == SHN_BAD)
11102                             return FALSE;
11103
11104                           sym.st_value += sec->output_offset;
11105                           if (!bfd_link_relocatable (flinfo->info))
11106                             {
11107                               sym.st_value += osec->vma;
11108                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
11109                                 {
11110                                   struct elf_link_hash_table *htab
11111                                     = elf_hash_table (flinfo->info);
11112
11113                                   /* STT_TLS symbols are relative to PT_TLS
11114                                      segment base.  */
11115                                   if (htab->tls_sec != NULL)
11116                                     sym.st_value -= htab->tls_sec->vma;
11117                                   else
11118                                     sym.st_info
11119                                       = ELF_ST_INFO (ELF_ST_BIND (sym.st_info),
11120                                                      STT_NOTYPE);
11121                                 }
11122                             }
11123
11124                           indx = bfd_get_symcount (output_bfd);
11125                           ret = elf_link_output_symstrtab (flinfo, name,
11126                                                            &sym, sec,
11127                                                            NULL);
11128                           if (ret == 0)
11129                             return FALSE;
11130                           else if (ret == 1)
11131                             flinfo->indices[r_symndx] = indx;
11132                           else
11133                             abort ();
11134                         }
11135
11136                       r_symndx = flinfo->indices[r_symndx];
11137                     }
11138
11139                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
11140                                    | (irela->r_info & r_type_mask));
11141                 }
11142
11143               /* Swap out the relocs.  */
11144               input_rel_hdr = esdi->rel.hdr;
11145               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
11146                 {
11147                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
11148                                                      input_rel_hdr,
11149                                                      internal_relocs,
11150                                                      rel_hash_list))
11151                     return FALSE;
11152                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
11153                                       * bed->s->int_rels_per_ext_rel);
11154                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
11155                 }
11156
11157               input_rela_hdr = esdi->rela.hdr;
11158               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
11159                 {
11160                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
11161                                                      input_rela_hdr,
11162                                                      internal_relocs,
11163                                                      rela_hash_list))
11164                     return FALSE;
11165                 }
11166             }
11167         }
11168
11169       /* Write out the modified section contents.  */
11170       if (bed->elf_backend_write_section
11171           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
11172                                                 contents))
11173         {
11174           /* Section written out.  */
11175         }
11176       else switch (o->sec_info_type)
11177         {
11178         case SEC_INFO_TYPE_STABS:
11179           if (! (_bfd_write_section_stabs
11180                  (output_bfd,
11181                   &elf_hash_table (flinfo->info)->stab_info,
11182                   o, &elf_section_data (o)->sec_info, contents)))
11183             return FALSE;
11184           break;
11185         case SEC_INFO_TYPE_MERGE:
11186           if (! _bfd_write_merged_section (output_bfd, o,
11187                                            elf_section_data (o)->sec_info))
11188             return FALSE;
11189           break;
11190         case SEC_INFO_TYPE_EH_FRAME:
11191           {
11192             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
11193                                                    o, contents))
11194               return FALSE;
11195           }
11196           break;
11197         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
11198           {
11199             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
11200                                                          flinfo->info,
11201                                                          o, contents))
11202               return FALSE;
11203           }
11204           break;
11205         default:
11206           {
11207             if (! (o->flags & SEC_EXCLUDE))
11208               {
11209                 file_ptr offset = (file_ptr) o->output_offset;
11210                 bfd_size_type todo = o->size;
11211
11212                 offset *= bfd_octets_per_byte (output_bfd);
11213
11214                 if ((o->flags & SEC_ELF_REVERSE_COPY))
11215                   {
11216                     /* Reverse-copy input section to output.  */
11217                     do
11218                       {
11219                         todo -= address_size;
11220                         if (! bfd_set_section_contents (output_bfd,
11221                                                         o->output_section,
11222                                                         contents + todo,
11223                                                         offset,
11224                                                         address_size))
11225                           return FALSE;
11226                         if (todo == 0)
11227                           break;
11228                         offset += address_size;
11229                       }
11230                     while (1);
11231                   }
11232                 else if (! bfd_set_section_contents (output_bfd,
11233                                                      o->output_section,
11234                                                      contents,
11235                                                      offset, todo))
11236                   return FALSE;
11237               }
11238           }
11239           break;
11240         }
11241     }
11242
11243   return TRUE;
11244 }
11245
11246 /* Generate a reloc when linking an ELF file.  This is a reloc
11247    requested by the linker, and does not come from any input file.  This
11248    is used to build constructor and destructor tables when linking
11249    with -Ur.  */
11250
11251 static bfd_boolean
11252 elf_reloc_link_order (bfd *output_bfd,
11253                       struct bfd_link_info *info,
11254                       asection *output_section,
11255                       struct bfd_link_order *link_order)
11256 {
11257   reloc_howto_type *howto;
11258   long indx;
11259   bfd_vma offset;
11260   bfd_vma addend;
11261   struct bfd_elf_section_reloc_data *reldata;
11262   struct elf_link_hash_entry **rel_hash_ptr;
11263   Elf_Internal_Shdr *rel_hdr;
11264   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
11265   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
11266   bfd_byte *erel;
11267   unsigned int i;
11268   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
11269
11270   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
11271   if (howto == NULL)
11272     {
11273       bfd_set_error (bfd_error_bad_value);
11274       return FALSE;
11275     }
11276
11277   addend = link_order->u.reloc.p->addend;
11278
11279   if (esdo->rel.hdr)
11280     reldata = &esdo->rel;
11281   else if (esdo->rela.hdr)
11282     reldata = &esdo->rela;
11283   else
11284     {
11285       reldata = NULL;
11286       BFD_ASSERT (0);
11287     }
11288
11289   /* Figure out the symbol index.  */
11290   rel_hash_ptr = reldata->hashes + reldata->count;
11291   if (link_order->type == bfd_section_reloc_link_order)
11292     {
11293       indx = link_order->u.reloc.p->u.section->target_index;
11294       BFD_ASSERT (indx != 0);
11295       *rel_hash_ptr = NULL;
11296     }
11297   else
11298     {
11299       struct elf_link_hash_entry *h;
11300
11301       /* Treat a reloc against a defined symbol as though it were
11302          actually against the section.  */
11303       h = ((struct elf_link_hash_entry *)
11304            bfd_wrapped_link_hash_lookup (output_bfd, info,
11305                                          link_order->u.reloc.p->u.name,
11306                                          FALSE, FALSE, TRUE));
11307       if (h != NULL
11308           && (h->root.type == bfd_link_hash_defined
11309               || h->root.type == bfd_link_hash_defweak))
11310         {
11311           asection *section;
11312
11313           section = h->root.u.def.section;
11314           indx = section->output_section->target_index;
11315           *rel_hash_ptr = NULL;
11316           /* It seems that we ought to add the symbol value to the
11317              addend here, but in practice it has already been added
11318              because it was passed to constructor_callback.  */
11319           addend += section->output_section->vma + section->output_offset;
11320         }
11321       else if (h != NULL)
11322         {
11323           /* Setting the index to -2 tells elf_link_output_extsym that
11324              this symbol is used by a reloc.  */
11325           h->indx = -2;
11326           *rel_hash_ptr = h;
11327           indx = 0;
11328         }
11329       else
11330         {
11331           (*info->callbacks->unattached_reloc)
11332             (info, link_order->u.reloc.p->u.name, NULL, NULL, 0);
11333           indx = 0;
11334         }
11335     }
11336
11337   /* If this is an inplace reloc, we must write the addend into the
11338      object file.  */
11339   if (howto->partial_inplace && addend != 0)
11340     {
11341       bfd_size_type size;
11342       bfd_reloc_status_type rstat;
11343       bfd_byte *buf;
11344       bfd_boolean ok;
11345       const char *sym_name;
11346
11347       size = (bfd_size_type) bfd_get_reloc_size (howto);
11348       buf = (bfd_byte *) bfd_zmalloc (size);
11349       if (buf == NULL && size != 0)
11350         return FALSE;
11351       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
11352       switch (rstat)
11353         {
11354         case bfd_reloc_ok:
11355           break;
11356
11357         default:
11358         case bfd_reloc_outofrange:
11359           abort ();
11360
11361         case bfd_reloc_overflow:
11362           if (link_order->type == bfd_section_reloc_link_order)
11363             sym_name = bfd_section_name (output_bfd,
11364                                          link_order->u.reloc.p->u.section);
11365           else
11366             sym_name = link_order->u.reloc.p->u.name;
11367           (*info->callbacks->reloc_overflow) (info, NULL, sym_name,
11368                                               howto->name, addend, NULL, NULL,
11369                                               (bfd_vma) 0);
11370           break;
11371         }
11372
11373       ok = bfd_set_section_contents (output_bfd, output_section, buf,
11374                                      link_order->offset
11375                                      * bfd_octets_per_byte (output_bfd),
11376                                      size);
11377       free (buf);
11378       if (! ok)
11379         return FALSE;
11380     }
11381
11382   /* The address of a reloc is relative to the section in a
11383      relocatable file, and is a virtual address in an executable
11384      file.  */
11385   offset = link_order->offset;
11386   if (! bfd_link_relocatable (info))
11387     offset += output_section->vma;
11388
11389   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
11390     {
11391       irel[i].r_offset = offset;
11392       irel[i].r_info = 0;
11393       irel[i].r_addend = 0;
11394     }
11395   if (bed->s->arch_size == 32)
11396     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
11397   else
11398     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
11399
11400   rel_hdr = reldata->hdr;
11401   erel = rel_hdr->contents;
11402   if (rel_hdr->sh_type == SHT_REL)
11403     {
11404       erel += reldata->count * bed->s->sizeof_rel;
11405       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
11406     }
11407   else
11408     {
11409       irel[0].r_addend = addend;
11410       erel += reldata->count * bed->s->sizeof_rela;
11411       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
11412     }
11413
11414   ++reldata->count;
11415
11416   return TRUE;
11417 }
11418
11419
11420 /* Get the output vma of the section pointed to by the sh_link field.  */
11421
11422 static bfd_vma
11423 elf_get_linked_section_vma (struct bfd_link_order *p)
11424 {
11425   Elf_Internal_Shdr **elf_shdrp;
11426   asection *s;
11427   int elfsec;
11428
11429   s = p->u.indirect.section;
11430   elf_shdrp = elf_elfsections (s->owner);
11431   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
11432   elfsec = elf_shdrp[elfsec]->sh_link;
11433   /* PR 290:
11434      The Intel C compiler generates SHT_IA_64_UNWIND with
11435      SHF_LINK_ORDER.  But it doesn't set the sh_link or
11436      sh_info fields.  Hence we could get the situation
11437      where elfsec is 0.  */
11438   if (elfsec == 0)
11439     {
11440       const struct elf_backend_data *bed
11441         = get_elf_backend_data (s->owner);
11442       if (bed->link_order_error_handler)
11443         bed->link_order_error_handler
11444           /* xgettext:c-format */
11445           (_("%pB: warning: sh_link not set for section `%pA'"), s->owner, s);
11446       return 0;
11447     }
11448   else
11449     {
11450       s = elf_shdrp[elfsec]->bfd_section;
11451       return s->output_section->vma + s->output_offset;
11452     }
11453 }
11454
11455
11456 /* Compare two sections based on the locations of the sections they are
11457    linked to.  Used by elf_fixup_link_order.  */
11458
11459 static int
11460 compare_link_order (const void * a, const void * b)
11461 {
11462   bfd_vma apos;
11463   bfd_vma bpos;
11464
11465   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
11466   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
11467   if (apos < bpos)
11468     return -1;
11469   return apos > bpos;
11470 }
11471
11472
11473 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
11474    order as their linked sections.  Returns false if this could not be done
11475    because an output section includes both ordered and unordered
11476    sections.  Ideally we'd do this in the linker proper.  */
11477
11478 static bfd_boolean
11479 elf_fixup_link_order (bfd *abfd, asection *o)
11480 {
11481   int seen_linkorder;
11482   int seen_other;
11483   int n;
11484   struct bfd_link_order *p;
11485   bfd *sub;
11486   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11487   unsigned elfsec;
11488   struct bfd_link_order **sections;
11489   asection *s, *other_sec, *linkorder_sec;
11490   bfd_vma offset;
11491
11492   other_sec = NULL;
11493   linkorder_sec = NULL;
11494   seen_other = 0;
11495   seen_linkorder = 0;
11496   for (p = o->map_head.link_order; p != NULL; p = p->next)
11497     {
11498       if (p->type == bfd_indirect_link_order)
11499         {
11500           s = p->u.indirect.section;
11501           sub = s->owner;
11502           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11503               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
11504               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
11505               && elfsec < elf_numsections (sub)
11506               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
11507               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
11508             {
11509               seen_linkorder++;
11510               linkorder_sec = s;
11511             }
11512           else
11513             {
11514               seen_other++;
11515               other_sec = s;
11516             }
11517         }
11518       else
11519         seen_other++;
11520
11521       if (seen_other && seen_linkorder)
11522         {
11523           if (other_sec && linkorder_sec)
11524             _bfd_error_handler
11525               /* xgettext:c-format */
11526               (_("%pA has both ordered [`%pA' in %pB] "
11527                  "and unordered [`%pA' in %pB] sections"),
11528                o, linkorder_sec, linkorder_sec->owner,
11529                other_sec, other_sec->owner);
11530           else
11531             _bfd_error_handler
11532               (_("%pA has both ordered and unordered sections"), o);
11533           bfd_set_error (bfd_error_bad_value);
11534           return FALSE;
11535         }
11536     }
11537
11538   if (!seen_linkorder)
11539     return TRUE;
11540
11541   sections = (struct bfd_link_order **)
11542     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
11543   if (sections == NULL)
11544     return FALSE;
11545   seen_linkorder = 0;
11546
11547   for (p = o->map_head.link_order; p != NULL; p = p->next)
11548     {
11549       sections[seen_linkorder++] = p;
11550     }
11551   /* Sort the input sections in the order of their linked section.  */
11552   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
11553          compare_link_order);
11554
11555   /* Change the offsets of the sections.  */
11556   offset = 0;
11557   for (n = 0; n < seen_linkorder; n++)
11558     {
11559       s = sections[n]->u.indirect.section;
11560       offset &= ~(bfd_vma) 0 << s->alignment_power;
11561       s->output_offset = offset / bfd_octets_per_byte (abfd);
11562       sections[n]->offset = offset;
11563       offset += sections[n]->size;
11564     }
11565
11566   free (sections);
11567   return TRUE;
11568 }
11569
11570 /* Generate an import library in INFO->implib_bfd from symbols in ABFD.
11571    Returns TRUE upon success, FALSE otherwise.  */
11572
11573 static bfd_boolean
11574 elf_output_implib (bfd *abfd, struct bfd_link_info *info)
11575 {
11576   bfd_boolean ret = FALSE;
11577   bfd *implib_bfd;
11578   const struct elf_backend_data *bed;
11579   flagword flags;
11580   enum bfd_architecture arch;
11581   unsigned int mach;
11582   asymbol **sympp = NULL;
11583   long symsize;
11584   long symcount;
11585   long src_count;
11586   elf_symbol_type *osymbuf;
11587
11588   implib_bfd = info->out_implib_bfd;
11589   bed = get_elf_backend_data (abfd);
11590
11591   if (!bfd_set_format (implib_bfd, bfd_object))
11592     return FALSE;
11593
11594   /* Use flag from executable but make it a relocatable object.  */
11595   flags = bfd_get_file_flags (abfd);
11596   flags &= ~HAS_RELOC;
11597   if (!bfd_set_start_address (implib_bfd, 0)
11598       || !bfd_set_file_flags (implib_bfd, flags & ~EXEC_P))
11599     return FALSE;
11600
11601   /* Copy architecture of output file to import library file.  */
11602   arch = bfd_get_arch (abfd);
11603   mach = bfd_get_mach (abfd);
11604   if (!bfd_set_arch_mach (implib_bfd, arch, mach)
11605       && (abfd->target_defaulted
11606           || bfd_get_arch (abfd) != bfd_get_arch (implib_bfd)))
11607     return FALSE;
11608
11609   /* Get symbol table size.  */
11610   symsize = bfd_get_symtab_upper_bound (abfd);
11611   if (symsize < 0)
11612     return FALSE;
11613
11614   /* Read in the symbol table.  */
11615   sympp = (asymbol **) xmalloc (symsize);
11616   symcount = bfd_canonicalize_symtab (abfd, sympp);
11617   if (symcount < 0)
11618     goto free_sym_buf;
11619
11620   /* Allow the BFD backend to copy any private header data it
11621      understands from the output BFD to the import library BFD.  */
11622   if (! bfd_copy_private_header_data (abfd, implib_bfd))
11623     goto free_sym_buf;
11624
11625   /* Filter symbols to appear in the import library.  */
11626   if (bed->elf_backend_filter_implib_symbols)
11627     symcount = bed->elf_backend_filter_implib_symbols (abfd, info, sympp,
11628                                                        symcount);
11629   else
11630     symcount = _bfd_elf_filter_global_symbols (abfd, info, sympp, symcount);
11631   if (symcount == 0)
11632     {
11633       bfd_set_error (bfd_error_no_symbols);
11634       _bfd_error_handler (_("%pB: no symbol found for import library"),
11635                           implib_bfd);
11636       goto free_sym_buf;
11637     }
11638
11639
11640   /* Make symbols absolute.  */
11641   osymbuf = (elf_symbol_type *) bfd_alloc2 (implib_bfd, symcount,
11642                                             sizeof (*osymbuf));
11643   for (src_count = 0; src_count < symcount; src_count++)
11644     {
11645       memcpy (&osymbuf[src_count], (elf_symbol_type *) sympp[src_count],
11646               sizeof (*osymbuf));
11647       osymbuf[src_count].symbol.section = bfd_abs_section_ptr;
11648       osymbuf[src_count].internal_elf_sym.st_shndx = SHN_ABS;
11649       osymbuf[src_count].symbol.value += sympp[src_count]->section->vma;
11650       osymbuf[src_count].internal_elf_sym.st_value =
11651         osymbuf[src_count].symbol.value;
11652       sympp[src_count] = &osymbuf[src_count].symbol;
11653     }
11654
11655   bfd_set_symtab (implib_bfd, sympp, symcount);
11656
11657   /* Allow the BFD backend to copy any private data it understands
11658      from the output BFD to the import library BFD.  This is done last
11659      to permit the routine to look at the filtered symbol table.  */
11660   if (! bfd_copy_private_bfd_data (abfd, implib_bfd))
11661     goto free_sym_buf;
11662
11663   if (!bfd_close (implib_bfd))
11664     goto free_sym_buf;
11665
11666   ret = TRUE;
11667
11668 free_sym_buf:
11669   free (sympp);
11670   return ret;
11671 }
11672
11673 static void
11674 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
11675 {
11676   asection *o;
11677
11678   if (flinfo->symstrtab != NULL)
11679     _bfd_elf_strtab_free (flinfo->symstrtab);
11680   if (flinfo->contents != NULL)
11681     free (flinfo->contents);
11682   if (flinfo->external_relocs != NULL)
11683     free (flinfo->external_relocs);
11684   if (flinfo->internal_relocs != NULL)
11685     free (flinfo->internal_relocs);
11686   if (flinfo->external_syms != NULL)
11687     free (flinfo->external_syms);
11688   if (flinfo->locsym_shndx != NULL)
11689     free (flinfo->locsym_shndx);
11690   if (flinfo->internal_syms != NULL)
11691     free (flinfo->internal_syms);
11692   if (flinfo->indices != NULL)
11693     free (flinfo->indices);
11694   if (flinfo->sections != NULL)
11695     free (flinfo->sections);
11696   if (flinfo->symshndxbuf != NULL
11697       && flinfo->symshndxbuf != (Elf_External_Sym_Shndx *) -1)
11698     free (flinfo->symshndxbuf);
11699   for (o = obfd->sections; o != NULL; o = o->next)
11700     {
11701       struct bfd_elf_section_data *esdo = elf_section_data (o);
11702       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11703         free (esdo->rel.hashes);
11704       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11705         free (esdo->rela.hashes);
11706     }
11707 }
11708
11709 /* Do the final step of an ELF link.  */
11710
11711 bfd_boolean
11712 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
11713 {
11714   bfd_boolean dynamic;
11715   bfd_boolean emit_relocs;
11716   bfd *dynobj;
11717   struct elf_final_link_info flinfo;
11718   asection *o;
11719   struct bfd_link_order *p;
11720   bfd *sub;
11721   bfd_size_type max_contents_size;
11722   bfd_size_type max_external_reloc_size;
11723   bfd_size_type max_internal_reloc_count;
11724   bfd_size_type max_sym_count;
11725   bfd_size_type max_sym_shndx_count;
11726   Elf_Internal_Sym elfsym;
11727   unsigned int i;
11728   Elf_Internal_Shdr *symtab_hdr;
11729   Elf_Internal_Shdr *symtab_shndx_hdr;
11730   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11731   struct elf_outext_info eoinfo;
11732   bfd_boolean merged;
11733   size_t relativecount = 0;
11734   asection *reldyn = 0;
11735   bfd_size_type amt;
11736   asection *attr_section = NULL;
11737   bfd_vma attr_size = 0;
11738   const char *std_attrs_section;
11739   struct elf_link_hash_table *htab = elf_hash_table (info);
11740
11741   if (!is_elf_hash_table (htab))
11742     return FALSE;
11743
11744   if (bfd_link_pic (info))
11745     abfd->flags |= DYNAMIC;
11746
11747   dynamic = htab->dynamic_sections_created;
11748   dynobj = htab->dynobj;
11749
11750   emit_relocs = (bfd_link_relocatable (info)
11751                  || info->emitrelocations);
11752
11753   flinfo.info = info;
11754   flinfo.output_bfd = abfd;
11755   flinfo.symstrtab = _bfd_elf_strtab_init ();
11756   if (flinfo.symstrtab == NULL)
11757     return FALSE;
11758
11759   if (! dynamic)
11760     {
11761       flinfo.hash_sec = NULL;
11762       flinfo.symver_sec = NULL;
11763     }
11764   else
11765     {
11766       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
11767       /* Note that dynsym_sec can be NULL (on VMS).  */
11768       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
11769       /* Note that it is OK if symver_sec is NULL.  */
11770     }
11771
11772   flinfo.contents = NULL;
11773   flinfo.external_relocs = NULL;
11774   flinfo.internal_relocs = NULL;
11775   flinfo.external_syms = NULL;
11776   flinfo.locsym_shndx = NULL;
11777   flinfo.internal_syms = NULL;
11778   flinfo.indices = NULL;
11779   flinfo.sections = NULL;
11780   flinfo.symshndxbuf = NULL;
11781   flinfo.filesym_count = 0;
11782
11783   /* The object attributes have been merged.  Remove the input
11784      sections from the link, and set the contents of the output
11785      secton.  */
11786   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
11787   for (o = abfd->sections; o != NULL; o = o->next)
11788     {
11789       bfd_boolean remove_section = FALSE;
11790
11791       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
11792           || strcmp (o->name, ".gnu.attributes") == 0)
11793         {
11794           for (p = o->map_head.link_order; p != NULL; p = p->next)
11795             {
11796               asection *input_section;
11797
11798               if (p->type != bfd_indirect_link_order)
11799                 continue;
11800               input_section = p->u.indirect.section;
11801               /* Hack: reset the SEC_HAS_CONTENTS flag so that
11802                  elf_link_input_bfd ignores this section.  */
11803               input_section->flags &= ~SEC_HAS_CONTENTS;
11804             }
11805
11806           attr_size = bfd_elf_obj_attr_size (abfd);
11807           bfd_set_section_size (abfd, o, attr_size);
11808           /* Skip this section later on.  */
11809           o->map_head.link_order = NULL;
11810           if (attr_size)
11811             attr_section = o;
11812           else
11813             remove_section = TRUE;
11814         }
11815       else if ((o->flags & SEC_GROUP) != 0 && o->size == 0)
11816         {
11817           /* Remove empty group section from linker output.  */
11818           remove_section = TRUE;
11819         }
11820       if (remove_section)
11821         {
11822           o->flags |= SEC_EXCLUDE;
11823           bfd_section_list_remove (abfd, o);
11824           abfd->section_count--;
11825         }
11826     }
11827
11828   /* Count up the number of relocations we will output for each output
11829      section, so that we know the sizes of the reloc sections.  We
11830      also figure out some maximum sizes.  */
11831   max_contents_size = 0;
11832   max_external_reloc_size = 0;
11833   max_internal_reloc_count = 0;
11834   max_sym_count = 0;
11835   max_sym_shndx_count = 0;
11836   merged = FALSE;
11837   for (o = abfd->sections; o != NULL; o = o->next)
11838     {
11839       struct bfd_elf_section_data *esdo = elf_section_data (o);
11840       o->reloc_count = 0;
11841
11842       for (p = o->map_head.link_order; p != NULL; p = p->next)
11843         {
11844           unsigned int reloc_count = 0;
11845           unsigned int additional_reloc_count = 0;
11846           struct bfd_elf_section_data *esdi = NULL;
11847
11848           if (p->type == bfd_section_reloc_link_order
11849               || p->type == bfd_symbol_reloc_link_order)
11850             reloc_count = 1;
11851           else if (p->type == bfd_indirect_link_order)
11852             {
11853               asection *sec;
11854
11855               sec = p->u.indirect.section;
11856
11857               /* Mark all sections which are to be included in the
11858                  link.  This will normally be every section.  We need
11859                  to do this so that we can identify any sections which
11860                  the linker has decided to not include.  */
11861               sec->linker_mark = TRUE;
11862
11863               if (sec->flags & SEC_MERGE)
11864                 merged = TRUE;
11865
11866               if (sec->rawsize > max_contents_size)
11867                 max_contents_size = sec->rawsize;
11868               if (sec->size > max_contents_size)
11869                 max_contents_size = sec->size;
11870
11871               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
11872                   && (sec->owner->flags & DYNAMIC) == 0)
11873                 {
11874                   size_t sym_count;
11875
11876                   /* We are interested in just local symbols, not all
11877                      symbols.  */
11878                   if (elf_bad_symtab (sec->owner))
11879                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
11880                                  / bed->s->sizeof_sym);
11881                   else
11882                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
11883
11884                   if (sym_count > max_sym_count)
11885                     max_sym_count = sym_count;
11886
11887                   if (sym_count > max_sym_shndx_count
11888                       && elf_symtab_shndx_list (sec->owner) != NULL)
11889                     max_sym_shndx_count = sym_count;
11890
11891                   if (esdo->this_hdr.sh_type == SHT_REL
11892                       || esdo->this_hdr.sh_type == SHT_RELA)
11893                     /* Some backends use reloc_count in relocation sections
11894                        to count particular types of relocs.  Of course,
11895                        reloc sections themselves can't have relocations.  */
11896                     ;
11897                   else if (emit_relocs)
11898                     {
11899                       reloc_count = sec->reloc_count;
11900                       if (bed->elf_backend_count_additional_relocs)
11901                         {
11902                           int c;
11903                           c = (*bed->elf_backend_count_additional_relocs) (sec);
11904                           additional_reloc_count += c;
11905                         }
11906                     }
11907                   else if (bed->elf_backend_count_relocs)
11908                     reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
11909
11910                   esdi = elf_section_data (sec);
11911
11912                   if ((sec->flags & SEC_RELOC) != 0)
11913                     {
11914                       size_t ext_size = 0;
11915
11916                       if (esdi->rel.hdr != NULL)
11917                         ext_size = esdi->rel.hdr->sh_size;
11918                       if (esdi->rela.hdr != NULL)
11919                         ext_size += esdi->rela.hdr->sh_size;
11920
11921                       if (ext_size > max_external_reloc_size)
11922                         max_external_reloc_size = ext_size;
11923                       if (sec->reloc_count > max_internal_reloc_count)
11924                         max_internal_reloc_count = sec->reloc_count;
11925                     }
11926                 }
11927             }
11928
11929           if (reloc_count == 0)
11930             continue;
11931
11932           reloc_count += additional_reloc_count;
11933           o->reloc_count += reloc_count;
11934
11935           if (p->type == bfd_indirect_link_order && emit_relocs)
11936             {
11937               if (esdi->rel.hdr)
11938                 {
11939                   esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11940                   esdo->rel.count += additional_reloc_count;
11941                 }
11942               if (esdi->rela.hdr)
11943                 {
11944                   esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11945                   esdo->rela.count += additional_reloc_count;
11946                 }
11947             }
11948           else
11949             {
11950               if (o->use_rela_p)
11951                 esdo->rela.count += reloc_count;
11952               else
11953                 esdo->rel.count += reloc_count;
11954             }
11955         }
11956
11957       if (o->reloc_count > 0)
11958         o->flags |= SEC_RELOC;
11959       else
11960         {
11961           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11962              set it (this is probably a bug) and if it is set
11963              assign_section_numbers will create a reloc section.  */
11964           o->flags &=~ SEC_RELOC;
11965         }
11966
11967       /* If the SEC_ALLOC flag is not set, force the section VMA to
11968          zero.  This is done in elf_fake_sections as well, but forcing
11969          the VMA to 0 here will ensure that relocs against these
11970          sections are handled correctly.  */
11971       if ((o->flags & SEC_ALLOC) == 0
11972           && ! o->user_set_vma)
11973         o->vma = 0;
11974     }
11975
11976   if (! bfd_link_relocatable (info) && merged)
11977     elf_link_hash_traverse (htab, _bfd_elf_link_sec_merge_syms, abfd);
11978
11979   /* Figure out the file positions for everything but the symbol table
11980      and the relocs.  We set symcount to force assign_section_numbers
11981      to create a symbol table.  */
11982   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11983   BFD_ASSERT (! abfd->output_has_begun);
11984   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11985     goto error_return;
11986
11987   /* Set sizes, and assign file positions for reloc sections.  */
11988   for (o = abfd->sections; o != NULL; o = o->next)
11989     {
11990       struct bfd_elf_section_data *esdo = elf_section_data (o);
11991       if ((o->flags & SEC_RELOC) != 0)
11992         {
11993           if (esdo->rel.hdr
11994               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11995             goto error_return;
11996
11997           if (esdo->rela.hdr
11998               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11999             goto error_return;
12000         }
12001
12002       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
12003          to count upwards while actually outputting the relocations.  */
12004       esdo->rel.count = 0;
12005       esdo->rela.count = 0;
12006
12007       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
12008         {
12009           /* Cache the section contents so that they can be compressed
12010              later.  Use bfd_malloc since it will be freed by
12011              bfd_compress_section_contents.  */
12012           unsigned char *contents = esdo->this_hdr.contents;
12013           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
12014             abort ();
12015           contents
12016             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
12017           if (contents == NULL)
12018             goto error_return;
12019           esdo->this_hdr.contents = contents;
12020         }
12021     }
12022
12023   /* We have now assigned file positions for all the sections except
12024      .symtab, .strtab, and non-loaded reloc sections.  We start the
12025      .symtab section at the current file position, and write directly
12026      to it.  We build the .strtab section in memory.  */
12027   bfd_get_symcount (abfd) = 0;
12028   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12029   /* sh_name is set in prep_headers.  */
12030   symtab_hdr->sh_type = SHT_SYMTAB;
12031   /* sh_flags, sh_addr and sh_size all start off zero.  */
12032   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
12033   /* sh_link is set in assign_section_numbers.  */
12034   /* sh_info is set below.  */
12035   /* sh_offset is set just below.  */
12036   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
12037
12038   if (max_sym_count < 20)
12039     max_sym_count = 20;
12040   htab->strtabsize = max_sym_count;
12041   amt = max_sym_count * sizeof (struct elf_sym_strtab);
12042   htab->strtab = (struct elf_sym_strtab *) bfd_malloc (amt);
12043   if (htab->strtab == NULL)
12044     goto error_return;
12045   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
12046   flinfo.symshndxbuf
12047     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
12048        ? (Elf_External_Sym_Shndx *) -1 : NULL);
12049
12050   if (info->strip != strip_all || emit_relocs)
12051     {
12052       file_ptr off = elf_next_file_pos (abfd);
12053
12054       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
12055
12056       /* Note that at this point elf_next_file_pos (abfd) is
12057          incorrect.  We do not yet know the size of the .symtab section.
12058          We correct next_file_pos below, after we do know the size.  */
12059
12060       /* Start writing out the symbol table.  The first symbol is always a
12061          dummy symbol.  */
12062       elfsym.st_value = 0;
12063       elfsym.st_size = 0;
12064       elfsym.st_info = 0;
12065       elfsym.st_other = 0;
12066       elfsym.st_shndx = SHN_UNDEF;
12067       elfsym.st_target_internal = 0;
12068       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
12069                                      bfd_und_section_ptr, NULL) != 1)
12070         goto error_return;
12071
12072       /* Output a symbol for each section.  We output these even if we are
12073          discarding local symbols, since they are used for relocs.  These
12074          symbols have no names.  We store the index of each one in the
12075          index field of the section, so that we can find it again when
12076          outputting relocs.  */
12077
12078       elfsym.st_size = 0;
12079       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
12080       elfsym.st_other = 0;
12081       elfsym.st_value = 0;
12082       elfsym.st_target_internal = 0;
12083       for (i = 1; i < elf_numsections (abfd); i++)
12084         {
12085           o = bfd_section_from_elf_index (abfd, i);
12086           if (o != NULL)
12087             {
12088               o->target_index = bfd_get_symcount (abfd);
12089               elfsym.st_shndx = i;
12090               if (!bfd_link_relocatable (info))
12091                 elfsym.st_value = o->vma;
12092               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
12093                                              NULL) != 1)
12094                 goto error_return;
12095             }
12096         }
12097     }
12098
12099   /* Allocate some memory to hold information read in from the input
12100      files.  */
12101   if (max_contents_size != 0)
12102     {
12103       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
12104       if (flinfo.contents == NULL)
12105         goto error_return;
12106     }
12107
12108   if (max_external_reloc_size != 0)
12109     {
12110       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
12111       if (flinfo.external_relocs == NULL)
12112         goto error_return;
12113     }
12114
12115   if (max_internal_reloc_count != 0)
12116     {
12117       amt = max_internal_reloc_count * sizeof (Elf_Internal_Rela);
12118       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
12119       if (flinfo.internal_relocs == NULL)
12120         goto error_return;
12121     }
12122
12123   if (max_sym_count != 0)
12124     {
12125       amt = max_sym_count * bed->s->sizeof_sym;
12126       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
12127       if (flinfo.external_syms == NULL)
12128         goto error_return;
12129
12130       amt = max_sym_count * sizeof (Elf_Internal_Sym);
12131       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
12132       if (flinfo.internal_syms == NULL)
12133         goto error_return;
12134
12135       amt = max_sym_count * sizeof (long);
12136       flinfo.indices = (long int *) bfd_malloc (amt);
12137       if (flinfo.indices == NULL)
12138         goto error_return;
12139
12140       amt = max_sym_count * sizeof (asection *);
12141       flinfo.sections = (asection **) bfd_malloc (amt);
12142       if (flinfo.sections == NULL)
12143         goto error_return;
12144     }
12145
12146   if (max_sym_shndx_count != 0)
12147     {
12148       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
12149       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
12150       if (flinfo.locsym_shndx == NULL)
12151         goto error_return;
12152     }
12153
12154   if (htab->tls_sec)
12155     {
12156       bfd_vma base, end = 0;
12157       asection *sec;
12158
12159       for (sec = htab->tls_sec;
12160            sec && (sec->flags & SEC_THREAD_LOCAL);
12161            sec = sec->next)
12162         {
12163           bfd_size_type size = sec->size;
12164
12165           if (size == 0
12166               && (sec->flags & SEC_HAS_CONTENTS) == 0)
12167             {
12168               struct bfd_link_order *ord = sec->map_tail.link_order;
12169
12170               if (ord != NULL)
12171                 size = ord->offset + ord->size;
12172             }
12173           end = sec->vma + size;
12174         }
12175       base = htab->tls_sec->vma;
12176       /* Only align end of TLS section if static TLS doesn't have special
12177          alignment requirements.  */
12178       if (bed->static_tls_alignment == 1)
12179         end = align_power (end, htab->tls_sec->alignment_power);
12180       htab->tls_size = end - base;
12181     }
12182
12183   /* Reorder SHF_LINK_ORDER sections.  */
12184   for (o = abfd->sections; o != NULL; o = o->next)
12185     {
12186       if (!elf_fixup_link_order (abfd, o))
12187         return FALSE;
12188     }
12189
12190   if (!_bfd_elf_fixup_eh_frame_hdr (info))
12191     return FALSE;
12192
12193   /* Since ELF permits relocations to be against local symbols, we
12194      must have the local symbols available when we do the relocations.
12195      Since we would rather only read the local symbols once, and we
12196      would rather not keep them in memory, we handle all the
12197      relocations for a single input file at the same time.
12198
12199      Unfortunately, there is no way to know the total number of local
12200      symbols until we have seen all of them, and the local symbol
12201      indices precede the global symbol indices.  This means that when
12202      we are generating relocatable output, and we see a reloc against
12203      a global symbol, we can not know the symbol index until we have
12204      finished examining all the local symbols to see which ones we are
12205      going to output.  To deal with this, we keep the relocations in
12206      memory, and don't output them until the end of the link.  This is
12207      an unfortunate waste of memory, but I don't see a good way around
12208      it.  Fortunately, it only happens when performing a relocatable
12209      link, which is not the common case.  FIXME: If keep_memory is set
12210      we could write the relocs out and then read them again; I don't
12211      know how bad the memory loss will be.  */
12212
12213   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12214     sub->output_has_begun = FALSE;
12215   for (o = abfd->sections; o != NULL; o = o->next)
12216     {
12217       for (p = o->map_head.link_order; p != NULL; p = p->next)
12218         {
12219           if (p->type == bfd_indirect_link_order
12220               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
12221                   == bfd_target_elf_flavour)
12222               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
12223             {
12224               if (! sub->output_has_begun)
12225                 {
12226                   if (! elf_link_input_bfd (&flinfo, sub))
12227                     goto error_return;
12228                   sub->output_has_begun = TRUE;
12229                 }
12230             }
12231           else if (p->type == bfd_section_reloc_link_order
12232                    || p->type == bfd_symbol_reloc_link_order)
12233             {
12234               if (! elf_reloc_link_order (abfd, info, o, p))
12235                 goto error_return;
12236             }
12237           else
12238             {
12239               if (! _bfd_default_link_order (abfd, info, o, p))
12240                 {
12241                   if (p->type == bfd_indirect_link_order
12242                       && (bfd_get_flavour (sub)
12243                           == bfd_target_elf_flavour)
12244                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
12245                           != bed->s->elfclass))
12246                     {
12247                       const char *iclass, *oclass;
12248
12249                       switch (bed->s->elfclass)
12250                         {
12251                         case ELFCLASS64: oclass = "ELFCLASS64"; break;
12252                         case ELFCLASS32: oclass = "ELFCLASS32"; break;
12253                         case ELFCLASSNONE: oclass = "ELFCLASSNONE"; break;
12254                         default: abort ();
12255                         }
12256
12257                       switch (elf_elfheader (sub)->e_ident[EI_CLASS])
12258                         {
12259                         case ELFCLASS64: iclass = "ELFCLASS64"; break;
12260                         case ELFCLASS32: iclass = "ELFCLASS32"; break;
12261                         case ELFCLASSNONE: iclass = "ELFCLASSNONE"; break;
12262                         default: abort ();
12263                         }
12264
12265                       bfd_set_error (bfd_error_wrong_format);
12266                       _bfd_error_handler
12267                         /* xgettext:c-format */
12268                         (_("%pB: file class %s incompatible with %s"),
12269                          sub, iclass, oclass);
12270                     }
12271
12272                   goto error_return;
12273                 }
12274             }
12275         }
12276     }
12277
12278   /* Free symbol buffer if needed.  */
12279   if (!info->reduce_memory_overheads)
12280     {
12281       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12282         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
12283             && elf_tdata (sub)->symbuf)
12284           {
12285             free (elf_tdata (sub)->symbuf);
12286             elf_tdata (sub)->symbuf = NULL;
12287           }
12288     }
12289
12290   /* Output any global symbols that got converted to local in a
12291      version script or due to symbol visibility.  We do this in a
12292      separate step since ELF requires all local symbols to appear
12293      prior to any global symbols.  FIXME: We should only do this if
12294      some global symbols were, in fact, converted to become local.
12295      FIXME: Will this work correctly with the Irix 5 linker?  */
12296   eoinfo.failed = FALSE;
12297   eoinfo.flinfo = &flinfo;
12298   eoinfo.localsyms = TRUE;
12299   eoinfo.file_sym_done = FALSE;
12300   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12301   if (eoinfo.failed)
12302     return FALSE;
12303
12304   /* If backend needs to output some local symbols not present in the hash
12305      table, do it now.  */
12306   if (bed->elf_backend_output_arch_local_syms
12307       && (info->strip != strip_all || emit_relocs))
12308     {
12309       typedef int (*out_sym_func)
12310         (void *, const char *, Elf_Internal_Sym *, asection *,
12311          struct elf_link_hash_entry *);
12312
12313       if (! ((*bed->elf_backend_output_arch_local_syms)
12314              (abfd, info, &flinfo,
12315               (out_sym_func) elf_link_output_symstrtab)))
12316         return FALSE;
12317     }
12318
12319   /* That wrote out all the local symbols.  Finish up the symbol table
12320      with the global symbols. Even if we want to strip everything we
12321      can, we still need to deal with those global symbols that got
12322      converted to local in a version script.  */
12323
12324   /* The sh_info field records the index of the first non local symbol.  */
12325   symtab_hdr->sh_info = bfd_get_symcount (abfd);
12326
12327   if (dynamic
12328       && htab->dynsym != NULL
12329       && htab->dynsym->output_section != bfd_abs_section_ptr)
12330     {
12331       Elf_Internal_Sym sym;
12332       bfd_byte *dynsym = htab->dynsym->contents;
12333
12334       o = htab->dynsym->output_section;
12335       elf_section_data (o)->this_hdr.sh_info = htab->local_dynsymcount + 1;
12336
12337       /* Write out the section symbols for the output sections.  */
12338       if (bfd_link_pic (info)
12339           || htab->is_relocatable_executable)
12340         {
12341           asection *s;
12342
12343           sym.st_size = 0;
12344           sym.st_name = 0;
12345           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
12346           sym.st_other = 0;
12347           sym.st_target_internal = 0;
12348
12349           for (s = abfd->sections; s != NULL; s = s->next)
12350             {
12351               int indx;
12352               bfd_byte *dest;
12353               long dynindx;
12354
12355               dynindx = elf_section_data (s)->dynindx;
12356               if (dynindx <= 0)
12357                 continue;
12358               indx = elf_section_data (s)->this_idx;
12359               BFD_ASSERT (indx > 0);
12360               sym.st_shndx = indx;
12361               if (! check_dynsym (abfd, &sym))
12362                 return FALSE;
12363               sym.st_value = s->vma;
12364               dest = dynsym + dynindx * bed->s->sizeof_sym;
12365               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12366             }
12367         }
12368
12369       /* Write out the local dynsyms.  */
12370       if (htab->dynlocal)
12371         {
12372           struct elf_link_local_dynamic_entry *e;
12373           for (e = htab->dynlocal; e ; e = e->next)
12374             {
12375               asection *s;
12376               bfd_byte *dest;
12377
12378               /* Copy the internal symbol and turn off visibility.
12379                  Note that we saved a word of storage and overwrote
12380                  the original st_name with the dynstr_index.  */
12381               sym = e->isym;
12382               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
12383
12384               s = bfd_section_from_elf_index (e->input_bfd,
12385                                               e->isym.st_shndx);
12386               if (s != NULL)
12387                 {
12388                   sym.st_shndx =
12389                     elf_section_data (s->output_section)->this_idx;
12390                   if (! check_dynsym (abfd, &sym))
12391                     return FALSE;
12392                   sym.st_value = (s->output_section->vma
12393                                   + s->output_offset
12394                                   + e->isym.st_value);
12395                 }
12396
12397               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
12398               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12399             }
12400         }
12401     }
12402
12403   /* We get the global symbols from the hash table.  */
12404   eoinfo.failed = FALSE;
12405   eoinfo.localsyms = FALSE;
12406   eoinfo.flinfo = &flinfo;
12407   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12408   if (eoinfo.failed)
12409     return FALSE;
12410
12411   /* If backend needs to output some symbols not present in the hash
12412      table, do it now.  */
12413   if (bed->elf_backend_output_arch_syms
12414       && (info->strip != strip_all || emit_relocs))
12415     {
12416       typedef int (*out_sym_func)
12417         (void *, const char *, Elf_Internal_Sym *, asection *,
12418          struct elf_link_hash_entry *);
12419
12420       if (! ((*bed->elf_backend_output_arch_syms)
12421              (abfd, info, &flinfo,
12422               (out_sym_func) elf_link_output_symstrtab)))
12423         return FALSE;
12424     }
12425
12426   /* Finalize the .strtab section.  */
12427   _bfd_elf_strtab_finalize (flinfo.symstrtab);
12428
12429   /* Swap out the .strtab section. */
12430   if (!elf_link_swap_symbols_out (&flinfo))
12431     return FALSE;
12432
12433   /* Now we know the size of the symtab section.  */
12434   if (bfd_get_symcount (abfd) > 0)
12435     {
12436       /* Finish up and write out the symbol string table (.strtab)
12437          section.  */
12438       Elf_Internal_Shdr *symstrtab_hdr = NULL;
12439       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
12440
12441       if (elf_symtab_shndx_list (abfd))
12442         {
12443           symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
12444
12445           if (symtab_shndx_hdr != NULL && symtab_shndx_hdr->sh_name != 0)
12446             {
12447               symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
12448               symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
12449               symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
12450               amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
12451               symtab_shndx_hdr->sh_size = amt;
12452
12453               off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
12454                                                                off, TRUE);
12455
12456               if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
12457                   || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
12458                 return FALSE;
12459             }
12460         }
12461
12462       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
12463       /* sh_name was set in prep_headers.  */
12464       symstrtab_hdr->sh_type = SHT_STRTAB;
12465       symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
12466       symstrtab_hdr->sh_addr = 0;
12467       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
12468       symstrtab_hdr->sh_entsize = 0;
12469       symstrtab_hdr->sh_link = 0;
12470       symstrtab_hdr->sh_info = 0;
12471       /* sh_offset is set just below.  */
12472       symstrtab_hdr->sh_addralign = 1;
12473
12474       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
12475                                                        off, TRUE);
12476       elf_next_file_pos (abfd) = off;
12477
12478       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
12479           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
12480         return FALSE;
12481     }
12482
12483   if (info->out_implib_bfd && !elf_output_implib (abfd, info))
12484     {
12485       _bfd_error_handler (_("%pB: failed to generate import library"),
12486                           info->out_implib_bfd);
12487       return FALSE;
12488     }
12489
12490   /* Adjust the relocs to have the correct symbol indices.  */
12491   for (o = abfd->sections; o != NULL; o = o->next)
12492     {
12493       struct bfd_elf_section_data *esdo = elf_section_data (o);
12494       bfd_boolean sort;
12495
12496       if ((o->flags & SEC_RELOC) == 0)
12497         continue;
12498
12499       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
12500       if (esdo->rel.hdr != NULL
12501           && !elf_link_adjust_relocs (abfd, o, &esdo->rel, sort, info))
12502         return FALSE;
12503       if (esdo->rela.hdr != NULL
12504           && !elf_link_adjust_relocs (abfd, o, &esdo->rela, sort, info))
12505         return FALSE;
12506
12507       /* Set the reloc_count field to 0 to prevent write_relocs from
12508          trying to swap the relocs out itself.  */
12509       o->reloc_count = 0;
12510     }
12511
12512   if (dynamic && info->combreloc && dynobj != NULL)
12513     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
12514
12515   /* If we are linking against a dynamic object, or generating a
12516      shared library, finish up the dynamic linking information.  */
12517   if (dynamic)
12518     {
12519       bfd_byte *dyncon, *dynconend;
12520
12521       /* Fix up .dynamic entries.  */
12522       o = bfd_get_linker_section (dynobj, ".dynamic");
12523       BFD_ASSERT (o != NULL);
12524
12525       dyncon = o->contents;
12526       dynconend = o->contents + o->size;
12527       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12528         {
12529           Elf_Internal_Dyn dyn;
12530           const char *name;
12531           unsigned int type;
12532           bfd_size_type sh_size;
12533           bfd_vma sh_addr;
12534
12535           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12536
12537           switch (dyn.d_tag)
12538             {
12539             default:
12540               continue;
12541             case DT_NULL:
12542               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
12543                 {
12544                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
12545                     {
12546                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
12547                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
12548                     default: continue;
12549                     }
12550                   dyn.d_un.d_val = relativecount;
12551                   relativecount = 0;
12552                   break;
12553                 }
12554               continue;
12555
12556             case DT_INIT:
12557               name = info->init_function;
12558               goto get_sym;
12559             case DT_FINI:
12560               name = info->fini_function;
12561             get_sym:
12562               {
12563                 struct elf_link_hash_entry *h;
12564
12565                 h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
12566                 if (h != NULL
12567                     && (h->root.type == bfd_link_hash_defined
12568                         || h->root.type == bfd_link_hash_defweak))
12569                   {
12570                     dyn.d_un.d_ptr = h->root.u.def.value;
12571                     o = h->root.u.def.section;
12572                     if (o->output_section != NULL)
12573                       dyn.d_un.d_ptr += (o->output_section->vma
12574                                          + o->output_offset);
12575                     else
12576                       {
12577                         /* The symbol is imported from another shared
12578                            library and does not apply to this one.  */
12579                         dyn.d_un.d_ptr = 0;
12580                       }
12581                     break;
12582                   }
12583               }
12584               continue;
12585
12586             case DT_PREINIT_ARRAYSZ:
12587               name = ".preinit_array";
12588               goto get_out_size;
12589             case DT_INIT_ARRAYSZ:
12590               name = ".init_array";
12591               goto get_out_size;
12592             case DT_FINI_ARRAYSZ:
12593               name = ".fini_array";
12594             get_out_size:
12595               o = bfd_get_section_by_name (abfd, name);
12596               if (o == NULL)
12597                 {
12598                   _bfd_error_handler
12599                     (_("could not find section %s"), name);
12600                   goto error_return;
12601                 }
12602               if (o->size == 0)
12603                 _bfd_error_handler
12604                   (_("warning: %s section has zero size"), name);
12605               dyn.d_un.d_val = o->size;
12606               break;
12607
12608             case DT_PREINIT_ARRAY:
12609               name = ".preinit_array";
12610               goto get_out_vma;
12611             case DT_INIT_ARRAY:
12612               name = ".init_array";
12613               goto get_out_vma;
12614             case DT_FINI_ARRAY:
12615               name = ".fini_array";
12616             get_out_vma:
12617               o = bfd_get_section_by_name (abfd, name);
12618               goto do_vma;
12619
12620             case DT_HASH:
12621               name = ".hash";
12622               goto get_vma;
12623             case DT_GNU_HASH:
12624               name = ".gnu.hash";
12625               goto get_vma;
12626             case DT_STRTAB:
12627               name = ".dynstr";
12628               goto get_vma;
12629             case DT_SYMTAB:
12630               name = ".dynsym";
12631               goto get_vma;
12632             case DT_VERDEF:
12633               name = ".gnu.version_d";
12634               goto get_vma;
12635             case DT_VERNEED:
12636               name = ".gnu.version_r";
12637               goto get_vma;
12638             case DT_VERSYM:
12639               name = ".gnu.version";
12640             get_vma:
12641               o = bfd_get_linker_section (dynobj, name);
12642             do_vma:
12643               if (o == NULL || bfd_is_abs_section (o->output_section))
12644                 {
12645                   _bfd_error_handler
12646                     (_("could not find section %s"), name);
12647                   goto error_return;
12648                 }
12649               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
12650                 {
12651                   _bfd_error_handler
12652                     (_("warning: section '%s' is being made into a note"), name);
12653                   bfd_set_error (bfd_error_nonrepresentable_section);
12654                   goto error_return;
12655                 }
12656               dyn.d_un.d_ptr = o->output_section->vma + o->output_offset;
12657               break;
12658
12659             case DT_REL:
12660             case DT_RELA:
12661             case DT_RELSZ:
12662             case DT_RELASZ:
12663               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
12664                 type = SHT_REL;
12665               else
12666                 type = SHT_RELA;
12667               sh_size = 0;
12668               sh_addr = 0;
12669               for (i = 1; i < elf_numsections (abfd); i++)
12670                 {
12671                   Elf_Internal_Shdr *hdr;
12672
12673                   hdr = elf_elfsections (abfd)[i];
12674                   if (hdr->sh_type == type
12675                       && (hdr->sh_flags & SHF_ALLOC) != 0)
12676                     {
12677                       sh_size += hdr->sh_size;
12678                       if (sh_addr == 0
12679                           || sh_addr > hdr->sh_addr)
12680                         sh_addr = hdr->sh_addr;
12681                     }
12682                 }
12683
12684               if (bed->dtrel_excludes_plt && htab->srelplt != NULL)
12685                 {
12686                   /* Don't count procedure linkage table relocs in the
12687                      overall reloc count.  */
12688                   sh_size -= htab->srelplt->size;
12689                   if (sh_size == 0)
12690                     /* If the size is zero, make the address zero too.
12691                        This is to avoid a glibc bug.  If the backend
12692                        emits DT_RELA/DT_RELASZ even when DT_RELASZ is
12693                        zero, then we'll put DT_RELA at the end of
12694                        DT_JMPREL.  glibc will interpret the end of
12695                        DT_RELA matching the end of DT_JMPREL as the
12696                        case where DT_RELA includes DT_JMPREL, and for
12697                        LD_BIND_NOW will decide that processing DT_RELA
12698                        will process the PLT relocs too.  Net result:
12699                        No PLT relocs applied.  */
12700                     sh_addr = 0;
12701
12702                   /* If .rela.plt is the first .rela section, exclude
12703                      it from DT_RELA.  */
12704                   else if (sh_addr == (htab->srelplt->output_section->vma
12705                                        + htab->srelplt->output_offset))
12706                     sh_addr += htab->srelplt->size;
12707                 }
12708
12709               if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
12710                 dyn.d_un.d_val = sh_size;
12711               else
12712                 dyn.d_un.d_ptr = sh_addr;
12713               break;
12714             }
12715           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
12716         }
12717     }
12718
12719   /* If we have created any dynamic sections, then output them.  */
12720   if (dynobj != NULL)
12721     {
12722       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
12723         goto error_return;
12724
12725       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
12726       if (((info->warn_shared_textrel && bfd_link_pic (info))
12727            || info->error_textrel)
12728           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
12729         {
12730           bfd_byte *dyncon, *dynconend;
12731
12732           dyncon = o->contents;
12733           dynconend = o->contents + o->size;
12734           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12735             {
12736               Elf_Internal_Dyn dyn;
12737
12738               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12739
12740               if (dyn.d_tag == DT_TEXTREL)
12741                 {
12742                   if (info->error_textrel)
12743                     info->callbacks->einfo
12744                       (_("%P%X: read-only segment has dynamic relocations\n"));
12745                   else
12746                     info->callbacks->einfo
12747                       (_("%P: warning: creating a DT_TEXTREL in a shared object\n"));
12748                   break;
12749                 }
12750             }
12751         }
12752
12753       for (o = dynobj->sections; o != NULL; o = o->next)
12754         {
12755           if ((o->flags & SEC_HAS_CONTENTS) == 0
12756               || o->size == 0
12757               || o->output_section == bfd_abs_section_ptr)
12758             continue;
12759           if ((o->flags & SEC_LINKER_CREATED) == 0)
12760             {
12761               /* At this point, we are only interested in sections
12762                  created by _bfd_elf_link_create_dynamic_sections.  */
12763               continue;
12764             }
12765           if (htab->stab_info.stabstr == o)
12766             continue;
12767           if (htab->eh_info.hdr_sec == o)
12768             continue;
12769           if (strcmp (o->name, ".dynstr") != 0)
12770             {
12771               if (! bfd_set_section_contents (abfd, o->output_section,
12772                                               o->contents,
12773                                               (file_ptr) o->output_offset
12774                                               * bfd_octets_per_byte (abfd),
12775                                               o->size))
12776                 goto error_return;
12777             }
12778           else
12779             {
12780               /* The contents of the .dynstr section are actually in a
12781                  stringtab.  */
12782               file_ptr off;
12783
12784               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
12785               if (bfd_seek (abfd, off, SEEK_SET) != 0
12786                   || !_bfd_elf_strtab_emit (abfd, htab->dynstr))
12787                 goto error_return;
12788             }
12789         }
12790     }
12791
12792   if (!info->resolve_section_groups)
12793     {
12794       bfd_boolean failed = FALSE;
12795
12796       BFD_ASSERT (bfd_link_relocatable (info));
12797       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
12798       if (failed)
12799         goto error_return;
12800     }
12801
12802   /* If we have optimized stabs strings, output them.  */
12803   if (htab->stab_info.stabstr != NULL)
12804     {
12805       if (!_bfd_write_stab_strings (abfd, &htab->stab_info))
12806         goto error_return;
12807     }
12808
12809   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
12810     goto error_return;
12811
12812   elf_final_link_free (abfd, &flinfo);
12813
12814   if (attr_section)
12815     {
12816       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
12817       if (contents == NULL)
12818         return FALSE;   /* Bail out and fail.  */
12819       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
12820       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
12821       free (contents);
12822     }
12823
12824   return TRUE;
12825
12826  error_return:
12827   elf_final_link_free (abfd, &flinfo);
12828   return FALSE;
12829 }
12830 \f
12831 /* Initialize COOKIE for input bfd ABFD.  */
12832
12833 static bfd_boolean
12834 init_reloc_cookie (struct elf_reloc_cookie *cookie,
12835                    struct bfd_link_info *info, bfd *abfd)
12836 {
12837   Elf_Internal_Shdr *symtab_hdr;
12838   const struct elf_backend_data *bed;
12839
12840   bed = get_elf_backend_data (abfd);
12841   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12842
12843   cookie->abfd = abfd;
12844   cookie->sym_hashes = elf_sym_hashes (abfd);
12845   cookie->bad_symtab = elf_bad_symtab (abfd);
12846   if (cookie->bad_symtab)
12847     {
12848       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12849       cookie->extsymoff = 0;
12850     }
12851   else
12852     {
12853       cookie->locsymcount = symtab_hdr->sh_info;
12854       cookie->extsymoff = symtab_hdr->sh_info;
12855     }
12856
12857   if (bed->s->arch_size == 32)
12858     cookie->r_sym_shift = 8;
12859   else
12860     cookie->r_sym_shift = 32;
12861
12862   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
12863   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
12864     {
12865       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12866                                               cookie->locsymcount, 0,
12867                                               NULL, NULL, NULL);
12868       if (cookie->locsyms == NULL)
12869         {
12870           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
12871           return FALSE;
12872         }
12873       if (info->keep_memory)
12874         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
12875     }
12876   return TRUE;
12877 }
12878
12879 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
12880
12881 static void
12882 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
12883 {
12884   Elf_Internal_Shdr *symtab_hdr;
12885
12886   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12887   if (cookie->locsyms != NULL
12888       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
12889     free (cookie->locsyms);
12890 }
12891
12892 /* Initialize the relocation information in COOKIE for input section SEC
12893    of input bfd ABFD.  */
12894
12895 static bfd_boolean
12896 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12897                         struct bfd_link_info *info, bfd *abfd,
12898                         asection *sec)
12899 {
12900   if (sec->reloc_count == 0)
12901     {
12902       cookie->rels = NULL;
12903       cookie->relend = NULL;
12904     }
12905   else
12906     {
12907       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
12908                                                 info->keep_memory);
12909       if (cookie->rels == NULL)
12910         return FALSE;
12911       cookie->rel = cookie->rels;
12912       cookie->relend = cookie->rels + sec->reloc_count;
12913     }
12914   cookie->rel = cookie->rels;
12915   return TRUE;
12916 }
12917
12918 /* Free the memory allocated by init_reloc_cookie_rels,
12919    if appropriate.  */
12920
12921 static void
12922 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12923                         asection *sec)
12924 {
12925   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
12926     free (cookie->rels);
12927 }
12928
12929 /* Initialize the whole of COOKIE for input section SEC.  */
12930
12931 static bfd_boolean
12932 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12933                                struct bfd_link_info *info,
12934                                asection *sec)
12935 {
12936   if (!init_reloc_cookie (cookie, info, sec->owner))
12937     goto error1;
12938   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
12939     goto error2;
12940   return TRUE;
12941
12942  error2:
12943   fini_reloc_cookie (cookie, sec->owner);
12944  error1:
12945   return FALSE;
12946 }
12947
12948 /* Free the memory allocated by init_reloc_cookie_for_section,
12949    if appropriate.  */
12950
12951 static void
12952 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12953                                asection *sec)
12954 {
12955   fini_reloc_cookie_rels (cookie, sec);
12956   fini_reloc_cookie (cookie, sec->owner);
12957 }
12958 \f
12959 /* Garbage collect unused sections.  */
12960
12961 /* Default gc_mark_hook.  */
12962
12963 asection *
12964 _bfd_elf_gc_mark_hook (asection *sec,
12965                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12966                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12967                        struct elf_link_hash_entry *h,
12968                        Elf_Internal_Sym *sym)
12969 {
12970   if (h != NULL)
12971     {
12972       switch (h->root.type)
12973         {
12974         case bfd_link_hash_defined:
12975         case bfd_link_hash_defweak:
12976           return h->root.u.def.section;
12977
12978         case bfd_link_hash_common:
12979           return h->root.u.c.p->section;
12980
12981         default:
12982           break;
12983         }
12984     }
12985   else
12986     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12987
12988   return NULL;
12989 }
12990
12991 /* Return the debug definition section.  */
12992
12993 static asection *
12994 elf_gc_mark_debug_section (asection *sec ATTRIBUTE_UNUSED,
12995                            struct bfd_link_info *info ATTRIBUTE_UNUSED,
12996                            Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12997                            struct elf_link_hash_entry *h,
12998                            Elf_Internal_Sym *sym)
12999 {
13000   if (h != NULL)
13001     {
13002       /* Return the global debug definition section.  */
13003       if ((h->root.type == bfd_link_hash_defined
13004            || h->root.type == bfd_link_hash_defweak)
13005           && (h->root.u.def.section->flags & SEC_DEBUGGING) != 0)
13006         return h->root.u.def.section;
13007     }
13008   else
13009     {
13010       /* Return the local debug definition section.  */
13011       asection *isec = bfd_section_from_elf_index (sec->owner,
13012                                                    sym->st_shndx);
13013       if ((isec->flags & SEC_DEBUGGING) != 0)
13014         return isec;
13015     }
13016
13017   return NULL;
13018 }
13019
13020 /* COOKIE->rel describes a relocation against section SEC, which is
13021    a section we've decided to keep.  Return the section that contains
13022    the relocation symbol, or NULL if no section contains it.  */
13023
13024 asection *
13025 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
13026                        elf_gc_mark_hook_fn gc_mark_hook,
13027                        struct elf_reloc_cookie *cookie,
13028                        bfd_boolean *start_stop)
13029 {
13030   unsigned long r_symndx;
13031   struct elf_link_hash_entry *h;
13032
13033   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
13034   if (r_symndx == STN_UNDEF)
13035     return NULL;
13036
13037   if (r_symndx >= cookie->locsymcount
13038       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13039     {
13040       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
13041       if (h == NULL)
13042         {
13043           info->callbacks->einfo (_("%F%P: corrupt input: %pB\n"),
13044                                   sec->owner);
13045           return NULL;
13046         }
13047       while (h->root.type == bfd_link_hash_indirect
13048              || h->root.type == bfd_link_hash_warning)
13049         h = (struct elf_link_hash_entry *) h->root.u.i.link;
13050       h->mark = 1;
13051       /* If this symbol is weak and there is a non-weak definition, we
13052          keep the non-weak definition because many backends put
13053          dynamic reloc info on the non-weak definition for code
13054          handling copy relocs.  */
13055       if (h->is_weakalias)
13056         weakdef (h)->mark = 1;
13057
13058       if (start_stop != NULL)
13059         {
13060           /* To work around a glibc bug, mark XXX input sections
13061              when there is a reference to __start_XXX or __stop_XXX
13062              symbols.  */
13063           if (h->start_stop)
13064             {
13065               asection *s = h->u2.start_stop_section;
13066               *start_stop = !s->gc_mark;
13067               return s;
13068             }
13069         }
13070
13071       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
13072     }
13073
13074   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
13075                           &cookie->locsyms[r_symndx]);
13076 }
13077
13078 /* COOKIE->rel describes a relocation against section SEC, which is
13079    a section we've decided to keep.  Mark the section that contains
13080    the relocation symbol.  */
13081
13082 bfd_boolean
13083 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
13084                         asection *sec,
13085                         elf_gc_mark_hook_fn gc_mark_hook,
13086                         struct elf_reloc_cookie *cookie)
13087 {
13088   asection *rsec;
13089   bfd_boolean start_stop = FALSE;
13090
13091   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie, &start_stop);
13092   while (rsec != NULL)
13093     {
13094       if (!rsec->gc_mark)
13095         {
13096           if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
13097               || (rsec->owner->flags & DYNAMIC) != 0)
13098             rsec->gc_mark = 1;
13099           else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
13100             return FALSE;
13101         }
13102       if (!start_stop)
13103         break;
13104       rsec = bfd_get_next_section_by_name (rsec->owner, rsec);
13105     }
13106   return TRUE;
13107 }
13108
13109 /* The mark phase of garbage collection.  For a given section, mark
13110    it and any sections in this section's group, and all the sections
13111    which define symbols to which it refers.  */
13112
13113 bfd_boolean
13114 _bfd_elf_gc_mark (struct bfd_link_info *info,
13115                   asection *sec,
13116                   elf_gc_mark_hook_fn gc_mark_hook)
13117 {
13118   bfd_boolean ret;
13119   asection *group_sec, *eh_frame;
13120
13121   sec->gc_mark = 1;
13122
13123   /* Mark all the sections in the group.  */
13124   group_sec = elf_section_data (sec)->next_in_group;
13125   if (group_sec && !group_sec->gc_mark)
13126     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
13127       return FALSE;
13128
13129   /* Look through the section relocs.  */
13130   ret = TRUE;
13131   eh_frame = elf_eh_frame_section (sec->owner);
13132   if ((sec->flags & SEC_RELOC) != 0
13133       && sec->reloc_count > 0
13134       && sec != eh_frame)
13135     {
13136       struct elf_reloc_cookie cookie;
13137
13138       if (!init_reloc_cookie_for_section (&cookie, info, sec))
13139         ret = FALSE;
13140       else
13141         {
13142           for (; cookie.rel < cookie.relend; cookie.rel++)
13143             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
13144               {
13145                 ret = FALSE;
13146                 break;
13147               }
13148           fini_reloc_cookie_for_section (&cookie, sec);
13149         }
13150     }
13151
13152   if (ret && eh_frame && elf_fde_list (sec))
13153     {
13154       struct elf_reloc_cookie cookie;
13155
13156       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
13157         ret = FALSE;
13158       else
13159         {
13160           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
13161                                       gc_mark_hook, &cookie))
13162             ret = FALSE;
13163           fini_reloc_cookie_for_section (&cookie, eh_frame);
13164         }
13165     }
13166
13167   eh_frame = elf_section_eh_frame_entry (sec);
13168   if (ret && eh_frame && !eh_frame->gc_mark)
13169     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
13170       ret = FALSE;
13171
13172   return ret;
13173 }
13174
13175 /* Scan and mark sections in a special or debug section group.  */
13176
13177 static void
13178 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
13179 {
13180   /* Point to first section of section group.  */
13181   asection *ssec;
13182   /* Used to iterate the section group.  */
13183   asection *msec;
13184
13185   bfd_boolean is_special_grp = TRUE;
13186   bfd_boolean is_debug_grp = TRUE;
13187
13188   /* First scan to see if group contains any section other than debug
13189      and special section.  */
13190   ssec = msec = elf_next_in_group (grp);
13191   do
13192     {
13193       if ((msec->flags & SEC_DEBUGGING) == 0)
13194         is_debug_grp = FALSE;
13195
13196       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
13197         is_special_grp = FALSE;
13198
13199       msec = elf_next_in_group (msec);
13200     }
13201   while (msec != ssec);
13202
13203   /* If this is a pure debug section group or pure special section group,
13204      keep all sections in this group.  */
13205   if (is_debug_grp || is_special_grp)
13206     {
13207       do
13208         {
13209           msec->gc_mark = 1;
13210           msec = elf_next_in_group (msec);
13211         }
13212       while (msec != ssec);
13213     }
13214 }
13215
13216 /* Keep debug and special sections.  */
13217
13218 bfd_boolean
13219 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
13220                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
13221 {
13222   bfd *ibfd;
13223
13224   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13225     {
13226       asection *isec;
13227       bfd_boolean some_kept;
13228       bfd_boolean debug_frag_seen;
13229       bfd_boolean has_kept_debug_info;
13230
13231       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13232         continue;
13233       isec = ibfd->sections;
13234       if (isec == NULL || isec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13235         continue;
13236
13237       /* Ensure all linker created sections are kept,
13238          see if any other section is already marked,
13239          and note if we have any fragmented debug sections.  */
13240       debug_frag_seen = some_kept = has_kept_debug_info = FALSE;
13241       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13242         {
13243           if ((isec->flags & SEC_LINKER_CREATED) != 0)
13244             isec->gc_mark = 1;
13245           else if (isec->gc_mark
13246                    && (isec->flags & SEC_ALLOC) != 0
13247                    && elf_section_type (isec) != SHT_NOTE)
13248             some_kept = TRUE;
13249
13250           if (!debug_frag_seen
13251               && (isec->flags & SEC_DEBUGGING)
13252               && CONST_STRNEQ (isec->name, ".debug_line."))
13253             debug_frag_seen = TRUE;
13254         }
13255
13256       /* If no non-note alloc section in this file will be kept, then
13257          we can toss out the debug and special sections.  */
13258       if (!some_kept)
13259         continue;
13260
13261       /* Keep debug and special sections like .comment when they are
13262          not part of a group.  Also keep section groups that contain
13263          just debug sections or special sections.  */
13264       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13265         {
13266           if ((isec->flags & SEC_GROUP) != 0)
13267             _bfd_elf_gc_mark_debug_special_section_group (isec);
13268           else if (((isec->flags & SEC_DEBUGGING) != 0
13269                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
13270                    && elf_next_in_group (isec) == NULL)
13271             isec->gc_mark = 1;
13272           if (isec->gc_mark && (isec->flags & SEC_DEBUGGING) != 0)
13273             has_kept_debug_info = TRUE;
13274         }
13275
13276       /* Look for CODE sections which are going to be discarded,
13277          and find and discard any fragmented debug sections which
13278          are associated with that code section.  */
13279       if (debug_frag_seen)
13280         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13281           if ((isec->flags & SEC_CODE) != 0
13282               && isec->gc_mark == 0)
13283             {
13284               unsigned int ilen;
13285               asection *dsec;
13286
13287               ilen = strlen (isec->name);
13288
13289               /* Association is determined by the name of the debug
13290                  section containing the name of the code section as
13291                  a suffix.  For example .debug_line.text.foo is a
13292                  debug section associated with .text.foo.  */
13293               for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
13294                 {
13295                   unsigned int dlen;
13296
13297                   if (dsec->gc_mark == 0
13298                       || (dsec->flags & SEC_DEBUGGING) == 0)
13299                     continue;
13300
13301                   dlen = strlen (dsec->name);
13302
13303                   if (dlen > ilen
13304                       && strncmp (dsec->name + (dlen - ilen),
13305                                   isec->name, ilen) == 0)
13306                     dsec->gc_mark = 0;
13307                 }
13308           }
13309
13310       /* Mark debug sections referenced by kept debug sections.  */
13311       if (has_kept_debug_info)
13312         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13313           if (isec->gc_mark
13314               && (isec->flags & SEC_DEBUGGING) != 0)
13315             if (!_bfd_elf_gc_mark (info, isec,
13316                                    elf_gc_mark_debug_section))
13317               return FALSE;
13318     }
13319   return TRUE;
13320 }
13321
13322 static bfd_boolean
13323 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
13324 {
13325   bfd *sub;
13326   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13327
13328   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13329     {
13330       asection *o;
13331
13332       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13333           || elf_object_id (sub) != elf_hash_table_id (elf_hash_table (info))
13334           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13335         continue;
13336       o = sub->sections;
13337       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13338         continue;
13339
13340       for (o = sub->sections; o != NULL; o = o->next)
13341         {
13342           /* When any section in a section group is kept, we keep all
13343              sections in the section group.  If the first member of
13344              the section group is excluded, we will also exclude the
13345              group section.  */
13346           if (o->flags & SEC_GROUP)
13347             {
13348               asection *first = elf_next_in_group (o);
13349               o->gc_mark = first->gc_mark;
13350             }
13351
13352           if (o->gc_mark)
13353             continue;
13354
13355           /* Skip sweeping sections already excluded.  */
13356           if (o->flags & SEC_EXCLUDE)
13357             continue;
13358
13359           /* Since this is early in the link process, it is simple
13360              to remove a section from the output.  */
13361           o->flags |= SEC_EXCLUDE;
13362
13363           if (info->print_gc_sections && o->size != 0)
13364             /* xgettext:c-format */
13365             _bfd_error_handler (_("removing unused section '%pA' in file '%pB'"),
13366                                 o, sub);
13367         }
13368     }
13369
13370   return TRUE;
13371 }
13372
13373 /* Propagate collected vtable information.  This is called through
13374    elf_link_hash_traverse.  */
13375
13376 static bfd_boolean
13377 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
13378 {
13379   /* Those that are not vtables.  */
13380   if (h->start_stop
13381       || h->u2.vtable == NULL
13382       || h->u2.vtable->parent == NULL)
13383     return TRUE;
13384
13385   /* Those vtables that do not have parents, we cannot merge.  */
13386   if (h->u2.vtable->parent == (struct elf_link_hash_entry *) -1)
13387     return TRUE;
13388
13389   /* If we've already been done, exit.  */
13390   if (h->u2.vtable->used && h->u2.vtable->used[-1])
13391     return TRUE;
13392
13393   /* Make sure the parent's table is up to date.  */
13394   elf_gc_propagate_vtable_entries_used (h->u2.vtable->parent, okp);
13395
13396   if (h->u2.vtable->used == NULL)
13397     {
13398       /* None of this table's entries were referenced.  Re-use the
13399          parent's table.  */
13400       h->u2.vtable->used = h->u2.vtable->parent->u2.vtable->used;
13401       h->u2.vtable->size = h->u2.vtable->parent->u2.vtable->size;
13402     }
13403   else
13404     {
13405       size_t n;
13406       bfd_boolean *cu, *pu;
13407
13408       /* Or the parent's entries into ours.  */
13409       cu = h->u2.vtable->used;
13410       cu[-1] = TRUE;
13411       pu = h->u2.vtable->parent->u2.vtable->used;
13412       if (pu != NULL)
13413         {
13414           const struct elf_backend_data *bed;
13415           unsigned int log_file_align;
13416
13417           bed = get_elf_backend_data (h->root.u.def.section->owner);
13418           log_file_align = bed->s->log_file_align;
13419           n = h->u2.vtable->parent->u2.vtable->size >> log_file_align;
13420           while (n--)
13421             {
13422               if (*pu)
13423                 *cu = TRUE;
13424               pu++;
13425               cu++;
13426             }
13427         }
13428     }
13429
13430   return TRUE;
13431 }
13432
13433 static bfd_boolean
13434 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
13435 {
13436   asection *sec;
13437   bfd_vma hstart, hend;
13438   Elf_Internal_Rela *relstart, *relend, *rel;
13439   const struct elf_backend_data *bed;
13440   unsigned int log_file_align;
13441
13442   /* Take care of both those symbols that do not describe vtables as
13443      well as those that are not loaded.  */
13444   if (h->start_stop
13445       || h->u2.vtable == NULL
13446       || h->u2.vtable->parent == NULL)
13447     return TRUE;
13448
13449   BFD_ASSERT (h->root.type == bfd_link_hash_defined
13450               || h->root.type == bfd_link_hash_defweak);
13451
13452   sec = h->root.u.def.section;
13453   hstart = h->root.u.def.value;
13454   hend = hstart + h->size;
13455
13456   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
13457   if (!relstart)
13458     return *(bfd_boolean *) okp = FALSE;
13459   bed = get_elf_backend_data (sec->owner);
13460   log_file_align = bed->s->log_file_align;
13461
13462   relend = relstart + sec->reloc_count;
13463
13464   for (rel = relstart; rel < relend; ++rel)
13465     if (rel->r_offset >= hstart && rel->r_offset < hend)
13466       {
13467         /* If the entry is in use, do nothing.  */
13468         if (h->u2.vtable->used
13469             && (rel->r_offset - hstart) < h->u2.vtable->size)
13470           {
13471             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
13472             if (h->u2.vtable->used[entry])
13473               continue;
13474           }
13475         /* Otherwise, kill it.  */
13476         rel->r_offset = rel->r_info = rel->r_addend = 0;
13477       }
13478
13479   return TRUE;
13480 }
13481
13482 /* Mark sections containing dynamically referenced symbols.  When
13483    building shared libraries, we must assume that any visible symbol is
13484    referenced.  */
13485
13486 bfd_boolean
13487 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
13488 {
13489   struct bfd_link_info *info = (struct bfd_link_info *) inf;
13490   struct bfd_elf_dynamic_list *d = info->dynamic_list;
13491
13492   if ((h->root.type == bfd_link_hash_defined
13493        || h->root.type == bfd_link_hash_defweak)
13494       && ((h->ref_dynamic && !h->forced_local)
13495           || ((h->def_regular || ELF_COMMON_DEF_P (h))
13496               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
13497               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
13498               && (!bfd_link_executable (info)
13499                   || info->gc_keep_exported
13500                   || info->export_dynamic
13501                   || (h->dynamic
13502                       && d != NULL
13503                       && (*d->match) (&d->head, NULL, h->root.root.string)))
13504               && (h->versioned >= versioned
13505                   || !bfd_hide_sym_by_version (info->version_info,
13506                                                h->root.root.string)))))
13507     h->root.u.def.section->flags |= SEC_KEEP;
13508
13509   return TRUE;
13510 }
13511
13512 /* Keep all sections containing symbols undefined on the command-line,
13513    and the section containing the entry symbol.  */
13514
13515 void
13516 _bfd_elf_gc_keep (struct bfd_link_info *info)
13517 {
13518   struct bfd_sym_chain *sym;
13519
13520   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
13521     {
13522       struct elf_link_hash_entry *h;
13523
13524       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
13525                                 FALSE, FALSE, FALSE);
13526
13527       if (h != NULL
13528           && (h->root.type == bfd_link_hash_defined
13529               || h->root.type == bfd_link_hash_defweak)
13530           && !bfd_is_abs_section (h->root.u.def.section)
13531           && !bfd_is_und_section (h->root.u.def.section))
13532         h->root.u.def.section->flags |= SEC_KEEP;
13533     }
13534 }
13535
13536 bfd_boolean
13537 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
13538                                 struct bfd_link_info *info)
13539 {
13540   bfd *ibfd = info->input_bfds;
13541
13542   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13543     {
13544       asection *sec;
13545       struct elf_reloc_cookie cookie;
13546
13547       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13548         continue;
13549       sec = ibfd->sections;
13550       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13551         continue;
13552
13553       if (!init_reloc_cookie (&cookie, info, ibfd))
13554         return FALSE;
13555
13556       for (sec = ibfd->sections; sec; sec = sec->next)
13557         {
13558           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
13559               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
13560             {
13561               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
13562               fini_reloc_cookie_rels (&cookie, sec);
13563             }
13564         }
13565     }
13566   return TRUE;
13567 }
13568
13569 /* Do mark and sweep of unused sections.  */
13570
13571 bfd_boolean
13572 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
13573 {
13574   bfd_boolean ok = TRUE;
13575   bfd *sub;
13576   elf_gc_mark_hook_fn gc_mark_hook;
13577   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13578   struct elf_link_hash_table *htab;
13579
13580   if (!bed->can_gc_sections
13581       || !is_elf_hash_table (info->hash))
13582     {
13583       _bfd_error_handler(_("warning: gc-sections option ignored"));
13584       return TRUE;
13585     }
13586
13587   bed->gc_keep (info);
13588   htab = elf_hash_table (info);
13589
13590   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
13591      at the .eh_frame section if we can mark the FDEs individually.  */
13592   for (sub = info->input_bfds;
13593        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
13594        sub = sub->link.next)
13595     {
13596       asection *sec;
13597       struct elf_reloc_cookie cookie;
13598
13599       sec = sub->sections;
13600       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13601         continue;
13602       sec = bfd_get_section_by_name (sub, ".eh_frame");
13603       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
13604         {
13605           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
13606           if (elf_section_data (sec)->sec_info
13607               && (sec->flags & SEC_LINKER_CREATED) == 0)
13608             elf_eh_frame_section (sub) = sec;
13609           fini_reloc_cookie_for_section (&cookie, sec);
13610           sec = bfd_get_next_section_by_name (NULL, sec);
13611         }
13612     }
13613
13614   /* Apply transitive closure to the vtable entry usage info.  */
13615   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
13616   if (!ok)
13617     return FALSE;
13618
13619   /* Kill the vtable relocations that were not used.  */
13620   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
13621   if (!ok)
13622     return FALSE;
13623
13624   /* Mark dynamically referenced symbols.  */
13625   if (htab->dynamic_sections_created || info->gc_keep_exported)
13626     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
13627
13628   /* Grovel through relocs to find out who stays ...  */
13629   gc_mark_hook = bed->gc_mark_hook;
13630   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13631     {
13632       asection *o;
13633
13634       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13635           || elf_object_id (sub) != elf_hash_table_id (htab)
13636           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13637         continue;
13638
13639       o = sub->sections;
13640       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13641         continue;
13642
13643       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
13644          Also treat note sections as a root, if the section is not part
13645          of a group.  We must keep all PREINIT_ARRAY, INIT_ARRAY as
13646          well as FINI_ARRAY sections for ld -r.  */
13647       for (o = sub->sections; o != NULL; o = o->next)
13648         if (!o->gc_mark
13649             && (o->flags & SEC_EXCLUDE) == 0
13650             && ((o->flags & SEC_KEEP) != 0
13651                 || (bfd_link_relocatable (info)
13652                     && ((elf_section_data (o)->this_hdr.sh_type
13653                          == SHT_PREINIT_ARRAY)
13654                         || (elf_section_data (o)->this_hdr.sh_type
13655                             == SHT_INIT_ARRAY)
13656                         || (elf_section_data (o)->this_hdr.sh_type
13657                             == SHT_FINI_ARRAY)))
13658                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
13659                     && elf_next_in_group (o) == NULL )))
13660           {
13661             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
13662               return FALSE;
13663           }
13664     }
13665
13666   /* Allow the backend to mark additional target specific sections.  */
13667   bed->gc_mark_extra_sections (info, gc_mark_hook);
13668
13669   /* ... and mark SEC_EXCLUDE for those that go.  */
13670   return elf_gc_sweep (abfd, info);
13671 }
13672 \f
13673 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
13674
13675 bfd_boolean
13676 bfd_elf_gc_record_vtinherit (bfd *abfd,
13677                              asection *sec,
13678                              struct elf_link_hash_entry *h,
13679                              bfd_vma offset)
13680 {
13681   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
13682   struct elf_link_hash_entry **search, *child;
13683   size_t extsymcount;
13684   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13685
13686   /* The sh_info field of the symtab header tells us where the
13687      external symbols start.  We don't care about the local symbols at
13688      this point.  */
13689   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
13690   if (!elf_bad_symtab (abfd))
13691     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
13692
13693   sym_hashes = elf_sym_hashes (abfd);
13694   sym_hashes_end = sym_hashes + extsymcount;
13695
13696   /* Hunt down the child symbol, which is in this section at the same
13697      offset as the relocation.  */
13698   for (search = sym_hashes; search != sym_hashes_end; ++search)
13699     {
13700       if ((child = *search) != NULL
13701           && (child->root.type == bfd_link_hash_defined
13702               || child->root.type == bfd_link_hash_defweak)
13703           && child->root.u.def.section == sec
13704           && child->root.u.def.value == offset)
13705         goto win;
13706     }
13707
13708   /* xgettext:c-format */
13709   _bfd_error_handler (_("%pB: %pA+%#" PRIx64 ": no symbol found for INHERIT"),
13710                       abfd, sec, (uint64_t) offset);
13711   bfd_set_error (bfd_error_invalid_operation);
13712   return FALSE;
13713
13714  win:
13715   if (!child->u2.vtable)
13716     {
13717       child->u2.vtable = ((struct elf_link_virtual_table_entry *)
13718                           bfd_zalloc (abfd, sizeof (*child->u2.vtable)));
13719       if (!child->u2.vtable)
13720         return FALSE;
13721     }
13722   if (!h)
13723     {
13724       /* This *should* only be the absolute section.  It could potentially
13725          be that someone has defined a non-global vtable though, which
13726          would be bad.  It isn't worth paging in the local symbols to be
13727          sure though; that case should simply be handled by the assembler.  */
13728
13729       child->u2.vtable->parent = (struct elf_link_hash_entry *) -1;
13730     }
13731   else
13732     child->u2.vtable->parent = h;
13733
13734   return TRUE;
13735 }
13736
13737 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
13738
13739 bfd_boolean
13740 bfd_elf_gc_record_vtentry (bfd *abfd, asection *sec,
13741                            struct elf_link_hash_entry *h,
13742                            bfd_vma addend)
13743 {
13744   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13745   unsigned int log_file_align = bed->s->log_file_align;
13746
13747   if (!h)
13748     {
13749       /* xgettext:c-format */
13750       _bfd_error_handler (_("%pB: section '%pA': corrupt VTENTRY entry"),
13751                           abfd, sec);
13752       bfd_set_error (bfd_error_bad_value);
13753       return FALSE;
13754     }
13755
13756   if (!h->u2.vtable)
13757     {
13758       h->u2.vtable = ((struct elf_link_virtual_table_entry *)
13759                       bfd_zalloc (abfd, sizeof (*h->u2.vtable)));
13760       if (!h->u2.vtable)
13761         return FALSE;
13762     }
13763
13764   if (addend >= h->u2.vtable->size)
13765     {
13766       size_t size, bytes, file_align;
13767       bfd_boolean *ptr = h->u2.vtable->used;
13768
13769       /* While the symbol is undefined, we have to be prepared to handle
13770          a zero size.  */
13771       file_align = 1 << log_file_align;
13772       if (h->root.type == bfd_link_hash_undefined)
13773         size = addend + file_align;
13774       else
13775         {
13776           size = h->size;
13777           if (addend >= size)
13778             {
13779               /* Oops!  We've got a reference past the defined end of
13780                  the table.  This is probably a bug -- shall we warn?  */
13781               size = addend + file_align;
13782             }
13783         }
13784       size = (size + file_align - 1) & -file_align;
13785
13786       /* Allocate one extra entry for use as a "done" flag for the
13787          consolidation pass.  */
13788       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
13789
13790       if (ptr)
13791         {
13792           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
13793
13794           if (ptr != NULL)
13795             {
13796               size_t oldbytes;
13797
13798               oldbytes = (((h->u2.vtable->size >> log_file_align) + 1)
13799                           * sizeof (bfd_boolean));
13800               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
13801             }
13802         }
13803       else
13804         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
13805
13806       if (ptr == NULL)
13807         return FALSE;
13808
13809       /* And arrange for that done flag to be at index -1.  */
13810       h->u2.vtable->used = ptr + 1;
13811       h->u2.vtable->size = size;
13812     }
13813
13814   h->u2.vtable->used[addend >> log_file_align] = TRUE;
13815
13816   return TRUE;
13817 }
13818
13819 /* Map an ELF section header flag to its corresponding string.  */
13820 typedef struct
13821 {
13822   char *flag_name;
13823   flagword flag_value;
13824 } elf_flags_to_name_table;
13825
13826 static elf_flags_to_name_table elf_flags_to_names [] =
13827 {
13828   { "SHF_WRITE", SHF_WRITE },
13829   { "SHF_ALLOC", SHF_ALLOC },
13830   { "SHF_EXECINSTR", SHF_EXECINSTR },
13831   { "SHF_MERGE", SHF_MERGE },
13832   { "SHF_STRINGS", SHF_STRINGS },
13833   { "SHF_INFO_LINK", SHF_INFO_LINK},
13834   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
13835   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
13836   { "SHF_GROUP", SHF_GROUP },
13837   { "SHF_TLS", SHF_TLS },
13838   { "SHF_MASKOS", SHF_MASKOS },
13839   { "SHF_EXCLUDE", SHF_EXCLUDE },
13840 };
13841
13842 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
13843 bfd_boolean
13844 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
13845                               struct flag_info *flaginfo,
13846                               asection *section)
13847 {
13848   const bfd_vma sh_flags = elf_section_flags (section);
13849
13850   if (!flaginfo->flags_initialized)
13851     {
13852       bfd *obfd = info->output_bfd;
13853       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13854       struct flag_info_list *tf = flaginfo->flag_list;
13855       int with_hex = 0;
13856       int without_hex = 0;
13857
13858       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
13859         {
13860           unsigned i;
13861           flagword (*lookup) (char *);
13862
13863           lookup = bed->elf_backend_lookup_section_flags_hook;
13864           if (lookup != NULL)
13865             {
13866               flagword hexval = (*lookup) ((char *) tf->name);
13867
13868               if (hexval != 0)
13869                 {
13870                   if (tf->with == with_flags)
13871                     with_hex |= hexval;
13872                   else if (tf->with == without_flags)
13873                     without_hex |= hexval;
13874                   tf->valid = TRUE;
13875                   continue;
13876                 }
13877             }
13878           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
13879             {
13880               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
13881                 {
13882                   if (tf->with == with_flags)
13883                     with_hex |= elf_flags_to_names[i].flag_value;
13884                   else if (tf->with == without_flags)
13885                     without_hex |= elf_flags_to_names[i].flag_value;
13886                   tf->valid = TRUE;
13887                   break;
13888                 }
13889             }
13890           if (!tf->valid)
13891             {
13892               info->callbacks->einfo
13893                 (_("unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
13894               return FALSE;
13895             }
13896         }
13897       flaginfo->flags_initialized = TRUE;
13898       flaginfo->only_with_flags |= with_hex;
13899       flaginfo->not_with_flags |= without_hex;
13900     }
13901
13902   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
13903     return FALSE;
13904
13905   if ((flaginfo->not_with_flags & sh_flags) != 0)
13906     return FALSE;
13907
13908   return TRUE;
13909 }
13910
13911 struct alloc_got_off_arg {
13912   bfd_vma gotoff;
13913   struct bfd_link_info *info;
13914 };
13915
13916 /* We need a special top-level link routine to convert got reference counts
13917    to real got offsets.  */
13918
13919 static bfd_boolean
13920 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
13921 {
13922   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
13923   bfd *obfd = gofarg->info->output_bfd;
13924   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13925
13926   if (h->got.refcount > 0)
13927     {
13928       h->got.offset = gofarg->gotoff;
13929       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
13930     }
13931   else
13932     h->got.offset = (bfd_vma) -1;
13933
13934   return TRUE;
13935 }
13936
13937 /* And an accompanying bit to work out final got entry offsets once
13938    we're done.  Should be called from final_link.  */
13939
13940 bfd_boolean
13941 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
13942                                         struct bfd_link_info *info)
13943 {
13944   bfd *i;
13945   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13946   bfd_vma gotoff;
13947   struct alloc_got_off_arg gofarg;
13948
13949   BFD_ASSERT (abfd == info->output_bfd);
13950
13951   if (! is_elf_hash_table (info->hash))
13952     return FALSE;
13953
13954   /* The GOT offset is relative to the .got section, but the GOT header is
13955      put into the .got.plt section, if the backend uses it.  */
13956   if (bed->want_got_plt)
13957     gotoff = 0;
13958   else
13959     gotoff = bed->got_header_size;
13960
13961   /* Do the local .got entries first.  */
13962   for (i = info->input_bfds; i; i = i->link.next)
13963     {
13964       bfd_signed_vma *local_got;
13965       size_t j, locsymcount;
13966       Elf_Internal_Shdr *symtab_hdr;
13967
13968       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13969         continue;
13970
13971       local_got = elf_local_got_refcounts (i);
13972       if (!local_got)
13973         continue;
13974
13975       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13976       if (elf_bad_symtab (i))
13977         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13978       else
13979         locsymcount = symtab_hdr->sh_info;
13980
13981       for (j = 0; j < locsymcount; ++j)
13982         {
13983           if (local_got[j] > 0)
13984             {
13985               local_got[j] = gotoff;
13986               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13987             }
13988           else
13989             local_got[j] = (bfd_vma) -1;
13990         }
13991     }
13992
13993   /* Then the global .got entries.  .plt refcounts are handled by
13994      adjust_dynamic_symbol  */
13995   gofarg.gotoff = gotoff;
13996   gofarg.info = info;
13997   elf_link_hash_traverse (elf_hash_table (info),
13998                           elf_gc_allocate_got_offsets,
13999                           &gofarg);
14000   return TRUE;
14001 }
14002
14003 /* Many folk need no more in the way of final link than this, once
14004    got entry reference counting is enabled.  */
14005
14006 bfd_boolean
14007 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
14008 {
14009   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
14010     return FALSE;
14011
14012   /* Invoke the regular ELF backend linker to do all the work.  */
14013   return bfd_elf_final_link (abfd, info);
14014 }
14015
14016 bfd_boolean
14017 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
14018 {
14019   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
14020
14021   if (rcookie->bad_symtab)
14022     rcookie->rel = rcookie->rels;
14023
14024   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
14025     {
14026       unsigned long r_symndx;
14027
14028       if (! rcookie->bad_symtab)
14029         if (rcookie->rel->r_offset > offset)
14030           return FALSE;
14031       if (rcookie->rel->r_offset != offset)
14032         continue;
14033
14034       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
14035       if (r_symndx == STN_UNDEF)
14036         return TRUE;
14037
14038       if (r_symndx >= rcookie->locsymcount
14039           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
14040         {
14041           struct elf_link_hash_entry *h;
14042
14043           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
14044
14045           while (h->root.type == bfd_link_hash_indirect
14046                  || h->root.type == bfd_link_hash_warning)
14047             h = (struct elf_link_hash_entry *) h->root.u.i.link;
14048
14049           if ((h->root.type == bfd_link_hash_defined
14050                || h->root.type == bfd_link_hash_defweak)
14051               && (h->root.u.def.section->owner != rcookie->abfd
14052                   || h->root.u.def.section->kept_section != NULL
14053                   || discarded_section (h->root.u.def.section)))
14054             return TRUE;
14055         }
14056       else
14057         {
14058           /* It's not a relocation against a global symbol,
14059              but it could be a relocation against a local
14060              symbol for a discarded section.  */
14061           asection *isec;
14062           Elf_Internal_Sym *isym;
14063
14064           /* Need to: get the symbol; get the section.  */
14065           isym = &rcookie->locsyms[r_symndx];
14066           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
14067           if (isec != NULL
14068               && (isec->kept_section != NULL
14069                   || discarded_section (isec)))
14070             return TRUE;
14071         }
14072       return FALSE;
14073     }
14074   return FALSE;
14075 }
14076
14077 /* Discard unneeded references to discarded sections.
14078    Returns -1 on error, 1 if any section's size was changed, 0 if
14079    nothing changed.  This function assumes that the relocations are in
14080    sorted order, which is true for all known assemblers.  */
14081
14082 int
14083 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
14084 {
14085   struct elf_reloc_cookie cookie;
14086   asection *o;
14087   bfd *abfd;
14088   int changed = 0;
14089
14090   if (info->traditional_format
14091       || !is_elf_hash_table (info->hash))
14092     return 0;
14093
14094   o = bfd_get_section_by_name (output_bfd, ".stab");
14095   if (o != NULL)
14096     {
14097       asection *i;
14098
14099       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
14100         {
14101           if (i->size == 0
14102               || i->reloc_count == 0
14103               || i->sec_info_type != SEC_INFO_TYPE_STABS)
14104             continue;
14105
14106           abfd = i->owner;
14107           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
14108             continue;
14109
14110           if (!init_reloc_cookie_for_section (&cookie, info, i))
14111             return -1;
14112
14113           if (_bfd_discard_section_stabs (abfd, i,
14114                                           elf_section_data (i)->sec_info,
14115                                           bfd_elf_reloc_symbol_deleted_p,
14116                                           &cookie))
14117             changed = 1;
14118
14119           fini_reloc_cookie_for_section (&cookie, i);
14120         }
14121     }
14122
14123   o = NULL;
14124   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
14125     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
14126   if (o != NULL)
14127     {
14128       asection *i;
14129       int eh_changed = 0;
14130       unsigned int eh_alignment;
14131
14132       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
14133         {
14134           if (i->size == 0)
14135             continue;
14136
14137           abfd = i->owner;
14138           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
14139             continue;
14140
14141           if (!init_reloc_cookie_for_section (&cookie, info, i))
14142             return -1;
14143
14144           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
14145           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
14146                                                  bfd_elf_reloc_symbol_deleted_p,
14147                                                  &cookie))
14148             {
14149               eh_changed = 1;
14150               if (i->size != i->rawsize)
14151                 changed = 1;
14152             }
14153
14154           fini_reloc_cookie_for_section (&cookie, i);
14155         }
14156
14157       eh_alignment = 1 << o->alignment_power;
14158       /* Skip over zero terminator, and prevent empty sections from
14159          adding alignment padding at the end.  */
14160       for (i = o->map_tail.s; i != NULL; i = i->map_tail.s)
14161         if (i->size == 0)
14162           i->flags |= SEC_EXCLUDE;
14163         else if (i->size > 4)
14164           break;
14165       /* The last non-empty eh_frame section doesn't need padding.  */
14166       if (i != NULL)
14167         i = i->map_tail.s;
14168       /* Any prior sections must pad the last FDE out to the output
14169          section alignment.  Otherwise we might have zero padding
14170          between sections, which would be seen as a terminator.  */
14171       for (; i != NULL; i = i->map_tail.s)
14172         if (i->size == 4)
14173           /* All but the last zero terminator should have been removed.  */
14174           BFD_FAIL ();
14175         else
14176           {
14177             bfd_size_type size
14178               = (i->size + eh_alignment - 1) & -eh_alignment;
14179             if (i->size != size)
14180               {
14181                 i->size = size;
14182                 changed = 1;
14183                 eh_changed = 1;
14184               }
14185           }
14186       if (eh_changed)
14187         elf_link_hash_traverse (elf_hash_table (info),
14188                                 _bfd_elf_adjust_eh_frame_global_symbol, NULL);
14189     }
14190
14191   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
14192     {
14193       const struct elf_backend_data *bed;
14194       asection *s;
14195
14196       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
14197         continue;
14198       s = abfd->sections;
14199       if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
14200         continue;
14201
14202       bed = get_elf_backend_data (abfd);
14203
14204       if (bed->elf_backend_discard_info != NULL)
14205         {
14206           if (!init_reloc_cookie (&cookie, info, abfd))
14207             return -1;
14208
14209           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
14210             changed = 1;
14211
14212           fini_reloc_cookie (&cookie, abfd);
14213         }
14214     }
14215
14216   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
14217     _bfd_elf_end_eh_frame_parsing (info);
14218
14219   if (info->eh_frame_hdr_type
14220       && !bfd_link_relocatable (info)
14221       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
14222     changed = 1;
14223
14224   return changed;
14225 }
14226
14227 bfd_boolean
14228 _bfd_elf_section_already_linked (bfd *abfd,
14229                                  asection *sec,
14230                                  struct bfd_link_info *info)
14231 {
14232   flagword flags;
14233   const char *name, *key;
14234   struct bfd_section_already_linked *l;
14235   struct bfd_section_already_linked_hash_entry *already_linked_list;
14236
14237   if (sec->output_section == bfd_abs_section_ptr)
14238     return FALSE;
14239
14240   flags = sec->flags;
14241
14242   /* Return if it isn't a linkonce section.  A comdat group section
14243      also has SEC_LINK_ONCE set.  */
14244   if ((flags & SEC_LINK_ONCE) == 0)
14245     return FALSE;
14246
14247   /* Don't put group member sections on our list of already linked
14248      sections.  They are handled as a group via their group section.  */
14249   if (elf_sec_group (sec) != NULL)
14250     return FALSE;
14251
14252   /* For a SHT_GROUP section, use the group signature as the key.  */
14253   name = sec->name;
14254   if ((flags & SEC_GROUP) != 0
14255       && elf_next_in_group (sec) != NULL
14256       && elf_group_name (elf_next_in_group (sec)) != NULL)
14257     key = elf_group_name (elf_next_in_group (sec));
14258   else
14259     {
14260       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
14261       if (CONST_STRNEQ (name, ".gnu.linkonce.")
14262           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
14263         key++;
14264       else
14265         /* Must be a user linkonce section that doesn't follow gcc's
14266            naming convention.  In this case we won't be matching
14267            single member groups.  */
14268         key = name;
14269     }
14270
14271   already_linked_list = bfd_section_already_linked_table_lookup (key);
14272
14273   for (l = already_linked_list->entry; l != NULL; l = l->next)
14274     {
14275       /* We may have 2 different types of sections on the list: group
14276          sections with a signature of <key> (<key> is some string),
14277          and linkonce sections named .gnu.linkonce.<type>.<key>.
14278          Match like sections.  LTO plugin sections are an exception.
14279          They are always named .gnu.linkonce.t.<key> and match either
14280          type of section.  */
14281       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
14282            && ((flags & SEC_GROUP) != 0
14283                || strcmp (name, l->sec->name) == 0))
14284           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
14285         {
14286           /* The section has already been linked.  See if we should
14287              issue a warning.  */
14288           if (!_bfd_handle_already_linked (sec, l, info))
14289             return FALSE;
14290
14291           if (flags & SEC_GROUP)
14292             {
14293               asection *first = elf_next_in_group (sec);
14294               asection *s = first;
14295
14296               while (s != NULL)
14297                 {
14298                   s->output_section = bfd_abs_section_ptr;
14299                   /* Record which group discards it.  */
14300                   s->kept_section = l->sec;
14301                   s = elf_next_in_group (s);
14302                   /* These lists are circular.  */
14303                   if (s == first)
14304                     break;
14305                 }
14306             }
14307
14308           return TRUE;
14309         }
14310     }
14311
14312   /* A single member comdat group section may be discarded by a
14313      linkonce section and vice versa.  */
14314   if ((flags & SEC_GROUP) != 0)
14315     {
14316       asection *first = elf_next_in_group (sec);
14317
14318       if (first != NULL && elf_next_in_group (first) == first)
14319         /* Check this single member group against linkonce sections.  */
14320         for (l = already_linked_list->entry; l != NULL; l = l->next)
14321           if ((l->sec->flags & SEC_GROUP) == 0
14322               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
14323             {
14324               first->output_section = bfd_abs_section_ptr;
14325               first->kept_section = l->sec;
14326               sec->output_section = bfd_abs_section_ptr;
14327               break;
14328             }
14329     }
14330   else
14331     /* Check this linkonce section against single member groups.  */
14332     for (l = already_linked_list->entry; l != NULL; l = l->next)
14333       if (l->sec->flags & SEC_GROUP)
14334         {
14335           asection *first = elf_next_in_group (l->sec);
14336
14337           if (first != NULL
14338               && elf_next_in_group (first) == first
14339               && bfd_elf_match_symbols_in_sections (first, sec, info))
14340             {
14341               sec->output_section = bfd_abs_section_ptr;
14342               sec->kept_section = first;
14343               break;
14344             }
14345         }
14346
14347   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
14348      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
14349      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
14350      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
14351      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
14352      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
14353      `.gnu.linkonce.t.F' section from a different bfd not requiring any
14354      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
14355      The reverse order cannot happen as there is never a bfd with only the
14356      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
14357      matter as here were are looking only for cross-bfd sections.  */
14358
14359   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
14360     for (l = already_linked_list->entry; l != NULL; l = l->next)
14361       if ((l->sec->flags & SEC_GROUP) == 0
14362           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
14363         {
14364           if (abfd != l->sec->owner)
14365             sec->output_section = bfd_abs_section_ptr;
14366           break;
14367         }
14368
14369   /* This is the first section with this name.  Record it.  */
14370   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
14371     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
14372   return sec->output_section == bfd_abs_section_ptr;
14373 }
14374
14375 bfd_boolean
14376 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
14377 {
14378   return sym->st_shndx == SHN_COMMON;
14379 }
14380
14381 unsigned int
14382 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
14383 {
14384   return SHN_COMMON;
14385 }
14386
14387 asection *
14388 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
14389 {
14390   return bfd_com_section_ptr;
14391 }
14392
14393 bfd_vma
14394 _bfd_elf_default_got_elt_size (bfd *abfd,
14395                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
14396                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
14397                                bfd *ibfd ATTRIBUTE_UNUSED,
14398                                unsigned long symndx ATTRIBUTE_UNUSED)
14399 {
14400   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14401   return bed->s->arch_size / 8;
14402 }
14403
14404 /* Routines to support the creation of dynamic relocs.  */
14405
14406 /* Returns the name of the dynamic reloc section associated with SEC.  */
14407
14408 static const char *
14409 get_dynamic_reloc_section_name (bfd *       abfd,
14410                                 asection *  sec,
14411                                 bfd_boolean is_rela)
14412 {
14413   char *name;
14414   const char *old_name = bfd_get_section_name (NULL, sec);
14415   const char *prefix = is_rela ? ".rela" : ".rel";
14416
14417   if (old_name == NULL)
14418     return NULL;
14419
14420   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
14421   sprintf (name, "%s%s", prefix, old_name);
14422
14423   return name;
14424 }
14425
14426 /* Returns the dynamic reloc section associated with SEC.
14427    If necessary compute the name of the dynamic reloc section based
14428    on SEC's name (looked up in ABFD's string table) and the setting
14429    of IS_RELA.  */
14430
14431 asection *
14432 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
14433                                     asection *  sec,
14434                                     bfd_boolean is_rela)
14435 {
14436   asection * reloc_sec = elf_section_data (sec)->sreloc;
14437
14438   if (reloc_sec == NULL)
14439     {
14440       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14441
14442       if (name != NULL)
14443         {
14444           reloc_sec = bfd_get_linker_section (abfd, name);
14445
14446           if (reloc_sec != NULL)
14447             elf_section_data (sec)->sreloc = reloc_sec;
14448         }
14449     }
14450
14451   return reloc_sec;
14452 }
14453
14454 /* Returns the dynamic reloc section associated with SEC.  If the
14455    section does not exist it is created and attached to the DYNOBJ
14456    bfd and stored in the SRELOC field of SEC's elf_section_data
14457    structure.
14458
14459    ALIGNMENT is the alignment for the newly created section and
14460    IS_RELA defines whether the name should be .rela.<SEC's name>
14461    or .rel.<SEC's name>.  The section name is looked up in the
14462    string table associated with ABFD.  */
14463
14464 asection *
14465 _bfd_elf_make_dynamic_reloc_section (asection *sec,
14466                                      bfd *dynobj,
14467                                      unsigned int alignment,
14468                                      bfd *abfd,
14469                                      bfd_boolean is_rela)
14470 {
14471   asection * reloc_sec = elf_section_data (sec)->sreloc;
14472
14473   if (reloc_sec == NULL)
14474     {
14475       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14476
14477       if (name == NULL)
14478         return NULL;
14479
14480       reloc_sec = bfd_get_linker_section (dynobj, name);
14481
14482       if (reloc_sec == NULL)
14483         {
14484           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
14485                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
14486           if ((sec->flags & SEC_ALLOC) != 0)
14487             flags |= SEC_ALLOC | SEC_LOAD;
14488
14489           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
14490           if (reloc_sec != NULL)
14491             {
14492               /* _bfd_elf_get_sec_type_attr chooses a section type by
14493                  name.  Override as it may be wrong, eg. for a user
14494                  section named "auto" we'll get ".relauto" which is
14495                  seen to be a .rela section.  */
14496               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
14497               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
14498                 reloc_sec = NULL;
14499             }
14500         }
14501
14502       elf_section_data (sec)->sreloc = reloc_sec;
14503     }
14504
14505   return reloc_sec;
14506 }
14507
14508 /* Copy the ELF symbol type and other attributes for a linker script
14509    assignment from HSRC to HDEST.  Generally this should be treated as
14510    if we found a strong non-dynamic definition for HDEST (except that
14511    ld ignores multiple definition errors).  */
14512 void
14513 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
14514                                      struct bfd_link_hash_entry *hdest,
14515                                      struct bfd_link_hash_entry *hsrc)
14516 {
14517   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
14518   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
14519   Elf_Internal_Sym isym;
14520
14521   ehdest->type = ehsrc->type;
14522   ehdest->target_internal = ehsrc->target_internal;
14523
14524   isym.st_other = ehsrc->other;
14525   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
14526 }
14527
14528 /* Append a RELA relocation REL to section S in BFD.  */
14529
14530 void
14531 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14532 {
14533   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14534   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
14535   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
14536   bed->s->swap_reloca_out (abfd, rel, loc);
14537 }
14538
14539 /* Append a REL relocation REL to section S in BFD.  */
14540
14541 void
14542 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14543 {
14544   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14545   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
14546   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
14547   bed->s->swap_reloc_out (abfd, rel, loc);
14548 }
14549
14550 /* Define __start, __stop, .startof. or .sizeof. symbol.  */
14551
14552 struct bfd_link_hash_entry *
14553 bfd_elf_define_start_stop (struct bfd_link_info *info,
14554                            const char *symbol, asection *sec)
14555 {
14556   struct elf_link_hash_entry *h;
14557
14558   h = elf_link_hash_lookup (elf_hash_table (info), symbol,
14559                             FALSE, FALSE, TRUE);
14560   if (h != NULL
14561       && (h->root.type == bfd_link_hash_undefined
14562           || h->root.type == bfd_link_hash_undefweak
14563           || ((h->ref_regular || h->def_dynamic) && !h->def_regular)))
14564     {
14565       bfd_boolean was_dynamic = h->ref_dynamic || h->def_dynamic;
14566       h->root.type = bfd_link_hash_defined;
14567       h->root.u.def.section = sec;
14568       h->root.u.def.value = 0;
14569       h->def_regular = 1;
14570       h->def_dynamic = 0;
14571       h->start_stop = 1;
14572       h->u2.start_stop_section = sec;
14573       if (symbol[0] == '.')
14574         {
14575           /* .startof. and .sizeof. symbols are local.  */
14576           const struct elf_backend_data *bed;
14577           bed = get_elf_backend_data (info->output_bfd);
14578           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
14579         }
14580       else
14581         {
14582           if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
14583             h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_PROTECTED;
14584           if (was_dynamic)
14585             bfd_elf_link_record_dynamic_symbol (info, h);
14586         }
14587       return &h->root;
14588     }
14589   return NULL;
14590 }