%L conversions
[external/binutils.git] / bfd / elflink.c
1 /* ELF linking support for BFD.
2    Copyright (C) 1995-2018 Free Software Foundation, Inc.
3
4    This file is part of BFD, the Binary File Descriptor library.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
19    MA 02110-1301, USA.  */
20
21 #include "sysdep.h"
22 #include "bfd.h"
23 #include "bfd_stdint.h"
24 #include "bfdlink.h"
25 #include "libbfd.h"
26 #define ARCH_SIZE 0
27 #include "elf-bfd.h"
28 #include "safe-ctype.h"
29 #include "libiberty.h"
30 #include "objalloc.h"
31 #if BFD_SUPPORTS_PLUGINS
32 #include "plugin-api.h"
33 #include "plugin.h"
34 #endif
35
36 /* This struct is used to pass information to routines called via
37    elf_link_hash_traverse which must return failure.  */
38
39 struct elf_info_failed
40 {
41   struct bfd_link_info *info;
42   bfd_boolean failed;
43 };
44
45 /* This structure is used to pass information to
46    _bfd_elf_link_find_version_dependencies.  */
47
48 struct elf_find_verdep_info
49 {
50   /* General link information.  */
51   struct bfd_link_info *info;
52   /* The number of dependencies.  */
53   unsigned int vers;
54   /* Whether we had a failure.  */
55   bfd_boolean failed;
56 };
57
58 static bfd_boolean _bfd_elf_fix_symbol_flags
59   (struct elf_link_hash_entry *, struct elf_info_failed *);
60
61 asection *
62 _bfd_elf_section_for_symbol (struct elf_reloc_cookie *cookie,
63                              unsigned long r_symndx,
64                              bfd_boolean discard)
65 {
66   if (r_symndx >= cookie->locsymcount
67       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
68     {
69       struct elf_link_hash_entry *h;
70
71       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
72
73       while (h->root.type == bfd_link_hash_indirect
74              || h->root.type == bfd_link_hash_warning)
75         h = (struct elf_link_hash_entry *) h->root.u.i.link;
76
77       if ((h->root.type == bfd_link_hash_defined
78            || h->root.type == bfd_link_hash_defweak)
79            && discarded_section (h->root.u.def.section))
80         return h->root.u.def.section;
81       else
82         return NULL;
83     }
84   else
85     {
86       /* It's not a relocation against a global symbol,
87          but it could be a relocation against a local
88          symbol for a discarded section.  */
89       asection *isec;
90       Elf_Internal_Sym *isym;
91
92       /* Need to: get the symbol; get the section.  */
93       isym = &cookie->locsyms[r_symndx];
94       isec = bfd_section_from_elf_index (cookie->abfd, isym->st_shndx);
95       if (isec != NULL
96           && discard ? discarded_section (isec) : 1)
97         return isec;
98      }
99   return NULL;
100 }
101
102 /* Define a symbol in a dynamic linkage section.  */
103
104 struct elf_link_hash_entry *
105 _bfd_elf_define_linkage_sym (bfd *abfd,
106                              struct bfd_link_info *info,
107                              asection *sec,
108                              const char *name)
109 {
110   struct elf_link_hash_entry *h;
111   struct bfd_link_hash_entry *bh;
112   const struct elf_backend_data *bed;
113
114   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
115   if (h != NULL)
116     {
117       /* Zap symbol defined in an as-needed lib that wasn't linked.
118          This is a symptom of a larger problem:  Absolute symbols
119          defined in shared libraries can't be overridden, because we
120          lose the link to the bfd which is via the symbol section.  */
121       h->root.type = bfd_link_hash_new;
122       bh = &h->root;
123     }
124   else
125     bh = NULL;
126
127   bed = get_elf_backend_data (abfd);
128   if (!_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL,
129                                          sec, 0, NULL, FALSE, bed->collect,
130                                          &bh))
131     return NULL;
132   h = (struct elf_link_hash_entry *) bh;
133   BFD_ASSERT (h != NULL);
134   h->def_regular = 1;
135   h->non_elf = 0;
136   h->root.linker_def = 1;
137   h->type = STT_OBJECT;
138   if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
139     h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
140
141   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
142   return h;
143 }
144
145 bfd_boolean
146 _bfd_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
147 {
148   flagword flags;
149   asection *s;
150   struct elf_link_hash_entry *h;
151   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
152   struct elf_link_hash_table *htab = elf_hash_table (info);
153
154   /* This function may be called more than once.  */
155   if (htab->sgot != NULL)
156     return TRUE;
157
158   flags = bed->dynamic_sec_flags;
159
160   s = bfd_make_section_anyway_with_flags (abfd,
161                                           (bed->rela_plts_and_copies_p
162                                            ? ".rela.got" : ".rel.got"),
163                                           (bed->dynamic_sec_flags
164                                            | SEC_READONLY));
165   if (s == NULL
166       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
167     return FALSE;
168   htab->srelgot = s;
169
170   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
171   if (s == NULL
172       || !bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
173     return FALSE;
174   htab->sgot = s;
175
176   if (bed->want_got_plt)
177     {
178       s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
179       if (s == NULL
180           || !bfd_set_section_alignment (abfd, s,
181                                          bed->s->log_file_align))
182         return FALSE;
183       htab->sgotplt = s;
184     }
185
186   /* The first bit of the global offset table is the header.  */
187   s->size += bed->got_header_size;
188
189   if (bed->want_got_sym)
190     {
191       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
192          (or .got.plt) section.  We don't do this in the linker script
193          because we don't want to define the symbol if we are not creating
194          a global offset table.  */
195       h = _bfd_elf_define_linkage_sym (abfd, info, s,
196                                        "_GLOBAL_OFFSET_TABLE_");
197       elf_hash_table (info)->hgot = h;
198       if (h == NULL)
199         return FALSE;
200     }
201
202   return TRUE;
203 }
204 \f
205 /* Create a strtab to hold the dynamic symbol names.  */
206 static bfd_boolean
207 _bfd_elf_link_create_dynstrtab (bfd *abfd, struct bfd_link_info *info)
208 {
209   struct elf_link_hash_table *hash_table;
210
211   hash_table = elf_hash_table (info);
212   if (hash_table->dynobj == NULL)
213     {
214       /* We may not set dynobj, an input file holding linker created
215          dynamic sections to abfd, which may be a dynamic object with
216          its own dynamic sections.  We need to find a normal input file
217          to hold linker created sections if possible.  */
218       if ((abfd->flags & (DYNAMIC | BFD_PLUGIN)) != 0)
219         {
220           bfd *ibfd;
221           asection *s;
222           for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link.next)
223             if ((ibfd->flags
224                  & (DYNAMIC | BFD_LINKER_CREATED | BFD_PLUGIN)) == 0
225                 && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
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     h->dynamic = 1;
590 }
591
592 /* Record an assignment to a symbol made by a linker script.  We need
593    this in case some dynamic object refers to this symbol.  */
594
595 bfd_boolean
596 bfd_elf_record_link_assignment (bfd *output_bfd,
597                                 struct bfd_link_info *info,
598                                 const char *name,
599                                 bfd_boolean provide,
600                                 bfd_boolean hidden)
601 {
602   struct elf_link_hash_entry *h, *hv;
603   struct elf_link_hash_table *htab;
604   const struct elf_backend_data *bed;
605
606   if (!is_elf_hash_table (info->hash))
607     return TRUE;
608
609   htab = elf_hash_table (info);
610   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
611   if (h == NULL)
612     return provide;
613
614   if (h->root.type == bfd_link_hash_warning)
615     h = (struct elf_link_hash_entry *) h->root.u.i.link;
616
617   if (h->versioned == unknown)
618     {
619       /* Set versioned if symbol version is unknown.  */
620       char *version = strrchr (name, ELF_VER_CHR);
621       if (version)
622         {
623           if (version > name && version[-1] != ELF_VER_CHR)
624             h->versioned = versioned_hidden;
625           else
626             h->versioned = versioned;
627         }
628     }
629
630   /* Symbols defined in a linker script but not referenced anywhere
631      else will have non_elf set.  */
632   if (h->non_elf)
633     {
634       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
635       h->non_elf = 0;
636     }
637
638   switch (h->root.type)
639     {
640     case bfd_link_hash_defined:
641     case bfd_link_hash_defweak:
642     case bfd_link_hash_common:
643       break;
644     case bfd_link_hash_undefweak:
645     case bfd_link_hash_undefined:
646       /* Since we're defining the symbol, don't let it seem to have not
647          been defined.  record_dynamic_symbol and size_dynamic_sections
648          may depend on this.  */
649       h->root.type = bfd_link_hash_new;
650       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
651         bfd_link_repair_undef_list (&htab->root);
652       break;
653     case bfd_link_hash_new:
654       break;
655     case bfd_link_hash_indirect:
656       /* We had a versioned symbol in a dynamic library.  We make the
657          the versioned symbol point to this one.  */
658       bed = get_elf_backend_data (output_bfd);
659       hv = h;
660       while (hv->root.type == bfd_link_hash_indirect
661              || hv->root.type == bfd_link_hash_warning)
662         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
663       /* We don't need to update h->root.u since linker will set them
664          later.  */
665       h->root.type = bfd_link_hash_undefined;
666       hv->root.type = bfd_link_hash_indirect;
667       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
668       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
669       break;
670     default:
671       BFD_FAIL ();
672       return FALSE;
673     }
674
675   /* If this symbol is being provided by the linker script, and it is
676      currently defined by a dynamic object, but not by a regular
677      object, then mark it as undefined so that the generic linker will
678      force the correct value.  */
679   if (provide
680       && h->def_dynamic
681       && !h->def_regular)
682     h->root.type = bfd_link_hash_undefined;
683
684   /* If this symbol is not being provided by the linker script, and it is
685      currently defined by a dynamic object, but not by a regular object,
686      then clear out any version information because the symbol will not be
687      associated with the dynamic object any more.  */
688   if (!provide
689       && h->def_dynamic
690       && !h->def_regular)
691     h->verinfo.verdef = NULL;
692
693   /* Make sure this symbol is not garbage collected.  */
694   h->mark = 1;
695
696   h->def_regular = 1;
697
698   if (hidden)
699     {
700       bed = get_elf_backend_data (output_bfd);
701       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
702         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
703       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
704     }
705
706   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
707      and executables.  */
708   if (!bfd_link_relocatable (info)
709       && h->dynindx != -1
710       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
711           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
712     h->forced_local = 1;
713
714   if ((h->def_dynamic
715        || h->ref_dynamic
716        || bfd_link_dll (info)
717        || elf_hash_table (info)->is_relocatable_executable)
718       && h->dynindx == -1)
719     {
720       if (! bfd_elf_link_record_dynamic_symbol (info, h))
721         return FALSE;
722
723       /* If this is a weak defined symbol, and we know a corresponding
724          real symbol from the same dynamic object, make sure the real
725          symbol is also made into a dynamic symbol.  */
726       if (h->is_weakalias)
727         {
728           struct elf_link_hash_entry *def = weakdef (h);
729
730           if (def->dynindx == -1
731               && !bfd_elf_link_record_dynamic_symbol (info, def))
732             return FALSE;
733         }
734     }
735
736   return TRUE;
737 }
738
739 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
740    success, and 2 on a failure caused by attempting to record a symbol
741    in a discarded section, eg. a discarded link-once section symbol.  */
742
743 int
744 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
745                                           bfd *input_bfd,
746                                           long input_indx)
747 {
748   bfd_size_type amt;
749   struct elf_link_local_dynamic_entry *entry;
750   struct elf_link_hash_table *eht;
751   struct elf_strtab_hash *dynstr;
752   size_t dynstr_index;
753   char *name;
754   Elf_External_Sym_Shndx eshndx;
755   char esym[sizeof (Elf64_External_Sym)];
756
757   if (! is_elf_hash_table (info->hash))
758     return 0;
759
760   /* See if the entry exists already.  */
761   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
762     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
763       return 1;
764
765   amt = sizeof (*entry);
766   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
767   if (entry == NULL)
768     return 0;
769
770   /* Go find the symbol, so that we can find it's name.  */
771   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
772                              1, input_indx, &entry->isym, esym, &eshndx))
773     {
774       bfd_release (input_bfd, entry);
775       return 0;
776     }
777
778   if (entry->isym.st_shndx != SHN_UNDEF
779       && entry->isym.st_shndx < SHN_LORESERVE)
780     {
781       asection *s;
782
783       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
784       if (s == NULL || bfd_is_abs_section (s->output_section))
785         {
786           /* We can still bfd_release here as nothing has done another
787              bfd_alloc.  We can't do this later in this function.  */
788           bfd_release (input_bfd, entry);
789           return 2;
790         }
791     }
792
793   name = (bfd_elf_string_from_elf_section
794           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
795            entry->isym.st_name));
796
797   dynstr = elf_hash_table (info)->dynstr;
798   if (dynstr == NULL)
799     {
800       /* Create a strtab to hold the dynamic symbol names.  */
801       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
802       if (dynstr == NULL)
803         return 0;
804     }
805
806   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
807   if (dynstr_index == (size_t) -1)
808     return 0;
809   entry->isym.st_name = dynstr_index;
810
811   eht = elf_hash_table (info);
812
813   entry->next = eht->dynlocal;
814   eht->dynlocal = entry;
815   entry->input_bfd = input_bfd;
816   entry->input_indx = input_indx;
817   eht->dynsymcount++;
818
819   /* Whatever binding the symbol had before, it's now local.  */
820   entry->isym.st_info
821     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
822
823   /* The dynindx will be set at the end of size_dynamic_sections.  */
824
825   return 1;
826 }
827
828 /* Return the dynindex of a local dynamic symbol.  */
829
830 long
831 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
832                                     bfd *input_bfd,
833                                     long input_indx)
834 {
835   struct elf_link_local_dynamic_entry *e;
836
837   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
838     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
839       return e->dynindx;
840   return -1;
841 }
842
843 /* This function is used to renumber the dynamic symbols, if some of
844    them are removed because they are marked as local.  This is called
845    via elf_link_hash_traverse.  */
846
847 static bfd_boolean
848 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
849                                       void *data)
850 {
851   size_t *count = (size_t *) data;
852
853   if (h->forced_local)
854     return TRUE;
855
856   if (h->dynindx != -1)
857     h->dynindx = ++(*count);
858
859   return TRUE;
860 }
861
862
863 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
864    STB_LOCAL binding.  */
865
866 static bfd_boolean
867 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
868                                             void *data)
869 {
870   size_t *count = (size_t *) data;
871
872   if (!h->forced_local)
873     return TRUE;
874
875   if (h->dynindx != -1)
876     h->dynindx = ++(*count);
877
878   return TRUE;
879 }
880
881 /* Return true if the dynamic symbol for a given section should be
882    omitted when creating a shared library.  */
883 bfd_boolean
884 _bfd_elf_omit_section_dynsym_default (bfd *output_bfd ATTRIBUTE_UNUSED,
885                                       struct bfd_link_info *info,
886                                       asection *p)
887 {
888   struct elf_link_hash_table *htab;
889   asection *ip;
890
891   switch (elf_section_data (p)->this_hdr.sh_type)
892     {
893     case SHT_PROGBITS:
894     case SHT_NOBITS:
895       /* If sh_type is yet undecided, assume it could be
896          SHT_PROGBITS/SHT_NOBITS.  */
897     case SHT_NULL:
898       htab = elf_hash_table (info);
899       if (p == htab->tls_sec)
900         return FALSE;
901
902       if (htab->text_index_section != NULL)
903         return p != htab->text_index_section && p != htab->data_index_section;
904
905       return (htab->dynobj != NULL
906               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
907               && ip->output_section == p);
908
909       /* There shouldn't be section relative relocations
910          against any other section.  */
911     default:
912       return TRUE;
913     }
914 }
915
916 bfd_boolean
917 _bfd_elf_omit_section_dynsym_all
918     (bfd *output_bfd ATTRIBUTE_UNUSED,
919      struct bfd_link_info *info ATTRIBUTE_UNUSED,
920      asection *p ATTRIBUTE_UNUSED)
921 {
922   return TRUE;
923 }
924
925 /* Assign dynsym indices.  In a shared library we generate a section
926    symbol for each output section, which come first.  Next come symbols
927    which have been forced to local binding.  Then all of the back-end
928    allocated local dynamic syms, followed by the rest of the global
929    symbols.  If SECTION_SYM_COUNT is NULL, section dynindx is not set.
930    (This prevents the early call before elf_backend_init_index_section
931    and strip_excluded_output_sections setting dynindx for sections
932    that are stripped.)  */
933
934 static unsigned long
935 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
936                                 struct bfd_link_info *info,
937                                 unsigned long *section_sym_count)
938 {
939   unsigned long dynsymcount = 0;
940   bfd_boolean do_sec = section_sym_count != NULL;
941
942   if (bfd_link_pic (info)
943       || elf_hash_table (info)->is_relocatable_executable)
944     {
945       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
946       asection *p;
947       for (p = output_bfd->sections; p ; p = p->next)
948         if ((p->flags & SEC_EXCLUDE) == 0
949             && (p->flags & SEC_ALLOC) != 0
950             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
951           {
952             ++dynsymcount;
953             if (do_sec)
954               elf_section_data (p)->dynindx = dynsymcount;
955           }
956         else if (do_sec)
957           elf_section_data (p)->dynindx = 0;
958     }
959   if (do_sec)
960     *section_sym_count = dynsymcount;
961
962   elf_link_hash_traverse (elf_hash_table (info),
963                           elf_link_renumber_local_hash_table_dynsyms,
964                           &dynsymcount);
965
966   if (elf_hash_table (info)->dynlocal)
967     {
968       struct elf_link_local_dynamic_entry *p;
969       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
970         p->dynindx = ++dynsymcount;
971     }
972   elf_hash_table (info)->local_dynsymcount = dynsymcount;
973
974   elf_link_hash_traverse (elf_hash_table (info),
975                           elf_link_renumber_hash_table_dynsyms,
976                           &dynsymcount);
977
978   /* There is an unused NULL entry at the head of the table which we
979      must account for in our count even if the table is empty since it
980      is intended for the mandatory DT_SYMTAB tag (.dynsym section) in
981      .dynamic section.  */
982   dynsymcount++;
983
984   elf_hash_table (info)->dynsymcount = dynsymcount;
985   return dynsymcount;
986 }
987
988 /* Merge st_other field.  */
989
990 static void
991 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
992                     const Elf_Internal_Sym *isym, asection *sec,
993                     bfd_boolean definition, bfd_boolean dynamic)
994 {
995   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
996
997   /* If st_other has a processor-specific meaning, specific
998      code might be needed here.  */
999   if (bed->elf_backend_merge_symbol_attribute)
1000     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
1001                                                 dynamic);
1002
1003   if (!dynamic)
1004     {
1005       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
1006       unsigned hvis = ELF_ST_VISIBILITY (h->other);
1007
1008       /* Keep the most constraining visibility.  Leave the remainder
1009          of the st_other field to elf_backend_merge_symbol_attribute.  */
1010       if (symvis - 1 < hvis - 1)
1011         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
1012     }
1013   else if (definition
1014            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
1015            && (sec->flags & SEC_READONLY) == 0)
1016     h->protected_def = 1;
1017 }
1018
1019 /* This function is called when we want to merge a new symbol with an
1020    existing symbol.  It handles the various cases which arise when we
1021    find a definition in a dynamic object, or when there is already a
1022    definition in a dynamic object.  The new symbol is described by
1023    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
1024    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
1025    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
1026    of an old common symbol.  We set OVERRIDE if the old symbol is
1027    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
1028    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
1029    to change.  By OK to change, we mean that we shouldn't warn if the
1030    type or size does change.  */
1031
1032 static bfd_boolean
1033 _bfd_elf_merge_symbol (bfd *abfd,
1034                        struct bfd_link_info *info,
1035                        const char *name,
1036                        Elf_Internal_Sym *sym,
1037                        asection **psec,
1038                        bfd_vma *pvalue,
1039                        struct elf_link_hash_entry **sym_hash,
1040                        bfd **poldbfd,
1041                        bfd_boolean *pold_weak,
1042                        unsigned int *pold_alignment,
1043                        bfd_boolean *skip,
1044                        bfd_boolean *override,
1045                        bfd_boolean *type_change_ok,
1046                        bfd_boolean *size_change_ok,
1047                        bfd_boolean *matched)
1048 {
1049   asection *sec, *oldsec;
1050   struct elf_link_hash_entry *h;
1051   struct elf_link_hash_entry *hi;
1052   struct elf_link_hash_entry *flip;
1053   int bind;
1054   bfd *oldbfd;
1055   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
1056   bfd_boolean newweak, oldweak, newfunc, oldfunc;
1057   const struct elf_backend_data *bed;
1058   char *new_version;
1059   bfd_boolean default_sym = *matched;
1060
1061   *skip = FALSE;
1062   *override = FALSE;
1063
1064   sec = *psec;
1065   bind = ELF_ST_BIND (sym->st_info);
1066
1067   if (! bfd_is_und_section (sec))
1068     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
1069   else
1070     h = ((struct elf_link_hash_entry *)
1071          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
1072   if (h == NULL)
1073     return FALSE;
1074   *sym_hash = h;
1075
1076   bed = get_elf_backend_data (abfd);
1077
1078   /* NEW_VERSION is the symbol version of the new symbol.  */
1079   if (h->versioned != unversioned)
1080     {
1081       /* Symbol version is unknown or versioned.  */
1082       new_version = strrchr (name, ELF_VER_CHR);
1083       if (new_version)
1084         {
1085           if (h->versioned == unknown)
1086             {
1087               if (new_version > name && new_version[-1] != ELF_VER_CHR)
1088                 h->versioned = versioned_hidden;
1089               else
1090                 h->versioned = versioned;
1091             }
1092           new_version += 1;
1093           if (new_version[0] == '\0')
1094             new_version = NULL;
1095         }
1096       else
1097         h->versioned = unversioned;
1098     }
1099   else
1100     new_version = NULL;
1101
1102   /* For merging, we only care about real symbols.  But we need to make
1103      sure that indirect symbol dynamic flags are updated.  */
1104   hi = h;
1105   while (h->root.type == bfd_link_hash_indirect
1106          || h->root.type == bfd_link_hash_warning)
1107     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1108
1109   if (!*matched)
1110     {
1111       if (hi == h || h->root.type == bfd_link_hash_new)
1112         *matched = TRUE;
1113       else
1114         {
1115           /* OLD_HIDDEN is true if the existing symbol is only visible
1116              to the symbol with the same symbol version.  NEW_HIDDEN is
1117              true if the new symbol is only visible to the symbol with
1118              the same symbol version.  */
1119           bfd_boolean old_hidden = h->versioned == versioned_hidden;
1120           bfd_boolean new_hidden = hi->versioned == versioned_hidden;
1121           if (!old_hidden && !new_hidden)
1122             /* The new symbol matches the existing symbol if both
1123                aren't hidden.  */
1124             *matched = TRUE;
1125           else
1126             {
1127               /* OLD_VERSION is the symbol version of the existing
1128                  symbol. */
1129               char *old_version;
1130
1131               if (h->versioned >= versioned)
1132                 old_version = strrchr (h->root.root.string,
1133                                        ELF_VER_CHR) + 1;
1134               else
1135                  old_version = NULL;
1136
1137               /* The new symbol matches the existing symbol if they
1138                  have the same symbol version.  */
1139               *matched = (old_version == new_version
1140                           || (old_version != NULL
1141                               && new_version != NULL
1142                               && strcmp (old_version, new_version) == 0));
1143             }
1144         }
1145     }
1146
1147   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
1148      existing symbol.  */
1149
1150   oldbfd = NULL;
1151   oldsec = NULL;
1152   switch (h->root.type)
1153     {
1154     default:
1155       break;
1156
1157     case bfd_link_hash_undefined:
1158     case bfd_link_hash_undefweak:
1159       oldbfd = h->root.u.undef.abfd;
1160       break;
1161
1162     case bfd_link_hash_defined:
1163     case bfd_link_hash_defweak:
1164       oldbfd = h->root.u.def.section->owner;
1165       oldsec = h->root.u.def.section;
1166       break;
1167
1168     case bfd_link_hash_common:
1169       oldbfd = h->root.u.c.p->section->owner;
1170       oldsec = h->root.u.c.p->section;
1171       if (pold_alignment)
1172         *pold_alignment = h->root.u.c.p->alignment_power;
1173       break;
1174     }
1175   if (poldbfd && *poldbfd == NULL)
1176     *poldbfd = oldbfd;
1177
1178   /* Differentiate strong and weak symbols.  */
1179   newweak = bind == STB_WEAK;
1180   oldweak = (h->root.type == bfd_link_hash_defweak
1181              || h->root.type == bfd_link_hash_undefweak);
1182   if (pold_weak)
1183     *pold_weak = oldweak;
1184
1185   /* We have to check it for every instance since the first few may be
1186      references and not all compilers emit symbol type for undefined
1187      symbols.  */
1188   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
1189
1190   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1191      respectively, is from a dynamic object.  */
1192
1193   newdyn = (abfd->flags & DYNAMIC) != 0;
1194
1195   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
1196      syms and defined syms in dynamic libraries respectively.
1197      ref_dynamic on the other hand can be set for a symbol defined in
1198      a dynamic library, and def_dynamic may not be set;  When the
1199      definition in a dynamic lib is overridden by a definition in the
1200      executable use of the symbol in the dynamic lib becomes a
1201      reference to the executable symbol.  */
1202   if (newdyn)
1203     {
1204       if (bfd_is_und_section (sec))
1205         {
1206           if (bind != STB_WEAK)
1207             {
1208               h->ref_dynamic_nonweak = 1;
1209               hi->ref_dynamic_nonweak = 1;
1210             }
1211         }
1212       else
1213         {
1214           /* Update the existing symbol only if they match. */
1215           if (*matched)
1216             h->dynamic_def = 1;
1217           hi->dynamic_def = 1;
1218         }
1219     }
1220
1221   /* If we just created the symbol, mark it as being an ELF symbol.
1222      Other than that, there is nothing to do--there is no merge issue
1223      with a newly defined symbol--so we just return.  */
1224
1225   if (h->root.type == bfd_link_hash_new)
1226     {
1227       h->non_elf = 0;
1228       return TRUE;
1229     }
1230
1231   /* In cases involving weak versioned symbols, we may wind up trying
1232      to merge a symbol with itself.  Catch that here, to avoid the
1233      confusion that results if we try to override a symbol with
1234      itself.  The additional tests catch cases like
1235      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1236      dynamic object, which we do want to handle here.  */
1237   if (abfd == oldbfd
1238       && (newweak || oldweak)
1239       && ((abfd->flags & DYNAMIC) == 0
1240           || !h->def_regular))
1241     return TRUE;
1242
1243   olddyn = FALSE;
1244   if (oldbfd != NULL)
1245     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1246   else if (oldsec != NULL)
1247     {
1248       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1249          indices used by MIPS ELF.  */
1250       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1251     }
1252
1253   /* Handle a case where plugin_notice won't be called and thus won't
1254      set the non_ir_ref flags on the first pass over symbols.  */
1255   if (oldbfd != NULL
1256       && (oldbfd->flags & BFD_PLUGIN) != (abfd->flags & BFD_PLUGIN)
1257       && newdyn != olddyn)
1258     {
1259       h->root.non_ir_ref_dynamic = TRUE;
1260       hi->root.non_ir_ref_dynamic = TRUE;
1261     }
1262
1263   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1264      respectively, appear to be a definition rather than reference.  */
1265
1266   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1267
1268   olddef = (h->root.type != bfd_link_hash_undefined
1269             && h->root.type != bfd_link_hash_undefweak
1270             && h->root.type != bfd_link_hash_common);
1271
1272   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1273      respectively, appear to be a function.  */
1274
1275   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1276              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1277
1278   oldfunc = (h->type != STT_NOTYPE
1279              && bed->is_function_type (h->type));
1280
1281   if (!(newfunc && oldfunc)
1282       && ELF_ST_TYPE (sym->st_info) != h->type
1283       && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1284       && h->type != STT_NOTYPE
1285       && (newdef || bfd_is_com_section (sec))
1286       && (olddef || h->root.type == bfd_link_hash_common))
1287     {
1288       /* If creating a default indirect symbol ("foo" or "foo@") from
1289          a dynamic versioned definition ("foo@@") skip doing so if
1290          there is an existing regular definition with a different
1291          type.  We don't want, for example, a "time" variable in the
1292          executable overriding a "time" function in a shared library.  */
1293       if (newdyn
1294           && !olddyn)
1295         {
1296           *skip = TRUE;
1297           return TRUE;
1298         }
1299
1300       /* When adding a symbol from a regular object file after we have
1301          created indirect symbols, undo the indirection and any
1302          dynamic state.  */
1303       if (hi != h
1304           && !newdyn
1305           && olddyn)
1306         {
1307           h = hi;
1308           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1309           h->forced_local = 0;
1310           h->ref_dynamic = 0;
1311           h->def_dynamic = 0;
1312           h->dynamic_def = 0;
1313           if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1314             {
1315               h->root.type = bfd_link_hash_undefined;
1316               h->root.u.undef.abfd = abfd;
1317             }
1318           else
1319             {
1320               h->root.type = bfd_link_hash_new;
1321               h->root.u.undef.abfd = NULL;
1322             }
1323           return TRUE;
1324         }
1325     }
1326
1327   /* Check TLS symbols.  We don't check undefined symbols introduced
1328      by "ld -u" which have no type (and oldbfd NULL), and we don't
1329      check symbols from plugins because they also have no type.  */
1330   if (oldbfd != NULL
1331       && (oldbfd->flags & BFD_PLUGIN) == 0
1332       && (abfd->flags & BFD_PLUGIN) == 0
1333       && ELF_ST_TYPE (sym->st_info) != h->type
1334       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1335     {
1336       bfd *ntbfd, *tbfd;
1337       bfd_boolean ntdef, tdef;
1338       asection *ntsec, *tsec;
1339
1340       if (h->type == STT_TLS)
1341         {
1342           ntbfd = abfd;
1343           ntsec = sec;
1344           ntdef = newdef;
1345           tbfd = oldbfd;
1346           tsec = oldsec;
1347           tdef = olddef;
1348         }
1349       else
1350         {
1351           ntbfd = oldbfd;
1352           ntsec = oldsec;
1353           ntdef = olddef;
1354           tbfd = abfd;
1355           tsec = sec;
1356           tdef = newdef;
1357         }
1358
1359       if (tdef && ntdef)
1360         _bfd_error_handler
1361           /* xgettext:c-format */
1362           (_("%s: TLS definition in %pB section %pA "
1363              "mismatches non-TLS definition in %pB section %pA"),
1364            h->root.root.string, tbfd, tsec, ntbfd, ntsec);
1365       else if (!tdef && !ntdef)
1366         _bfd_error_handler
1367           /* xgettext:c-format */
1368           (_("%s: TLS reference in %pB "
1369              "mismatches non-TLS reference in %pB"),
1370            h->root.root.string, tbfd, ntbfd);
1371       else if (tdef)
1372         _bfd_error_handler
1373           /* xgettext:c-format */
1374           (_("%s: TLS definition in %pB section %pA "
1375              "mismatches non-TLS reference in %pB"),
1376            h->root.root.string, tbfd, tsec, ntbfd);
1377       else
1378         _bfd_error_handler
1379           /* xgettext:c-format */
1380           (_("%s: TLS reference in %pB "
1381              "mismatches non-TLS definition in %pB section %pA"),
1382            h->root.root.string, tbfd, ntbfd, ntsec);
1383
1384       bfd_set_error (bfd_error_bad_value);
1385       return FALSE;
1386     }
1387
1388   /* If the old symbol has non-default visibility, we ignore the new
1389      definition from a dynamic object.  */
1390   if (newdyn
1391       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1392       && !bfd_is_und_section (sec))
1393     {
1394       *skip = TRUE;
1395       /* Make sure this symbol is dynamic.  */
1396       h->ref_dynamic = 1;
1397       hi->ref_dynamic = 1;
1398       /* A protected symbol has external availability. Make sure it is
1399          recorded as dynamic.
1400
1401          FIXME: Should we check type and size for protected symbol?  */
1402       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1403         return bfd_elf_link_record_dynamic_symbol (info, h);
1404       else
1405         return TRUE;
1406     }
1407   else if (!newdyn
1408            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1409            && h->def_dynamic)
1410     {
1411       /* If the new symbol with non-default visibility comes from a
1412          relocatable file and the old definition comes from a dynamic
1413          object, we remove the old definition.  */
1414       if (hi->root.type == bfd_link_hash_indirect)
1415         {
1416           /* Handle the case where the old dynamic definition is
1417              default versioned.  We need to copy the symbol info from
1418              the symbol with default version to the normal one if it
1419              was referenced before.  */
1420           if (h->ref_regular)
1421             {
1422               hi->root.type = h->root.type;
1423               h->root.type = bfd_link_hash_indirect;
1424               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1425
1426               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1427               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1428                 {
1429                   /* If the new symbol is hidden or internal, completely undo
1430                      any dynamic link state.  */
1431                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1432                   h->forced_local = 0;
1433                   h->ref_dynamic = 0;
1434                 }
1435               else
1436                 h->ref_dynamic = 1;
1437
1438               h->def_dynamic = 0;
1439               /* FIXME: Should we check type and size for protected symbol?  */
1440               h->size = 0;
1441               h->type = 0;
1442
1443               h = hi;
1444             }
1445           else
1446             h = hi;
1447         }
1448
1449       /* If the old symbol was undefined before, then it will still be
1450          on the undefs list.  If the new symbol is undefined or
1451          common, we can't make it bfd_link_hash_new here, because new
1452          undefined or common symbols will be added to the undefs list
1453          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1454          added twice to the undefs list.  Also, if the new symbol is
1455          undefweak then we don't want to lose the strong undef.  */
1456       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1457         {
1458           h->root.type = bfd_link_hash_undefined;
1459           h->root.u.undef.abfd = abfd;
1460         }
1461       else
1462         {
1463           h->root.type = bfd_link_hash_new;
1464           h->root.u.undef.abfd = NULL;
1465         }
1466
1467       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1468         {
1469           /* If the new symbol is hidden or internal, completely undo
1470              any dynamic link state.  */
1471           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1472           h->forced_local = 0;
1473           h->ref_dynamic = 0;
1474         }
1475       else
1476         h->ref_dynamic = 1;
1477       h->def_dynamic = 0;
1478       /* FIXME: Should we check type and size for protected symbol?  */
1479       h->size = 0;
1480       h->type = 0;
1481       return TRUE;
1482     }
1483
1484   /* If a new weak symbol definition comes from a regular file and the
1485      old symbol comes from a dynamic library, we treat the new one as
1486      strong.  Similarly, an old weak symbol definition from a regular
1487      file is treated as strong when the new symbol comes from a dynamic
1488      library.  Further, an old weak symbol from a dynamic library is
1489      treated as strong if the new symbol is from a dynamic library.
1490      This reflects the way glibc's ld.so works.
1491
1492      Also allow a weak symbol to override a linker script symbol
1493      defined by an early pass over the script.  This is done so the
1494      linker knows the symbol is defined in an object file, for the
1495      DEFINED script function.
1496
1497      Do this before setting *type_change_ok or *size_change_ok so that
1498      we warn properly when dynamic library symbols are overridden.  */
1499
1500   if (newdef && !newdyn && (olddyn || h->root.ldscript_def))
1501     newweak = FALSE;
1502   if (olddef && newdyn)
1503     oldweak = FALSE;
1504
1505   /* Allow changes between different types of function symbol.  */
1506   if (newfunc && oldfunc)
1507     *type_change_ok = TRUE;
1508
1509   /* It's OK to change the type if either the existing symbol or the
1510      new symbol is weak.  A type change is also OK if the old symbol
1511      is undefined and the new symbol is defined.  */
1512
1513   if (oldweak
1514       || newweak
1515       || (newdef
1516           && h->root.type == bfd_link_hash_undefined))
1517     *type_change_ok = TRUE;
1518
1519   /* It's OK to change the size if either the existing symbol or the
1520      new symbol is weak, or if the old symbol is undefined.  */
1521
1522   if (*type_change_ok
1523       || h->root.type == bfd_link_hash_undefined)
1524     *size_change_ok = TRUE;
1525
1526   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1527      symbol, respectively, appears to be a common symbol in a dynamic
1528      object.  If a symbol appears in an uninitialized section, and is
1529      not weak, and is not a function, then it may be a common symbol
1530      which was resolved when the dynamic object was created.  We want
1531      to treat such symbols specially, because they raise special
1532      considerations when setting the symbol size: if the symbol
1533      appears as a common symbol in a regular object, and the size in
1534      the regular object is larger, we must make sure that we use the
1535      larger size.  This problematic case can always be avoided in C,
1536      but it must be handled correctly when using Fortran shared
1537      libraries.
1538
1539      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1540      likewise for OLDDYNCOMMON and OLDDEF.
1541
1542      Note that this test is just a heuristic, and that it is quite
1543      possible to have an uninitialized symbol in a shared object which
1544      is really a definition, rather than a common symbol.  This could
1545      lead to some minor confusion when the symbol really is a common
1546      symbol in some regular object.  However, I think it will be
1547      harmless.  */
1548
1549   if (newdyn
1550       && newdef
1551       && !newweak
1552       && (sec->flags & SEC_ALLOC) != 0
1553       && (sec->flags & SEC_LOAD) == 0
1554       && sym->st_size > 0
1555       && !newfunc)
1556     newdyncommon = TRUE;
1557   else
1558     newdyncommon = FALSE;
1559
1560   if (olddyn
1561       && olddef
1562       && h->root.type == bfd_link_hash_defined
1563       && h->def_dynamic
1564       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1565       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1566       && h->size > 0
1567       && !oldfunc)
1568     olddyncommon = TRUE;
1569   else
1570     olddyncommon = FALSE;
1571
1572   /* We now know everything about the old and new symbols.  We ask the
1573      backend to check if we can merge them.  */
1574   if (bed->merge_symbol != NULL)
1575     {
1576       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1577         return FALSE;
1578       sec = *psec;
1579     }
1580
1581   /* There are multiple definitions of a normal symbol.  Skip the
1582      default symbol as well as definition from an IR object.  */
1583   if (olddef && !olddyn && !oldweak && newdef && !newdyn && !newweak
1584       && !default_sym && h->def_regular
1585       && !(oldbfd != NULL
1586            && (oldbfd->flags & BFD_PLUGIN) != 0
1587            && (abfd->flags & BFD_PLUGIN) == 0))
1588     {
1589       /* Handle a multiple definition.  */
1590       (*info->callbacks->multiple_definition) (info, &h->root,
1591                                                abfd, sec, *pvalue);
1592       *skip = TRUE;
1593       return TRUE;
1594     }
1595
1596   /* If both the old and the new symbols look like common symbols in a
1597      dynamic object, set the size of the symbol to the larger of the
1598      two.  */
1599
1600   if (olddyncommon
1601       && newdyncommon
1602       && sym->st_size != h->size)
1603     {
1604       /* Since we think we have two common symbols, issue a multiple
1605          common warning if desired.  Note that we only warn if the
1606          size is different.  If the size is the same, we simply let
1607          the old symbol override the new one as normally happens with
1608          symbols defined in dynamic objects.  */
1609
1610       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1611                                            bfd_link_hash_common, sym->st_size);
1612       if (sym->st_size > h->size)
1613         h->size = sym->st_size;
1614
1615       *size_change_ok = TRUE;
1616     }
1617
1618   /* If we are looking at a dynamic object, and we have found a
1619      definition, we need to see if the symbol was already defined by
1620      some other object.  If so, we want to use the existing
1621      definition, and we do not want to report a multiple symbol
1622      definition error; we do this by clobbering *PSEC to be
1623      bfd_und_section_ptr.
1624
1625      We treat a common symbol as a definition if the symbol in the
1626      shared library is a function, since common symbols always
1627      represent variables; this can cause confusion in principle, but
1628      any such confusion would seem to indicate an erroneous program or
1629      shared library.  We also permit a common symbol in a regular
1630      object to override a weak symbol in a shared object.  */
1631
1632   if (newdyn
1633       && newdef
1634       && (olddef
1635           || (h->root.type == bfd_link_hash_common
1636               && (newweak || newfunc))))
1637     {
1638       *override = TRUE;
1639       newdef = FALSE;
1640       newdyncommon = FALSE;
1641
1642       *psec = sec = bfd_und_section_ptr;
1643       *size_change_ok = TRUE;
1644
1645       /* If we get here when the old symbol is a common symbol, then
1646          we are explicitly letting it override a weak symbol or
1647          function in a dynamic object, and we don't want to warn about
1648          a type change.  If the old symbol is a defined symbol, a type
1649          change warning may still be appropriate.  */
1650
1651       if (h->root.type == bfd_link_hash_common)
1652         *type_change_ok = TRUE;
1653     }
1654
1655   /* Handle the special case of an old common symbol merging with a
1656      new symbol which looks like a common symbol in a shared object.
1657      We change *PSEC and *PVALUE to make the new symbol look like a
1658      common symbol, and let _bfd_generic_link_add_one_symbol do the
1659      right thing.  */
1660
1661   if (newdyncommon
1662       && h->root.type == bfd_link_hash_common)
1663     {
1664       *override = TRUE;
1665       newdef = FALSE;
1666       newdyncommon = FALSE;
1667       *pvalue = sym->st_size;
1668       *psec = sec = bed->common_section (oldsec);
1669       *size_change_ok = TRUE;
1670     }
1671
1672   /* Skip weak definitions of symbols that are already defined.  */
1673   if (newdef && olddef && newweak)
1674     {
1675       /* Don't skip new non-IR weak syms.  */
1676       if (!(oldbfd != NULL
1677             && (oldbfd->flags & BFD_PLUGIN) != 0
1678             && (abfd->flags & BFD_PLUGIN) == 0))
1679         {
1680           newdef = FALSE;
1681           *skip = TRUE;
1682         }
1683
1684       /* Merge st_other.  If the symbol already has a dynamic index,
1685          but visibility says it should not be visible, turn it into a
1686          local symbol.  */
1687       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1688       if (h->dynindx != -1)
1689         switch (ELF_ST_VISIBILITY (h->other))
1690           {
1691           case STV_INTERNAL:
1692           case STV_HIDDEN:
1693             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1694             break;
1695           }
1696     }
1697
1698   /* If the old symbol is from a dynamic object, and the new symbol is
1699      a definition which is not from a dynamic object, then the new
1700      symbol overrides the old symbol.  Symbols from regular files
1701      always take precedence over symbols from dynamic objects, even if
1702      they are defined after the dynamic object in the link.
1703
1704      As above, we again permit a common symbol in a regular object to
1705      override a definition in a shared object if the shared object
1706      symbol is a function or is weak.  */
1707
1708   flip = NULL;
1709   if (!newdyn
1710       && (newdef
1711           || (bfd_is_com_section (sec)
1712               && (oldweak || oldfunc)))
1713       && olddyn
1714       && olddef
1715       && h->def_dynamic)
1716     {
1717       /* Change the hash table entry to undefined, and let
1718          _bfd_generic_link_add_one_symbol do the right thing with the
1719          new definition.  */
1720
1721       h->root.type = bfd_link_hash_undefined;
1722       h->root.u.undef.abfd = h->root.u.def.section->owner;
1723       *size_change_ok = TRUE;
1724
1725       olddef = FALSE;
1726       olddyncommon = FALSE;
1727
1728       /* We again permit a type change when a common symbol may be
1729          overriding a function.  */
1730
1731       if (bfd_is_com_section (sec))
1732         {
1733           if (oldfunc)
1734             {
1735               /* If a common symbol overrides a function, make sure
1736                  that it isn't defined dynamically nor has type
1737                  function.  */
1738               h->def_dynamic = 0;
1739               h->type = STT_NOTYPE;
1740             }
1741           *type_change_ok = TRUE;
1742         }
1743
1744       if (hi->root.type == bfd_link_hash_indirect)
1745         flip = hi;
1746       else
1747         /* This union may have been set to be non-NULL when this symbol
1748            was seen in a dynamic object.  We must force the union to be
1749            NULL, so that it is correct for a regular symbol.  */
1750         h->verinfo.vertree = NULL;
1751     }
1752
1753   /* Handle the special case of a new common symbol merging with an
1754      old symbol that looks like it might be a common symbol defined in
1755      a shared object.  Note that we have already handled the case in
1756      which a new common symbol should simply override the definition
1757      in the shared library.  */
1758
1759   if (! newdyn
1760       && bfd_is_com_section (sec)
1761       && olddyncommon)
1762     {
1763       /* It would be best if we could set the hash table entry to a
1764          common symbol, but we don't know what to use for the section
1765          or the alignment.  */
1766       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1767                                            bfd_link_hash_common, sym->st_size);
1768
1769       /* If the presumed common symbol in the dynamic object is
1770          larger, pretend that the new symbol has its size.  */
1771
1772       if (h->size > *pvalue)
1773         *pvalue = h->size;
1774
1775       /* We need to remember the alignment required by the symbol
1776          in the dynamic object.  */
1777       BFD_ASSERT (pold_alignment);
1778       *pold_alignment = h->root.u.def.section->alignment_power;
1779
1780       olddef = FALSE;
1781       olddyncommon = FALSE;
1782
1783       h->root.type = bfd_link_hash_undefined;
1784       h->root.u.undef.abfd = h->root.u.def.section->owner;
1785
1786       *size_change_ok = TRUE;
1787       *type_change_ok = TRUE;
1788
1789       if (hi->root.type == bfd_link_hash_indirect)
1790         flip = hi;
1791       else
1792         h->verinfo.vertree = NULL;
1793     }
1794
1795   if (flip != NULL)
1796     {
1797       /* Handle the case where we had a versioned symbol in a dynamic
1798          library and now find a definition in a normal object.  In this
1799          case, we make the versioned symbol point to the normal one.  */
1800       flip->root.type = h->root.type;
1801       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1802       h->root.type = bfd_link_hash_indirect;
1803       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1804       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1805       if (h->def_dynamic)
1806         {
1807           h->def_dynamic = 0;
1808           flip->ref_dynamic = 1;
1809         }
1810     }
1811
1812   return TRUE;
1813 }
1814
1815 /* This function is called to create an indirect symbol from the
1816    default for the symbol with the default version if needed. The
1817    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1818    set DYNSYM if the new indirect symbol is dynamic.  */
1819
1820 static bfd_boolean
1821 _bfd_elf_add_default_symbol (bfd *abfd,
1822                              struct bfd_link_info *info,
1823                              struct elf_link_hash_entry *h,
1824                              const char *name,
1825                              Elf_Internal_Sym *sym,
1826                              asection *sec,
1827                              bfd_vma value,
1828                              bfd **poldbfd,
1829                              bfd_boolean *dynsym)
1830 {
1831   bfd_boolean type_change_ok;
1832   bfd_boolean size_change_ok;
1833   bfd_boolean skip;
1834   char *shortname;
1835   struct elf_link_hash_entry *hi;
1836   struct bfd_link_hash_entry *bh;
1837   const struct elf_backend_data *bed;
1838   bfd_boolean collect;
1839   bfd_boolean dynamic;
1840   bfd_boolean override;
1841   char *p;
1842   size_t len, shortlen;
1843   asection *tmp_sec;
1844   bfd_boolean matched;
1845
1846   if (h->versioned == unversioned || h->versioned == versioned_hidden)
1847     return TRUE;
1848
1849   /* If this symbol has a version, and it is the default version, we
1850      create an indirect symbol from the default name to the fully
1851      decorated name.  This will cause external references which do not
1852      specify a version to be bound to this version of the symbol.  */
1853   p = strchr (name, ELF_VER_CHR);
1854   if (h->versioned == unknown)
1855     {
1856       if (p == NULL)
1857         {
1858           h->versioned = unversioned;
1859           return TRUE;
1860         }
1861       else
1862         {
1863           if (p[1] != ELF_VER_CHR)
1864             {
1865               h->versioned = versioned_hidden;
1866               return TRUE;
1867             }
1868           else
1869             h->versioned = versioned;
1870         }
1871     }
1872   else
1873     {
1874       /* PR ld/19073: We may see an unversioned definition after the
1875          default version.  */
1876       if (p == NULL)
1877         return TRUE;
1878     }
1879
1880   bed = get_elf_backend_data (abfd);
1881   collect = bed->collect;
1882   dynamic = (abfd->flags & DYNAMIC) != 0;
1883
1884   shortlen = p - name;
1885   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1886   if (shortname == NULL)
1887     return FALSE;
1888   memcpy (shortname, name, shortlen);
1889   shortname[shortlen] = '\0';
1890
1891   /* We are going to create a new symbol.  Merge it with any existing
1892      symbol with this name.  For the purposes of the merge, act as
1893      though we were defining the symbol we just defined, although we
1894      actually going to define an indirect symbol.  */
1895   type_change_ok = FALSE;
1896   size_change_ok = FALSE;
1897   matched = TRUE;
1898   tmp_sec = sec;
1899   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1900                               &hi, poldbfd, NULL, NULL, &skip, &override,
1901                               &type_change_ok, &size_change_ok, &matched))
1902     return FALSE;
1903
1904   if (skip)
1905     goto nondefault;
1906
1907   if (hi->def_regular)
1908     {
1909       /* If the undecorated symbol will have a version added by a
1910          script different to H, then don't indirect to/from the
1911          undecorated symbol.  This isn't ideal because we may not yet
1912          have seen symbol versions, if given by a script on the
1913          command line rather than via --version-script.  */
1914       if (hi->verinfo.vertree == NULL && info->version_info != NULL)
1915         {
1916           bfd_boolean hide;
1917
1918           hi->verinfo.vertree
1919             = bfd_find_version_for_sym (info->version_info,
1920                                         hi->root.root.string, &hide);
1921           if (hi->verinfo.vertree != NULL && hide)
1922             {
1923               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
1924               goto nondefault;
1925             }
1926         }
1927       if (hi->verinfo.vertree != NULL
1928           && strcmp (p + 1 + (p[1] == '@'), hi->verinfo.vertree->name) != 0)
1929         goto nondefault;
1930     }
1931
1932   if (! override)
1933     {
1934       /* Add the default symbol if not performing a relocatable link.  */
1935       if (! bfd_link_relocatable (info))
1936         {
1937           bh = &hi->root;
1938           if (! (_bfd_generic_link_add_one_symbol
1939                  (info, abfd, shortname, BSF_INDIRECT,
1940                   bfd_ind_section_ptr,
1941                   0, name, FALSE, collect, &bh)))
1942             return FALSE;
1943           hi = (struct elf_link_hash_entry *) bh;
1944         }
1945     }
1946   else
1947     {
1948       /* In this case the symbol named SHORTNAME is overriding the
1949          indirect symbol we want to add.  We were planning on making
1950          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1951          is the name without a version.  NAME is the fully versioned
1952          name, and it is the default version.
1953
1954          Overriding means that we already saw a definition for the
1955          symbol SHORTNAME in a regular object, and it is overriding
1956          the symbol defined in the dynamic object.
1957
1958          When this happens, we actually want to change NAME, the
1959          symbol we just added, to refer to SHORTNAME.  This will cause
1960          references to NAME in the shared object to become references
1961          to SHORTNAME in the regular object.  This is what we expect
1962          when we override a function in a shared object: that the
1963          references in the shared object will be mapped to the
1964          definition in the regular object.  */
1965
1966       while (hi->root.type == bfd_link_hash_indirect
1967              || hi->root.type == bfd_link_hash_warning)
1968         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1969
1970       h->root.type = bfd_link_hash_indirect;
1971       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1972       if (h->def_dynamic)
1973         {
1974           h->def_dynamic = 0;
1975           hi->ref_dynamic = 1;
1976           if (hi->ref_regular
1977               || hi->def_regular)
1978             {
1979               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1980                 return FALSE;
1981             }
1982         }
1983
1984       /* Now set HI to H, so that the following code will set the
1985          other fields correctly.  */
1986       hi = h;
1987     }
1988
1989   /* Check if HI is a warning symbol.  */
1990   if (hi->root.type == bfd_link_hash_warning)
1991     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1992
1993   /* If there is a duplicate definition somewhere, then HI may not
1994      point to an indirect symbol.  We will have reported an error to
1995      the user in that case.  */
1996
1997   if (hi->root.type == bfd_link_hash_indirect)
1998     {
1999       struct elf_link_hash_entry *ht;
2000
2001       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
2002       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
2003
2004       /* A reference to the SHORTNAME symbol from a dynamic library
2005          will be satisfied by the versioned symbol at runtime.  In
2006          effect, we have a reference to the versioned symbol.  */
2007       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
2008       hi->dynamic_def |= ht->dynamic_def;
2009
2010       /* See if the new flags lead us to realize that the symbol must
2011          be dynamic.  */
2012       if (! *dynsym)
2013         {
2014           if (! dynamic)
2015             {
2016               if (! bfd_link_executable (info)
2017                   || hi->def_dynamic
2018                   || hi->ref_dynamic)
2019                 *dynsym = TRUE;
2020             }
2021           else
2022             {
2023               if (hi->ref_regular)
2024                 *dynsym = TRUE;
2025             }
2026         }
2027     }
2028
2029   /* We also need to define an indirection from the nondefault version
2030      of the symbol.  */
2031
2032 nondefault:
2033   len = strlen (name);
2034   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
2035   if (shortname == NULL)
2036     return FALSE;
2037   memcpy (shortname, name, shortlen);
2038   memcpy (shortname + shortlen, p + 1, len - shortlen);
2039
2040   /* Once again, merge with any existing symbol.  */
2041   type_change_ok = FALSE;
2042   size_change_ok = FALSE;
2043   tmp_sec = sec;
2044   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
2045                               &hi, poldbfd, NULL, NULL, &skip, &override,
2046                               &type_change_ok, &size_change_ok, &matched))
2047     return FALSE;
2048
2049   if (skip)
2050     return TRUE;
2051
2052   if (override)
2053     {
2054       /* Here SHORTNAME is a versioned name, so we don't expect to see
2055          the type of override we do in the case above unless it is
2056          overridden by a versioned definition.  */
2057       if (hi->root.type != bfd_link_hash_defined
2058           && hi->root.type != bfd_link_hash_defweak)
2059         _bfd_error_handler
2060           /* xgettext:c-format */
2061           (_("%pB: unexpected redefinition of indirect versioned symbol `%s'"),
2062            abfd, shortname);
2063     }
2064   else
2065     {
2066       bh = &hi->root;
2067       if (! (_bfd_generic_link_add_one_symbol
2068              (info, abfd, shortname, BSF_INDIRECT,
2069               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
2070         return FALSE;
2071       hi = (struct elf_link_hash_entry *) bh;
2072
2073       /* If there is a duplicate definition somewhere, then HI may not
2074          point to an indirect symbol.  We will have reported an error
2075          to the user in that case.  */
2076
2077       if (hi->root.type == bfd_link_hash_indirect)
2078         {
2079           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
2080           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
2081           hi->dynamic_def |= h->dynamic_def;
2082
2083           /* See if the new flags lead us to realize that the symbol
2084              must be dynamic.  */
2085           if (! *dynsym)
2086             {
2087               if (! dynamic)
2088                 {
2089                   if (! bfd_link_executable (info)
2090                       || hi->ref_dynamic)
2091                     *dynsym = TRUE;
2092                 }
2093               else
2094                 {
2095                   if (hi->ref_regular)
2096                     *dynsym = TRUE;
2097                 }
2098             }
2099         }
2100     }
2101
2102   return TRUE;
2103 }
2104 \f
2105 /* This routine is used to export all defined symbols into the dynamic
2106    symbol table.  It is called via elf_link_hash_traverse.  */
2107
2108 static bfd_boolean
2109 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
2110 {
2111   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2112
2113   /* Ignore indirect symbols.  These are added by the versioning code.  */
2114   if (h->root.type == bfd_link_hash_indirect)
2115     return TRUE;
2116
2117   /* Ignore this if we won't export it.  */
2118   if (!eif->info->export_dynamic && !h->dynamic)
2119     return TRUE;
2120
2121   if (h->dynindx == -1
2122       && (h->def_regular || h->ref_regular)
2123       && ! bfd_hide_sym_by_version (eif->info->version_info,
2124                                     h->root.root.string))
2125     {
2126       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2127         {
2128           eif->failed = TRUE;
2129           return FALSE;
2130         }
2131     }
2132
2133   return TRUE;
2134 }
2135 \f
2136 /* Look through the symbols which are defined in other shared
2137    libraries and referenced here.  Update the list of version
2138    dependencies.  This will be put into the .gnu.version_r section.
2139    This function is called via elf_link_hash_traverse.  */
2140
2141 static bfd_boolean
2142 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
2143                                          void *data)
2144 {
2145   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
2146   Elf_Internal_Verneed *t;
2147   Elf_Internal_Vernaux *a;
2148   bfd_size_type amt;
2149
2150   /* We only care about symbols defined in shared objects with version
2151      information.  */
2152   if (!h->def_dynamic
2153       || h->def_regular
2154       || h->dynindx == -1
2155       || h->verinfo.verdef == NULL
2156       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
2157           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
2158     return TRUE;
2159
2160   /* See if we already know about this version.  */
2161   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
2162        t != NULL;
2163        t = t->vn_nextref)
2164     {
2165       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
2166         continue;
2167
2168       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
2169         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
2170           return TRUE;
2171
2172       break;
2173     }
2174
2175   /* This is a new version.  Add it to tree we are building.  */
2176
2177   if (t == NULL)
2178     {
2179       amt = sizeof *t;
2180       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
2181       if (t == NULL)
2182         {
2183           rinfo->failed = TRUE;
2184           return FALSE;
2185         }
2186
2187       t->vn_bfd = h->verinfo.verdef->vd_bfd;
2188       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
2189       elf_tdata (rinfo->info->output_bfd)->verref = t;
2190     }
2191
2192   amt = sizeof *a;
2193   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
2194   if (a == NULL)
2195     {
2196       rinfo->failed = TRUE;
2197       return FALSE;
2198     }
2199
2200   /* Note that we are copying a string pointer here, and testing it
2201      above.  If bfd_elf_string_from_elf_section is ever changed to
2202      discard the string data when low in memory, this will have to be
2203      fixed.  */
2204   a->vna_nodename = h->verinfo.verdef->vd_nodename;
2205
2206   a->vna_flags = h->verinfo.verdef->vd_flags;
2207   a->vna_nextptr = t->vn_auxptr;
2208
2209   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
2210   ++rinfo->vers;
2211
2212   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
2213
2214   t->vn_auxptr = a;
2215
2216   return TRUE;
2217 }
2218
2219 /* Figure out appropriate versions for all the symbols.  We may not
2220    have the version number script until we have read all of the input
2221    files, so until that point we don't know which symbols should be
2222    local.  This function is called via elf_link_hash_traverse.  */
2223
2224 static bfd_boolean
2225 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2226 {
2227   struct elf_info_failed *sinfo;
2228   struct bfd_link_info *info;
2229   const struct elf_backend_data *bed;
2230   struct elf_info_failed eif;
2231   char *p;
2232
2233   sinfo = (struct elf_info_failed *) data;
2234   info = sinfo->info;
2235
2236   /* Fix the symbol flags.  */
2237   eif.failed = FALSE;
2238   eif.info = info;
2239   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2240     {
2241       if (eif.failed)
2242         sinfo->failed = TRUE;
2243       return FALSE;
2244     }
2245
2246   /* We only need version numbers for symbols defined in regular
2247      objects.  */
2248   if (!h->def_regular)
2249     return TRUE;
2250
2251   bed = get_elf_backend_data (info->output_bfd);
2252   p = strchr (h->root.root.string, ELF_VER_CHR);
2253   if (p != NULL && h->verinfo.vertree == NULL)
2254     {
2255       struct bfd_elf_version_tree *t;
2256
2257       ++p;
2258       if (*p == ELF_VER_CHR)
2259         ++p;
2260
2261       /* If there is no version string, we can just return out.  */
2262       if (*p == '\0')
2263         return TRUE;
2264
2265       /* Look for the version.  If we find it, it is no longer weak.  */
2266       for (t = sinfo->info->version_info; t != NULL; t = t->next)
2267         {
2268           if (strcmp (t->name, p) == 0)
2269             {
2270               size_t len;
2271               char *alc;
2272               struct bfd_elf_version_expr *d;
2273
2274               len = p - h->root.root.string;
2275               alc = (char *) bfd_malloc (len);
2276               if (alc == NULL)
2277                 {
2278                   sinfo->failed = TRUE;
2279                   return FALSE;
2280                 }
2281               memcpy (alc, h->root.root.string, len - 1);
2282               alc[len - 1] = '\0';
2283               if (alc[len - 2] == ELF_VER_CHR)
2284                 alc[len - 2] = '\0';
2285
2286               h->verinfo.vertree = t;
2287               t->used = TRUE;
2288               d = NULL;
2289
2290               if (t->globals.list != NULL)
2291                 d = (*t->match) (&t->globals, NULL, alc);
2292
2293               /* See if there is anything to force this symbol to
2294                  local scope.  */
2295               if (d == NULL && t->locals.list != NULL)
2296                 {
2297                   d = (*t->match) (&t->locals, NULL, alc);
2298                   if (d != NULL
2299                       && h->dynindx != -1
2300                       && ! info->export_dynamic)
2301                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2302                 }
2303
2304               free (alc);
2305               break;
2306             }
2307         }
2308
2309       /* If we are building an application, we need to create a
2310          version node for this version.  */
2311       if (t == NULL && bfd_link_executable (info))
2312         {
2313           struct bfd_elf_version_tree **pp;
2314           int version_index;
2315
2316           /* If we aren't going to export this symbol, we don't need
2317              to worry about it.  */
2318           if (h->dynindx == -1)
2319             return TRUE;
2320
2321           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd,
2322                                                           sizeof *t);
2323           if (t == NULL)
2324             {
2325               sinfo->failed = TRUE;
2326               return FALSE;
2327             }
2328
2329           t->name = p;
2330           t->name_indx = (unsigned int) -1;
2331           t->used = TRUE;
2332
2333           version_index = 1;
2334           /* Don't count anonymous version tag.  */
2335           if (sinfo->info->version_info != NULL
2336               && sinfo->info->version_info->vernum == 0)
2337             version_index = 0;
2338           for (pp = &sinfo->info->version_info;
2339                *pp != NULL;
2340                pp = &(*pp)->next)
2341             ++version_index;
2342           t->vernum = version_index;
2343
2344           *pp = t;
2345
2346           h->verinfo.vertree = t;
2347         }
2348       else if (t == NULL)
2349         {
2350           /* We could not find the version for a symbol when
2351              generating a shared archive.  Return an error.  */
2352           _bfd_error_handler
2353             /* xgettext:c-format */
2354             (_("%pB: version node not found for symbol %s"),
2355              info->output_bfd, h->root.root.string);
2356           bfd_set_error (bfd_error_bad_value);
2357           sinfo->failed = TRUE;
2358           return FALSE;
2359         }
2360     }
2361
2362   /* If we don't have a version for this symbol, see if we can find
2363      something.  */
2364   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2365     {
2366       bfd_boolean hide;
2367
2368       h->verinfo.vertree
2369         = bfd_find_version_for_sym (sinfo->info->version_info,
2370                                     h->root.root.string, &hide);
2371       if (h->verinfo.vertree != NULL && hide)
2372         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2373     }
2374
2375   return TRUE;
2376 }
2377 \f
2378 /* Read and swap the relocs from the section indicated by SHDR.  This
2379    may be either a REL or a RELA section.  The relocations are
2380    translated into RELA relocations and stored in INTERNAL_RELOCS,
2381    which should have already been allocated to contain enough space.
2382    The EXTERNAL_RELOCS are a buffer where the external form of the
2383    relocations should be stored.
2384
2385    Returns FALSE if something goes wrong.  */
2386
2387 static bfd_boolean
2388 elf_link_read_relocs_from_section (bfd *abfd,
2389                                    asection *sec,
2390                                    Elf_Internal_Shdr *shdr,
2391                                    void *external_relocs,
2392                                    Elf_Internal_Rela *internal_relocs)
2393 {
2394   const struct elf_backend_data *bed;
2395   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2396   const bfd_byte *erela;
2397   const bfd_byte *erelaend;
2398   Elf_Internal_Rela *irela;
2399   Elf_Internal_Shdr *symtab_hdr;
2400   size_t nsyms;
2401
2402   /* Position ourselves at the start of the section.  */
2403   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2404     return FALSE;
2405
2406   /* Read the relocations.  */
2407   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2408     return FALSE;
2409
2410   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2411   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2412
2413   bed = get_elf_backend_data (abfd);
2414
2415   /* Convert the external relocations to the internal format.  */
2416   if (shdr->sh_entsize == bed->s->sizeof_rel)
2417     swap_in = bed->s->swap_reloc_in;
2418   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2419     swap_in = bed->s->swap_reloca_in;
2420   else
2421     {
2422       bfd_set_error (bfd_error_wrong_format);
2423       return FALSE;
2424     }
2425
2426   erela = (const bfd_byte *) external_relocs;
2427   erelaend = erela + shdr->sh_size;
2428   irela = internal_relocs;
2429   while (erela < erelaend)
2430     {
2431       bfd_vma r_symndx;
2432
2433       (*swap_in) (abfd, erela, irela);
2434       r_symndx = ELF32_R_SYM (irela->r_info);
2435       if (bed->s->arch_size == 64)
2436         r_symndx >>= 24;
2437       if (nsyms > 0)
2438         {
2439           if ((size_t) r_symndx >= nsyms)
2440             {
2441               _bfd_error_handler
2442                 /* xgettext:c-format */
2443                 (_("%pB: bad reloc symbol index (%#" PRIx64 " >= %#lx)"
2444                    " for offset %#" PRIx64 " in section `%pA'"),
2445                  abfd, (uint64_t) r_symndx, (unsigned long) nsyms,
2446                  (uint64_t) irela->r_offset, sec);
2447               bfd_set_error (bfd_error_bad_value);
2448               return FALSE;
2449             }
2450         }
2451       else if (r_symndx != STN_UNDEF)
2452         {
2453           _bfd_error_handler
2454             /* xgettext:c-format */
2455             (_("%pB: non-zero symbol index (%#" PRIx64 ")"
2456                " for offset %#" PRIx64 " in section `%pA'"
2457                " when the object file has no symbol table"),
2458              abfd, (uint64_t) r_symndx,
2459              (uint64_t) irela->r_offset, sec);
2460           bfd_set_error (bfd_error_bad_value);
2461           return FALSE;
2462         }
2463       irela += bed->s->int_rels_per_ext_rel;
2464       erela += shdr->sh_entsize;
2465     }
2466
2467   return TRUE;
2468 }
2469
2470 /* Read and swap the relocs for a section O.  They may have been
2471    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2472    not NULL, they are used as buffers to read into.  They are known to
2473    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2474    the return value is allocated using either malloc or bfd_alloc,
2475    according to the KEEP_MEMORY argument.  If O has two relocation
2476    sections (both REL and RELA relocations), then the REL_HDR
2477    relocations will appear first in INTERNAL_RELOCS, followed by the
2478    RELA_HDR relocations.  */
2479
2480 Elf_Internal_Rela *
2481 _bfd_elf_link_read_relocs (bfd *abfd,
2482                            asection *o,
2483                            void *external_relocs,
2484                            Elf_Internal_Rela *internal_relocs,
2485                            bfd_boolean keep_memory)
2486 {
2487   void *alloc1 = NULL;
2488   Elf_Internal_Rela *alloc2 = NULL;
2489   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2490   struct bfd_elf_section_data *esdo = elf_section_data (o);
2491   Elf_Internal_Rela *internal_rela_relocs;
2492
2493   if (esdo->relocs != NULL)
2494     return esdo->relocs;
2495
2496   if (o->reloc_count == 0)
2497     return NULL;
2498
2499   if (internal_relocs == NULL)
2500     {
2501       bfd_size_type size;
2502
2503       size = (bfd_size_type) o->reloc_count * sizeof (Elf_Internal_Rela);
2504       if (keep_memory)
2505         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2506       else
2507         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2508       if (internal_relocs == NULL)
2509         goto error_return;
2510     }
2511
2512   if (external_relocs == NULL)
2513     {
2514       bfd_size_type size = 0;
2515
2516       if (esdo->rel.hdr)
2517         size += esdo->rel.hdr->sh_size;
2518       if (esdo->rela.hdr)
2519         size += esdo->rela.hdr->sh_size;
2520
2521       alloc1 = bfd_malloc (size);
2522       if (alloc1 == NULL)
2523         goto error_return;
2524       external_relocs = alloc1;
2525     }
2526
2527   internal_rela_relocs = internal_relocs;
2528   if (esdo->rel.hdr)
2529     {
2530       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2531                                               external_relocs,
2532                                               internal_relocs))
2533         goto error_return;
2534       external_relocs = (((bfd_byte *) external_relocs)
2535                          + esdo->rel.hdr->sh_size);
2536       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2537                                * bed->s->int_rels_per_ext_rel);
2538     }
2539
2540   if (esdo->rela.hdr
2541       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2542                                               external_relocs,
2543                                               internal_rela_relocs)))
2544     goto error_return;
2545
2546   /* Cache the results for next time, if we can.  */
2547   if (keep_memory)
2548     esdo->relocs = internal_relocs;
2549
2550   if (alloc1 != NULL)
2551     free (alloc1);
2552
2553   /* Don't free alloc2, since if it was allocated we are passing it
2554      back (under the name of internal_relocs).  */
2555
2556   return internal_relocs;
2557
2558  error_return:
2559   if (alloc1 != NULL)
2560     free (alloc1);
2561   if (alloc2 != NULL)
2562     {
2563       if (keep_memory)
2564         bfd_release (abfd, alloc2);
2565       else
2566         free (alloc2);
2567     }
2568   return NULL;
2569 }
2570
2571 /* Compute the size of, and allocate space for, REL_HDR which is the
2572    section header for a section containing relocations for O.  */
2573
2574 static bfd_boolean
2575 _bfd_elf_link_size_reloc_section (bfd *abfd,
2576                                   struct bfd_elf_section_reloc_data *reldata)
2577 {
2578   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2579
2580   /* That allows us to calculate the size of the section.  */
2581   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2582
2583   /* The contents field must last into write_object_contents, so we
2584      allocate it with bfd_alloc rather than malloc.  Also since we
2585      cannot be sure that the contents will actually be filled in,
2586      we zero the allocated space.  */
2587   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2588   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2589     return FALSE;
2590
2591   if (reldata->hashes == NULL && reldata->count)
2592     {
2593       struct elf_link_hash_entry **p;
2594
2595       p = ((struct elf_link_hash_entry **)
2596            bfd_zmalloc (reldata->count * sizeof (*p)));
2597       if (p == NULL)
2598         return FALSE;
2599
2600       reldata->hashes = p;
2601     }
2602
2603   return TRUE;
2604 }
2605
2606 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2607    originated from the section given by INPUT_REL_HDR) to the
2608    OUTPUT_BFD.  */
2609
2610 bfd_boolean
2611 _bfd_elf_link_output_relocs (bfd *output_bfd,
2612                              asection *input_section,
2613                              Elf_Internal_Shdr *input_rel_hdr,
2614                              Elf_Internal_Rela *internal_relocs,
2615                              struct elf_link_hash_entry **rel_hash
2616                                ATTRIBUTE_UNUSED)
2617 {
2618   Elf_Internal_Rela *irela;
2619   Elf_Internal_Rela *irelaend;
2620   bfd_byte *erel;
2621   struct bfd_elf_section_reloc_data *output_reldata;
2622   asection *output_section;
2623   const struct elf_backend_data *bed;
2624   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2625   struct bfd_elf_section_data *esdo;
2626
2627   output_section = input_section->output_section;
2628
2629   bed = get_elf_backend_data (output_bfd);
2630   esdo = elf_section_data (output_section);
2631   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2632     {
2633       output_reldata = &esdo->rel;
2634       swap_out = bed->s->swap_reloc_out;
2635     }
2636   else if (esdo->rela.hdr
2637            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2638     {
2639       output_reldata = &esdo->rela;
2640       swap_out = bed->s->swap_reloca_out;
2641     }
2642   else
2643     {
2644       _bfd_error_handler
2645         /* xgettext:c-format */
2646         (_("%pB: relocation size mismatch in %pB section %pA"),
2647          output_bfd, input_section->owner, input_section);
2648       bfd_set_error (bfd_error_wrong_format);
2649       return FALSE;
2650     }
2651
2652   erel = output_reldata->hdr->contents;
2653   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2654   irela = internal_relocs;
2655   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2656                       * bed->s->int_rels_per_ext_rel);
2657   while (irela < irelaend)
2658     {
2659       (*swap_out) (output_bfd, irela, erel);
2660       irela += bed->s->int_rels_per_ext_rel;
2661       erel += input_rel_hdr->sh_entsize;
2662     }
2663
2664   /* Bump the counter, so that we know where to add the next set of
2665      relocations.  */
2666   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2667
2668   return TRUE;
2669 }
2670 \f
2671 /* Make weak undefined symbols in PIE dynamic.  */
2672
2673 bfd_boolean
2674 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2675                                  struct elf_link_hash_entry *h)
2676 {
2677   if (bfd_link_pie (info)
2678       && h->dynindx == -1
2679       && h->root.type == bfd_link_hash_undefweak)
2680     return bfd_elf_link_record_dynamic_symbol (info, h);
2681
2682   return TRUE;
2683 }
2684
2685 /* Fix up the flags for a symbol.  This handles various cases which
2686    can only be fixed after all the input files are seen.  This is
2687    currently called by both adjust_dynamic_symbol and
2688    assign_sym_version, which is unnecessary but perhaps more robust in
2689    the face of future changes.  */
2690
2691 static bfd_boolean
2692 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2693                            struct elf_info_failed *eif)
2694 {
2695   const struct elf_backend_data *bed;
2696
2697   /* If this symbol was mentioned in a non-ELF file, try to set
2698      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2699      permit a non-ELF file to correctly refer to a symbol defined in
2700      an ELF dynamic object.  */
2701   if (h->non_elf)
2702     {
2703       while (h->root.type == bfd_link_hash_indirect)
2704         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2705
2706       if (h->root.type != bfd_link_hash_defined
2707           && h->root.type != bfd_link_hash_defweak)
2708         {
2709           h->ref_regular = 1;
2710           h->ref_regular_nonweak = 1;
2711         }
2712       else
2713         {
2714           if (h->root.u.def.section->owner != NULL
2715               && (bfd_get_flavour (h->root.u.def.section->owner)
2716                   == bfd_target_elf_flavour))
2717             {
2718               h->ref_regular = 1;
2719               h->ref_regular_nonweak = 1;
2720             }
2721           else
2722             h->def_regular = 1;
2723         }
2724
2725       if (h->dynindx == -1
2726           && (h->def_dynamic
2727               || h->ref_dynamic))
2728         {
2729           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2730             {
2731               eif->failed = TRUE;
2732               return FALSE;
2733             }
2734         }
2735     }
2736   else
2737     {
2738       /* Unfortunately, NON_ELF is only correct if the symbol
2739          was first seen in a non-ELF file.  Fortunately, if the symbol
2740          was first seen in an ELF file, we're probably OK unless the
2741          symbol was defined in a non-ELF file.  Catch that case here.
2742          FIXME: We're still in trouble if the symbol was first seen in
2743          a dynamic object, and then later in a non-ELF regular object.  */
2744       if ((h->root.type == bfd_link_hash_defined
2745            || h->root.type == bfd_link_hash_defweak)
2746           && !h->def_regular
2747           && (h->root.u.def.section->owner != NULL
2748               ? (bfd_get_flavour (h->root.u.def.section->owner)
2749                  != bfd_target_elf_flavour)
2750               : (bfd_is_abs_section (h->root.u.def.section)
2751                  && !h->def_dynamic)))
2752         h->def_regular = 1;
2753     }
2754
2755   /* Backend specific symbol fixup.  */
2756   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2757   if (bed->elf_backend_fixup_symbol
2758       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2759     return FALSE;
2760
2761   /* If this is a final link, and the symbol was defined as a common
2762      symbol in a regular object file, and there was no definition in
2763      any dynamic object, then the linker will have allocated space for
2764      the symbol in a common section but the DEF_REGULAR
2765      flag will not have been set.  */
2766   if (h->root.type == bfd_link_hash_defined
2767       && !h->def_regular
2768       && h->ref_regular
2769       && !h->def_dynamic
2770       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2771     h->def_regular = 1;
2772
2773   /* If a weak undefined symbol has non-default visibility, we also
2774      hide it from the dynamic linker.  */
2775   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2776       && h->root.type == bfd_link_hash_undefweak)
2777     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2778
2779   /* A hidden versioned symbol in executable should be forced local if
2780      it is is locally defined, not referenced by shared library and not
2781      exported.  */
2782   else if (bfd_link_executable (eif->info)
2783            && h->versioned == versioned_hidden
2784            && !eif->info->export_dynamic
2785            && !h->dynamic
2786            && !h->ref_dynamic
2787            && h->def_regular)
2788     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2789
2790   /* If -Bsymbolic was used (which means to bind references to global
2791      symbols to the definition within the shared object), and this
2792      symbol was defined in a regular object, then it actually doesn't
2793      need a PLT entry.  Likewise, if the symbol has non-default
2794      visibility.  If the symbol has hidden or internal visibility, we
2795      will force it local.  */
2796   else if (h->needs_plt
2797            && bfd_link_pic (eif->info)
2798            && is_elf_hash_table (eif->info->hash)
2799            && (SYMBOLIC_BIND (eif->info, h)
2800                || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2801            && h->def_regular)
2802     {
2803       bfd_boolean force_local;
2804
2805       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2806                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2807       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2808     }
2809
2810   /* If this is a weak defined symbol in a dynamic object, and we know
2811      the real definition in the dynamic object, copy interesting flags
2812      over to the real definition.  */
2813   if (h->is_weakalias)
2814     {
2815       struct elf_link_hash_entry *def = weakdef (h);
2816
2817       /* If the real definition is defined by a regular object file,
2818          don't do anything special.  See the longer description in
2819          _bfd_elf_adjust_dynamic_symbol, below.  */
2820       if (def->def_regular)
2821         {
2822           h = def;
2823           while ((h = h->u.alias) != def)
2824             h->is_weakalias = 0;
2825         }
2826       else
2827         {
2828           while (h->root.type == bfd_link_hash_indirect)
2829             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2830           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2831                       || h->root.type == bfd_link_hash_defweak);
2832           BFD_ASSERT (def->def_dynamic);
2833           BFD_ASSERT (def->root.type == bfd_link_hash_defined);
2834           (*bed->elf_backend_copy_indirect_symbol) (eif->info, def, h);
2835         }
2836     }
2837
2838   return TRUE;
2839 }
2840
2841 /* Make the backend pick a good value for a dynamic symbol.  This is
2842    called via elf_link_hash_traverse, and also calls itself
2843    recursively.  */
2844
2845 static bfd_boolean
2846 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2847 {
2848   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2849   struct elf_link_hash_table *htab;
2850   const struct elf_backend_data *bed;
2851
2852   if (! is_elf_hash_table (eif->info->hash))
2853     return FALSE;
2854
2855   /* Ignore indirect symbols.  These are added by the versioning code.  */
2856   if (h->root.type == bfd_link_hash_indirect)
2857     return TRUE;
2858
2859   /* Fix the symbol flags.  */
2860   if (! _bfd_elf_fix_symbol_flags (h, eif))
2861     return FALSE;
2862
2863   htab = elf_hash_table (eif->info);
2864   bed = get_elf_backend_data (htab->dynobj);
2865
2866   if (h->root.type == bfd_link_hash_undefweak)
2867     {
2868       if (eif->info->dynamic_undefined_weak == 0)
2869         (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2870       else if (eif->info->dynamic_undefined_weak > 0
2871                && h->ref_regular
2872                && ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2873                && !bfd_hide_sym_by_version (eif->info->version_info,
2874                                             h->root.root.string))
2875         {
2876           if (!bfd_elf_link_record_dynamic_symbol (eif->info, h))
2877             {
2878               eif->failed = TRUE;
2879               return FALSE;
2880             }
2881         }
2882     }
2883
2884   /* If this symbol does not require a PLT entry, and it is not
2885      defined by a dynamic object, or is not referenced by a regular
2886      object, ignore it.  We do have to handle a weak defined symbol,
2887      even if no regular object refers to it, if we decided to add it
2888      to the dynamic symbol table.  FIXME: Do we normally need to worry
2889      about symbols which are defined by one dynamic object and
2890      referenced by another one?  */
2891   if (!h->needs_plt
2892       && h->type != STT_GNU_IFUNC
2893       && (h->def_regular
2894           || !h->def_dynamic
2895           || (!h->ref_regular
2896               && (!h->is_weakalias || weakdef (h)->dynindx == -1))))
2897     {
2898       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2899       return TRUE;
2900     }
2901
2902   /* If we've already adjusted this symbol, don't do it again.  This
2903      can happen via a recursive call.  */
2904   if (h->dynamic_adjusted)
2905     return TRUE;
2906
2907   /* Don't look at this symbol again.  Note that we must set this
2908      after checking the above conditions, because we may look at a
2909      symbol once, decide not to do anything, and then get called
2910      recursively later after REF_REGULAR is set below.  */
2911   h->dynamic_adjusted = 1;
2912
2913   /* If this is a weak definition, and we know a real definition, and
2914      the real symbol is not itself defined by a regular object file,
2915      then get a good value for the real definition.  We handle the
2916      real symbol first, for the convenience of the backend routine.
2917
2918      Note that there is a confusing case here.  If the real definition
2919      is defined by a regular object file, we don't get the real symbol
2920      from the dynamic object, but we do get the weak symbol.  If the
2921      processor backend uses a COPY reloc, then if some routine in the
2922      dynamic object changes the real symbol, we will not see that
2923      change in the corresponding weak symbol.  This is the way other
2924      ELF linkers work as well, and seems to be a result of the shared
2925      library model.
2926
2927      I will clarify this issue.  Most SVR4 shared libraries define the
2928      variable _timezone and define timezone as a weak synonym.  The
2929      tzset call changes _timezone.  If you write
2930        extern int timezone;
2931        int _timezone = 5;
2932        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2933      you might expect that, since timezone is a synonym for _timezone,
2934      the same number will print both times.  However, if the processor
2935      backend uses a COPY reloc, then actually timezone will be copied
2936      into your process image, and, since you define _timezone
2937      yourself, _timezone will not.  Thus timezone and _timezone will
2938      wind up at different memory locations.  The tzset call will set
2939      _timezone, leaving timezone unchanged.  */
2940
2941   if (h->is_weakalias)
2942     {
2943       struct elf_link_hash_entry *def = weakdef (h);
2944
2945       /* If we get to this point, there is an implicit reference to
2946          the alias by a regular object file via the weak symbol H.  */
2947       def->ref_regular = 1;
2948
2949       /* Ensure that the backend adjust_dynamic_symbol function sees
2950          the strong alias before H by recursively calling ourselves.  */
2951       if (!_bfd_elf_adjust_dynamic_symbol (def, eif))
2952         return FALSE;
2953     }
2954
2955   /* If a symbol has no type and no size and does not require a PLT
2956      entry, then we are probably about to do the wrong thing here: we
2957      are probably going to create a COPY reloc for an empty object.
2958      This case can arise when a shared object is built with assembly
2959      code, and the assembly code fails to set the symbol type.  */
2960   if (h->size == 0
2961       && h->type == STT_NOTYPE
2962       && !h->needs_plt)
2963     _bfd_error_handler
2964       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2965        h->root.root.string);
2966
2967   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2968     {
2969       eif->failed = TRUE;
2970       return FALSE;
2971     }
2972
2973   return TRUE;
2974 }
2975
2976 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2977    DYNBSS.  */
2978
2979 bfd_boolean
2980 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
2981                               struct elf_link_hash_entry *h,
2982                               asection *dynbss)
2983 {
2984   unsigned int power_of_two;
2985   bfd_vma mask;
2986   asection *sec = h->root.u.def.section;
2987
2988   /* The section alignment of the definition is the maximum alignment
2989      requirement of symbols defined in the section.  Since we don't
2990      know the symbol alignment requirement, we start with the
2991      maximum alignment and check low bits of the symbol address
2992      for the minimum alignment.  */
2993   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2994   mask = ((bfd_vma) 1 << power_of_two) - 1;
2995   while ((h->root.u.def.value & mask) != 0)
2996     {
2997        mask >>= 1;
2998        --power_of_two;
2999     }
3000
3001   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
3002                                                 dynbss))
3003     {
3004       /* Adjust the section alignment if needed.  */
3005       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
3006                                        power_of_two))
3007         return FALSE;
3008     }
3009
3010   /* We make sure that the symbol will be aligned properly.  */
3011   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
3012
3013   /* Define the symbol as being at this point in DYNBSS.  */
3014   h->root.u.def.section = dynbss;
3015   h->root.u.def.value = dynbss->size;
3016
3017   /* Increment the size of DYNBSS to make room for the symbol.  */
3018   dynbss->size += h->size;
3019
3020   /* No error if extern_protected_data is true.  */
3021   if (h->protected_def
3022       && (!info->extern_protected_data
3023           || (info->extern_protected_data < 0
3024               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
3025     info->callbacks->einfo
3026       (_("%P: copy reloc against protected `%pT' is dangerous\n"),
3027        h->root.root.string);
3028
3029   return TRUE;
3030 }
3031
3032 /* Adjust all external symbols pointing into SEC_MERGE sections
3033    to reflect the object merging within the sections.  */
3034
3035 static bfd_boolean
3036 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
3037 {
3038   asection *sec;
3039
3040   if ((h->root.type == bfd_link_hash_defined
3041        || h->root.type == bfd_link_hash_defweak)
3042       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
3043       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
3044     {
3045       bfd *output_bfd = (bfd *) data;
3046
3047       h->root.u.def.value =
3048         _bfd_merged_section_offset (output_bfd,
3049                                     &h->root.u.def.section,
3050                                     elf_section_data (sec)->sec_info,
3051                                     h->root.u.def.value);
3052     }
3053
3054   return TRUE;
3055 }
3056
3057 /* Returns false if the symbol referred to by H should be considered
3058    to resolve local to the current module, and true if it should be
3059    considered to bind dynamically.  */
3060
3061 bfd_boolean
3062 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
3063                            struct bfd_link_info *info,
3064                            bfd_boolean not_local_protected)
3065 {
3066   bfd_boolean binding_stays_local_p;
3067   const struct elf_backend_data *bed;
3068   struct elf_link_hash_table *hash_table;
3069
3070   if (h == NULL)
3071     return FALSE;
3072
3073   while (h->root.type == bfd_link_hash_indirect
3074          || h->root.type == bfd_link_hash_warning)
3075     h = (struct elf_link_hash_entry *) h->root.u.i.link;
3076
3077   /* If it was forced local, then clearly it's not dynamic.  */
3078   if (h->dynindx == -1)
3079     return FALSE;
3080   if (h->forced_local)
3081     return FALSE;
3082
3083   /* Identify the cases where name binding rules say that a
3084      visible symbol resolves locally.  */
3085   binding_stays_local_p = (bfd_link_executable (info)
3086                            || SYMBOLIC_BIND (info, h));
3087
3088   switch (ELF_ST_VISIBILITY (h->other))
3089     {
3090     case STV_INTERNAL:
3091     case STV_HIDDEN:
3092       return FALSE;
3093
3094     case STV_PROTECTED:
3095       hash_table = elf_hash_table (info);
3096       if (!is_elf_hash_table (hash_table))
3097         return FALSE;
3098
3099       bed = get_elf_backend_data (hash_table->dynobj);
3100
3101       /* Proper resolution for function pointer equality may require
3102          that these symbols perhaps be resolved dynamically, even though
3103          we should be resolving them to the current module.  */
3104       if (!not_local_protected || !bed->is_function_type (h->type))
3105         binding_stays_local_p = TRUE;
3106       break;
3107
3108     default:
3109       break;
3110     }
3111
3112   /* If it isn't defined locally, then clearly it's dynamic.  */
3113   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
3114     return TRUE;
3115
3116   /* Otherwise, the symbol is dynamic if binding rules don't tell
3117      us that it remains local.  */
3118   return !binding_stays_local_p;
3119 }
3120
3121 /* Return true if the symbol referred to by H should be considered
3122    to resolve local to the current module, and false otherwise.  Differs
3123    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
3124    undefined symbols.  The two functions are virtually identical except
3125    for the place where dynindx == -1 is tested.  If that test is true,
3126    _bfd_elf_dynamic_symbol_p will say the symbol is local, while
3127    _bfd_elf_symbol_refs_local_p will say the symbol is local only for
3128    defined symbols.
3129    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
3130    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
3131    treatment of undefined weak symbols.  For those that do not make
3132    undefined weak symbols dynamic, both functions may return false.  */
3133
3134 bfd_boolean
3135 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
3136                               struct bfd_link_info *info,
3137                               bfd_boolean local_protected)
3138 {
3139   const struct elf_backend_data *bed;
3140   struct elf_link_hash_table *hash_table;
3141
3142   /* If it's a local sym, of course we resolve locally.  */
3143   if (h == NULL)
3144     return TRUE;
3145
3146   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
3147   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
3148       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
3149     return TRUE;
3150
3151   /* Forced local symbols resolve locally.  */
3152   if (h->forced_local)
3153     return TRUE;
3154
3155   /* Common symbols that become definitions don't get the DEF_REGULAR
3156      flag set, so test it first, and don't bail out.  */
3157   if (ELF_COMMON_DEF_P (h))
3158     /* Do nothing.  */;
3159   /* If we don't have a definition in a regular file, then we can't
3160      resolve locally.  The sym is either undefined or dynamic.  */
3161   else if (!h->def_regular)
3162     return FALSE;
3163
3164   /* Non-dynamic symbols resolve locally.  */
3165   if (h->dynindx == -1)
3166     return TRUE;
3167
3168   /* At this point, we know the symbol is defined and dynamic.  In an
3169      executable it must resolve locally, likewise when building symbolic
3170      shared libraries.  */
3171   if (bfd_link_executable (info) || SYMBOLIC_BIND (info, h))
3172     return TRUE;
3173
3174   /* Now deal with defined dynamic symbols in shared libraries.  Ones
3175      with default visibility might not resolve locally.  */
3176   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
3177     return FALSE;
3178
3179   hash_table = elf_hash_table (info);
3180   if (!is_elf_hash_table (hash_table))
3181     return TRUE;
3182
3183   bed = get_elf_backend_data (hash_table->dynobj);
3184
3185   /* If extern_protected_data is false, STV_PROTECTED non-function
3186      symbols are local.  */
3187   if ((!info->extern_protected_data
3188        || (info->extern_protected_data < 0
3189            && !bed->extern_protected_data))
3190       && !bed->is_function_type (h->type))
3191     return TRUE;
3192
3193   /* Function pointer equality tests may require that STV_PROTECTED
3194      symbols be treated as dynamic symbols.  If the address of a
3195      function not defined in an executable is set to that function's
3196      plt entry in the executable, then the address of the function in
3197      a shared library must also be the plt entry in the executable.  */
3198   return local_protected;
3199 }
3200
3201 /* Caches some TLS segment info, and ensures that the TLS segment vma is
3202    aligned.  Returns the first TLS output section.  */
3203
3204 struct bfd_section *
3205 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
3206 {
3207   struct bfd_section *sec, *tls;
3208   unsigned int align = 0;
3209
3210   for (sec = obfd->sections; sec != NULL; sec = sec->next)
3211     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
3212       break;
3213   tls = sec;
3214
3215   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
3216     if (sec->alignment_power > align)
3217       align = sec->alignment_power;
3218
3219   elf_hash_table (info)->tls_sec = tls;
3220
3221   /* Ensure the alignment of the first section is the largest alignment,
3222      so that the tls segment starts aligned.  */
3223   if (tls != NULL)
3224     tls->alignment_power = align;
3225
3226   return tls;
3227 }
3228
3229 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
3230 static bfd_boolean
3231 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
3232                                   Elf_Internal_Sym *sym)
3233 {
3234   const struct elf_backend_data *bed;
3235
3236   /* Local symbols do not count, but target specific ones might.  */
3237   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
3238       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
3239     return FALSE;
3240
3241   bed = get_elf_backend_data (abfd);
3242   /* Function symbols do not count.  */
3243   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
3244     return FALSE;
3245
3246   /* If the section is undefined, then so is the symbol.  */
3247   if (sym->st_shndx == SHN_UNDEF)
3248     return FALSE;
3249
3250   /* If the symbol is defined in the common section, then
3251      it is a common definition and so does not count.  */
3252   if (bed->common_definition (sym))
3253     return FALSE;
3254
3255   /* If the symbol is in a target specific section then we
3256      must rely upon the backend to tell us what it is.  */
3257   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3258     /* FIXME - this function is not coded yet:
3259
3260        return _bfd_is_global_symbol_definition (abfd, sym);
3261
3262        Instead for now assume that the definition is not global,
3263        Even if this is wrong, at least the linker will behave
3264        in the same way that it used to do.  */
3265     return FALSE;
3266
3267   return TRUE;
3268 }
3269
3270 /* Search the symbol table of the archive element of the archive ABFD
3271    whose archive map contains a mention of SYMDEF, and determine if
3272    the symbol is defined in this element.  */
3273 static bfd_boolean
3274 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3275 {
3276   Elf_Internal_Shdr * hdr;
3277   size_t symcount;
3278   size_t extsymcount;
3279   size_t extsymoff;
3280   Elf_Internal_Sym *isymbuf;
3281   Elf_Internal_Sym *isym;
3282   Elf_Internal_Sym *isymend;
3283   bfd_boolean result;
3284
3285   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3286   if (abfd == NULL)
3287     return FALSE;
3288
3289   if (! bfd_check_format (abfd, bfd_object))
3290     return FALSE;
3291
3292   /* Select the appropriate symbol table.  If we don't know if the
3293      object file is an IR object, give linker LTO plugin a chance to
3294      get the correct symbol table.  */
3295   if (abfd->plugin_format == bfd_plugin_yes
3296 #if BFD_SUPPORTS_PLUGINS
3297       || (abfd->plugin_format == bfd_plugin_unknown
3298           && bfd_link_plugin_object_p (abfd))
3299 #endif
3300       )
3301     {
3302       /* Use the IR symbol table if the object has been claimed by
3303          plugin.  */
3304       abfd = abfd->plugin_dummy_bfd;
3305       hdr = &elf_tdata (abfd)->symtab_hdr;
3306     }
3307   else if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3308     hdr = &elf_tdata (abfd)->symtab_hdr;
3309   else
3310     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3311
3312   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3313
3314   /* The sh_info field of the symtab header tells us where the
3315      external symbols start.  We don't care about the local symbols.  */
3316   if (elf_bad_symtab (abfd))
3317     {
3318       extsymcount = symcount;
3319       extsymoff = 0;
3320     }
3321   else
3322     {
3323       extsymcount = symcount - hdr->sh_info;
3324       extsymoff = hdr->sh_info;
3325     }
3326
3327   if (extsymcount == 0)
3328     return FALSE;
3329
3330   /* Read in the symbol table.  */
3331   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3332                                   NULL, NULL, NULL);
3333   if (isymbuf == NULL)
3334     return FALSE;
3335
3336   /* Scan the symbol table looking for SYMDEF.  */
3337   result = FALSE;
3338   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3339     {
3340       const char *name;
3341
3342       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3343                                               isym->st_name);
3344       if (name == NULL)
3345         break;
3346
3347       if (strcmp (name, symdef->name) == 0)
3348         {
3349           result = is_global_data_symbol_definition (abfd, isym);
3350           break;
3351         }
3352     }
3353
3354   free (isymbuf);
3355
3356   return result;
3357 }
3358 \f
3359 /* Add an entry to the .dynamic table.  */
3360
3361 bfd_boolean
3362 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3363                             bfd_vma tag,
3364                             bfd_vma val)
3365 {
3366   struct elf_link_hash_table *hash_table;
3367   const struct elf_backend_data *bed;
3368   asection *s;
3369   bfd_size_type newsize;
3370   bfd_byte *newcontents;
3371   Elf_Internal_Dyn dyn;
3372
3373   hash_table = elf_hash_table (info);
3374   if (! is_elf_hash_table (hash_table))
3375     return FALSE;
3376
3377   bed = get_elf_backend_data (hash_table->dynobj);
3378   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3379   BFD_ASSERT (s != NULL);
3380
3381   newsize = s->size + bed->s->sizeof_dyn;
3382   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3383   if (newcontents == NULL)
3384     return FALSE;
3385
3386   dyn.d_tag = tag;
3387   dyn.d_un.d_val = val;
3388   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3389
3390   s->size = newsize;
3391   s->contents = newcontents;
3392
3393   return TRUE;
3394 }
3395
3396 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3397    otherwise just check whether one already exists.  Returns -1 on error,
3398    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3399
3400 static int
3401 elf_add_dt_needed_tag (bfd *abfd,
3402                        struct bfd_link_info *info,
3403                        const char *soname,
3404                        bfd_boolean do_it)
3405 {
3406   struct elf_link_hash_table *hash_table;
3407   size_t strindex;
3408
3409   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3410     return -1;
3411
3412   hash_table = elf_hash_table (info);
3413   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3414   if (strindex == (size_t) -1)
3415     return -1;
3416
3417   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3418     {
3419       asection *sdyn;
3420       const struct elf_backend_data *bed;
3421       bfd_byte *extdyn;
3422
3423       bed = get_elf_backend_data (hash_table->dynobj);
3424       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3425       if (sdyn != NULL)
3426         for (extdyn = sdyn->contents;
3427              extdyn < sdyn->contents + sdyn->size;
3428              extdyn += bed->s->sizeof_dyn)
3429           {
3430             Elf_Internal_Dyn dyn;
3431
3432             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3433             if (dyn.d_tag == DT_NEEDED
3434                 && dyn.d_un.d_val == strindex)
3435               {
3436                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3437                 return 1;
3438               }
3439           }
3440     }
3441
3442   if (do_it)
3443     {
3444       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3445         return -1;
3446
3447       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3448         return -1;
3449     }
3450   else
3451     /* We were just checking for existence of the tag.  */
3452     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3453
3454   return 0;
3455 }
3456
3457 /* Return true if SONAME is on the needed list between NEEDED and STOP
3458    (or the end of list if STOP is NULL), and needed by a library that
3459    will be loaded.  */
3460
3461 static bfd_boolean
3462 on_needed_list (const char *soname,
3463                 struct bfd_link_needed_list *needed,
3464                 struct bfd_link_needed_list *stop)
3465 {
3466   struct bfd_link_needed_list *look;
3467   for (look = needed; look != stop; look = look->next)
3468     if (strcmp (soname, look->name) == 0
3469         && ((elf_dyn_lib_class (look->by) & DYN_AS_NEEDED) == 0
3470             /* If needed by a library that itself is not directly
3471                needed, recursively check whether that library is
3472                indirectly needed.  Since we add DT_NEEDED entries to
3473                the end of the list, library dependencies appear after
3474                the library.  Therefore search prior to the current
3475                LOOK, preventing possible infinite recursion.  */
3476             || on_needed_list (elf_dt_name (look->by), needed, look)))
3477       return TRUE;
3478
3479   return FALSE;
3480 }
3481
3482 /* Sort symbol by value, section, and size.  */
3483 static int
3484 elf_sort_symbol (const void *arg1, const void *arg2)
3485 {
3486   const struct elf_link_hash_entry *h1;
3487   const struct elf_link_hash_entry *h2;
3488   bfd_signed_vma vdiff;
3489
3490   h1 = *(const struct elf_link_hash_entry **) arg1;
3491   h2 = *(const struct elf_link_hash_entry **) arg2;
3492   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3493   if (vdiff != 0)
3494     return vdiff > 0 ? 1 : -1;
3495   else
3496     {
3497       int sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3498       if (sdiff != 0)
3499         return sdiff > 0 ? 1 : -1;
3500     }
3501   vdiff = h1->size - h2->size;
3502   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3503 }
3504
3505 /* This function is used to adjust offsets into .dynstr for
3506    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3507
3508 static bfd_boolean
3509 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3510 {
3511   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3512
3513   if (h->dynindx != -1)
3514     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3515   return TRUE;
3516 }
3517
3518 /* Assign string offsets in .dynstr, update all structures referencing
3519    them.  */
3520
3521 static bfd_boolean
3522 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3523 {
3524   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3525   struct elf_link_local_dynamic_entry *entry;
3526   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3527   bfd *dynobj = hash_table->dynobj;
3528   asection *sdyn;
3529   bfd_size_type size;
3530   const struct elf_backend_data *bed;
3531   bfd_byte *extdyn;
3532
3533   _bfd_elf_strtab_finalize (dynstr);
3534   size = _bfd_elf_strtab_size (dynstr);
3535
3536   bed = get_elf_backend_data (dynobj);
3537   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3538   BFD_ASSERT (sdyn != NULL);
3539
3540   /* Update all .dynamic entries referencing .dynstr strings.  */
3541   for (extdyn = sdyn->contents;
3542        extdyn < sdyn->contents + sdyn->size;
3543        extdyn += bed->s->sizeof_dyn)
3544     {
3545       Elf_Internal_Dyn dyn;
3546
3547       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3548       switch (dyn.d_tag)
3549         {
3550         case DT_STRSZ:
3551           dyn.d_un.d_val = size;
3552           break;
3553         case DT_NEEDED:
3554         case DT_SONAME:
3555         case DT_RPATH:
3556         case DT_RUNPATH:
3557         case DT_FILTER:
3558         case DT_AUXILIARY:
3559         case DT_AUDIT:
3560         case DT_DEPAUDIT:
3561           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3562           break;
3563         default:
3564           continue;
3565         }
3566       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3567     }
3568
3569   /* Now update local dynamic symbols.  */
3570   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3571     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3572                                                   entry->isym.st_name);
3573
3574   /* And the rest of dynamic symbols.  */
3575   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3576
3577   /* Adjust version definitions.  */
3578   if (elf_tdata (output_bfd)->cverdefs)
3579     {
3580       asection *s;
3581       bfd_byte *p;
3582       size_t i;
3583       Elf_Internal_Verdef def;
3584       Elf_Internal_Verdaux defaux;
3585
3586       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3587       p = s->contents;
3588       do
3589         {
3590           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3591                                    &def);
3592           p += sizeof (Elf_External_Verdef);
3593           if (def.vd_aux != sizeof (Elf_External_Verdef))
3594             continue;
3595           for (i = 0; i < def.vd_cnt; ++i)
3596             {
3597               _bfd_elf_swap_verdaux_in (output_bfd,
3598                                         (Elf_External_Verdaux *) p, &defaux);
3599               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3600                                                         defaux.vda_name);
3601               _bfd_elf_swap_verdaux_out (output_bfd,
3602                                          &defaux, (Elf_External_Verdaux *) p);
3603               p += sizeof (Elf_External_Verdaux);
3604             }
3605         }
3606       while (def.vd_next);
3607     }
3608
3609   /* Adjust version references.  */
3610   if (elf_tdata (output_bfd)->verref)
3611     {
3612       asection *s;
3613       bfd_byte *p;
3614       size_t i;
3615       Elf_Internal_Verneed need;
3616       Elf_Internal_Vernaux needaux;
3617
3618       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3619       p = s->contents;
3620       do
3621         {
3622           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3623                                     &need);
3624           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3625           _bfd_elf_swap_verneed_out (output_bfd, &need,
3626                                      (Elf_External_Verneed *) p);
3627           p += sizeof (Elf_External_Verneed);
3628           for (i = 0; i < need.vn_cnt; ++i)
3629             {
3630               _bfd_elf_swap_vernaux_in (output_bfd,
3631                                         (Elf_External_Vernaux *) p, &needaux);
3632               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3633                                                          needaux.vna_name);
3634               _bfd_elf_swap_vernaux_out (output_bfd,
3635                                          &needaux,
3636                                          (Elf_External_Vernaux *) p);
3637               p += sizeof (Elf_External_Vernaux);
3638             }
3639         }
3640       while (need.vn_next);
3641     }
3642
3643   return TRUE;
3644 }
3645 \f
3646 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3647    The default is to only match when the INPUT and OUTPUT are exactly
3648    the same target.  */
3649
3650 bfd_boolean
3651 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3652                                     const bfd_target *output)
3653 {
3654   return input == output;
3655 }
3656
3657 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3658    This version is used when different targets for the same architecture
3659    are virtually identical.  */
3660
3661 bfd_boolean
3662 _bfd_elf_relocs_compatible (const bfd_target *input,
3663                             const bfd_target *output)
3664 {
3665   const struct elf_backend_data *obed, *ibed;
3666
3667   if (input == output)
3668     return TRUE;
3669
3670   ibed = xvec_get_elf_backend_data (input);
3671   obed = xvec_get_elf_backend_data (output);
3672
3673   if (ibed->arch != obed->arch)
3674     return FALSE;
3675
3676   /* If both backends are using this function, deem them compatible.  */
3677   return ibed->relocs_compatible == obed->relocs_compatible;
3678 }
3679
3680 /* Make a special call to the linker "notice" function to tell it that
3681    we are about to handle an as-needed lib, or have finished
3682    processing the lib.  */
3683
3684 bfd_boolean
3685 _bfd_elf_notice_as_needed (bfd *ibfd,
3686                            struct bfd_link_info *info,
3687                            enum notice_asneeded_action act)
3688 {
3689   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3690 }
3691
3692 /* Check relocations an ELF object file.  */
3693
3694 bfd_boolean
3695 _bfd_elf_link_check_relocs (bfd *abfd, struct bfd_link_info *info)
3696 {
3697   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3698   struct elf_link_hash_table *htab = elf_hash_table (info);
3699
3700   /* If this object is the same format as the output object, and it is
3701      not a shared library, then let the backend look through the
3702      relocs.
3703
3704      This is required to build global offset table entries and to
3705      arrange for dynamic relocs.  It is not required for the
3706      particular common case of linking non PIC code, even when linking
3707      against shared libraries, but unfortunately there is no way of
3708      knowing whether an object file has been compiled PIC or not.
3709      Looking through the relocs is not particularly time consuming.
3710      The problem is that we must either (1) keep the relocs in memory,
3711      which causes the linker to require additional runtime memory or
3712      (2) read the relocs twice from the input file, which wastes time.
3713      This would be a good case for using mmap.
3714
3715      I have no idea how to handle linking PIC code into a file of a
3716      different format.  It probably can't be done.  */
3717   if ((abfd->flags & DYNAMIC) == 0
3718       && is_elf_hash_table (htab)
3719       && bed->check_relocs != NULL
3720       && elf_object_id (abfd) == elf_hash_table_id (htab)
3721       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
3722     {
3723       asection *o;
3724
3725       for (o = abfd->sections; o != NULL; o = o->next)
3726         {
3727           Elf_Internal_Rela *internal_relocs;
3728           bfd_boolean ok;
3729
3730           /* Don't check relocations in excluded sections.  */
3731           if ((o->flags & SEC_RELOC) == 0
3732               || (o->flags & SEC_EXCLUDE) != 0
3733               || o->reloc_count == 0
3734               || ((info->strip == strip_all || info->strip == strip_debugger)
3735                   && (o->flags & SEC_DEBUGGING) != 0)
3736               || bfd_is_abs_section (o->output_section))
3737             continue;
3738
3739           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
3740                                                        info->keep_memory);
3741           if (internal_relocs == NULL)
3742             return FALSE;
3743
3744           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
3745
3746           if (elf_section_data (o)->relocs != internal_relocs)
3747             free (internal_relocs);
3748
3749           if (! ok)
3750             return FALSE;
3751         }
3752     }
3753
3754   return TRUE;
3755 }
3756
3757 /* Add symbols from an ELF object file to the linker hash table.  */
3758
3759 static bfd_boolean
3760 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3761 {
3762   Elf_Internal_Ehdr *ehdr;
3763   Elf_Internal_Shdr *hdr;
3764   size_t symcount;
3765   size_t extsymcount;
3766   size_t extsymoff;
3767   struct elf_link_hash_entry **sym_hash;
3768   bfd_boolean dynamic;
3769   Elf_External_Versym *extversym = NULL;
3770   Elf_External_Versym *ever;
3771   struct elf_link_hash_entry *weaks;
3772   struct elf_link_hash_entry **nondeflt_vers = NULL;
3773   size_t nondeflt_vers_cnt = 0;
3774   Elf_Internal_Sym *isymbuf = NULL;
3775   Elf_Internal_Sym *isym;
3776   Elf_Internal_Sym *isymend;
3777   const struct elf_backend_data *bed;
3778   bfd_boolean add_needed;
3779   struct elf_link_hash_table *htab;
3780   bfd_size_type amt;
3781   void *alloc_mark = NULL;
3782   struct bfd_hash_entry **old_table = NULL;
3783   unsigned int old_size = 0;
3784   unsigned int old_count = 0;
3785   void *old_tab = NULL;
3786   void *old_ent;
3787   struct bfd_link_hash_entry *old_undefs = NULL;
3788   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3789   void *old_strtab = NULL;
3790   size_t tabsize = 0;
3791   asection *s;
3792   bfd_boolean just_syms;
3793
3794   htab = elf_hash_table (info);
3795   bed = get_elf_backend_data (abfd);
3796
3797   if ((abfd->flags & DYNAMIC) == 0)
3798     dynamic = FALSE;
3799   else
3800     {
3801       dynamic = TRUE;
3802
3803       /* You can't use -r against a dynamic object.  Also, there's no
3804          hope of using a dynamic object which does not exactly match
3805          the format of the output file.  */
3806       if (bfd_link_relocatable (info)
3807           || !is_elf_hash_table (htab)
3808           || info->output_bfd->xvec != abfd->xvec)
3809         {
3810           if (bfd_link_relocatable (info))
3811             bfd_set_error (bfd_error_invalid_operation);
3812           else
3813             bfd_set_error (bfd_error_wrong_format);
3814           goto error_return;
3815         }
3816     }
3817
3818   ehdr = elf_elfheader (abfd);
3819   if (info->warn_alternate_em
3820       && bed->elf_machine_code != ehdr->e_machine
3821       && ((bed->elf_machine_alt1 != 0
3822            && ehdr->e_machine == bed->elf_machine_alt1)
3823           || (bed->elf_machine_alt2 != 0
3824               && ehdr->e_machine == bed->elf_machine_alt2)))
3825     info->callbacks->einfo
3826       /* xgettext:c-format */
3827       (_("%P: alternate ELF machine code found (%d) in %pB, expecting %d\n"),
3828        ehdr->e_machine, abfd, bed->elf_machine_code);
3829
3830   /* As a GNU extension, any input sections which are named
3831      .gnu.warning.SYMBOL are treated as warning symbols for the given
3832      symbol.  This differs from .gnu.warning sections, which generate
3833      warnings when they are included in an output file.  */
3834   /* PR 12761: Also generate this warning when building shared libraries.  */
3835   for (s = abfd->sections; s != NULL; s = s->next)
3836     {
3837       const char *name;
3838
3839       name = bfd_get_section_name (abfd, s);
3840       if (CONST_STRNEQ (name, ".gnu.warning."))
3841         {
3842           char *msg;
3843           bfd_size_type sz;
3844
3845           name += sizeof ".gnu.warning." - 1;
3846
3847           /* If this is a shared object, then look up the symbol
3848              in the hash table.  If it is there, and it is already
3849              been defined, then we will not be using the entry
3850              from this shared object, so we don't need to warn.
3851              FIXME: If we see the definition in a regular object
3852              later on, we will warn, but we shouldn't.  The only
3853              fix is to keep track of what warnings we are supposed
3854              to emit, and then handle them all at the end of the
3855              link.  */
3856           if (dynamic)
3857             {
3858               struct elf_link_hash_entry *h;
3859
3860               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3861
3862               /* FIXME: What about bfd_link_hash_common?  */
3863               if (h != NULL
3864                   && (h->root.type == bfd_link_hash_defined
3865                       || h->root.type == bfd_link_hash_defweak))
3866                 continue;
3867             }
3868
3869           sz = s->size;
3870           msg = (char *) bfd_alloc (abfd, sz + 1);
3871           if (msg == NULL)
3872             goto error_return;
3873
3874           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3875             goto error_return;
3876
3877           msg[sz] = '\0';
3878
3879           if (! (_bfd_generic_link_add_one_symbol
3880                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3881                   FALSE, bed->collect, NULL)))
3882             goto error_return;
3883
3884           if (bfd_link_executable (info))
3885             {
3886               /* Clobber the section size so that the warning does
3887                  not get copied into the output file.  */
3888               s->size = 0;
3889
3890               /* Also set SEC_EXCLUDE, so that symbols defined in
3891                  the warning section don't get copied to the output.  */
3892               s->flags |= SEC_EXCLUDE;
3893             }
3894         }
3895     }
3896
3897   just_syms = ((s = abfd->sections) != NULL
3898                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3899
3900   add_needed = TRUE;
3901   if (! dynamic)
3902     {
3903       /* If we are creating a shared library, create all the dynamic
3904          sections immediately.  We need to attach them to something,
3905          so we attach them to this BFD, provided it is the right
3906          format and is not from ld --just-symbols.  Always create the
3907          dynamic sections for -E/--dynamic-list.  FIXME: If there
3908          are no input BFD's of the same format as the output, we can't
3909          make a shared library.  */
3910       if (!just_syms
3911           && (bfd_link_pic (info)
3912               || (!bfd_link_relocatable (info)
3913                   && info->nointerp
3914                   && (info->export_dynamic || info->dynamic)))
3915           && is_elf_hash_table (htab)
3916           && info->output_bfd->xvec == abfd->xvec
3917           && !htab->dynamic_sections_created)
3918         {
3919           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3920             goto error_return;
3921         }
3922     }
3923   else if (!is_elf_hash_table (htab))
3924     goto error_return;
3925   else
3926     {
3927       const char *soname = NULL;
3928       char *audit = NULL;
3929       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3930       const Elf_Internal_Phdr *phdr;
3931       int ret;
3932
3933       /* ld --just-symbols and dynamic objects don't mix very well.
3934          ld shouldn't allow it.  */
3935       if (just_syms)
3936         abort ();
3937
3938       /* If this dynamic lib was specified on the command line with
3939          --as-needed in effect, then we don't want to add a DT_NEEDED
3940          tag unless the lib is actually used.  Similary for libs brought
3941          in by another lib's DT_NEEDED.  When --no-add-needed is used
3942          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3943          any dynamic library in DT_NEEDED tags in the dynamic lib at
3944          all.  */
3945       add_needed = (elf_dyn_lib_class (abfd)
3946                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3947                        | DYN_NO_NEEDED)) == 0;
3948
3949       s = bfd_get_section_by_name (abfd, ".dynamic");
3950       if (s != NULL)
3951         {
3952           bfd_byte *dynbuf;
3953           bfd_byte *extdyn;
3954           unsigned int elfsec;
3955           unsigned long shlink;
3956
3957           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3958             {
3959 error_free_dyn:
3960               free (dynbuf);
3961               goto error_return;
3962             }
3963
3964           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3965           if (elfsec == SHN_BAD)
3966             goto error_free_dyn;
3967           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3968
3969           for (extdyn = dynbuf;
3970                extdyn < dynbuf + s->size;
3971                extdyn += bed->s->sizeof_dyn)
3972             {
3973               Elf_Internal_Dyn dyn;
3974
3975               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3976               if (dyn.d_tag == DT_SONAME)
3977                 {
3978                   unsigned int tagv = dyn.d_un.d_val;
3979                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3980                   if (soname == NULL)
3981                     goto error_free_dyn;
3982                 }
3983               if (dyn.d_tag == DT_NEEDED)
3984                 {
3985                   struct bfd_link_needed_list *n, **pn;
3986                   char *fnm, *anm;
3987                   unsigned int tagv = dyn.d_un.d_val;
3988
3989                   amt = sizeof (struct bfd_link_needed_list);
3990                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3991                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3992                   if (n == NULL || fnm == NULL)
3993                     goto error_free_dyn;
3994                   amt = strlen (fnm) + 1;
3995                   anm = (char *) bfd_alloc (abfd, amt);
3996                   if (anm == NULL)
3997                     goto error_free_dyn;
3998                   memcpy (anm, fnm, amt);
3999                   n->name = anm;
4000                   n->by = abfd;
4001                   n->next = NULL;
4002                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
4003                     ;
4004                   *pn = n;
4005                 }
4006               if (dyn.d_tag == DT_RUNPATH)
4007                 {
4008                   struct bfd_link_needed_list *n, **pn;
4009                   char *fnm, *anm;
4010                   unsigned int tagv = dyn.d_un.d_val;
4011
4012                   amt = sizeof (struct bfd_link_needed_list);
4013                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
4014                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4015                   if (n == NULL || fnm == NULL)
4016                     goto error_free_dyn;
4017                   amt = strlen (fnm) + 1;
4018                   anm = (char *) bfd_alloc (abfd, amt);
4019                   if (anm == NULL)
4020                     goto error_free_dyn;
4021                   memcpy (anm, fnm, amt);
4022                   n->name = anm;
4023                   n->by = abfd;
4024                   n->next = NULL;
4025                   for (pn = & runpath;
4026                        *pn != NULL;
4027                        pn = &(*pn)->next)
4028                     ;
4029                   *pn = n;
4030                 }
4031               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
4032               if (!runpath && dyn.d_tag == DT_RPATH)
4033                 {
4034                   struct bfd_link_needed_list *n, **pn;
4035                   char *fnm, *anm;
4036                   unsigned int tagv = dyn.d_un.d_val;
4037
4038                   amt = sizeof (struct bfd_link_needed_list);
4039                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
4040                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4041                   if (n == NULL || fnm == NULL)
4042                     goto error_free_dyn;
4043                   amt = strlen (fnm) + 1;
4044                   anm = (char *) bfd_alloc (abfd, amt);
4045                   if (anm == NULL)
4046                     goto error_free_dyn;
4047                   memcpy (anm, fnm, amt);
4048                   n->name = anm;
4049                   n->by = abfd;
4050                   n->next = NULL;
4051                   for (pn = & rpath;
4052                        *pn != NULL;
4053                        pn = &(*pn)->next)
4054                     ;
4055                   *pn = n;
4056                 }
4057               if (dyn.d_tag == DT_AUDIT)
4058                 {
4059                   unsigned int tagv = dyn.d_un.d_val;
4060                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4061                 }
4062             }
4063
4064           free (dynbuf);
4065         }
4066
4067       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
4068          frees all more recently bfd_alloc'd blocks as well.  */
4069       if (runpath)
4070         rpath = runpath;
4071
4072       if (rpath)
4073         {
4074           struct bfd_link_needed_list **pn;
4075           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
4076             ;
4077           *pn = rpath;
4078         }
4079
4080       /* If we have a PT_GNU_RELRO program header, mark as read-only
4081          all sections contained fully therein.  This makes relro
4082          shared library sections appear as they will at run-time.  */
4083       phdr = elf_tdata (abfd)->phdr + elf_elfheader (abfd)->e_phnum;
4084       while (--phdr >= elf_tdata (abfd)->phdr)
4085         if (phdr->p_type == PT_GNU_RELRO)
4086           {
4087             for (s = abfd->sections; s != NULL; s = s->next)
4088               if ((s->flags & SEC_ALLOC) != 0
4089                   && s->vma >= phdr->p_vaddr
4090                   && s->vma + s->size <= phdr->p_vaddr + phdr->p_memsz)
4091                 s->flags |= SEC_READONLY;
4092             break;
4093           }
4094
4095       /* We do not want to include any of the sections in a dynamic
4096          object in the output file.  We hack by simply clobbering the
4097          list of sections in the BFD.  This could be handled more
4098          cleanly by, say, a new section flag; the existing
4099          SEC_NEVER_LOAD flag is not the one we want, because that one
4100          still implies that the section takes up space in the output
4101          file.  */
4102       bfd_section_list_clear (abfd);
4103
4104       /* Find the name to use in a DT_NEEDED entry that refers to this
4105          object.  If the object has a DT_SONAME entry, we use it.
4106          Otherwise, if the generic linker stuck something in
4107          elf_dt_name, we use that.  Otherwise, we just use the file
4108          name.  */
4109       if (soname == NULL || *soname == '\0')
4110         {
4111           soname = elf_dt_name (abfd);
4112           if (soname == NULL || *soname == '\0')
4113             soname = bfd_get_filename (abfd);
4114         }
4115
4116       /* Save the SONAME because sometimes the linker emulation code
4117          will need to know it.  */
4118       elf_dt_name (abfd) = soname;
4119
4120       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4121       if (ret < 0)
4122         goto error_return;
4123
4124       /* If we have already included this dynamic object in the
4125          link, just ignore it.  There is no reason to include a
4126          particular dynamic object more than once.  */
4127       if (ret > 0)
4128         return TRUE;
4129
4130       /* Save the DT_AUDIT entry for the linker emulation code. */
4131       elf_dt_audit (abfd) = audit;
4132     }
4133
4134   /* If this is a dynamic object, we always link against the .dynsym
4135      symbol table, not the .symtab symbol table.  The dynamic linker
4136      will only see the .dynsym symbol table, so there is no reason to
4137      look at .symtab for a dynamic object.  */
4138
4139   if (! dynamic || elf_dynsymtab (abfd) == 0)
4140     hdr = &elf_tdata (abfd)->symtab_hdr;
4141   else
4142     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
4143
4144   symcount = hdr->sh_size / bed->s->sizeof_sym;
4145
4146   /* The sh_info field of the symtab header tells us where the
4147      external symbols start.  We don't care about the local symbols at
4148      this point.  */
4149   if (elf_bad_symtab (abfd))
4150     {
4151       extsymcount = symcount;
4152       extsymoff = 0;
4153     }
4154   else
4155     {
4156       extsymcount = symcount - hdr->sh_info;
4157       extsymoff = hdr->sh_info;
4158     }
4159
4160   sym_hash = elf_sym_hashes (abfd);
4161   if (extsymcount != 0)
4162     {
4163       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
4164                                       NULL, NULL, NULL);
4165       if (isymbuf == NULL)
4166         goto error_return;
4167
4168       if (sym_hash == NULL)
4169         {
4170           /* We store a pointer to the hash table entry for each
4171              external symbol.  */
4172           amt = extsymcount;
4173           amt *= sizeof (struct elf_link_hash_entry *);
4174           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
4175           if (sym_hash == NULL)
4176             goto error_free_sym;
4177           elf_sym_hashes (abfd) = sym_hash;
4178         }
4179     }
4180
4181   if (dynamic)
4182     {
4183       /* Read in any version definitions.  */
4184       if (!_bfd_elf_slurp_version_tables (abfd,
4185                                           info->default_imported_symver))
4186         goto error_free_sym;
4187
4188       /* Read in the symbol versions, but don't bother to convert them
4189          to internal format.  */
4190       if (elf_dynversym (abfd) != 0)
4191         {
4192           Elf_Internal_Shdr *versymhdr;
4193
4194           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
4195           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
4196           if (extversym == NULL)
4197             goto error_free_sym;
4198           amt = versymhdr->sh_size;
4199           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
4200               || bfd_bread (extversym, amt, abfd) != amt)
4201             goto error_free_vers;
4202         }
4203     }
4204
4205   /* If we are loading an as-needed shared lib, save the symbol table
4206      state before we start adding symbols.  If the lib turns out
4207      to be unneeded, restore the state.  */
4208   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4209     {
4210       unsigned int i;
4211       size_t entsize;
4212
4213       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
4214         {
4215           struct bfd_hash_entry *p;
4216           struct elf_link_hash_entry *h;
4217
4218           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4219             {
4220               h = (struct elf_link_hash_entry *) p;
4221               entsize += htab->root.table.entsize;
4222               if (h->root.type == bfd_link_hash_warning)
4223                 entsize += htab->root.table.entsize;
4224             }
4225         }
4226
4227       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
4228       old_tab = bfd_malloc (tabsize + entsize);
4229       if (old_tab == NULL)
4230         goto error_free_vers;
4231
4232       /* Remember the current objalloc pointer, so that all mem for
4233          symbols added can later be reclaimed.  */
4234       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
4235       if (alloc_mark == NULL)
4236         goto error_free_vers;
4237
4238       /* Make a special call to the linker "notice" function to
4239          tell it that we are about to handle an as-needed lib.  */
4240       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
4241         goto error_free_vers;
4242
4243       /* Clone the symbol table.  Remember some pointers into the
4244          symbol table, and dynamic symbol count.  */
4245       old_ent = (char *) old_tab + tabsize;
4246       memcpy (old_tab, htab->root.table.table, tabsize);
4247       old_undefs = htab->root.undefs;
4248       old_undefs_tail = htab->root.undefs_tail;
4249       old_table = htab->root.table.table;
4250       old_size = htab->root.table.size;
4251       old_count = htab->root.table.count;
4252       old_strtab = _bfd_elf_strtab_save (htab->dynstr);
4253       if (old_strtab == NULL)
4254         goto error_free_vers;
4255
4256       for (i = 0; i < htab->root.table.size; i++)
4257         {
4258           struct bfd_hash_entry *p;
4259           struct elf_link_hash_entry *h;
4260
4261           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4262             {
4263               memcpy (old_ent, p, htab->root.table.entsize);
4264               old_ent = (char *) old_ent + htab->root.table.entsize;
4265               h = (struct elf_link_hash_entry *) p;
4266               if (h->root.type == bfd_link_hash_warning)
4267                 {
4268                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
4269                   old_ent = (char *) old_ent + htab->root.table.entsize;
4270                 }
4271             }
4272         }
4273     }
4274
4275   weaks = NULL;
4276   ever = extversym != NULL ? extversym + extsymoff : NULL;
4277   for (isym = isymbuf, isymend = isymbuf + extsymcount;
4278        isym < isymend;
4279        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
4280     {
4281       int bind;
4282       bfd_vma value;
4283       asection *sec, *new_sec;
4284       flagword flags;
4285       const char *name;
4286       struct elf_link_hash_entry *h;
4287       struct elf_link_hash_entry *hi;
4288       bfd_boolean definition;
4289       bfd_boolean size_change_ok;
4290       bfd_boolean type_change_ok;
4291       bfd_boolean new_weak;
4292       bfd_boolean old_weak;
4293       bfd_boolean override;
4294       bfd_boolean common;
4295       bfd_boolean discarded;
4296       unsigned int old_alignment;
4297       bfd *old_bfd;
4298       bfd_boolean matched;
4299
4300       override = FALSE;
4301
4302       flags = BSF_NO_FLAGS;
4303       sec = NULL;
4304       value = isym->st_value;
4305       common = bed->common_definition (isym);
4306       if (common && info->inhibit_common_definition)
4307         {
4308           /* Treat common symbol as undefined for --no-define-common.  */
4309           isym->st_shndx = SHN_UNDEF;
4310           common = FALSE;
4311         }
4312       discarded = FALSE;
4313
4314       bind = ELF_ST_BIND (isym->st_info);
4315       switch (bind)
4316         {
4317         case STB_LOCAL:
4318           /* This should be impossible, since ELF requires that all
4319              global symbols follow all local symbols, and that sh_info
4320              point to the first global symbol.  Unfortunately, Irix 5
4321              screws this up.  */
4322           continue;
4323
4324         case STB_GLOBAL:
4325           if (isym->st_shndx != SHN_UNDEF && !common)
4326             flags = BSF_GLOBAL;
4327           break;
4328
4329         case STB_WEAK:
4330           flags = BSF_WEAK;
4331           break;
4332
4333         case STB_GNU_UNIQUE:
4334           flags = BSF_GNU_UNIQUE;
4335           break;
4336
4337         default:
4338           /* Leave it up to the processor backend.  */
4339           break;
4340         }
4341
4342       if (isym->st_shndx == SHN_UNDEF)
4343         sec = bfd_und_section_ptr;
4344       else if (isym->st_shndx == SHN_ABS)
4345         sec = bfd_abs_section_ptr;
4346       else if (isym->st_shndx == SHN_COMMON)
4347         {
4348           sec = bfd_com_section_ptr;
4349           /* What ELF calls the size we call the value.  What ELF
4350              calls the value we call the alignment.  */
4351           value = isym->st_size;
4352         }
4353       else
4354         {
4355           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
4356           if (sec == NULL)
4357             sec = bfd_abs_section_ptr;
4358           else if (discarded_section (sec))
4359             {
4360               /* Symbols from discarded section are undefined.  We keep
4361                  its visibility.  */
4362               sec = bfd_und_section_ptr;
4363               discarded = TRUE;
4364               isym->st_shndx = SHN_UNDEF;
4365             }
4366           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
4367             value -= sec->vma;
4368         }
4369
4370       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4371                                               isym->st_name);
4372       if (name == NULL)
4373         goto error_free_vers;
4374
4375       if (isym->st_shndx == SHN_COMMON
4376           && (abfd->flags & BFD_PLUGIN) != 0)
4377         {
4378           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4379
4380           if (xc == NULL)
4381             {
4382               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4383                                  | SEC_EXCLUDE);
4384               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4385               if (xc == NULL)
4386                 goto error_free_vers;
4387             }
4388           sec = xc;
4389         }
4390       else if (isym->st_shndx == SHN_COMMON
4391                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4392                && !bfd_link_relocatable (info))
4393         {
4394           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4395
4396           if (tcomm == NULL)
4397             {
4398               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4399                                  | SEC_LINKER_CREATED);
4400               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4401               if (tcomm == NULL)
4402                 goto error_free_vers;
4403             }
4404           sec = tcomm;
4405         }
4406       else if (bed->elf_add_symbol_hook)
4407         {
4408           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4409                                              &sec, &value))
4410             goto error_free_vers;
4411
4412           /* The hook function sets the name to NULL if this symbol
4413              should be skipped for some reason.  */
4414           if (name == NULL)
4415             continue;
4416         }
4417
4418       /* Sanity check that all possibilities were handled.  */
4419       if (sec == NULL)
4420         {
4421           bfd_set_error (bfd_error_bad_value);
4422           goto error_free_vers;
4423         }
4424
4425       /* Silently discard TLS symbols from --just-syms.  There's
4426          no way to combine a static TLS block with a new TLS block
4427          for this executable.  */
4428       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4429           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4430         continue;
4431
4432       if (bfd_is_und_section (sec)
4433           || bfd_is_com_section (sec))
4434         definition = FALSE;
4435       else
4436         definition = TRUE;
4437
4438       size_change_ok = FALSE;
4439       type_change_ok = bed->type_change_ok;
4440       old_weak = FALSE;
4441       matched = FALSE;
4442       old_alignment = 0;
4443       old_bfd = NULL;
4444       new_sec = sec;
4445
4446       if (is_elf_hash_table (htab))
4447         {
4448           Elf_Internal_Versym iver;
4449           unsigned int vernum = 0;
4450           bfd_boolean skip;
4451
4452           if (ever == NULL)
4453             {
4454               if (info->default_imported_symver)
4455                 /* Use the default symbol version created earlier.  */
4456                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4457               else
4458                 iver.vs_vers = 0;
4459             }
4460           else
4461             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4462
4463           vernum = iver.vs_vers & VERSYM_VERSION;
4464
4465           /* If this is a hidden symbol, or if it is not version
4466              1, we append the version name to the symbol name.
4467              However, we do not modify a non-hidden absolute symbol
4468              if it is not a function, because it might be the version
4469              symbol itself.  FIXME: What if it isn't?  */
4470           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4471               || (vernum > 1
4472                   && (!bfd_is_abs_section (sec)
4473                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4474             {
4475               const char *verstr;
4476               size_t namelen, verlen, newlen;
4477               char *newname, *p;
4478
4479               if (isym->st_shndx != SHN_UNDEF)
4480                 {
4481                   if (vernum > elf_tdata (abfd)->cverdefs)
4482                     verstr = NULL;
4483                   else if (vernum > 1)
4484                     verstr =
4485                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4486                   else
4487                     verstr = "";
4488
4489                   if (verstr == NULL)
4490                     {
4491                       _bfd_error_handler
4492                         /* xgettext:c-format */
4493                         (_("%pB: %s: invalid version %u (max %d)"),
4494                          abfd, name, vernum,
4495                          elf_tdata (abfd)->cverdefs);
4496                       bfd_set_error (bfd_error_bad_value);
4497                       goto error_free_vers;
4498                     }
4499                 }
4500               else
4501                 {
4502                   /* We cannot simply test for the number of
4503                      entries in the VERNEED section since the
4504                      numbers for the needed versions do not start
4505                      at 0.  */
4506                   Elf_Internal_Verneed *t;
4507
4508                   verstr = NULL;
4509                   for (t = elf_tdata (abfd)->verref;
4510                        t != NULL;
4511                        t = t->vn_nextref)
4512                     {
4513                       Elf_Internal_Vernaux *a;
4514
4515                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4516                         {
4517                           if (a->vna_other == vernum)
4518                             {
4519                               verstr = a->vna_nodename;
4520                               break;
4521                             }
4522                         }
4523                       if (a != NULL)
4524                         break;
4525                     }
4526                   if (verstr == NULL)
4527                     {
4528                       _bfd_error_handler
4529                         /* xgettext:c-format */
4530                         (_("%pB: %s: invalid needed version %d"),
4531                          abfd, name, vernum);
4532                       bfd_set_error (bfd_error_bad_value);
4533                       goto error_free_vers;
4534                     }
4535                 }
4536
4537               namelen = strlen (name);
4538               verlen = strlen (verstr);
4539               newlen = namelen + verlen + 2;
4540               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4541                   && isym->st_shndx != SHN_UNDEF)
4542                 ++newlen;
4543
4544               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4545               if (newname == NULL)
4546                 goto error_free_vers;
4547               memcpy (newname, name, namelen);
4548               p = newname + namelen;
4549               *p++ = ELF_VER_CHR;
4550               /* If this is a defined non-hidden version symbol,
4551                  we add another @ to the name.  This indicates the
4552                  default version of the symbol.  */
4553               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4554                   && isym->st_shndx != SHN_UNDEF)
4555                 *p++ = ELF_VER_CHR;
4556               memcpy (p, verstr, verlen + 1);
4557
4558               name = newname;
4559             }
4560
4561           /* If this symbol has default visibility and the user has
4562              requested we not re-export it, then mark it as hidden.  */
4563           if (!bfd_is_und_section (sec)
4564               && !dynamic
4565               && abfd->no_export
4566               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4567             isym->st_other = (STV_HIDDEN
4568                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4569
4570           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4571                                       sym_hash, &old_bfd, &old_weak,
4572                                       &old_alignment, &skip, &override,
4573                                       &type_change_ok, &size_change_ok,
4574                                       &matched))
4575             goto error_free_vers;
4576
4577           if (skip)
4578             continue;
4579
4580           /* Override a definition only if the new symbol matches the
4581              existing one.  */
4582           if (override && matched)
4583             definition = FALSE;
4584
4585           h = *sym_hash;
4586           while (h->root.type == bfd_link_hash_indirect
4587                  || h->root.type == bfd_link_hash_warning)
4588             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4589
4590           if (elf_tdata (abfd)->verdef != NULL
4591               && vernum > 1
4592               && definition)
4593             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4594         }
4595
4596       if (! (_bfd_generic_link_add_one_symbol
4597              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4598               (struct bfd_link_hash_entry **) sym_hash)))
4599         goto error_free_vers;
4600
4601       if ((flags & BSF_GNU_UNIQUE)
4602           && (abfd->flags & DYNAMIC) == 0
4603           && bfd_get_flavour (info->output_bfd) == bfd_target_elf_flavour)
4604         elf_tdata (info->output_bfd)->has_gnu_symbols |= elf_gnu_symbol_unique;
4605
4606       h = *sym_hash;
4607       /* We need to make sure that indirect symbol dynamic flags are
4608          updated.  */
4609       hi = h;
4610       while (h->root.type == bfd_link_hash_indirect
4611              || h->root.type == bfd_link_hash_warning)
4612         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4613
4614       /* Setting the index to -3 tells elf_link_output_extsym that
4615          this symbol is defined in a discarded section.  */
4616       if (discarded)
4617         h->indx = -3;
4618
4619       *sym_hash = h;
4620
4621       new_weak = (flags & BSF_WEAK) != 0;
4622       if (dynamic
4623           && definition
4624           && new_weak
4625           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4626           && is_elf_hash_table (htab)
4627           && h->u.alias == NULL)
4628         {
4629           /* Keep a list of all weak defined non function symbols from
4630              a dynamic object, using the alias field.  Later in this
4631              function we will set the alias field to the correct
4632              value.  We only put non-function symbols from dynamic
4633              objects on this list, because that happens to be the only
4634              time we need to know the normal symbol corresponding to a
4635              weak symbol, and the information is time consuming to
4636              figure out.  If the alias field is not already NULL,
4637              then this symbol was already defined by some previous
4638              dynamic object, and we will be using that previous
4639              definition anyhow.  */
4640
4641           h->u.alias = weaks;
4642           weaks = h;
4643         }
4644
4645       /* Set the alignment of a common symbol.  */
4646       if ((common || bfd_is_com_section (sec))
4647           && h->root.type == bfd_link_hash_common)
4648         {
4649           unsigned int align;
4650
4651           if (common)
4652             align = bfd_log2 (isym->st_value);
4653           else
4654             {
4655               /* The new symbol is a common symbol in a shared object.
4656                  We need to get the alignment from the section.  */
4657               align = new_sec->alignment_power;
4658             }
4659           if (align > old_alignment)
4660             h->root.u.c.p->alignment_power = align;
4661           else
4662             h->root.u.c.p->alignment_power = old_alignment;
4663         }
4664
4665       if (is_elf_hash_table (htab))
4666         {
4667           /* Set a flag in the hash table entry indicating the type of
4668              reference or definition we just found.  A dynamic symbol
4669              is one which is referenced or defined by both a regular
4670              object and a shared object.  */
4671           bfd_boolean dynsym = FALSE;
4672
4673           /* Plugin symbols aren't normal.  Don't set def_regular or
4674              ref_regular for them, or make them dynamic.  */
4675           if ((abfd->flags & BFD_PLUGIN) != 0)
4676             ;
4677           else if (! dynamic)
4678             {
4679               if (! definition)
4680                 {
4681                   h->ref_regular = 1;
4682                   if (bind != STB_WEAK)
4683                     h->ref_regular_nonweak = 1;
4684                 }
4685               else
4686                 {
4687                   h->def_regular = 1;
4688                   if (h->def_dynamic)
4689                     {
4690                       h->def_dynamic = 0;
4691                       h->ref_dynamic = 1;
4692                     }
4693                 }
4694
4695               /* If the indirect symbol has been forced local, don't
4696                  make the real symbol dynamic.  */
4697               if ((h == hi || !hi->forced_local)
4698                   && (bfd_link_dll (info)
4699                       || h->def_dynamic
4700                       || h->ref_dynamic))
4701                 dynsym = TRUE;
4702             }
4703           else
4704             {
4705               if (! definition)
4706                 {
4707                   h->ref_dynamic = 1;
4708                   hi->ref_dynamic = 1;
4709                 }
4710               else
4711                 {
4712                   h->def_dynamic = 1;
4713                   hi->def_dynamic = 1;
4714                 }
4715
4716               /* If the indirect symbol has been forced local, don't
4717                  make the real symbol dynamic.  */
4718               if ((h == hi || !hi->forced_local)
4719                   && (h->def_regular
4720                       || h->ref_regular
4721                       || (h->is_weakalias
4722                           && weakdef (h)->dynindx != -1)))
4723                 dynsym = TRUE;
4724             }
4725
4726           /* Check to see if we need to add an indirect symbol for
4727              the default name.  */
4728           if (definition
4729               || (!override && h->root.type == bfd_link_hash_common))
4730             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4731                                               sec, value, &old_bfd, &dynsym))
4732               goto error_free_vers;
4733
4734           /* Check the alignment when a common symbol is involved. This
4735              can change when a common symbol is overridden by a normal
4736              definition or a common symbol is ignored due to the old
4737              normal definition. We need to make sure the maximum
4738              alignment is maintained.  */
4739           if ((old_alignment || common)
4740               && h->root.type != bfd_link_hash_common)
4741             {
4742               unsigned int common_align;
4743               unsigned int normal_align;
4744               unsigned int symbol_align;
4745               bfd *normal_bfd;
4746               bfd *common_bfd;
4747
4748               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4749                           || h->root.type == bfd_link_hash_defweak);
4750
4751               symbol_align = ffs (h->root.u.def.value) - 1;
4752               if (h->root.u.def.section->owner != NULL
4753                   && (h->root.u.def.section->owner->flags
4754                        & (DYNAMIC | BFD_PLUGIN)) == 0)
4755                 {
4756                   normal_align = h->root.u.def.section->alignment_power;
4757                   if (normal_align > symbol_align)
4758                     normal_align = symbol_align;
4759                 }
4760               else
4761                 normal_align = symbol_align;
4762
4763               if (old_alignment)
4764                 {
4765                   common_align = old_alignment;
4766                   common_bfd = old_bfd;
4767                   normal_bfd = abfd;
4768                 }
4769               else
4770                 {
4771                   common_align = bfd_log2 (isym->st_value);
4772                   common_bfd = abfd;
4773                   normal_bfd = old_bfd;
4774                 }
4775
4776               if (normal_align < common_align)
4777                 {
4778                   /* PR binutils/2735 */
4779                   if (normal_bfd == NULL)
4780                     _bfd_error_handler
4781                       /* xgettext:c-format */
4782                       (_("Warning: alignment %u of common symbol `%s' in %pB is"
4783                          " greater than the alignment (%u) of its section %pA"),
4784                        1 << common_align, name, common_bfd,
4785                        1 << normal_align, h->root.u.def.section);
4786                   else
4787                     _bfd_error_handler
4788                       /* xgettext:c-format */
4789                       (_("Warning: alignment %u of symbol `%s' in %pB"
4790                          " is smaller than %u in %pB"),
4791                        1 << normal_align, name, normal_bfd,
4792                        1 << common_align, common_bfd);
4793                 }
4794             }
4795
4796           /* Remember the symbol size if it isn't undefined.  */
4797           if (isym->st_size != 0
4798               && isym->st_shndx != SHN_UNDEF
4799               && (definition || h->size == 0))
4800             {
4801               if (h->size != 0
4802                   && h->size != isym->st_size
4803                   && ! size_change_ok)
4804                 _bfd_error_handler
4805                   /* xgettext:c-format */
4806                   (_("Warning: size of symbol `%s' changed"
4807                      " from %" PRIu64 " in %pB to %" PRIu64 " in %pB"),
4808                    name, (uint64_t) h->size, old_bfd,
4809                    (uint64_t) isym->st_size, abfd);
4810
4811               h->size = isym->st_size;
4812             }
4813
4814           /* If this is a common symbol, then we always want H->SIZE
4815              to be the size of the common symbol.  The code just above
4816              won't fix the size if a common symbol becomes larger.  We
4817              don't warn about a size change here, because that is
4818              covered by --warn-common.  Allow changes between different
4819              function types.  */
4820           if (h->root.type == bfd_link_hash_common)
4821             h->size = h->root.u.c.size;
4822
4823           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4824               && ((definition && !new_weak)
4825                   || (old_weak && h->root.type == bfd_link_hash_common)
4826                   || h->type == STT_NOTYPE))
4827             {
4828               unsigned int type = ELF_ST_TYPE (isym->st_info);
4829
4830               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4831                  symbol.  */
4832               if (type == STT_GNU_IFUNC
4833                   && (abfd->flags & DYNAMIC) != 0)
4834                 type = STT_FUNC;
4835
4836               if (h->type != type)
4837                 {
4838                   if (h->type != STT_NOTYPE && ! type_change_ok)
4839                     /* xgettext:c-format */
4840                     _bfd_error_handler
4841                       (_("Warning: type of symbol `%s' changed"
4842                          " from %d to %d in %pB"),
4843                        name, h->type, type, abfd);
4844
4845                   h->type = type;
4846                 }
4847             }
4848
4849           /* Merge st_other field.  */
4850           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4851
4852           /* We don't want to make debug symbol dynamic.  */
4853           if (definition
4854               && (sec->flags & SEC_DEBUGGING)
4855               && !bfd_link_relocatable (info))
4856             dynsym = FALSE;
4857
4858           /* Nor should we make plugin symbols dynamic.  */
4859           if ((abfd->flags & BFD_PLUGIN) != 0)
4860             dynsym = FALSE;
4861
4862           if (definition)
4863             {
4864               h->target_internal = isym->st_target_internal;
4865               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4866             }
4867
4868           if (definition && !dynamic)
4869             {
4870               char *p = strchr (name, ELF_VER_CHR);
4871               if (p != NULL && p[1] != ELF_VER_CHR)
4872                 {
4873                   /* Queue non-default versions so that .symver x, x@FOO
4874                      aliases can be checked.  */
4875                   if (!nondeflt_vers)
4876                     {
4877                       amt = ((isymend - isym + 1)
4878                              * sizeof (struct elf_link_hash_entry *));
4879                       nondeflt_vers
4880                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
4881                       if (!nondeflt_vers)
4882                         goto error_free_vers;
4883                     }
4884                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4885                 }
4886             }
4887
4888           if (dynsym && h->dynindx == -1)
4889             {
4890               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4891                 goto error_free_vers;
4892               if (h->is_weakalias
4893                   && weakdef (h)->dynindx == -1)
4894                 {
4895                   if (!bfd_elf_link_record_dynamic_symbol (info, weakdef (h)))
4896                     goto error_free_vers;
4897                 }
4898             }
4899           else if (h->dynindx != -1)
4900             /* If the symbol already has a dynamic index, but
4901                visibility says it should not be visible, turn it into
4902                a local symbol.  */
4903             switch (ELF_ST_VISIBILITY (h->other))
4904               {
4905               case STV_INTERNAL:
4906               case STV_HIDDEN:
4907                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4908                 dynsym = FALSE;
4909                 break;
4910               }
4911
4912           /* Don't add DT_NEEDED for references from the dummy bfd nor
4913              for unmatched symbol.  */
4914           if (!add_needed
4915               && matched
4916               && definition
4917               && ((dynsym
4918                    && h->ref_regular_nonweak
4919                    && (old_bfd == NULL
4920                        || (old_bfd->flags & BFD_PLUGIN) == 0))
4921                   || (h->ref_dynamic_nonweak
4922                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4923                       && !on_needed_list (elf_dt_name (abfd),
4924                                           htab->needed, NULL))))
4925             {
4926               int ret;
4927               const char *soname = elf_dt_name (abfd);
4928
4929               info->callbacks->minfo ("%!", soname, old_bfd,
4930                                       h->root.root.string);
4931
4932               /* A symbol from a library loaded via DT_NEEDED of some
4933                  other library is referenced by a regular object.
4934                  Add a DT_NEEDED entry for it.  Issue an error if
4935                  --no-add-needed is used and the reference was not
4936                  a weak one.  */
4937               if (old_bfd != NULL
4938                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4939                 {
4940                   _bfd_error_handler
4941                     /* xgettext:c-format */
4942                     (_("%pB: undefined reference to symbol '%s'"),
4943                      old_bfd, name);
4944                   bfd_set_error (bfd_error_missing_dso);
4945                   goto error_free_vers;
4946                 }
4947
4948               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4949                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4950
4951               add_needed = TRUE;
4952               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4953               if (ret < 0)
4954                 goto error_free_vers;
4955
4956               BFD_ASSERT (ret == 0);
4957             }
4958         }
4959     }
4960
4961   if (info->lto_plugin_active
4962       && !bfd_link_relocatable (info)
4963       && (abfd->flags & BFD_PLUGIN) == 0
4964       && !just_syms
4965       && extsymcount)
4966     {
4967       int r_sym_shift;
4968
4969       if (bed->s->arch_size == 32)
4970         r_sym_shift = 8;
4971       else
4972         r_sym_shift = 32;
4973
4974       /* If linker plugin is enabled, set non_ir_ref_regular on symbols
4975          referenced in regular objects so that linker plugin will get
4976          the correct symbol resolution.  */
4977
4978       sym_hash = elf_sym_hashes (abfd);
4979       for (s = abfd->sections; s != NULL; s = s->next)
4980         {
4981           Elf_Internal_Rela *internal_relocs;
4982           Elf_Internal_Rela *rel, *relend;
4983
4984           /* Don't check relocations in excluded sections.  */
4985           if ((s->flags & SEC_RELOC) == 0
4986               || s->reloc_count == 0
4987               || (s->flags & SEC_EXCLUDE) != 0
4988               || ((info->strip == strip_all
4989                    || info->strip == strip_debugger)
4990                   && (s->flags & SEC_DEBUGGING) != 0))
4991             continue;
4992
4993           internal_relocs = _bfd_elf_link_read_relocs (abfd, s, NULL,
4994                                                        NULL,
4995                                                        info->keep_memory);
4996           if (internal_relocs == NULL)
4997             goto error_free_vers;
4998
4999           rel = internal_relocs;
5000           relend = rel + s->reloc_count;
5001           for ( ; rel < relend; rel++)
5002             {
5003               unsigned long r_symndx = rel->r_info >> r_sym_shift;
5004               struct elf_link_hash_entry *h;
5005
5006               /* Skip local symbols.  */
5007               if (r_symndx < extsymoff)
5008                 continue;
5009
5010               h = sym_hash[r_symndx - extsymoff];
5011               if (h != NULL)
5012                 h->root.non_ir_ref_regular = 1;
5013             }
5014
5015           if (elf_section_data (s)->relocs != internal_relocs)
5016             free (internal_relocs);
5017         }
5018     }
5019
5020   if (extversym != NULL)
5021     {
5022       free (extversym);
5023       extversym = NULL;
5024     }
5025
5026   if (isymbuf != NULL)
5027     {
5028       free (isymbuf);
5029       isymbuf = NULL;
5030     }
5031
5032   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
5033     {
5034       unsigned int i;
5035
5036       /* Restore the symbol table.  */
5037       old_ent = (char *) old_tab + tabsize;
5038       memset (elf_sym_hashes (abfd), 0,
5039               extsymcount * sizeof (struct elf_link_hash_entry *));
5040       htab->root.table.table = old_table;
5041       htab->root.table.size = old_size;
5042       htab->root.table.count = old_count;
5043       memcpy (htab->root.table.table, old_tab, tabsize);
5044       htab->root.undefs = old_undefs;
5045       htab->root.undefs_tail = old_undefs_tail;
5046       _bfd_elf_strtab_restore (htab->dynstr, old_strtab);
5047       free (old_strtab);
5048       old_strtab = NULL;
5049       for (i = 0; i < htab->root.table.size; i++)
5050         {
5051           struct bfd_hash_entry *p;
5052           struct elf_link_hash_entry *h;
5053           bfd_size_type size;
5054           unsigned int alignment_power;
5055           unsigned int non_ir_ref_dynamic;
5056
5057           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
5058             {
5059               h = (struct elf_link_hash_entry *) p;
5060               if (h->root.type == bfd_link_hash_warning)
5061                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
5062
5063               /* Preserve the maximum alignment and size for common
5064                  symbols even if this dynamic lib isn't on DT_NEEDED
5065                  since it can still be loaded at run time by another
5066                  dynamic lib.  */
5067               if (h->root.type == bfd_link_hash_common)
5068                 {
5069                   size = h->root.u.c.size;
5070                   alignment_power = h->root.u.c.p->alignment_power;
5071                 }
5072               else
5073                 {
5074                   size = 0;
5075                   alignment_power = 0;
5076                 }
5077               /* Preserve non_ir_ref_dynamic so that this symbol
5078                  will be exported when the dynamic lib becomes needed
5079                  in the second pass.  */
5080               non_ir_ref_dynamic = h->root.non_ir_ref_dynamic;
5081               memcpy (p, old_ent, htab->root.table.entsize);
5082               old_ent = (char *) old_ent + htab->root.table.entsize;
5083               h = (struct elf_link_hash_entry *) p;
5084               if (h->root.type == bfd_link_hash_warning)
5085                 {
5086                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
5087                   old_ent = (char *) old_ent + htab->root.table.entsize;
5088                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
5089                 }
5090               if (h->root.type == bfd_link_hash_common)
5091                 {
5092                   if (size > h->root.u.c.size)
5093                     h->root.u.c.size = size;
5094                   if (alignment_power > h->root.u.c.p->alignment_power)
5095                     h->root.u.c.p->alignment_power = alignment_power;
5096                 }
5097               h->root.non_ir_ref_dynamic = non_ir_ref_dynamic;
5098             }
5099         }
5100
5101       /* Make a special call to the linker "notice" function to
5102          tell it that symbols added for crefs may need to be removed.  */
5103       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
5104         goto error_free_vers;
5105
5106       free (old_tab);
5107       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
5108                            alloc_mark);
5109       if (nondeflt_vers != NULL)
5110         free (nondeflt_vers);
5111       return TRUE;
5112     }
5113
5114   if (old_tab != NULL)
5115     {
5116       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
5117         goto error_free_vers;
5118       free (old_tab);
5119       old_tab = NULL;
5120     }
5121
5122   /* Now that all the symbols from this input file are created, if
5123      not performing a relocatable link, handle .symver foo, foo@BAR
5124      such that any relocs against foo become foo@BAR.  */
5125   if (!bfd_link_relocatable (info) && nondeflt_vers != NULL)
5126     {
5127       size_t cnt, symidx;
5128
5129       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
5130         {
5131           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
5132           char *shortname, *p;
5133
5134           p = strchr (h->root.root.string, ELF_VER_CHR);
5135           if (p == NULL
5136               || (h->root.type != bfd_link_hash_defined
5137                   && h->root.type != bfd_link_hash_defweak))
5138             continue;
5139
5140           amt = p - h->root.root.string;
5141           shortname = (char *) bfd_malloc (amt + 1);
5142           if (!shortname)
5143             goto error_free_vers;
5144           memcpy (shortname, h->root.root.string, amt);
5145           shortname[amt] = '\0';
5146
5147           hi = (struct elf_link_hash_entry *)
5148                bfd_link_hash_lookup (&htab->root, shortname,
5149                                      FALSE, FALSE, FALSE);
5150           if (hi != NULL
5151               && hi->root.type == h->root.type
5152               && hi->root.u.def.value == h->root.u.def.value
5153               && hi->root.u.def.section == h->root.u.def.section)
5154             {
5155               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
5156               hi->root.type = bfd_link_hash_indirect;
5157               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
5158               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
5159               sym_hash = elf_sym_hashes (abfd);
5160               if (sym_hash)
5161                 for (symidx = 0; symidx < extsymcount; ++symidx)
5162                   if (sym_hash[symidx] == hi)
5163                     {
5164                       sym_hash[symidx] = h;
5165                       break;
5166                     }
5167             }
5168           free (shortname);
5169         }
5170       free (nondeflt_vers);
5171       nondeflt_vers = NULL;
5172     }
5173
5174   /* Now set the alias field correctly for all the weak defined
5175      symbols we found.  The only way to do this is to search all the
5176      symbols.  Since we only need the information for non functions in
5177      dynamic objects, that's the only time we actually put anything on
5178      the list WEAKS.  We need this information so that if a regular
5179      object refers to a symbol defined weakly in a dynamic object, the
5180      real symbol in the dynamic object is also put in the dynamic
5181      symbols; we also must arrange for both symbols to point to the
5182      same memory location.  We could handle the general case of symbol
5183      aliasing, but a general symbol alias can only be generated in
5184      assembler code, handling it correctly would be very time
5185      consuming, and other ELF linkers don't handle general aliasing
5186      either.  */
5187   if (weaks != NULL)
5188     {
5189       struct elf_link_hash_entry **hpp;
5190       struct elf_link_hash_entry **hppend;
5191       struct elf_link_hash_entry **sorted_sym_hash;
5192       struct elf_link_hash_entry *h;
5193       size_t sym_count;
5194
5195       /* Since we have to search the whole symbol list for each weak
5196          defined symbol, search time for N weak defined symbols will be
5197          O(N^2). Binary search will cut it down to O(NlogN).  */
5198       amt = extsymcount;
5199       amt *= sizeof (struct elf_link_hash_entry *);
5200       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
5201       if (sorted_sym_hash == NULL)
5202         goto error_return;
5203       sym_hash = sorted_sym_hash;
5204       hpp = elf_sym_hashes (abfd);
5205       hppend = hpp + extsymcount;
5206       sym_count = 0;
5207       for (; hpp < hppend; hpp++)
5208         {
5209           h = *hpp;
5210           if (h != NULL
5211               && h->root.type == bfd_link_hash_defined
5212               && !bed->is_function_type (h->type))
5213             {
5214               *sym_hash = h;
5215               sym_hash++;
5216               sym_count++;
5217             }
5218         }
5219
5220       qsort (sorted_sym_hash, sym_count,
5221              sizeof (struct elf_link_hash_entry *),
5222              elf_sort_symbol);
5223
5224       while (weaks != NULL)
5225         {
5226           struct elf_link_hash_entry *hlook;
5227           asection *slook;
5228           bfd_vma vlook;
5229           size_t i, j, idx = 0;
5230
5231           hlook = weaks;
5232           weaks = hlook->u.alias;
5233           hlook->u.alias = NULL;
5234
5235           if (hlook->root.type != bfd_link_hash_defined
5236               && hlook->root.type != bfd_link_hash_defweak)
5237             continue;
5238
5239           slook = hlook->root.u.def.section;
5240           vlook = hlook->root.u.def.value;
5241
5242           i = 0;
5243           j = sym_count;
5244           while (i != j)
5245             {
5246               bfd_signed_vma vdiff;
5247               idx = (i + j) / 2;
5248               h = sorted_sym_hash[idx];
5249               vdiff = vlook - h->root.u.def.value;
5250               if (vdiff < 0)
5251                 j = idx;
5252               else if (vdiff > 0)
5253                 i = idx + 1;
5254               else
5255                 {
5256                   int sdiff = slook->id - h->root.u.def.section->id;
5257                   if (sdiff < 0)
5258                     j = idx;
5259                   else if (sdiff > 0)
5260                     i = idx + 1;
5261                   else
5262                     break;
5263                 }
5264             }
5265
5266           /* We didn't find a value/section match.  */
5267           if (i == j)
5268             continue;
5269
5270           /* With multiple aliases, or when the weak symbol is already
5271              strongly defined, we have multiple matching symbols and
5272              the binary search above may land on any of them.  Step
5273              one past the matching symbol(s).  */
5274           while (++idx != j)
5275             {
5276               h = sorted_sym_hash[idx];
5277               if (h->root.u.def.section != slook
5278                   || h->root.u.def.value != vlook)
5279                 break;
5280             }
5281
5282           /* Now look back over the aliases.  Since we sorted by size
5283              as well as value and section, we'll choose the one with
5284              the largest size.  */
5285           while (idx-- != i)
5286             {
5287               h = sorted_sym_hash[idx];
5288
5289               /* Stop if value or section doesn't match.  */
5290               if (h->root.u.def.section != slook
5291                   || h->root.u.def.value != vlook)
5292                 break;
5293               else if (h != hlook)
5294                 {
5295                   struct elf_link_hash_entry *t;
5296
5297                   hlook->u.alias = h;
5298                   hlook->is_weakalias = 1;
5299                   t = h;
5300                   if (t->u.alias != NULL)
5301                     while (t->u.alias != h)
5302                       t = t->u.alias;
5303                   t->u.alias = hlook;
5304
5305                   /* If the weak definition is in the list of dynamic
5306                      symbols, make sure the real definition is put
5307                      there as well.  */
5308                   if (hlook->dynindx != -1 && h->dynindx == -1)
5309                     {
5310                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
5311                         {
5312                         err_free_sym_hash:
5313                           free (sorted_sym_hash);
5314                           goto error_return;
5315                         }
5316                     }
5317
5318                   /* If the real definition is in the list of dynamic
5319                      symbols, make sure the weak definition is put
5320                      there as well.  If we don't do this, then the
5321                      dynamic loader might not merge the entries for the
5322                      real definition and the weak definition.  */
5323                   if (h->dynindx != -1 && hlook->dynindx == -1)
5324                     {
5325                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
5326                         goto err_free_sym_hash;
5327                     }
5328                   break;
5329                 }
5330             }
5331         }
5332
5333       free (sorted_sym_hash);
5334     }
5335
5336   if (bed->check_directives
5337       && !(*bed->check_directives) (abfd, info))
5338     return FALSE;
5339
5340   /* If this is a non-traditional link, try to optimize the handling
5341      of the .stab/.stabstr sections.  */
5342   if (! dynamic
5343       && ! info->traditional_format
5344       && is_elf_hash_table (htab)
5345       && (info->strip != strip_all && info->strip != strip_debugger))
5346     {
5347       asection *stabstr;
5348
5349       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
5350       if (stabstr != NULL)
5351         {
5352           bfd_size_type string_offset = 0;
5353           asection *stab;
5354
5355           for (stab = abfd->sections; stab; stab = stab->next)
5356             if (CONST_STRNEQ (stab->name, ".stab")
5357                 && (!stab->name[5] ||
5358                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
5359                 && (stab->flags & SEC_MERGE) == 0
5360                 && !bfd_is_abs_section (stab->output_section))
5361               {
5362                 struct bfd_elf_section_data *secdata;
5363
5364                 secdata = elf_section_data (stab);
5365                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
5366                                                stabstr, &secdata->sec_info,
5367                                                &string_offset))
5368                   goto error_return;
5369                 if (secdata->sec_info)
5370                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
5371             }
5372         }
5373     }
5374
5375   if (is_elf_hash_table (htab) && add_needed)
5376     {
5377       /* Add this bfd to the loaded list.  */
5378       struct elf_link_loaded_list *n;
5379
5380       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
5381       if (n == NULL)
5382         goto error_return;
5383       n->abfd = abfd;
5384       n->next = htab->loaded;
5385       htab->loaded = n;
5386     }
5387
5388   return TRUE;
5389
5390  error_free_vers:
5391   if (old_tab != NULL)
5392     free (old_tab);
5393   if (old_strtab != NULL)
5394     free (old_strtab);
5395   if (nondeflt_vers != NULL)
5396     free (nondeflt_vers);
5397   if (extversym != NULL)
5398     free (extversym);
5399  error_free_sym:
5400   if (isymbuf != NULL)
5401     free (isymbuf);
5402  error_return:
5403   return FALSE;
5404 }
5405
5406 /* Return the linker hash table entry of a symbol that might be
5407    satisfied by an archive symbol.  Return -1 on error.  */
5408
5409 struct elf_link_hash_entry *
5410 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5411                                 struct bfd_link_info *info,
5412                                 const char *name)
5413 {
5414   struct elf_link_hash_entry *h;
5415   char *p, *copy;
5416   size_t len, first;
5417
5418   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5419   if (h != NULL)
5420     return h;
5421
5422   /* If this is a default version (the name contains @@), look up the
5423      symbol again with only one `@' as well as without the version.
5424      The effect is that references to the symbol with and without the
5425      version will be matched by the default symbol in the archive.  */
5426
5427   p = strchr (name, ELF_VER_CHR);
5428   if (p == NULL || p[1] != ELF_VER_CHR)
5429     return h;
5430
5431   /* First check with only one `@'.  */
5432   len = strlen (name);
5433   copy = (char *) bfd_alloc (abfd, len);
5434   if (copy == NULL)
5435     return (struct elf_link_hash_entry *) -1;
5436
5437   first = p - name + 1;
5438   memcpy (copy, name, first);
5439   memcpy (copy + first, name + first + 1, len - first);
5440
5441   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5442   if (h == NULL)
5443     {
5444       /* We also need to check references to the symbol without the
5445          version.  */
5446       copy[first - 1] = '\0';
5447       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5448                                 FALSE, FALSE, TRUE);
5449     }
5450
5451   bfd_release (abfd, copy);
5452   return h;
5453 }
5454
5455 /* Add symbols from an ELF archive file to the linker hash table.  We
5456    don't use _bfd_generic_link_add_archive_symbols because we need to
5457    handle versioned symbols.
5458
5459    Fortunately, ELF archive handling is simpler than that done by
5460    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5461    oddities.  In ELF, if we find a symbol in the archive map, and the
5462    symbol is currently undefined, we know that we must pull in that
5463    object file.
5464
5465    Unfortunately, we do have to make multiple passes over the symbol
5466    table until nothing further is resolved.  */
5467
5468 static bfd_boolean
5469 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5470 {
5471   symindex c;
5472   unsigned char *included = NULL;
5473   carsym *symdefs;
5474   bfd_boolean loop;
5475   bfd_size_type amt;
5476   const struct elf_backend_data *bed;
5477   struct elf_link_hash_entry * (*archive_symbol_lookup)
5478     (bfd *, struct bfd_link_info *, const char *);
5479
5480   if (! bfd_has_map (abfd))
5481     {
5482       /* An empty archive is a special case.  */
5483       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5484         return TRUE;
5485       bfd_set_error (bfd_error_no_armap);
5486       return FALSE;
5487     }
5488
5489   /* Keep track of all symbols we know to be already defined, and all
5490      files we know to be already included.  This is to speed up the
5491      second and subsequent passes.  */
5492   c = bfd_ardata (abfd)->symdef_count;
5493   if (c == 0)
5494     return TRUE;
5495   amt = c;
5496   amt *= sizeof (*included);
5497   included = (unsigned char *) bfd_zmalloc (amt);
5498   if (included == NULL)
5499     return FALSE;
5500
5501   symdefs = bfd_ardata (abfd)->symdefs;
5502   bed = get_elf_backend_data (abfd);
5503   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5504
5505   do
5506     {
5507       file_ptr last;
5508       symindex i;
5509       carsym *symdef;
5510       carsym *symdefend;
5511
5512       loop = FALSE;
5513       last = -1;
5514
5515       symdef = symdefs;
5516       symdefend = symdef + c;
5517       for (i = 0; symdef < symdefend; symdef++, i++)
5518         {
5519           struct elf_link_hash_entry *h;
5520           bfd *element;
5521           struct bfd_link_hash_entry *undefs_tail;
5522           symindex mark;
5523
5524           if (included[i])
5525             continue;
5526           if (symdef->file_offset == last)
5527             {
5528               included[i] = TRUE;
5529               continue;
5530             }
5531
5532           h = archive_symbol_lookup (abfd, info, symdef->name);
5533           if (h == (struct elf_link_hash_entry *) -1)
5534             goto error_return;
5535
5536           if (h == NULL)
5537             continue;
5538
5539           if (h->root.type == bfd_link_hash_common)
5540             {
5541               /* We currently have a common symbol.  The archive map contains
5542                  a reference to this symbol, so we may want to include it.  We
5543                  only want to include it however, if this archive element
5544                  contains a definition of the symbol, not just another common
5545                  declaration of it.
5546
5547                  Unfortunately some archivers (including GNU ar) will put
5548                  declarations of common symbols into their archive maps, as
5549                  well as real definitions, so we cannot just go by the archive
5550                  map alone.  Instead we must read in the element's symbol
5551                  table and check that to see what kind of symbol definition
5552                  this is.  */
5553               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5554                 continue;
5555             }
5556           else if (h->root.type != bfd_link_hash_undefined)
5557             {
5558               if (h->root.type != bfd_link_hash_undefweak)
5559                 /* Symbol must be defined.  Don't check it again.  */
5560                 included[i] = TRUE;
5561               continue;
5562             }
5563
5564           /* We need to include this archive member.  */
5565           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5566           if (element == NULL)
5567             goto error_return;
5568
5569           if (! bfd_check_format (element, bfd_object))
5570             goto error_return;
5571
5572           undefs_tail = info->hash->undefs_tail;
5573
5574           if (!(*info->callbacks
5575                 ->add_archive_element) (info, element, symdef->name, &element))
5576             continue;
5577           if (!bfd_link_add_symbols (element, info))
5578             goto error_return;
5579
5580           /* If there are any new undefined symbols, we need to make
5581              another pass through the archive in order to see whether
5582              they can be defined.  FIXME: This isn't perfect, because
5583              common symbols wind up on undefs_tail and because an
5584              undefined symbol which is defined later on in this pass
5585              does not require another pass.  This isn't a bug, but it
5586              does make the code less efficient than it could be.  */
5587           if (undefs_tail != info->hash->undefs_tail)
5588             loop = TRUE;
5589
5590           /* Look backward to mark all symbols from this object file
5591              which we have already seen in this pass.  */
5592           mark = i;
5593           do
5594             {
5595               included[mark] = TRUE;
5596               if (mark == 0)
5597                 break;
5598               --mark;
5599             }
5600           while (symdefs[mark].file_offset == symdef->file_offset);
5601
5602           /* We mark subsequent symbols from this object file as we go
5603              on through the loop.  */
5604           last = symdef->file_offset;
5605         }
5606     }
5607   while (loop);
5608
5609   free (included);
5610
5611   return TRUE;
5612
5613  error_return:
5614   if (included != NULL)
5615     free (included);
5616   return FALSE;
5617 }
5618
5619 /* Given an ELF BFD, add symbols to the global hash table as
5620    appropriate.  */
5621
5622 bfd_boolean
5623 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5624 {
5625   switch (bfd_get_format (abfd))
5626     {
5627     case bfd_object:
5628       return elf_link_add_object_symbols (abfd, info);
5629     case bfd_archive:
5630       return elf_link_add_archive_symbols (abfd, info);
5631     default:
5632       bfd_set_error (bfd_error_wrong_format);
5633       return FALSE;
5634     }
5635 }
5636 \f
5637 struct hash_codes_info
5638 {
5639   unsigned long *hashcodes;
5640   bfd_boolean error;
5641 };
5642
5643 /* This function will be called though elf_link_hash_traverse to store
5644    all hash value of the exported symbols in an array.  */
5645
5646 static bfd_boolean
5647 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5648 {
5649   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5650   const char *name;
5651   unsigned long ha;
5652   char *alc = NULL;
5653
5654   /* Ignore indirect symbols.  These are added by the versioning code.  */
5655   if (h->dynindx == -1)
5656     return TRUE;
5657
5658   name = h->root.root.string;
5659   if (h->versioned >= versioned)
5660     {
5661       char *p = strchr (name, ELF_VER_CHR);
5662       if (p != NULL)
5663         {
5664           alc = (char *) bfd_malloc (p - name + 1);
5665           if (alc == NULL)
5666             {
5667               inf->error = TRUE;
5668               return FALSE;
5669             }
5670           memcpy (alc, name, p - name);
5671           alc[p - name] = '\0';
5672           name = alc;
5673         }
5674     }
5675
5676   /* Compute the hash value.  */
5677   ha = bfd_elf_hash (name);
5678
5679   /* Store the found hash value in the array given as the argument.  */
5680   *(inf->hashcodes)++ = ha;
5681
5682   /* And store it in the struct so that we can put it in the hash table
5683      later.  */
5684   h->u.elf_hash_value = ha;
5685
5686   if (alc != NULL)
5687     free (alc);
5688
5689   return TRUE;
5690 }
5691
5692 struct collect_gnu_hash_codes
5693 {
5694   bfd *output_bfd;
5695   const struct elf_backend_data *bed;
5696   unsigned long int nsyms;
5697   unsigned long int maskbits;
5698   unsigned long int *hashcodes;
5699   unsigned long int *hashval;
5700   unsigned long int *indx;
5701   unsigned long int *counts;
5702   bfd_vma *bitmask;
5703   bfd_byte *contents;
5704   long int min_dynindx;
5705   unsigned long int bucketcount;
5706   unsigned long int symindx;
5707   long int local_indx;
5708   long int shift1, shift2;
5709   unsigned long int mask;
5710   bfd_boolean error;
5711 };
5712
5713 /* This function will be called though elf_link_hash_traverse to store
5714    all hash value of the exported symbols in an array.  */
5715
5716 static bfd_boolean
5717 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5718 {
5719   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5720   const char *name;
5721   unsigned long ha;
5722   char *alc = NULL;
5723
5724   /* Ignore indirect symbols.  These are added by the versioning code.  */
5725   if (h->dynindx == -1)
5726     return TRUE;
5727
5728   /* Ignore also local symbols and undefined symbols.  */
5729   if (! (*s->bed->elf_hash_symbol) (h))
5730     return TRUE;
5731
5732   name = h->root.root.string;
5733   if (h->versioned >= versioned)
5734     {
5735       char *p = strchr (name, ELF_VER_CHR);
5736       if (p != NULL)
5737         {
5738           alc = (char *) bfd_malloc (p - name + 1);
5739           if (alc == NULL)
5740             {
5741               s->error = TRUE;
5742               return FALSE;
5743             }
5744           memcpy (alc, name, p - name);
5745           alc[p - name] = '\0';
5746           name = alc;
5747         }
5748     }
5749
5750   /* Compute the hash value.  */
5751   ha = bfd_elf_gnu_hash (name);
5752
5753   /* Store the found hash value in the array for compute_bucket_count,
5754      and also for .dynsym reordering purposes.  */
5755   s->hashcodes[s->nsyms] = ha;
5756   s->hashval[h->dynindx] = ha;
5757   ++s->nsyms;
5758   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5759     s->min_dynindx = h->dynindx;
5760
5761   if (alc != NULL)
5762     free (alc);
5763
5764   return TRUE;
5765 }
5766
5767 /* This function will be called though elf_link_hash_traverse to do
5768    final dynaminc symbol renumbering.  */
5769
5770 static bfd_boolean
5771 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5772 {
5773   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5774   unsigned long int bucket;
5775   unsigned long int val;
5776
5777   /* Ignore indirect symbols.  */
5778   if (h->dynindx == -1)
5779     return TRUE;
5780
5781   /* Ignore also local symbols and undefined symbols.  */
5782   if (! (*s->bed->elf_hash_symbol) (h))
5783     {
5784       if (h->dynindx >= s->min_dynindx)
5785         h->dynindx = s->local_indx++;
5786       return TRUE;
5787     }
5788
5789   bucket = s->hashval[h->dynindx] % s->bucketcount;
5790   val = (s->hashval[h->dynindx] >> s->shift1)
5791         & ((s->maskbits >> s->shift1) - 1);
5792   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5793   s->bitmask[val]
5794     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5795   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5796   if (s->counts[bucket] == 1)
5797     /* Last element terminates the chain.  */
5798     val |= 1;
5799   bfd_put_32 (s->output_bfd, val,
5800               s->contents + (s->indx[bucket] - s->symindx) * 4);
5801   --s->counts[bucket];
5802   h->dynindx = s->indx[bucket]++;
5803   return TRUE;
5804 }
5805
5806 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5807
5808 bfd_boolean
5809 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5810 {
5811   return !(h->forced_local
5812            || h->root.type == bfd_link_hash_undefined
5813            || h->root.type == bfd_link_hash_undefweak
5814            || ((h->root.type == bfd_link_hash_defined
5815                 || h->root.type == bfd_link_hash_defweak)
5816                && h->root.u.def.section->output_section == NULL));
5817 }
5818
5819 /* Array used to determine the number of hash table buckets to use
5820    based on the number of symbols there are.  If there are fewer than
5821    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5822    fewer than 37 we use 17 buckets, and so forth.  We never use more
5823    than 32771 buckets.  */
5824
5825 static const size_t elf_buckets[] =
5826 {
5827   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5828   16411, 32771, 0
5829 };
5830
5831 /* Compute bucket count for hashing table.  We do not use a static set
5832    of possible tables sizes anymore.  Instead we determine for all
5833    possible reasonable sizes of the table the outcome (i.e., the
5834    number of collisions etc) and choose the best solution.  The
5835    weighting functions are not too simple to allow the table to grow
5836    without bounds.  Instead one of the weighting factors is the size.
5837    Therefore the result is always a good payoff between few collisions
5838    (= short chain lengths) and table size.  */
5839 static size_t
5840 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5841                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5842                       unsigned long int nsyms,
5843                       int gnu_hash)
5844 {
5845   size_t best_size = 0;
5846   unsigned long int i;
5847
5848   /* We have a problem here.  The following code to optimize the table
5849      size requires an integer type with more the 32 bits.  If
5850      BFD_HOST_U_64_BIT is set we know about such a type.  */
5851 #ifdef BFD_HOST_U_64_BIT
5852   if (info->optimize)
5853     {
5854       size_t minsize;
5855       size_t maxsize;
5856       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5857       bfd *dynobj = elf_hash_table (info)->dynobj;
5858       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5859       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5860       unsigned long int *counts;
5861       bfd_size_type amt;
5862       unsigned int no_improvement_count = 0;
5863
5864       /* Possible optimization parameters: if we have NSYMS symbols we say
5865          that the hashing table must at least have NSYMS/4 and at most
5866          2*NSYMS buckets.  */
5867       minsize = nsyms / 4;
5868       if (minsize == 0)
5869         minsize = 1;
5870       best_size = maxsize = nsyms * 2;
5871       if (gnu_hash)
5872         {
5873           if (minsize < 2)
5874             minsize = 2;
5875           if ((best_size & 31) == 0)
5876             ++best_size;
5877         }
5878
5879       /* Create array where we count the collisions in.  We must use bfd_malloc
5880          since the size could be large.  */
5881       amt = maxsize;
5882       amt *= sizeof (unsigned long int);
5883       counts = (unsigned long int *) bfd_malloc (amt);
5884       if (counts == NULL)
5885         return 0;
5886
5887       /* Compute the "optimal" size for the hash table.  The criteria is a
5888          minimal chain length.  The minor criteria is (of course) the size
5889          of the table.  */
5890       for (i = minsize; i < maxsize; ++i)
5891         {
5892           /* Walk through the array of hashcodes and count the collisions.  */
5893           BFD_HOST_U_64_BIT max;
5894           unsigned long int j;
5895           unsigned long int fact;
5896
5897           if (gnu_hash && (i & 31) == 0)
5898             continue;
5899
5900           memset (counts, '\0', i * sizeof (unsigned long int));
5901
5902           /* Determine how often each hash bucket is used.  */
5903           for (j = 0; j < nsyms; ++j)
5904             ++counts[hashcodes[j] % i];
5905
5906           /* For the weight function we need some information about the
5907              pagesize on the target.  This is information need not be 100%
5908              accurate.  Since this information is not available (so far) we
5909              define it here to a reasonable default value.  If it is crucial
5910              to have a better value some day simply define this value.  */
5911 # ifndef BFD_TARGET_PAGESIZE
5912 #  define BFD_TARGET_PAGESIZE   (4096)
5913 # endif
5914
5915           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5916              and the chains.  */
5917           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5918
5919 # if 1
5920           /* Variant 1: optimize for short chains.  We add the squares
5921              of all the chain lengths (which favors many small chain
5922              over a few long chains).  */
5923           for (j = 0; j < i; ++j)
5924             max += counts[j] * counts[j];
5925
5926           /* This adds penalties for the overall size of the table.  */
5927           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5928           max *= fact * fact;
5929 # else
5930           /* Variant 2: Optimize a lot more for small table.  Here we
5931              also add squares of the size but we also add penalties for
5932              empty slots (the +1 term).  */
5933           for (j = 0; j < i; ++j)
5934             max += (1 + counts[j]) * (1 + counts[j]);
5935
5936           /* The overall size of the table is considered, but not as
5937              strong as in variant 1, where it is squared.  */
5938           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5939           max *= fact;
5940 # endif
5941
5942           /* Compare with current best results.  */
5943           if (max < best_chlen)
5944             {
5945               best_chlen = max;
5946               best_size = i;
5947               no_improvement_count = 0;
5948             }
5949           /* PR 11843: Avoid futile long searches for the best bucket size
5950              when there are a large number of symbols.  */
5951           else if (++no_improvement_count == 100)
5952             break;
5953         }
5954
5955       free (counts);
5956     }
5957   else
5958 #endif /* defined (BFD_HOST_U_64_BIT) */
5959     {
5960       /* This is the fallback solution if no 64bit type is available or if we
5961          are not supposed to spend much time on optimizations.  We select the
5962          bucket count using a fixed set of numbers.  */
5963       for (i = 0; elf_buckets[i] != 0; i++)
5964         {
5965           best_size = elf_buckets[i];
5966           if (nsyms < elf_buckets[i + 1])
5967             break;
5968         }
5969       if (gnu_hash && best_size < 2)
5970         best_size = 2;
5971     }
5972
5973   return best_size;
5974 }
5975
5976 /* Size any SHT_GROUP section for ld -r.  */
5977
5978 bfd_boolean
5979 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5980 {
5981   bfd *ibfd;
5982   asection *s;
5983
5984   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5985     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5986         && (s = ibfd->sections) != NULL
5987         && s->sec_info_type != SEC_INFO_TYPE_JUST_SYMS
5988         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5989       return FALSE;
5990   return TRUE;
5991 }
5992
5993 /* Set a default stack segment size.  The value in INFO wins.  If it
5994    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
5995    undefined it is initialized.  */
5996
5997 bfd_boolean
5998 bfd_elf_stack_segment_size (bfd *output_bfd,
5999                             struct bfd_link_info *info,
6000                             const char *legacy_symbol,
6001                             bfd_vma default_size)
6002 {
6003   struct elf_link_hash_entry *h = NULL;
6004
6005   /* Look for legacy symbol.  */
6006   if (legacy_symbol)
6007     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
6008                               FALSE, FALSE, FALSE);
6009   if (h && (h->root.type == bfd_link_hash_defined
6010             || h->root.type == bfd_link_hash_defweak)
6011       && h->def_regular
6012       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
6013     {
6014       /* The symbol has no type if specified on the command line.  */
6015       h->type = STT_OBJECT;
6016       if (info->stacksize)
6017         /* xgettext:c-format */
6018         _bfd_error_handler (_("%pB: stack size specified and %s set"),
6019                             output_bfd, legacy_symbol);
6020       else if (h->root.u.def.section != bfd_abs_section_ptr)
6021         /* xgettext:c-format */
6022         _bfd_error_handler (_("%pB: %s not absolute"),
6023                             output_bfd, legacy_symbol);
6024       else
6025         info->stacksize = h->root.u.def.value;
6026     }
6027
6028   if (!info->stacksize)
6029     /* If the user didn't set a size, or explicitly inhibit the
6030        size, set it now.  */
6031     info->stacksize = default_size;
6032
6033   /* Provide the legacy symbol, if it is referenced.  */
6034   if (h && (h->root.type == bfd_link_hash_undefined
6035             || h->root.type == bfd_link_hash_undefweak))
6036     {
6037       struct bfd_link_hash_entry *bh = NULL;
6038
6039       if (!(_bfd_generic_link_add_one_symbol
6040             (info, output_bfd, legacy_symbol,
6041              BSF_GLOBAL, bfd_abs_section_ptr,
6042              info->stacksize >= 0 ? info->stacksize : 0,
6043              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
6044         return FALSE;
6045
6046       h = (struct elf_link_hash_entry *) bh;
6047       h->def_regular = 1;
6048       h->type = STT_OBJECT;
6049     }
6050
6051   return TRUE;
6052 }
6053
6054 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
6055
6056 struct elf_gc_sweep_symbol_info
6057 {
6058   struct bfd_link_info *info;
6059   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
6060                        bfd_boolean);
6061 };
6062
6063 static bfd_boolean
6064 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
6065 {
6066   if (!h->mark
6067       && (((h->root.type == bfd_link_hash_defined
6068             || h->root.type == bfd_link_hash_defweak)
6069            && !((h->def_regular || ELF_COMMON_DEF_P (h))
6070                 && h->root.u.def.section->gc_mark))
6071           || h->root.type == bfd_link_hash_undefined
6072           || h->root.type == bfd_link_hash_undefweak))
6073     {
6074       struct elf_gc_sweep_symbol_info *inf;
6075
6076       inf = (struct elf_gc_sweep_symbol_info *) data;
6077       (*inf->hide_symbol) (inf->info, h, TRUE);
6078       h->def_regular = 0;
6079       h->ref_regular = 0;
6080       h->ref_regular_nonweak = 0;
6081     }
6082
6083   return TRUE;
6084 }
6085
6086 /* Set up the sizes and contents of the ELF dynamic sections.  This is
6087    called by the ELF linker emulation before_allocation routine.  We
6088    must set the sizes of the sections before the linker sets the
6089    addresses of the various sections.  */
6090
6091 bfd_boolean
6092 bfd_elf_size_dynamic_sections (bfd *output_bfd,
6093                                const char *soname,
6094                                const char *rpath,
6095                                const char *filter_shlib,
6096                                const char *audit,
6097                                const char *depaudit,
6098                                const char * const *auxiliary_filters,
6099                                struct bfd_link_info *info,
6100                                asection **sinterpptr)
6101 {
6102   bfd *dynobj;
6103   const struct elf_backend_data *bed;
6104
6105   *sinterpptr = NULL;
6106
6107   if (!is_elf_hash_table (info->hash))
6108     return TRUE;
6109
6110   dynobj = elf_hash_table (info)->dynobj;
6111
6112   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6113     {
6114       struct bfd_elf_version_tree *verdefs;
6115       struct elf_info_failed asvinfo;
6116       struct bfd_elf_version_tree *t;
6117       struct bfd_elf_version_expr *d;
6118       asection *s;
6119       size_t soname_indx;
6120
6121       /* If we are supposed to export all symbols into the dynamic symbol
6122          table (this is not the normal case), then do so.  */
6123       if (info->export_dynamic
6124           || (bfd_link_executable (info) && info->dynamic))
6125         {
6126           struct elf_info_failed eif;
6127
6128           eif.info = info;
6129           eif.failed = FALSE;
6130           elf_link_hash_traverse (elf_hash_table (info),
6131                                   _bfd_elf_export_symbol,
6132                                   &eif);
6133           if (eif.failed)
6134             return FALSE;
6135         }
6136
6137       if (soname != NULL)
6138         {
6139           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6140                                              soname, TRUE);
6141           if (soname_indx == (size_t) -1
6142               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
6143             return FALSE;
6144         }
6145       else
6146         soname_indx = (size_t) -1;
6147
6148       /* Make all global versions with definition.  */
6149       for (t = info->version_info; t != NULL; t = t->next)
6150         for (d = t->globals.list; d != NULL; d = d->next)
6151           if (!d->symver && d->literal)
6152             {
6153               const char *verstr, *name;
6154               size_t namelen, verlen, newlen;
6155               char *newname, *p, leading_char;
6156               struct elf_link_hash_entry *newh;
6157
6158               leading_char = bfd_get_symbol_leading_char (output_bfd);
6159               name = d->pattern;
6160               namelen = strlen (name) + (leading_char != '\0');
6161               verstr = t->name;
6162               verlen = strlen (verstr);
6163               newlen = namelen + verlen + 3;
6164
6165               newname = (char *) bfd_malloc (newlen);
6166               if (newname == NULL)
6167                 return FALSE;
6168               newname[0] = leading_char;
6169               memcpy (newname + (leading_char != '\0'), name, namelen);
6170
6171               /* Check the hidden versioned definition.  */
6172               p = newname + namelen;
6173               *p++ = ELF_VER_CHR;
6174               memcpy (p, verstr, verlen + 1);
6175               newh = elf_link_hash_lookup (elf_hash_table (info),
6176                                            newname, FALSE, FALSE,
6177                                            FALSE);
6178               if (newh == NULL
6179                   || (newh->root.type != bfd_link_hash_defined
6180                       && newh->root.type != bfd_link_hash_defweak))
6181                 {
6182                   /* Check the default versioned definition.  */
6183                   *p++ = ELF_VER_CHR;
6184                   memcpy (p, verstr, verlen + 1);
6185                   newh = elf_link_hash_lookup (elf_hash_table (info),
6186                                                newname, FALSE, FALSE,
6187                                                FALSE);
6188                 }
6189               free (newname);
6190
6191               /* Mark this version if there is a definition and it is
6192                  not defined in a shared object.  */
6193               if (newh != NULL
6194                   && !newh->def_dynamic
6195                   && (newh->root.type == bfd_link_hash_defined
6196                       || newh->root.type == bfd_link_hash_defweak))
6197                 d->symver = 1;
6198             }
6199
6200       /* Attach all the symbols to their version information.  */
6201       asvinfo.info = info;
6202       asvinfo.failed = FALSE;
6203
6204       elf_link_hash_traverse (elf_hash_table (info),
6205                               _bfd_elf_link_assign_sym_version,
6206                               &asvinfo);
6207       if (asvinfo.failed)
6208         return FALSE;
6209
6210       if (!info->allow_undefined_version)
6211         {
6212           /* Check if all global versions have a definition.  */
6213           bfd_boolean all_defined = TRUE;
6214           for (t = info->version_info; t != NULL; t = t->next)
6215             for (d = t->globals.list; d != NULL; d = d->next)
6216               if (d->literal && !d->symver && !d->script)
6217                 {
6218                   _bfd_error_handler
6219                     (_("%s: undefined version: %s"),
6220                      d->pattern, t->name);
6221                   all_defined = FALSE;
6222                 }
6223
6224           if (!all_defined)
6225             {
6226               bfd_set_error (bfd_error_bad_value);
6227               return FALSE;
6228             }
6229         }
6230
6231       /* Set up the version definition section.  */
6232       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6233       BFD_ASSERT (s != NULL);
6234
6235       /* We may have created additional version definitions if we are
6236          just linking a regular application.  */
6237       verdefs = info->version_info;
6238
6239       /* Skip anonymous version tag.  */
6240       if (verdefs != NULL && verdefs->vernum == 0)
6241         verdefs = verdefs->next;
6242
6243       if (verdefs == NULL && !info->create_default_symver)
6244         s->flags |= SEC_EXCLUDE;
6245       else
6246         {
6247           unsigned int cdefs;
6248           bfd_size_type size;
6249           bfd_byte *p;
6250           Elf_Internal_Verdef def;
6251           Elf_Internal_Verdaux defaux;
6252           struct bfd_link_hash_entry *bh;
6253           struct elf_link_hash_entry *h;
6254           const char *name;
6255
6256           cdefs = 0;
6257           size = 0;
6258
6259           /* Make space for the base version.  */
6260           size += sizeof (Elf_External_Verdef);
6261           size += sizeof (Elf_External_Verdaux);
6262           ++cdefs;
6263
6264           /* Make space for the default version.  */
6265           if (info->create_default_symver)
6266             {
6267               size += sizeof (Elf_External_Verdef);
6268               ++cdefs;
6269             }
6270
6271           for (t = verdefs; t != NULL; t = t->next)
6272             {
6273               struct bfd_elf_version_deps *n;
6274
6275               /* Don't emit base version twice.  */
6276               if (t->vernum == 0)
6277                 continue;
6278
6279               size += sizeof (Elf_External_Verdef);
6280               size += sizeof (Elf_External_Verdaux);
6281               ++cdefs;
6282
6283               for (n = t->deps; n != NULL; n = n->next)
6284                 size += sizeof (Elf_External_Verdaux);
6285             }
6286
6287           s->size = size;
6288           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6289           if (s->contents == NULL && s->size != 0)
6290             return FALSE;
6291
6292           /* Fill in the version definition section.  */
6293
6294           p = s->contents;
6295
6296           def.vd_version = VER_DEF_CURRENT;
6297           def.vd_flags = VER_FLG_BASE;
6298           def.vd_ndx = 1;
6299           def.vd_cnt = 1;
6300           if (info->create_default_symver)
6301             {
6302               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6303               def.vd_next = sizeof (Elf_External_Verdef);
6304             }
6305           else
6306             {
6307               def.vd_aux = sizeof (Elf_External_Verdef);
6308               def.vd_next = (sizeof (Elf_External_Verdef)
6309                              + sizeof (Elf_External_Verdaux));
6310             }
6311
6312           if (soname_indx != (size_t) -1)
6313             {
6314               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6315                                       soname_indx);
6316               def.vd_hash = bfd_elf_hash (soname);
6317               defaux.vda_name = soname_indx;
6318               name = soname;
6319             }
6320           else
6321             {
6322               size_t indx;
6323
6324               name = lbasename (output_bfd->filename);
6325               def.vd_hash = bfd_elf_hash (name);
6326               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6327                                           name, FALSE);
6328               if (indx == (size_t) -1)
6329                 return FALSE;
6330               defaux.vda_name = indx;
6331             }
6332           defaux.vda_next = 0;
6333
6334           _bfd_elf_swap_verdef_out (output_bfd, &def,
6335                                     (Elf_External_Verdef *) p);
6336           p += sizeof (Elf_External_Verdef);
6337           if (info->create_default_symver)
6338             {
6339               /* Add a symbol representing this version.  */
6340               bh = NULL;
6341               if (! (_bfd_generic_link_add_one_symbol
6342                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6343                       0, NULL, FALSE,
6344                       get_elf_backend_data (dynobj)->collect, &bh)))
6345                 return FALSE;
6346               h = (struct elf_link_hash_entry *) bh;
6347               h->non_elf = 0;
6348               h->def_regular = 1;
6349               h->type = STT_OBJECT;
6350               h->verinfo.vertree = NULL;
6351
6352               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6353                 return FALSE;
6354
6355               /* Create a duplicate of the base version with the same
6356                  aux block, but different flags.  */
6357               def.vd_flags = 0;
6358               def.vd_ndx = 2;
6359               def.vd_aux = sizeof (Elf_External_Verdef);
6360               if (verdefs)
6361                 def.vd_next = (sizeof (Elf_External_Verdef)
6362                                + sizeof (Elf_External_Verdaux));
6363               else
6364                 def.vd_next = 0;
6365               _bfd_elf_swap_verdef_out (output_bfd, &def,
6366                                         (Elf_External_Verdef *) p);
6367               p += sizeof (Elf_External_Verdef);
6368             }
6369           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6370                                      (Elf_External_Verdaux *) p);
6371           p += sizeof (Elf_External_Verdaux);
6372
6373           for (t = verdefs; t != NULL; t = t->next)
6374             {
6375               unsigned int cdeps;
6376               struct bfd_elf_version_deps *n;
6377
6378               /* Don't emit the base version twice.  */
6379               if (t->vernum == 0)
6380                 continue;
6381
6382               cdeps = 0;
6383               for (n = t->deps; n != NULL; n = n->next)
6384                 ++cdeps;
6385
6386               /* Add a symbol representing this version.  */
6387               bh = NULL;
6388               if (! (_bfd_generic_link_add_one_symbol
6389                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6390                       0, NULL, FALSE,
6391                       get_elf_backend_data (dynobj)->collect, &bh)))
6392                 return FALSE;
6393               h = (struct elf_link_hash_entry *) bh;
6394               h->non_elf = 0;
6395               h->def_regular = 1;
6396               h->type = STT_OBJECT;
6397               h->verinfo.vertree = t;
6398
6399               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6400                 return FALSE;
6401
6402               def.vd_version = VER_DEF_CURRENT;
6403               def.vd_flags = 0;
6404               if (t->globals.list == NULL
6405                   && t->locals.list == NULL
6406                   && ! t->used)
6407                 def.vd_flags |= VER_FLG_WEAK;
6408               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6409               def.vd_cnt = cdeps + 1;
6410               def.vd_hash = bfd_elf_hash (t->name);
6411               def.vd_aux = sizeof (Elf_External_Verdef);
6412               def.vd_next = 0;
6413
6414               /* If a basever node is next, it *must* be the last node in
6415                  the chain, otherwise Verdef construction breaks.  */
6416               if (t->next != NULL && t->next->vernum == 0)
6417                 BFD_ASSERT (t->next->next == NULL);
6418
6419               if (t->next != NULL && t->next->vernum != 0)
6420                 def.vd_next = (sizeof (Elf_External_Verdef)
6421                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6422
6423               _bfd_elf_swap_verdef_out (output_bfd, &def,
6424                                         (Elf_External_Verdef *) p);
6425               p += sizeof (Elf_External_Verdef);
6426
6427               defaux.vda_name = h->dynstr_index;
6428               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6429                                       h->dynstr_index);
6430               defaux.vda_next = 0;
6431               if (t->deps != NULL)
6432                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6433               t->name_indx = defaux.vda_name;
6434
6435               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6436                                          (Elf_External_Verdaux *) p);
6437               p += sizeof (Elf_External_Verdaux);
6438
6439               for (n = t->deps; n != NULL; n = n->next)
6440                 {
6441                   if (n->version_needed == NULL)
6442                     {
6443                       /* This can happen if there was an error in the
6444                          version script.  */
6445                       defaux.vda_name = 0;
6446                     }
6447                   else
6448                     {
6449                       defaux.vda_name = n->version_needed->name_indx;
6450                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6451                                               defaux.vda_name);
6452                     }
6453                   if (n->next == NULL)
6454                     defaux.vda_next = 0;
6455                   else
6456                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6457
6458                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6459                                              (Elf_External_Verdaux *) p);
6460                   p += sizeof (Elf_External_Verdaux);
6461                 }
6462             }
6463
6464           elf_tdata (output_bfd)->cverdefs = cdefs;
6465         }
6466     }
6467
6468   bed = get_elf_backend_data (output_bfd);
6469
6470   if (info->gc_sections && bed->can_gc_sections)
6471     {
6472       struct elf_gc_sweep_symbol_info sweep_info;
6473
6474       /* Remove the symbols that were in the swept sections from the
6475          dynamic symbol table.  */
6476       sweep_info.info = info;
6477       sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
6478       elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
6479                               &sweep_info);
6480     }
6481
6482   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6483     {
6484       asection *s;
6485       struct elf_find_verdep_info sinfo;
6486
6487       /* Work out the size of the version reference section.  */
6488
6489       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6490       BFD_ASSERT (s != NULL);
6491
6492       sinfo.info = info;
6493       sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6494       if (sinfo.vers == 0)
6495         sinfo.vers = 1;
6496       sinfo.failed = FALSE;
6497
6498       elf_link_hash_traverse (elf_hash_table (info),
6499                               _bfd_elf_link_find_version_dependencies,
6500                               &sinfo);
6501       if (sinfo.failed)
6502         return FALSE;
6503
6504       if (elf_tdata (output_bfd)->verref == NULL)
6505         s->flags |= SEC_EXCLUDE;
6506       else
6507         {
6508           Elf_Internal_Verneed *vn;
6509           unsigned int size;
6510           unsigned int crefs;
6511           bfd_byte *p;
6512
6513           /* Build the version dependency section.  */
6514           size = 0;
6515           crefs = 0;
6516           for (vn = elf_tdata (output_bfd)->verref;
6517                vn != NULL;
6518                vn = vn->vn_nextref)
6519             {
6520               Elf_Internal_Vernaux *a;
6521
6522               size += sizeof (Elf_External_Verneed);
6523               ++crefs;
6524               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6525                 size += sizeof (Elf_External_Vernaux);
6526             }
6527
6528           s->size = size;
6529           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6530           if (s->contents == NULL)
6531             return FALSE;
6532
6533           p = s->contents;
6534           for (vn = elf_tdata (output_bfd)->verref;
6535                vn != NULL;
6536                vn = vn->vn_nextref)
6537             {
6538               unsigned int caux;
6539               Elf_Internal_Vernaux *a;
6540               size_t indx;
6541
6542               caux = 0;
6543               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6544                 ++caux;
6545
6546               vn->vn_version = VER_NEED_CURRENT;
6547               vn->vn_cnt = caux;
6548               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6549                                           elf_dt_name (vn->vn_bfd) != NULL
6550                                           ? elf_dt_name (vn->vn_bfd)
6551                                           : lbasename (vn->vn_bfd->filename),
6552                                           FALSE);
6553               if (indx == (size_t) -1)
6554                 return FALSE;
6555               vn->vn_file = indx;
6556               vn->vn_aux = sizeof (Elf_External_Verneed);
6557               if (vn->vn_nextref == NULL)
6558                 vn->vn_next = 0;
6559               else
6560                 vn->vn_next = (sizeof (Elf_External_Verneed)
6561                                + caux * sizeof (Elf_External_Vernaux));
6562
6563               _bfd_elf_swap_verneed_out (output_bfd, vn,
6564                                          (Elf_External_Verneed *) p);
6565               p += sizeof (Elf_External_Verneed);
6566
6567               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6568                 {
6569                   a->vna_hash = bfd_elf_hash (a->vna_nodename);
6570                   indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6571                                               a->vna_nodename, FALSE);
6572                   if (indx == (size_t) -1)
6573                     return FALSE;
6574                   a->vna_name = indx;
6575                   if (a->vna_nextptr == NULL)
6576                     a->vna_next = 0;
6577                   else
6578                     a->vna_next = sizeof (Elf_External_Vernaux);
6579
6580                   _bfd_elf_swap_vernaux_out (output_bfd, a,
6581                                              (Elf_External_Vernaux *) p);
6582                   p += sizeof (Elf_External_Vernaux);
6583                 }
6584             }
6585
6586           elf_tdata (output_bfd)->cverrefs = crefs;
6587         }
6588     }
6589
6590   /* Any syms created from now on start with -1 in
6591      got.refcount/offset and plt.refcount/offset.  */
6592   elf_hash_table (info)->init_got_refcount
6593     = elf_hash_table (info)->init_got_offset;
6594   elf_hash_table (info)->init_plt_refcount
6595     = elf_hash_table (info)->init_plt_offset;
6596
6597   if (bfd_link_relocatable (info)
6598       && !_bfd_elf_size_group_sections (info))
6599     return FALSE;
6600
6601   /* The backend may have to create some sections regardless of whether
6602      we're dynamic or not.  */
6603   if (bed->elf_backend_always_size_sections
6604       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
6605     return FALSE;
6606
6607   /* Determine any GNU_STACK segment requirements, after the backend
6608      has had a chance to set a default segment size.  */
6609   if (info->execstack)
6610     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
6611   else if (info->noexecstack)
6612     elf_stack_flags (output_bfd) = PF_R | PF_W;
6613   else
6614     {
6615       bfd *inputobj;
6616       asection *notesec = NULL;
6617       int exec = 0;
6618
6619       for (inputobj = info->input_bfds;
6620            inputobj;
6621            inputobj = inputobj->link.next)
6622         {
6623           asection *s;
6624
6625           if (inputobj->flags
6626               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
6627             continue;
6628           s = inputobj->sections;
6629           if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
6630             continue;
6631
6632           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
6633           if (s)
6634             {
6635               if (s->flags & SEC_CODE)
6636                 exec = PF_X;
6637               notesec = s;
6638             }
6639           else if (bed->default_execstack)
6640             exec = PF_X;
6641         }
6642       if (notesec || info->stacksize > 0)
6643         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
6644       if (notesec && exec && bfd_link_relocatable (info)
6645           && notesec->output_section != bfd_abs_section_ptr)
6646         notesec->output_section->flags |= SEC_CODE;
6647     }
6648
6649   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6650     {
6651       struct elf_info_failed eif;
6652       struct elf_link_hash_entry *h;
6653       asection *dynstr;
6654       asection *s;
6655
6656       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
6657       BFD_ASSERT (*sinterpptr != NULL || !bfd_link_executable (info) || info->nointerp);
6658
6659       if (info->symbolic)
6660         {
6661           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
6662             return FALSE;
6663           info->flags |= DF_SYMBOLIC;
6664         }
6665
6666       if (rpath != NULL)
6667         {
6668           size_t indx;
6669           bfd_vma tag;
6670
6671           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
6672                                       TRUE);
6673           if (indx == (size_t) -1)
6674             return FALSE;
6675
6676           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
6677           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
6678             return FALSE;
6679         }
6680
6681       if (filter_shlib != NULL)
6682         {
6683           size_t indx;
6684
6685           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6686                                       filter_shlib, TRUE);
6687           if (indx == (size_t) -1
6688               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
6689             return FALSE;
6690         }
6691
6692       if (auxiliary_filters != NULL)
6693         {
6694           const char * const *p;
6695
6696           for (p = auxiliary_filters; *p != NULL; p++)
6697             {
6698               size_t indx;
6699
6700               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6701                                           *p, TRUE);
6702               if (indx == (size_t) -1
6703                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
6704                 return FALSE;
6705             }
6706         }
6707
6708       if (audit != NULL)
6709         {
6710           size_t indx;
6711
6712           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
6713                                       TRUE);
6714           if (indx == (size_t) -1
6715               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
6716             return FALSE;
6717         }
6718
6719       if (depaudit != NULL)
6720         {
6721           size_t indx;
6722
6723           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
6724                                       TRUE);
6725           if (indx == (size_t) -1
6726               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
6727             return FALSE;
6728         }
6729
6730       eif.info = info;
6731       eif.failed = FALSE;
6732
6733       /* Find all symbols which were defined in a dynamic object and make
6734          the backend pick a reasonable value for them.  */
6735       elf_link_hash_traverse (elf_hash_table (info),
6736                               _bfd_elf_adjust_dynamic_symbol,
6737                               &eif);
6738       if (eif.failed)
6739         return FALSE;
6740
6741       /* Add some entries to the .dynamic section.  We fill in some of the
6742          values later, in bfd_elf_final_link, but we must add the entries
6743          now so that we know the final size of the .dynamic section.  */
6744
6745       /* If there are initialization and/or finalization functions to
6746          call then add the corresponding DT_INIT/DT_FINI entries.  */
6747       h = (info->init_function
6748            ? elf_link_hash_lookup (elf_hash_table (info),
6749                                    info->init_function, FALSE,
6750                                    FALSE, FALSE)
6751            : NULL);
6752       if (h != NULL
6753           && (h->ref_regular
6754               || h->def_regular))
6755         {
6756           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
6757             return FALSE;
6758         }
6759       h = (info->fini_function
6760            ? elf_link_hash_lookup (elf_hash_table (info),
6761                                    info->fini_function, FALSE,
6762                                    FALSE, FALSE)
6763            : NULL);
6764       if (h != NULL
6765           && (h->ref_regular
6766               || h->def_regular))
6767         {
6768           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
6769             return FALSE;
6770         }
6771
6772       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
6773       if (s != NULL && s->linker_has_input)
6774         {
6775           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
6776           if (! bfd_link_executable (info))
6777             {
6778               bfd *sub;
6779               asection *o;
6780
6781               for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
6782                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour
6783                     && (o = sub->sections) != NULL
6784                     && o->sec_info_type != SEC_INFO_TYPE_JUST_SYMS)
6785                   for (o = sub->sections; o != NULL; o = o->next)
6786                     if (elf_section_data (o)->this_hdr.sh_type
6787                         == SHT_PREINIT_ARRAY)
6788                       {
6789                         _bfd_error_handler
6790                           (_("%pB: .preinit_array section is not allowed in DSO"),
6791                            sub);
6792                         break;
6793                       }
6794
6795               bfd_set_error (bfd_error_nonrepresentable_section);
6796               return FALSE;
6797             }
6798
6799           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6800               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6801             return FALSE;
6802         }
6803       s = bfd_get_section_by_name (output_bfd, ".init_array");
6804       if (s != NULL && s->linker_has_input)
6805         {
6806           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6807               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6808             return FALSE;
6809         }
6810       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6811       if (s != NULL && s->linker_has_input)
6812         {
6813           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6814               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6815             return FALSE;
6816         }
6817
6818       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6819       /* If .dynstr is excluded from the link, we don't want any of
6820          these tags.  Strictly, we should be checking each section
6821          individually;  This quick check covers for the case where
6822          someone does a /DISCARD/ : { *(*) }.  */
6823       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6824         {
6825           bfd_size_type strsize;
6826
6827           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6828           if ((info->emit_hash
6829                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6830               || (info->emit_gnu_hash
6831                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6832               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6833               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6834               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6835               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6836                                               bed->s->sizeof_sym))
6837             return FALSE;
6838         }
6839     }
6840
6841   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6842     return FALSE;
6843
6844   /* The backend must work out the sizes of all the other dynamic
6845      sections.  */
6846   if (dynobj != NULL
6847       && bed->elf_backend_size_dynamic_sections != NULL
6848       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6849     return FALSE;
6850
6851   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6852     {
6853       if (elf_tdata (output_bfd)->cverdefs)
6854         {
6855           unsigned int crefs = elf_tdata (output_bfd)->cverdefs;
6856
6857           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6858               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, crefs))
6859             return FALSE;
6860         }
6861
6862       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6863         {
6864           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6865             return FALSE;
6866         }
6867       else if (info->flags & DF_BIND_NOW)
6868         {
6869           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6870             return FALSE;
6871         }
6872
6873       if (info->flags_1)
6874         {
6875           if (bfd_link_executable (info))
6876             info->flags_1 &= ~ (DF_1_INITFIRST
6877                                 | DF_1_NODELETE
6878                                 | DF_1_NOOPEN);
6879           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6880             return FALSE;
6881         }
6882
6883       if (elf_tdata (output_bfd)->cverrefs)
6884         {
6885           unsigned int crefs = elf_tdata (output_bfd)->cverrefs;
6886
6887           if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6888               || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6889             return FALSE;
6890         }
6891
6892       if ((elf_tdata (output_bfd)->cverrefs == 0
6893            && elf_tdata (output_bfd)->cverdefs == 0)
6894           || _bfd_elf_link_renumber_dynsyms (output_bfd, info, NULL) <= 1)
6895         {
6896           asection *s;
6897
6898           s = bfd_get_linker_section (dynobj, ".gnu.version");
6899           s->flags |= SEC_EXCLUDE;
6900         }
6901     }
6902   return TRUE;
6903 }
6904
6905 /* Find the first non-excluded output section.  We'll use its
6906    section symbol for some emitted relocs.  */
6907 void
6908 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6909 {
6910   asection *s;
6911
6912   for (s = output_bfd->sections; s != NULL; s = s->next)
6913     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6914         && !_bfd_elf_omit_section_dynsym_default (output_bfd, info, s))
6915       {
6916         elf_hash_table (info)->text_index_section = s;
6917         break;
6918       }
6919 }
6920
6921 /* Find two non-excluded output sections, one for code, one for data.
6922    We'll use their section symbols for some emitted relocs.  */
6923 void
6924 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6925 {
6926   asection *s;
6927
6928   /* Data first, since setting text_index_section changes
6929      _bfd_elf_link_omit_section_dynsym.  */
6930   for (s = output_bfd->sections; s != NULL; s = s->next)
6931     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6932         && !_bfd_elf_omit_section_dynsym_default (output_bfd, info, s))
6933       {
6934         elf_hash_table (info)->data_index_section = s;
6935         break;
6936       }
6937
6938   for (s = output_bfd->sections; s != NULL; s = s->next)
6939     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6940          == (SEC_ALLOC | SEC_READONLY))
6941         && !_bfd_elf_omit_section_dynsym_default (output_bfd, info, s))
6942       {
6943         elf_hash_table (info)->text_index_section = s;
6944         break;
6945       }
6946
6947   if (elf_hash_table (info)->text_index_section == NULL)
6948     elf_hash_table (info)->text_index_section
6949       = elf_hash_table (info)->data_index_section;
6950 }
6951
6952 bfd_boolean
6953 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6954 {
6955   const struct elf_backend_data *bed;
6956   unsigned long section_sym_count;
6957   bfd_size_type dynsymcount = 0;
6958
6959   if (!is_elf_hash_table (info->hash))
6960     return TRUE;
6961
6962   bed = get_elf_backend_data (output_bfd);
6963   (*bed->elf_backend_init_index_section) (output_bfd, info);
6964
6965   /* Assign dynsym indices.  In a shared library we generate a section
6966      symbol for each output section, which come first.  Next come all
6967      of the back-end allocated local dynamic syms, followed by the rest
6968      of the global symbols.
6969
6970      This is usually not needed for static binaries, however backends
6971      can request to always do it, e.g. the MIPS backend uses dynamic
6972      symbol counts to lay out GOT, which will be produced in the
6973      presence of GOT relocations even in static binaries (holding fixed
6974      data in that case, to satisfy those relocations).  */
6975
6976   if (elf_hash_table (info)->dynamic_sections_created
6977       || bed->always_renumber_dynsyms)
6978     dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6979                                                   &section_sym_count);
6980
6981   if (elf_hash_table (info)->dynamic_sections_created)
6982     {
6983       bfd *dynobj;
6984       asection *s;
6985       unsigned int dtagcount;
6986
6987       dynobj = elf_hash_table (info)->dynobj;
6988
6989       /* Work out the size of the symbol version section.  */
6990       s = bfd_get_linker_section (dynobj, ".gnu.version");
6991       BFD_ASSERT (s != NULL);
6992       if ((s->flags & SEC_EXCLUDE) == 0)
6993         {
6994           s->size = dynsymcount * sizeof (Elf_External_Versym);
6995           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6996           if (s->contents == NULL)
6997             return FALSE;
6998
6999           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
7000             return FALSE;
7001         }
7002
7003       /* Set the size of the .dynsym and .hash sections.  We counted
7004          the number of dynamic symbols in elf_link_add_object_symbols.
7005          We will build the contents of .dynsym and .hash when we build
7006          the final symbol table, because until then we do not know the
7007          correct value to give the symbols.  We built the .dynstr
7008          section as we went along in elf_link_add_object_symbols.  */
7009       s = elf_hash_table (info)->dynsym;
7010       BFD_ASSERT (s != NULL);
7011       s->size = dynsymcount * bed->s->sizeof_sym;
7012
7013       s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
7014       if (s->contents == NULL)
7015         return FALSE;
7016
7017       /* The first entry in .dynsym is a dummy symbol.  Clear all the
7018          section syms, in case we don't output them all.  */
7019       ++section_sym_count;
7020       memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
7021
7022       elf_hash_table (info)->bucketcount = 0;
7023
7024       /* Compute the size of the hashing table.  As a side effect this
7025          computes the hash values for all the names we export.  */
7026       if (info->emit_hash)
7027         {
7028           unsigned long int *hashcodes;
7029           struct hash_codes_info hashinf;
7030           bfd_size_type amt;
7031           unsigned long int nsyms;
7032           size_t bucketcount;
7033           size_t hash_entry_size;
7034
7035           /* Compute the hash values for all exported symbols.  At the same
7036              time store the values in an array so that we could use them for
7037              optimizations.  */
7038           amt = dynsymcount * sizeof (unsigned long int);
7039           hashcodes = (unsigned long int *) bfd_malloc (amt);
7040           if (hashcodes == NULL)
7041             return FALSE;
7042           hashinf.hashcodes = hashcodes;
7043           hashinf.error = FALSE;
7044
7045           /* Put all hash values in HASHCODES.  */
7046           elf_link_hash_traverse (elf_hash_table (info),
7047                                   elf_collect_hash_codes, &hashinf);
7048           if (hashinf.error)
7049             {
7050               free (hashcodes);
7051               return FALSE;
7052             }
7053
7054           nsyms = hashinf.hashcodes - hashcodes;
7055           bucketcount
7056             = compute_bucket_count (info, hashcodes, nsyms, 0);
7057           free (hashcodes);
7058
7059           if (bucketcount == 0 && nsyms > 0)
7060             return FALSE;
7061
7062           elf_hash_table (info)->bucketcount = bucketcount;
7063
7064           s = bfd_get_linker_section (dynobj, ".hash");
7065           BFD_ASSERT (s != NULL);
7066           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
7067           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
7068           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7069           if (s->contents == NULL)
7070             return FALSE;
7071
7072           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
7073           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
7074                    s->contents + hash_entry_size);
7075         }
7076
7077       if (info->emit_gnu_hash)
7078         {
7079           size_t i, cnt;
7080           unsigned char *contents;
7081           struct collect_gnu_hash_codes cinfo;
7082           bfd_size_type amt;
7083           size_t bucketcount;
7084
7085           memset (&cinfo, 0, sizeof (cinfo));
7086
7087           /* Compute the hash values for all exported symbols.  At the same
7088              time store the values in an array so that we could use them for
7089              optimizations.  */
7090           amt = dynsymcount * 2 * sizeof (unsigned long int);
7091           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
7092           if (cinfo.hashcodes == NULL)
7093             return FALSE;
7094
7095           cinfo.hashval = cinfo.hashcodes + dynsymcount;
7096           cinfo.min_dynindx = -1;
7097           cinfo.output_bfd = output_bfd;
7098           cinfo.bed = bed;
7099
7100           /* Put all hash values in HASHCODES.  */
7101           elf_link_hash_traverse (elf_hash_table (info),
7102                                   elf_collect_gnu_hash_codes, &cinfo);
7103           if (cinfo.error)
7104             {
7105               free (cinfo.hashcodes);
7106               return FALSE;
7107             }
7108
7109           bucketcount
7110             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
7111
7112           if (bucketcount == 0)
7113             {
7114               free (cinfo.hashcodes);
7115               return FALSE;
7116             }
7117
7118           s = bfd_get_linker_section (dynobj, ".gnu.hash");
7119           BFD_ASSERT (s != NULL);
7120
7121           if (cinfo.nsyms == 0)
7122             {
7123               /* Empty .gnu.hash section is special.  */
7124               BFD_ASSERT (cinfo.min_dynindx == -1);
7125               free (cinfo.hashcodes);
7126               s->size = 5 * 4 + bed->s->arch_size / 8;
7127               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7128               if (contents == NULL)
7129                 return FALSE;
7130               s->contents = contents;
7131               /* 1 empty bucket.  */
7132               bfd_put_32 (output_bfd, 1, contents);
7133               /* SYMIDX above the special symbol 0.  */
7134               bfd_put_32 (output_bfd, 1, contents + 4);
7135               /* Just one word for bitmask.  */
7136               bfd_put_32 (output_bfd, 1, contents + 8);
7137               /* Only hash fn bloom filter.  */
7138               bfd_put_32 (output_bfd, 0, contents + 12);
7139               /* No hashes are valid - empty bitmask.  */
7140               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
7141               /* No hashes in the only bucket.  */
7142               bfd_put_32 (output_bfd, 0,
7143                           contents + 16 + bed->s->arch_size / 8);
7144             }
7145           else
7146             {
7147               unsigned long int maskwords, maskbitslog2, x;
7148               BFD_ASSERT (cinfo.min_dynindx != -1);
7149
7150               x = cinfo.nsyms;
7151               maskbitslog2 = 1;
7152               while ((x >>= 1) != 0)
7153                 ++maskbitslog2;
7154               if (maskbitslog2 < 3)
7155                 maskbitslog2 = 5;
7156               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
7157                 maskbitslog2 = maskbitslog2 + 3;
7158               else
7159                 maskbitslog2 = maskbitslog2 + 2;
7160               if (bed->s->arch_size == 64)
7161                 {
7162                   if (maskbitslog2 == 5)
7163                     maskbitslog2 = 6;
7164                   cinfo.shift1 = 6;
7165                 }
7166               else
7167                 cinfo.shift1 = 5;
7168               cinfo.mask = (1 << cinfo.shift1) - 1;
7169               cinfo.shift2 = maskbitslog2;
7170               cinfo.maskbits = 1 << maskbitslog2;
7171               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
7172               amt = bucketcount * sizeof (unsigned long int) * 2;
7173               amt += maskwords * sizeof (bfd_vma);
7174               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
7175               if (cinfo.bitmask == NULL)
7176                 {
7177                   free (cinfo.hashcodes);
7178                   return FALSE;
7179                 }
7180
7181               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
7182               cinfo.indx = cinfo.counts + bucketcount;
7183               cinfo.symindx = dynsymcount - cinfo.nsyms;
7184               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
7185
7186               /* Determine how often each hash bucket is used.  */
7187               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
7188               for (i = 0; i < cinfo.nsyms; ++i)
7189                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
7190
7191               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
7192                 if (cinfo.counts[i] != 0)
7193                   {
7194                     cinfo.indx[i] = cnt;
7195                     cnt += cinfo.counts[i];
7196                   }
7197               BFD_ASSERT (cnt == dynsymcount);
7198               cinfo.bucketcount = bucketcount;
7199               cinfo.local_indx = cinfo.min_dynindx;
7200
7201               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
7202               s->size += cinfo.maskbits / 8;
7203               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7204               if (contents == NULL)
7205                 {
7206                   free (cinfo.bitmask);
7207                   free (cinfo.hashcodes);
7208                   return FALSE;
7209                 }
7210
7211               s->contents = contents;
7212               bfd_put_32 (output_bfd, bucketcount, contents);
7213               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
7214               bfd_put_32 (output_bfd, maskwords, contents + 8);
7215               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
7216               contents += 16 + cinfo.maskbits / 8;
7217
7218               for (i = 0; i < bucketcount; ++i)
7219                 {
7220                   if (cinfo.counts[i] == 0)
7221                     bfd_put_32 (output_bfd, 0, contents);
7222                   else
7223                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
7224                   contents += 4;
7225                 }
7226
7227               cinfo.contents = contents;
7228
7229               /* Renumber dynamic symbols, populate .gnu.hash section.  */
7230               elf_link_hash_traverse (elf_hash_table (info),
7231                                       elf_renumber_gnu_hash_syms, &cinfo);
7232
7233               contents = s->contents + 16;
7234               for (i = 0; i < maskwords; ++i)
7235                 {
7236                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
7237                            contents);
7238                   contents += bed->s->arch_size / 8;
7239                 }
7240
7241               free (cinfo.bitmask);
7242               free (cinfo.hashcodes);
7243             }
7244         }
7245
7246       s = bfd_get_linker_section (dynobj, ".dynstr");
7247       BFD_ASSERT (s != NULL);
7248
7249       elf_finalize_dynstr (output_bfd, info);
7250
7251       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
7252
7253       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
7254         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
7255           return FALSE;
7256     }
7257
7258   return TRUE;
7259 }
7260 \f
7261 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
7262
7263 static void
7264 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
7265                             asection *sec)
7266 {
7267   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
7268   sec->sec_info_type = SEC_INFO_TYPE_NONE;
7269 }
7270
7271 /* Finish SHF_MERGE section merging.  */
7272
7273 bfd_boolean
7274 _bfd_elf_merge_sections (bfd *obfd, struct bfd_link_info *info)
7275 {
7276   bfd *ibfd;
7277   asection *sec;
7278
7279   if (!is_elf_hash_table (info->hash))
7280     return FALSE;
7281
7282   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
7283     if ((ibfd->flags & DYNAMIC) == 0
7284         && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
7285         && (elf_elfheader (ibfd)->e_ident[EI_CLASS]
7286             == get_elf_backend_data (obfd)->s->elfclass))
7287       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
7288         if ((sec->flags & SEC_MERGE) != 0
7289             && !bfd_is_abs_section (sec->output_section))
7290           {
7291             struct bfd_elf_section_data *secdata;
7292
7293             secdata = elf_section_data (sec);
7294             if (! _bfd_add_merge_section (obfd,
7295                                           &elf_hash_table (info)->merge_info,
7296                                           sec, &secdata->sec_info))
7297               return FALSE;
7298             else if (secdata->sec_info)
7299               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
7300           }
7301
7302   if (elf_hash_table (info)->merge_info != NULL)
7303     _bfd_merge_sections (obfd, info, elf_hash_table (info)->merge_info,
7304                          merge_sections_remove_hook);
7305   return TRUE;
7306 }
7307
7308 /* Create an entry in an ELF linker hash table.  */
7309
7310 struct bfd_hash_entry *
7311 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
7312                             struct bfd_hash_table *table,
7313                             const char *string)
7314 {
7315   /* Allocate the structure if it has not already been allocated by a
7316      subclass.  */
7317   if (entry == NULL)
7318     {
7319       entry = (struct bfd_hash_entry *)
7320         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
7321       if (entry == NULL)
7322         return entry;
7323     }
7324
7325   /* Call the allocation method of the superclass.  */
7326   entry = _bfd_link_hash_newfunc (entry, table, string);
7327   if (entry != NULL)
7328     {
7329       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
7330       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
7331
7332       /* Set local fields.  */
7333       ret->indx = -1;
7334       ret->dynindx = -1;
7335       ret->got = htab->init_got_refcount;
7336       ret->plt = htab->init_plt_refcount;
7337       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
7338                               - offsetof (struct elf_link_hash_entry, size)));
7339       /* Assume that we have been called by a non-ELF symbol reader.
7340          This flag is then reset by the code which reads an ELF input
7341          file.  This ensures that a symbol created by a non-ELF symbol
7342          reader will have the flag set correctly.  */
7343       ret->non_elf = 1;
7344     }
7345
7346   return entry;
7347 }
7348
7349 /* Copy data from an indirect symbol to its direct symbol, hiding the
7350    old indirect symbol.  Also used for copying flags to a weakdef.  */
7351
7352 void
7353 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
7354                                   struct elf_link_hash_entry *dir,
7355                                   struct elf_link_hash_entry *ind)
7356 {
7357   struct elf_link_hash_table *htab;
7358
7359   /* Copy down any references that we may have already seen to the
7360      symbol which just became indirect.  */
7361
7362   if (dir->versioned != versioned_hidden)
7363     dir->ref_dynamic |= ind->ref_dynamic;
7364   dir->ref_regular |= ind->ref_regular;
7365   dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
7366   dir->non_got_ref |= ind->non_got_ref;
7367   dir->needs_plt |= ind->needs_plt;
7368   dir->pointer_equality_needed |= ind->pointer_equality_needed;
7369
7370   if (ind->root.type != bfd_link_hash_indirect)
7371     return;
7372
7373   /* Copy over the global and procedure linkage table refcount entries.
7374      These may have been already set up by a check_relocs routine.  */
7375   htab = elf_hash_table (info);
7376   if (ind->got.refcount > htab->init_got_refcount.refcount)
7377     {
7378       if (dir->got.refcount < 0)
7379         dir->got.refcount = 0;
7380       dir->got.refcount += ind->got.refcount;
7381       ind->got.refcount = htab->init_got_refcount.refcount;
7382     }
7383
7384   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
7385     {
7386       if (dir->plt.refcount < 0)
7387         dir->plt.refcount = 0;
7388       dir->plt.refcount += ind->plt.refcount;
7389       ind->plt.refcount = htab->init_plt_refcount.refcount;
7390     }
7391
7392   if (ind->dynindx != -1)
7393     {
7394       if (dir->dynindx != -1)
7395         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
7396       dir->dynindx = ind->dynindx;
7397       dir->dynstr_index = ind->dynstr_index;
7398       ind->dynindx = -1;
7399       ind->dynstr_index = 0;
7400     }
7401 }
7402
7403 void
7404 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
7405                                 struct elf_link_hash_entry *h,
7406                                 bfd_boolean force_local)
7407 {
7408   /* STT_GNU_IFUNC symbol must go through PLT.  */
7409   if (h->type != STT_GNU_IFUNC)
7410     {
7411       h->plt = elf_hash_table (info)->init_plt_offset;
7412       h->needs_plt = 0;
7413     }
7414   if (force_local)
7415     {
7416       h->forced_local = 1;
7417       if (h->dynindx != -1)
7418         {
7419           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
7420                                   h->dynstr_index);
7421           h->dynindx = -1;
7422           h->dynstr_index = 0;
7423         }
7424     }
7425 }
7426
7427 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
7428    caller.  */
7429
7430 bfd_boolean
7431 _bfd_elf_link_hash_table_init
7432   (struct elf_link_hash_table *table,
7433    bfd *abfd,
7434    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
7435                                       struct bfd_hash_table *,
7436                                       const char *),
7437    unsigned int entsize,
7438    enum elf_target_id target_id)
7439 {
7440   bfd_boolean ret;
7441   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
7442
7443   table->init_got_refcount.refcount = can_refcount - 1;
7444   table->init_plt_refcount.refcount = can_refcount - 1;
7445   table->init_got_offset.offset = -(bfd_vma) 1;
7446   table->init_plt_offset.offset = -(bfd_vma) 1;
7447   /* The first dynamic symbol is a dummy.  */
7448   table->dynsymcount = 1;
7449
7450   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
7451
7452   table->root.type = bfd_link_elf_hash_table;
7453   table->hash_table_id = target_id;
7454
7455   return ret;
7456 }
7457
7458 /* Create an ELF linker hash table.  */
7459
7460 struct bfd_link_hash_table *
7461 _bfd_elf_link_hash_table_create (bfd *abfd)
7462 {
7463   struct elf_link_hash_table *ret;
7464   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7465
7466   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7467   if (ret == NULL)
7468     return NULL;
7469
7470   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7471                                        sizeof (struct elf_link_hash_entry),
7472                                        GENERIC_ELF_DATA))
7473     {
7474       free (ret);
7475       return NULL;
7476     }
7477   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7478
7479   return &ret->root;
7480 }
7481
7482 /* Destroy an ELF linker hash table.  */
7483
7484 void
7485 _bfd_elf_link_hash_table_free (bfd *obfd)
7486 {
7487   struct elf_link_hash_table *htab;
7488
7489   htab = (struct elf_link_hash_table *) obfd->link.hash;
7490   if (htab->dynstr != NULL)
7491     _bfd_elf_strtab_free (htab->dynstr);
7492   _bfd_merge_sections_free (htab->merge_info);
7493   _bfd_generic_link_hash_table_free (obfd);
7494 }
7495
7496 /* This is a hook for the ELF emulation code in the generic linker to
7497    tell the backend linker what file name to use for the DT_NEEDED
7498    entry for a dynamic object.  */
7499
7500 void
7501 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7502 {
7503   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7504       && bfd_get_format (abfd) == bfd_object)
7505     elf_dt_name (abfd) = name;
7506 }
7507
7508 int
7509 bfd_elf_get_dyn_lib_class (bfd *abfd)
7510 {
7511   int lib_class;
7512   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7513       && bfd_get_format (abfd) == bfd_object)
7514     lib_class = elf_dyn_lib_class (abfd);
7515   else
7516     lib_class = 0;
7517   return lib_class;
7518 }
7519
7520 void
7521 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7522 {
7523   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7524       && bfd_get_format (abfd) == bfd_object)
7525     elf_dyn_lib_class (abfd) = lib_class;
7526 }
7527
7528 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7529    the linker ELF emulation code.  */
7530
7531 struct bfd_link_needed_list *
7532 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7533                          struct bfd_link_info *info)
7534 {
7535   if (! is_elf_hash_table (info->hash))
7536     return NULL;
7537   return elf_hash_table (info)->needed;
7538 }
7539
7540 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7541    hook for the linker ELF emulation code.  */
7542
7543 struct bfd_link_needed_list *
7544 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7545                           struct bfd_link_info *info)
7546 {
7547   if (! is_elf_hash_table (info->hash))
7548     return NULL;
7549   return elf_hash_table (info)->runpath;
7550 }
7551
7552 /* Get the name actually used for a dynamic object for a link.  This
7553    is the SONAME entry if there is one.  Otherwise, it is the string
7554    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7555
7556 const char *
7557 bfd_elf_get_dt_soname (bfd *abfd)
7558 {
7559   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7560       && bfd_get_format (abfd) == bfd_object)
7561     return elf_dt_name (abfd);
7562   return NULL;
7563 }
7564
7565 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7566    the ELF linker emulation code.  */
7567
7568 bfd_boolean
7569 bfd_elf_get_bfd_needed_list (bfd *abfd,
7570                              struct bfd_link_needed_list **pneeded)
7571 {
7572   asection *s;
7573   bfd_byte *dynbuf = NULL;
7574   unsigned int elfsec;
7575   unsigned long shlink;
7576   bfd_byte *extdyn, *extdynend;
7577   size_t extdynsize;
7578   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7579
7580   *pneeded = NULL;
7581
7582   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7583       || bfd_get_format (abfd) != bfd_object)
7584     return TRUE;
7585
7586   s = bfd_get_section_by_name (abfd, ".dynamic");
7587   if (s == NULL || s->size == 0)
7588     return TRUE;
7589
7590   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7591     goto error_return;
7592
7593   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7594   if (elfsec == SHN_BAD)
7595     goto error_return;
7596
7597   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7598
7599   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7600   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7601
7602   extdyn = dynbuf;
7603   extdynend = extdyn + s->size;
7604   for (; extdyn < extdynend; extdyn += extdynsize)
7605     {
7606       Elf_Internal_Dyn dyn;
7607
7608       (*swap_dyn_in) (abfd, extdyn, &dyn);
7609
7610       if (dyn.d_tag == DT_NULL)
7611         break;
7612
7613       if (dyn.d_tag == DT_NEEDED)
7614         {
7615           const char *string;
7616           struct bfd_link_needed_list *l;
7617           unsigned int tagv = dyn.d_un.d_val;
7618           bfd_size_type amt;
7619
7620           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7621           if (string == NULL)
7622             goto error_return;
7623
7624           amt = sizeof *l;
7625           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7626           if (l == NULL)
7627             goto error_return;
7628
7629           l->by = abfd;
7630           l->name = string;
7631           l->next = *pneeded;
7632           *pneeded = l;
7633         }
7634     }
7635
7636   free (dynbuf);
7637
7638   return TRUE;
7639
7640  error_return:
7641   if (dynbuf != NULL)
7642     free (dynbuf);
7643   return FALSE;
7644 }
7645
7646 struct elf_symbuf_symbol
7647 {
7648   unsigned long st_name;        /* Symbol name, index in string tbl */
7649   unsigned char st_info;        /* Type and binding attributes */
7650   unsigned char st_other;       /* Visibilty, and target specific */
7651 };
7652
7653 struct elf_symbuf_head
7654 {
7655   struct elf_symbuf_symbol *ssym;
7656   size_t count;
7657   unsigned int st_shndx;
7658 };
7659
7660 struct elf_symbol
7661 {
7662   union
7663     {
7664       Elf_Internal_Sym *isym;
7665       struct elf_symbuf_symbol *ssym;
7666     } u;
7667   const char *name;
7668 };
7669
7670 /* Sort references to symbols by ascending section number.  */
7671
7672 static int
7673 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7674 {
7675   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7676   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7677
7678   return s1->st_shndx - s2->st_shndx;
7679 }
7680
7681 static int
7682 elf_sym_name_compare (const void *arg1, const void *arg2)
7683 {
7684   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7685   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7686   return strcmp (s1->name, s2->name);
7687 }
7688
7689 static struct elf_symbuf_head *
7690 elf_create_symbuf (size_t symcount, Elf_Internal_Sym *isymbuf)
7691 {
7692   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7693   struct elf_symbuf_symbol *ssym;
7694   struct elf_symbuf_head *ssymbuf, *ssymhead;
7695   size_t i, shndx_count, total_size;
7696
7697   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7698   if (indbuf == NULL)
7699     return NULL;
7700
7701   for (ind = indbuf, i = 0; i < symcount; i++)
7702     if (isymbuf[i].st_shndx != SHN_UNDEF)
7703       *ind++ = &isymbuf[i];
7704   indbufend = ind;
7705
7706   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7707          elf_sort_elf_symbol);
7708
7709   shndx_count = 0;
7710   if (indbufend > indbuf)
7711     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7712       if (ind[0]->st_shndx != ind[1]->st_shndx)
7713         shndx_count++;
7714
7715   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7716                 + (indbufend - indbuf) * sizeof (*ssym));
7717   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7718   if (ssymbuf == NULL)
7719     {
7720       free (indbuf);
7721       return NULL;
7722     }
7723
7724   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7725   ssymbuf->ssym = NULL;
7726   ssymbuf->count = shndx_count;
7727   ssymbuf->st_shndx = 0;
7728   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7729     {
7730       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7731         {
7732           ssymhead++;
7733           ssymhead->ssym = ssym;
7734           ssymhead->count = 0;
7735           ssymhead->st_shndx = (*ind)->st_shndx;
7736         }
7737       ssym->st_name = (*ind)->st_name;
7738       ssym->st_info = (*ind)->st_info;
7739       ssym->st_other = (*ind)->st_other;
7740       ssymhead->count++;
7741     }
7742   BFD_ASSERT ((size_t) (ssymhead - ssymbuf) == shndx_count
7743               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7744                   == total_size));
7745
7746   free (indbuf);
7747   return ssymbuf;
7748 }
7749
7750 /* Check if 2 sections define the same set of local and global
7751    symbols.  */
7752
7753 static bfd_boolean
7754 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7755                                    struct bfd_link_info *info)
7756 {
7757   bfd *bfd1, *bfd2;
7758   const struct elf_backend_data *bed1, *bed2;
7759   Elf_Internal_Shdr *hdr1, *hdr2;
7760   size_t symcount1, symcount2;
7761   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7762   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7763   Elf_Internal_Sym *isym, *isymend;
7764   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7765   size_t count1, count2, i;
7766   unsigned int shndx1, shndx2;
7767   bfd_boolean result;
7768
7769   bfd1 = sec1->owner;
7770   bfd2 = sec2->owner;
7771
7772   /* Both sections have to be in ELF.  */
7773   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7774       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7775     return FALSE;
7776
7777   if (elf_section_type (sec1) != elf_section_type (sec2))
7778     return FALSE;
7779
7780   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7781   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7782   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7783     return FALSE;
7784
7785   bed1 = get_elf_backend_data (bfd1);
7786   bed2 = get_elf_backend_data (bfd2);
7787   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7788   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7789   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7790   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7791
7792   if (symcount1 == 0 || symcount2 == 0)
7793     return FALSE;
7794
7795   result = FALSE;
7796   isymbuf1 = NULL;
7797   isymbuf2 = NULL;
7798   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7799   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7800
7801   if (ssymbuf1 == NULL)
7802     {
7803       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7804                                        NULL, NULL, NULL);
7805       if (isymbuf1 == NULL)
7806         goto done;
7807
7808       if (!info->reduce_memory_overheads)
7809         elf_tdata (bfd1)->symbuf = ssymbuf1
7810           = elf_create_symbuf (symcount1, isymbuf1);
7811     }
7812
7813   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7814     {
7815       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7816                                        NULL, NULL, NULL);
7817       if (isymbuf2 == NULL)
7818         goto done;
7819
7820       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7821         elf_tdata (bfd2)->symbuf = ssymbuf2
7822           = elf_create_symbuf (symcount2, isymbuf2);
7823     }
7824
7825   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7826     {
7827       /* Optimized faster version.  */
7828       size_t lo, hi, mid;
7829       struct elf_symbol *symp;
7830       struct elf_symbuf_symbol *ssym, *ssymend;
7831
7832       lo = 0;
7833       hi = ssymbuf1->count;
7834       ssymbuf1++;
7835       count1 = 0;
7836       while (lo < hi)
7837         {
7838           mid = (lo + hi) / 2;
7839           if (shndx1 < ssymbuf1[mid].st_shndx)
7840             hi = mid;
7841           else if (shndx1 > ssymbuf1[mid].st_shndx)
7842             lo = mid + 1;
7843           else
7844             {
7845               count1 = ssymbuf1[mid].count;
7846               ssymbuf1 += mid;
7847               break;
7848             }
7849         }
7850
7851       lo = 0;
7852       hi = ssymbuf2->count;
7853       ssymbuf2++;
7854       count2 = 0;
7855       while (lo < hi)
7856         {
7857           mid = (lo + hi) / 2;
7858           if (shndx2 < ssymbuf2[mid].st_shndx)
7859             hi = mid;
7860           else if (shndx2 > ssymbuf2[mid].st_shndx)
7861             lo = mid + 1;
7862           else
7863             {
7864               count2 = ssymbuf2[mid].count;
7865               ssymbuf2 += mid;
7866               break;
7867             }
7868         }
7869
7870       if (count1 == 0 || count2 == 0 || count1 != count2)
7871         goto done;
7872
7873       symtable1
7874         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
7875       symtable2
7876         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
7877       if (symtable1 == NULL || symtable2 == NULL)
7878         goto done;
7879
7880       symp = symtable1;
7881       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7882            ssym < ssymend; ssym++, symp++)
7883         {
7884           symp->u.ssym = ssym;
7885           symp->name = bfd_elf_string_from_elf_section (bfd1,
7886                                                         hdr1->sh_link,
7887                                                         ssym->st_name);
7888         }
7889
7890       symp = symtable2;
7891       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7892            ssym < ssymend; ssym++, symp++)
7893         {
7894           symp->u.ssym = ssym;
7895           symp->name = bfd_elf_string_from_elf_section (bfd2,
7896                                                         hdr2->sh_link,
7897                                                         ssym->st_name);
7898         }
7899
7900       /* Sort symbol by name.  */
7901       qsort (symtable1, count1, sizeof (struct elf_symbol),
7902              elf_sym_name_compare);
7903       qsort (symtable2, count1, sizeof (struct elf_symbol),
7904              elf_sym_name_compare);
7905
7906       for (i = 0; i < count1; i++)
7907         /* Two symbols must have the same binding, type and name.  */
7908         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7909             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7910             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7911           goto done;
7912
7913       result = TRUE;
7914       goto done;
7915     }
7916
7917   symtable1 = (struct elf_symbol *)
7918       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7919   symtable2 = (struct elf_symbol *)
7920       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7921   if (symtable1 == NULL || symtable2 == NULL)
7922     goto done;
7923
7924   /* Count definitions in the section.  */
7925   count1 = 0;
7926   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7927     if (isym->st_shndx == shndx1)
7928       symtable1[count1++].u.isym = isym;
7929
7930   count2 = 0;
7931   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7932     if (isym->st_shndx == shndx2)
7933       symtable2[count2++].u.isym = isym;
7934
7935   if (count1 == 0 || count2 == 0 || count1 != count2)
7936     goto done;
7937
7938   for (i = 0; i < count1; i++)
7939     symtable1[i].name
7940       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7941                                          symtable1[i].u.isym->st_name);
7942
7943   for (i = 0; i < count2; i++)
7944     symtable2[i].name
7945       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7946                                          symtable2[i].u.isym->st_name);
7947
7948   /* Sort symbol by name.  */
7949   qsort (symtable1, count1, sizeof (struct elf_symbol),
7950          elf_sym_name_compare);
7951   qsort (symtable2, count1, sizeof (struct elf_symbol),
7952          elf_sym_name_compare);
7953
7954   for (i = 0; i < count1; i++)
7955     /* Two symbols must have the same binding, type and name.  */
7956     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7957         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7958         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7959       goto done;
7960
7961   result = TRUE;
7962
7963 done:
7964   if (symtable1)
7965     free (symtable1);
7966   if (symtable2)
7967     free (symtable2);
7968   if (isymbuf1)
7969     free (isymbuf1);
7970   if (isymbuf2)
7971     free (isymbuf2);
7972
7973   return result;
7974 }
7975
7976 /* Return TRUE if 2 section types are compatible.  */
7977
7978 bfd_boolean
7979 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7980                                  bfd *bbfd, const asection *bsec)
7981 {
7982   if (asec == NULL
7983       || bsec == NULL
7984       || abfd->xvec->flavour != bfd_target_elf_flavour
7985       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7986     return TRUE;
7987
7988   return elf_section_type (asec) == elf_section_type (bsec);
7989 }
7990 \f
7991 /* Final phase of ELF linker.  */
7992
7993 /* A structure we use to avoid passing large numbers of arguments.  */
7994
7995 struct elf_final_link_info
7996 {
7997   /* General link information.  */
7998   struct bfd_link_info *info;
7999   /* Output BFD.  */
8000   bfd *output_bfd;
8001   /* Symbol string table.  */
8002   struct elf_strtab_hash *symstrtab;
8003   /* .hash section.  */
8004   asection *hash_sec;
8005   /* symbol version section (.gnu.version).  */
8006   asection *symver_sec;
8007   /* Buffer large enough to hold contents of any section.  */
8008   bfd_byte *contents;
8009   /* Buffer large enough to hold external relocs of any section.  */
8010   void *external_relocs;
8011   /* Buffer large enough to hold internal relocs of any section.  */
8012   Elf_Internal_Rela *internal_relocs;
8013   /* Buffer large enough to hold external local symbols of any input
8014      BFD.  */
8015   bfd_byte *external_syms;
8016   /* And a buffer for symbol section indices.  */
8017   Elf_External_Sym_Shndx *locsym_shndx;
8018   /* Buffer large enough to hold internal local symbols of any input
8019      BFD.  */
8020   Elf_Internal_Sym *internal_syms;
8021   /* Array large enough to hold a symbol index for each local symbol
8022      of any input BFD.  */
8023   long *indices;
8024   /* Array large enough to hold a section pointer for each local
8025      symbol of any input BFD.  */
8026   asection **sections;
8027   /* Buffer for SHT_SYMTAB_SHNDX section.  */
8028   Elf_External_Sym_Shndx *symshndxbuf;
8029   /* Number of STT_FILE syms seen.  */
8030   size_t filesym_count;
8031 };
8032
8033 /* This struct is used to pass information to elf_link_output_extsym.  */
8034
8035 struct elf_outext_info
8036 {
8037   bfd_boolean failed;
8038   bfd_boolean localsyms;
8039   bfd_boolean file_sym_done;
8040   struct elf_final_link_info *flinfo;
8041 };
8042
8043
8044 /* Support for evaluating a complex relocation.
8045
8046    Complex relocations are generalized, self-describing relocations.  The
8047    implementation of them consists of two parts: complex symbols, and the
8048    relocations themselves.
8049
8050    The relocations are use a reserved elf-wide relocation type code (R_RELC
8051    external / BFD_RELOC_RELC internal) and an encoding of relocation field
8052    information (start bit, end bit, word width, etc) into the addend.  This
8053    information is extracted from CGEN-generated operand tables within gas.
8054
8055    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
8056    internal) representing prefix-notation expressions, including but not
8057    limited to those sorts of expressions normally encoded as addends in the
8058    addend field.  The symbol mangling format is:
8059
8060    <node> := <literal>
8061           |  <unary-operator> ':' <node>
8062           |  <binary-operator> ':' <node> ':' <node>
8063           ;
8064
8065    <literal> := 's' <digits=N> ':' <N character symbol name>
8066              |  'S' <digits=N> ':' <N character section name>
8067              |  '#' <hexdigits>
8068              ;
8069
8070    <binary-operator> := as in C
8071    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
8072
8073 static void
8074 set_symbol_value (bfd *bfd_with_globals,
8075                   Elf_Internal_Sym *isymbuf,
8076                   size_t locsymcount,
8077                   size_t symidx,
8078                   bfd_vma val)
8079 {
8080   struct elf_link_hash_entry **sym_hashes;
8081   struct elf_link_hash_entry *h;
8082   size_t extsymoff = locsymcount;
8083
8084   if (symidx < locsymcount)
8085     {
8086       Elf_Internal_Sym *sym;
8087
8088       sym = isymbuf + symidx;
8089       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
8090         {
8091           /* It is a local symbol: move it to the
8092              "absolute" section and give it a value.  */
8093           sym->st_shndx = SHN_ABS;
8094           sym->st_value = val;
8095           return;
8096         }
8097       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
8098       extsymoff = 0;
8099     }
8100
8101   /* It is a global symbol: set its link type
8102      to "defined" and give it a value.  */
8103
8104   sym_hashes = elf_sym_hashes (bfd_with_globals);
8105   h = sym_hashes [symidx - extsymoff];
8106   while (h->root.type == bfd_link_hash_indirect
8107          || h->root.type == bfd_link_hash_warning)
8108     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8109   h->root.type = bfd_link_hash_defined;
8110   h->root.u.def.value = val;
8111   h->root.u.def.section = bfd_abs_section_ptr;
8112 }
8113
8114 static bfd_boolean
8115 resolve_symbol (const char *name,
8116                 bfd *input_bfd,
8117                 struct elf_final_link_info *flinfo,
8118                 bfd_vma *result,
8119                 Elf_Internal_Sym *isymbuf,
8120                 size_t locsymcount)
8121 {
8122   Elf_Internal_Sym *sym;
8123   struct bfd_link_hash_entry *global_entry;
8124   const char *candidate = NULL;
8125   Elf_Internal_Shdr *symtab_hdr;
8126   size_t i;
8127
8128   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
8129
8130   for (i = 0; i < locsymcount; ++ i)
8131     {
8132       sym = isymbuf + i;
8133
8134       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
8135         continue;
8136
8137       candidate = bfd_elf_string_from_elf_section (input_bfd,
8138                                                    symtab_hdr->sh_link,
8139                                                    sym->st_name);
8140 #ifdef DEBUG
8141       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
8142               name, candidate, (unsigned long) sym->st_value);
8143 #endif
8144       if (candidate && strcmp (candidate, name) == 0)
8145         {
8146           asection *sec = flinfo->sections [i];
8147
8148           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
8149           *result += sec->output_offset + sec->output_section->vma;
8150 #ifdef DEBUG
8151           printf ("Found symbol with value %8.8lx\n",
8152                   (unsigned long) *result);
8153 #endif
8154           return TRUE;
8155         }
8156     }
8157
8158   /* Hmm, haven't found it yet. perhaps it is a global.  */
8159   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
8160                                        FALSE, FALSE, TRUE);
8161   if (!global_entry)
8162     return FALSE;
8163
8164   if (global_entry->type == bfd_link_hash_defined
8165       || global_entry->type == bfd_link_hash_defweak)
8166     {
8167       *result = (global_entry->u.def.value
8168                  + global_entry->u.def.section->output_section->vma
8169                  + global_entry->u.def.section->output_offset);
8170 #ifdef DEBUG
8171       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
8172               global_entry->root.string, (unsigned long) *result);
8173 #endif
8174       return TRUE;
8175     }
8176
8177   return FALSE;
8178 }
8179
8180 /* Looks up NAME in SECTIONS.  If found sets RESULT to NAME's address (in
8181    bytes) and returns TRUE, otherwise returns FALSE.  Accepts pseudo-section
8182    names like "foo.end" which is the end address of section "foo".  */
8183
8184 static bfd_boolean
8185 resolve_section (const char *name,
8186                  asection *sections,
8187                  bfd_vma *result,
8188                  bfd * abfd)
8189 {
8190   asection *curr;
8191   unsigned int len;
8192
8193   for (curr = sections; curr; curr = curr->next)
8194     if (strcmp (curr->name, name) == 0)
8195       {
8196         *result = curr->vma;
8197         return TRUE;
8198       }
8199
8200   /* Hmm. still haven't found it. try pseudo-section names.  */
8201   /* FIXME: This could be coded more efficiently...  */
8202   for (curr = sections; curr; curr = curr->next)
8203     {
8204       len = strlen (curr->name);
8205       if (len > strlen (name))
8206         continue;
8207
8208       if (strncmp (curr->name, name, len) == 0)
8209         {
8210           if (strncmp (".end", name + len, 4) == 0)
8211             {
8212               *result = curr->vma + curr->size / bfd_octets_per_byte (abfd);
8213               return TRUE;
8214             }
8215
8216           /* Insert more pseudo-section names here, if you like.  */
8217         }
8218     }
8219
8220   return FALSE;
8221 }
8222
8223 static void
8224 undefined_reference (const char *reftype, const char *name)
8225 {
8226   /* xgettext:c-format */
8227   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
8228                       reftype, name);
8229 }
8230
8231 static bfd_boolean
8232 eval_symbol (bfd_vma *result,
8233              const char **symp,
8234              bfd *input_bfd,
8235              struct elf_final_link_info *flinfo,
8236              bfd_vma dot,
8237              Elf_Internal_Sym *isymbuf,
8238              size_t locsymcount,
8239              int signed_p)
8240 {
8241   size_t len;
8242   size_t symlen;
8243   bfd_vma a;
8244   bfd_vma b;
8245   char symbuf[4096];
8246   const char *sym = *symp;
8247   const char *symend;
8248   bfd_boolean symbol_is_section = FALSE;
8249
8250   len = strlen (sym);
8251   symend = sym + len;
8252
8253   if (len < 1 || len > sizeof (symbuf))
8254     {
8255       bfd_set_error (bfd_error_invalid_operation);
8256       return FALSE;
8257     }
8258
8259   switch (* sym)
8260     {
8261     case '.':
8262       *result = dot;
8263       *symp = sym + 1;
8264       return TRUE;
8265
8266     case '#':
8267       ++sym;
8268       *result = strtoul (sym, (char **) symp, 16);
8269       return TRUE;
8270
8271     case 'S':
8272       symbol_is_section = TRUE;
8273       /* Fall through.  */
8274     case 's':
8275       ++sym;
8276       symlen = strtol (sym, (char **) symp, 10);
8277       sym = *symp + 1; /* Skip the trailing ':'.  */
8278
8279       if (symend < sym || symlen + 1 > sizeof (symbuf))
8280         {
8281           bfd_set_error (bfd_error_invalid_operation);
8282           return FALSE;
8283         }
8284
8285       memcpy (symbuf, sym, symlen);
8286       symbuf[symlen] = '\0';
8287       *symp = sym + symlen;
8288
8289       /* Is it always possible, with complex symbols, that gas "mis-guessed"
8290          the symbol as a section, or vice-versa. so we're pretty liberal in our
8291          interpretation here; section means "try section first", not "must be a
8292          section", and likewise with symbol.  */
8293
8294       if (symbol_is_section)
8295         {
8296           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result, input_bfd)
8297               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
8298                                   isymbuf, locsymcount))
8299             {
8300               undefined_reference ("section", symbuf);
8301               return FALSE;
8302             }
8303         }
8304       else
8305         {
8306           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
8307                                isymbuf, locsymcount)
8308               && !resolve_section (symbuf, flinfo->output_bfd->sections,
8309                                    result, input_bfd))
8310             {
8311               undefined_reference ("symbol", symbuf);
8312               return FALSE;
8313             }
8314         }
8315
8316       return TRUE;
8317
8318       /* All that remains are operators.  */
8319
8320 #define UNARY_OP(op)                                            \
8321   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8322     {                                                           \
8323       sym += strlen (#op);                                      \
8324       if (*sym == ':')                                          \
8325         ++sym;                                                  \
8326       *symp = sym;                                              \
8327       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8328                         isymbuf, locsymcount, signed_p))        \
8329         return FALSE;                                           \
8330       if (signed_p)                                             \
8331         *result = op ((bfd_signed_vma) a);                      \
8332       else                                                      \
8333         *result = op a;                                         \
8334       return TRUE;                                              \
8335     }
8336
8337 #define BINARY_OP(op)                                           \
8338   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8339     {                                                           \
8340       sym += strlen (#op);                                      \
8341       if (*sym == ':')                                          \
8342         ++sym;                                                  \
8343       *symp = sym;                                              \
8344       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8345                         isymbuf, locsymcount, signed_p))        \
8346         return FALSE;                                           \
8347       ++*symp;                                                  \
8348       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
8349                         isymbuf, locsymcount, signed_p))        \
8350         return FALSE;                                           \
8351       if (signed_p)                                             \
8352         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
8353       else                                                      \
8354         *result = a op b;                                       \
8355       return TRUE;                                              \
8356     }
8357
8358     default:
8359       UNARY_OP  (0-);
8360       BINARY_OP (<<);
8361       BINARY_OP (>>);
8362       BINARY_OP (==);
8363       BINARY_OP (!=);
8364       BINARY_OP (<=);
8365       BINARY_OP (>=);
8366       BINARY_OP (&&);
8367       BINARY_OP (||);
8368       UNARY_OP  (~);
8369       UNARY_OP  (!);
8370       BINARY_OP (*);
8371       BINARY_OP (/);
8372       BINARY_OP (%);
8373       BINARY_OP (^);
8374       BINARY_OP (|);
8375       BINARY_OP (&);
8376       BINARY_OP (+);
8377       BINARY_OP (-);
8378       BINARY_OP (<);
8379       BINARY_OP (>);
8380 #undef UNARY_OP
8381 #undef BINARY_OP
8382       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
8383       bfd_set_error (bfd_error_invalid_operation);
8384       return FALSE;
8385     }
8386 }
8387
8388 static void
8389 put_value (bfd_vma size,
8390            unsigned long chunksz,
8391            bfd *input_bfd,
8392            bfd_vma x,
8393            bfd_byte *location)
8394 {
8395   location += (size - chunksz);
8396
8397   for (; size; size -= chunksz, location -= chunksz)
8398     {
8399       switch (chunksz)
8400         {
8401         case 1:
8402           bfd_put_8 (input_bfd, x, location);
8403           x >>= 8;
8404           break;
8405         case 2:
8406           bfd_put_16 (input_bfd, x, location);
8407           x >>= 16;
8408           break;
8409         case 4:
8410           bfd_put_32 (input_bfd, x, location);
8411           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
8412           x >>= 16;
8413           x >>= 16;
8414           break;
8415 #ifdef BFD64
8416         case 8:
8417           bfd_put_64 (input_bfd, x, location);
8418           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
8419           x >>= 32;
8420           x >>= 32;
8421           break;
8422 #endif
8423         default:
8424           abort ();
8425           break;
8426         }
8427     }
8428 }
8429
8430 static bfd_vma
8431 get_value (bfd_vma size,
8432            unsigned long chunksz,
8433            bfd *input_bfd,
8434            bfd_byte *location)
8435 {
8436   int shift;
8437   bfd_vma x = 0;
8438
8439   /* Sanity checks.  */
8440   BFD_ASSERT (chunksz <= sizeof (x)
8441               && size >= chunksz
8442               && chunksz != 0
8443               && (size % chunksz) == 0
8444               && input_bfd != NULL
8445               && location != NULL);
8446
8447   if (chunksz == sizeof (x))
8448     {
8449       BFD_ASSERT (size == chunksz);
8450
8451       /* Make sure that we do not perform an undefined shift operation.
8452          We know that size == chunksz so there will only be one iteration
8453          of the loop below.  */
8454       shift = 0;
8455     }
8456   else
8457     shift = 8 * chunksz;
8458
8459   for (; size; size -= chunksz, location += chunksz)
8460     {
8461       switch (chunksz)
8462         {
8463         case 1:
8464           x = (x << shift) | bfd_get_8 (input_bfd, location);
8465           break;
8466         case 2:
8467           x = (x << shift) | bfd_get_16 (input_bfd, location);
8468           break;
8469         case 4:
8470           x = (x << shift) | bfd_get_32 (input_bfd, location);
8471           break;
8472 #ifdef BFD64
8473         case 8:
8474           x = (x << shift) | bfd_get_64 (input_bfd, location);
8475           break;
8476 #endif
8477         default:
8478           abort ();
8479         }
8480     }
8481   return x;
8482 }
8483
8484 static void
8485 decode_complex_addend (unsigned long *start,   /* in bits */
8486                        unsigned long *oplen,   /* in bits */
8487                        unsigned long *len,     /* in bits */
8488                        unsigned long *wordsz,  /* in bytes */
8489                        unsigned long *chunksz, /* in bytes */
8490                        unsigned long *lsb0_p,
8491                        unsigned long *signed_p,
8492                        unsigned long *trunc_p,
8493                        unsigned long encoded)
8494 {
8495   * start     =  encoded        & 0x3F;
8496   * len       = (encoded >>  6) & 0x3F;
8497   * oplen     = (encoded >> 12) & 0x3F;
8498   * wordsz    = (encoded >> 18) & 0xF;
8499   * chunksz   = (encoded >> 22) & 0xF;
8500   * lsb0_p    = (encoded >> 27) & 1;
8501   * signed_p  = (encoded >> 28) & 1;
8502   * trunc_p   = (encoded >> 29) & 1;
8503 }
8504
8505 bfd_reloc_status_type
8506 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8507                                     asection *input_section ATTRIBUTE_UNUSED,
8508                                     bfd_byte *contents,
8509                                     Elf_Internal_Rela *rel,
8510                                     bfd_vma relocation)
8511 {
8512   bfd_vma shift, x, mask;
8513   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8514   bfd_reloc_status_type r;
8515
8516   /*  Perform this reloc, since it is complex.
8517       (this is not to say that it necessarily refers to a complex
8518       symbol; merely that it is a self-describing CGEN based reloc.
8519       i.e. the addend has the complete reloc information (bit start, end,
8520       word size, etc) encoded within it.).  */
8521
8522   decode_complex_addend (&start, &oplen, &len, &wordsz,
8523                          &chunksz, &lsb0_p, &signed_p,
8524                          &trunc_p, rel->r_addend);
8525
8526   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8527
8528   if (lsb0_p)
8529     shift = (start + 1) - len;
8530   else
8531     shift = (8 * wordsz) - (start + len);
8532
8533   x = get_value (wordsz, chunksz, input_bfd,
8534                  contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8535
8536 #ifdef DEBUG
8537   printf ("Doing complex reloc: "
8538           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8539           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8540           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8541           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8542           oplen, (unsigned long) x, (unsigned long) mask,
8543           (unsigned long) relocation);
8544 #endif
8545
8546   r = bfd_reloc_ok;
8547   if (! trunc_p)
8548     /* Now do an overflow check.  */
8549     r = bfd_check_overflow ((signed_p
8550                              ? complain_overflow_signed
8551                              : complain_overflow_unsigned),
8552                             len, 0, (8 * wordsz),
8553                             relocation);
8554
8555   /* Do the deed.  */
8556   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8557
8558 #ifdef DEBUG
8559   printf ("           relocation: %8.8lx\n"
8560           "         shifted mask: %8.8lx\n"
8561           " shifted/masked reloc: %8.8lx\n"
8562           "               result: %8.8lx\n",
8563           (unsigned long) relocation, (unsigned long) (mask << shift),
8564           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8565 #endif
8566   put_value (wordsz, chunksz, input_bfd, x,
8567              contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8568   return r;
8569 }
8570
8571 /* Functions to read r_offset from external (target order) reloc
8572    entry.  Faster than bfd_getl32 et al, because we let the compiler
8573    know the value is aligned.  */
8574
8575 static bfd_vma
8576 ext32l_r_offset (const void *p)
8577 {
8578   union aligned32
8579   {
8580     uint32_t v;
8581     unsigned char c[4];
8582   };
8583   const union aligned32 *a
8584     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8585
8586   uint32_t aval = (  (uint32_t) a->c[0]
8587                    | (uint32_t) a->c[1] << 8
8588                    | (uint32_t) a->c[2] << 16
8589                    | (uint32_t) a->c[3] << 24);
8590   return aval;
8591 }
8592
8593 static bfd_vma
8594 ext32b_r_offset (const void *p)
8595 {
8596   union aligned32
8597   {
8598     uint32_t v;
8599     unsigned char c[4];
8600   };
8601   const union aligned32 *a
8602     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8603
8604   uint32_t aval = (  (uint32_t) a->c[0] << 24
8605                    | (uint32_t) a->c[1] << 16
8606                    | (uint32_t) a->c[2] << 8
8607                    | (uint32_t) a->c[3]);
8608   return aval;
8609 }
8610
8611 #ifdef BFD_HOST_64_BIT
8612 static bfd_vma
8613 ext64l_r_offset (const void *p)
8614 {
8615   union aligned64
8616   {
8617     uint64_t v;
8618     unsigned char c[8];
8619   };
8620   const union aligned64 *a
8621     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8622
8623   uint64_t aval = (  (uint64_t) a->c[0]
8624                    | (uint64_t) a->c[1] << 8
8625                    | (uint64_t) a->c[2] << 16
8626                    | (uint64_t) a->c[3] << 24
8627                    | (uint64_t) a->c[4] << 32
8628                    | (uint64_t) a->c[5] << 40
8629                    | (uint64_t) a->c[6] << 48
8630                    | (uint64_t) a->c[7] << 56);
8631   return aval;
8632 }
8633
8634 static bfd_vma
8635 ext64b_r_offset (const void *p)
8636 {
8637   union aligned64
8638   {
8639     uint64_t v;
8640     unsigned char c[8];
8641   };
8642   const union aligned64 *a
8643     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8644
8645   uint64_t aval = (  (uint64_t) a->c[0] << 56
8646                    | (uint64_t) a->c[1] << 48
8647                    | (uint64_t) a->c[2] << 40
8648                    | (uint64_t) a->c[3] << 32
8649                    | (uint64_t) a->c[4] << 24
8650                    | (uint64_t) a->c[5] << 16
8651                    | (uint64_t) a->c[6] << 8
8652                    | (uint64_t) a->c[7]);
8653   return aval;
8654 }
8655 #endif
8656
8657 /* When performing a relocatable link, the input relocations are
8658    preserved.  But, if they reference global symbols, the indices
8659    referenced must be updated.  Update all the relocations found in
8660    RELDATA.  */
8661
8662 static bfd_boolean
8663 elf_link_adjust_relocs (bfd *abfd,
8664                         asection *sec,
8665                         struct bfd_elf_section_reloc_data *reldata,
8666                         bfd_boolean sort,
8667                         struct bfd_link_info *info)
8668 {
8669   unsigned int i;
8670   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8671   bfd_byte *erela;
8672   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8673   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8674   bfd_vma r_type_mask;
8675   int r_sym_shift;
8676   unsigned int count = reldata->count;
8677   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8678
8679   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8680     {
8681       swap_in = bed->s->swap_reloc_in;
8682       swap_out = bed->s->swap_reloc_out;
8683     }
8684   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8685     {
8686       swap_in = bed->s->swap_reloca_in;
8687       swap_out = bed->s->swap_reloca_out;
8688     }
8689   else
8690     abort ();
8691
8692   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8693     abort ();
8694
8695   if (bed->s->arch_size == 32)
8696     {
8697       r_type_mask = 0xff;
8698       r_sym_shift = 8;
8699     }
8700   else
8701     {
8702       r_type_mask = 0xffffffff;
8703       r_sym_shift = 32;
8704     }
8705
8706   erela = reldata->hdr->contents;
8707   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8708     {
8709       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8710       unsigned int j;
8711
8712       if (*rel_hash == NULL)
8713         continue;
8714
8715       if ((*rel_hash)->indx == -2
8716           && info->gc_sections
8717           && ! info->gc_keep_exported)
8718         {
8719           /* PR 21524: Let the user know if a symbol was removed by garbage collection.  */
8720           _bfd_error_handler (_("%pB:%pA: error: relocation references symbol %s which was removed by garbage collection."),
8721                               abfd, sec,
8722                               (*rel_hash)->root.root.string);
8723           _bfd_error_handler (_("%pB:%pA: error: try relinking with --gc-keep-exported enabled."),
8724                               abfd, sec);
8725           bfd_set_error (bfd_error_invalid_operation);
8726           return FALSE;
8727         }
8728       BFD_ASSERT ((*rel_hash)->indx >= 0);
8729
8730       (*swap_in) (abfd, erela, irela);
8731       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8732         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8733                            | (irela[j].r_info & r_type_mask));
8734       (*swap_out) (abfd, irela, erela);
8735     }
8736
8737   if (bed->elf_backend_update_relocs)
8738     (*bed->elf_backend_update_relocs) (sec, reldata);
8739
8740   if (sort && count != 0)
8741     {
8742       bfd_vma (*ext_r_off) (const void *);
8743       bfd_vma r_off;
8744       size_t elt_size;
8745       bfd_byte *base, *end, *p, *loc;
8746       bfd_byte *buf = NULL;
8747
8748       if (bed->s->arch_size == 32)
8749         {
8750           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8751             ext_r_off = ext32l_r_offset;
8752           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8753             ext_r_off = ext32b_r_offset;
8754           else
8755             abort ();
8756         }
8757       else
8758         {
8759 #ifdef BFD_HOST_64_BIT
8760           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8761             ext_r_off = ext64l_r_offset;
8762           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8763             ext_r_off = ext64b_r_offset;
8764           else
8765 #endif
8766             abort ();
8767         }
8768
8769       /*  Must use a stable sort here.  A modified insertion sort,
8770           since the relocs are mostly sorted already.  */
8771       elt_size = reldata->hdr->sh_entsize;
8772       base = reldata->hdr->contents;
8773       end = base + count * elt_size;
8774       if (elt_size > sizeof (Elf64_External_Rela))
8775         abort ();
8776
8777       /* Ensure the first element is lowest.  This acts as a sentinel,
8778          speeding the main loop below.  */
8779       r_off = (*ext_r_off) (base);
8780       for (p = loc = base; (p += elt_size) < end; )
8781         {
8782           bfd_vma r_off2 = (*ext_r_off) (p);
8783           if (r_off > r_off2)
8784             {
8785               r_off = r_off2;
8786               loc = p;
8787             }
8788         }
8789       if (loc != base)
8790         {
8791           /* Don't just swap *base and *loc as that changes the order
8792              of the original base[0] and base[1] if they happen to
8793              have the same r_offset.  */
8794           bfd_byte onebuf[sizeof (Elf64_External_Rela)];
8795           memcpy (onebuf, loc, elt_size);
8796           memmove (base + elt_size, base, loc - base);
8797           memcpy (base, onebuf, elt_size);
8798         }
8799
8800       for (p = base + elt_size; (p += elt_size) < end; )
8801         {
8802           /* base to p is sorted, *p is next to insert.  */
8803           r_off = (*ext_r_off) (p);
8804           /* Search the sorted region for location to insert.  */
8805           loc = p - elt_size;
8806           while (r_off < (*ext_r_off) (loc))
8807             loc -= elt_size;
8808           loc += elt_size;
8809           if (loc != p)
8810             {
8811               /* Chances are there is a run of relocs to insert here,
8812                  from one of more input files.  Files are not always
8813                  linked in order due to the way elf_link_input_bfd is
8814                  called.  See pr17666.  */
8815               size_t sortlen = p - loc;
8816               bfd_vma r_off2 = (*ext_r_off) (loc);
8817               size_t runlen = elt_size;
8818               size_t buf_size = 96 * 1024;
8819               while (p + runlen < end
8820                      && (sortlen <= buf_size
8821                          || runlen + elt_size <= buf_size)
8822                      && r_off2 > (*ext_r_off) (p + runlen))
8823                 runlen += elt_size;
8824               if (buf == NULL)
8825                 {
8826                   buf = bfd_malloc (buf_size);
8827                   if (buf == NULL)
8828                     return FALSE;
8829                 }
8830               if (runlen < sortlen)
8831                 {
8832                   memcpy (buf, p, runlen);
8833                   memmove (loc + runlen, loc, sortlen);
8834                   memcpy (loc, buf, runlen);
8835                 }
8836               else
8837                 {
8838                   memcpy (buf, loc, sortlen);
8839                   memmove (loc, p, runlen);
8840                   memcpy (loc + runlen, buf, sortlen);
8841                 }
8842               p += runlen - elt_size;
8843             }
8844         }
8845       /* Hashes are no longer valid.  */
8846       free (reldata->hashes);
8847       reldata->hashes = NULL;
8848       free (buf);
8849     }
8850   return TRUE;
8851 }
8852
8853 struct elf_link_sort_rela
8854 {
8855   union {
8856     bfd_vma offset;
8857     bfd_vma sym_mask;
8858   } u;
8859   enum elf_reloc_type_class type;
8860   /* We use this as an array of size int_rels_per_ext_rel.  */
8861   Elf_Internal_Rela rela[1];
8862 };
8863
8864 static int
8865 elf_link_sort_cmp1 (const void *A, const void *B)
8866 {
8867   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8868   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8869   int relativea, relativeb;
8870
8871   relativea = a->type == reloc_class_relative;
8872   relativeb = b->type == reloc_class_relative;
8873
8874   if (relativea < relativeb)
8875     return 1;
8876   if (relativea > relativeb)
8877     return -1;
8878   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8879     return -1;
8880   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8881     return 1;
8882   if (a->rela->r_offset < b->rela->r_offset)
8883     return -1;
8884   if (a->rela->r_offset > b->rela->r_offset)
8885     return 1;
8886   return 0;
8887 }
8888
8889 static int
8890 elf_link_sort_cmp2 (const void *A, const void *B)
8891 {
8892   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8893   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8894
8895   if (a->type < b->type)
8896     return -1;
8897   if (a->type > b->type)
8898     return 1;
8899   if (a->u.offset < b->u.offset)
8900     return -1;
8901   if (a->u.offset > b->u.offset)
8902     return 1;
8903   if (a->rela->r_offset < b->rela->r_offset)
8904     return -1;
8905   if (a->rela->r_offset > b->rela->r_offset)
8906     return 1;
8907   return 0;
8908 }
8909
8910 static size_t
8911 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8912 {
8913   asection *dynamic_relocs;
8914   asection *rela_dyn;
8915   asection *rel_dyn;
8916   bfd_size_type count, size;
8917   size_t i, ret, sort_elt, ext_size;
8918   bfd_byte *sort, *s_non_relative, *p;
8919   struct elf_link_sort_rela *sq;
8920   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8921   int i2e = bed->s->int_rels_per_ext_rel;
8922   unsigned int opb = bfd_octets_per_byte (abfd);
8923   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8924   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8925   struct bfd_link_order *lo;
8926   bfd_vma r_sym_mask;
8927   bfd_boolean use_rela;
8928
8929   /* Find a dynamic reloc section.  */
8930   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8931   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8932   if (rela_dyn != NULL && rela_dyn->size > 0
8933       && rel_dyn != NULL && rel_dyn->size > 0)
8934     {
8935       bfd_boolean use_rela_initialised = FALSE;
8936
8937       /* This is just here to stop gcc from complaining.
8938          Its initialization checking code is not perfect.  */
8939       use_rela = TRUE;
8940
8941       /* Both sections are present.  Examine the sizes
8942          of the indirect sections to help us choose.  */
8943       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8944         if (lo->type == bfd_indirect_link_order)
8945           {
8946             asection *o = lo->u.indirect.section;
8947
8948             if ((o->size % bed->s->sizeof_rela) == 0)
8949               {
8950                 if ((o->size % bed->s->sizeof_rel) == 0)
8951                   /* Section size is divisible by both rel and rela sizes.
8952                      It is of no help to us.  */
8953                   ;
8954                 else
8955                   {
8956                     /* Section size is only divisible by rela.  */
8957                     if (use_rela_initialised && !use_rela)
8958                       {
8959                         _bfd_error_handler (_("%pB: Unable to sort relocs - "
8960                                               "they are in more than one size"),
8961                                             abfd);
8962                         bfd_set_error (bfd_error_invalid_operation);
8963                         return 0;
8964                       }
8965                     else
8966                       {
8967                         use_rela = TRUE;
8968                         use_rela_initialised = TRUE;
8969                       }
8970                   }
8971               }
8972             else if ((o->size % bed->s->sizeof_rel) == 0)
8973               {
8974                 /* Section size is only divisible by rel.  */
8975                 if (use_rela_initialised && use_rela)
8976                   {
8977                     _bfd_error_handler (_("%pB: Unable to sort relocs - "
8978                                           "they are in more than one size"),
8979                                         abfd);
8980                     bfd_set_error (bfd_error_invalid_operation);
8981                     return 0;
8982                   }
8983                 else
8984                   {
8985                     use_rela = FALSE;
8986                     use_rela_initialised = TRUE;
8987                   }
8988               }
8989             else
8990               {
8991                 /* The section size is not divisible by either -
8992                    something is wrong.  */
8993                 _bfd_error_handler (_("%pB: Unable to sort relocs - "
8994                                       "they are of an unknown size"), abfd);
8995                 bfd_set_error (bfd_error_invalid_operation);
8996                 return 0;
8997               }
8998           }
8999
9000       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
9001         if (lo->type == bfd_indirect_link_order)
9002           {
9003             asection *o = lo->u.indirect.section;
9004
9005             if ((o->size % bed->s->sizeof_rela) == 0)
9006               {
9007                 if ((o->size % bed->s->sizeof_rel) == 0)
9008                   /* Section size is divisible by both rel and rela sizes.
9009                      It is of no help to us.  */
9010                   ;
9011                 else
9012                   {
9013                     /* Section size is only divisible by rela.  */
9014                     if (use_rela_initialised && !use_rela)
9015                       {
9016                         _bfd_error_handler (_("%pB: Unable to sort relocs - "
9017                                               "they are in more than one size"),
9018                                             abfd);
9019                         bfd_set_error (bfd_error_invalid_operation);
9020                         return 0;
9021                       }
9022                     else
9023                       {
9024                         use_rela = TRUE;
9025                         use_rela_initialised = TRUE;
9026                       }
9027                   }
9028               }
9029             else if ((o->size % bed->s->sizeof_rel) == 0)
9030               {
9031                 /* Section size is only divisible by rel.  */
9032                 if (use_rela_initialised && use_rela)
9033                   {
9034                     _bfd_error_handler (_("%pB: Unable to sort relocs - "
9035                                           "they are in more than one size"),
9036                                         abfd);
9037                     bfd_set_error (bfd_error_invalid_operation);
9038                     return 0;
9039                   }
9040                 else
9041                   {
9042                     use_rela = FALSE;
9043                     use_rela_initialised = TRUE;
9044                   }
9045               }
9046             else
9047               {
9048                 /* The section size is not divisible by either -
9049                    something is wrong.  */
9050                 _bfd_error_handler (_("%pB: Unable to sort relocs - "
9051                                       "they are of an unknown size"), abfd);
9052                 bfd_set_error (bfd_error_invalid_operation);
9053                 return 0;
9054               }
9055           }
9056
9057       if (! use_rela_initialised)
9058         /* Make a guess.  */
9059         use_rela = TRUE;
9060     }
9061   else if (rela_dyn != NULL && rela_dyn->size > 0)
9062     use_rela = TRUE;
9063   else if (rel_dyn != NULL && rel_dyn->size > 0)
9064     use_rela = FALSE;
9065   else
9066     return 0;
9067
9068   if (use_rela)
9069     {
9070       dynamic_relocs = rela_dyn;
9071       ext_size = bed->s->sizeof_rela;
9072       swap_in = bed->s->swap_reloca_in;
9073       swap_out = bed->s->swap_reloca_out;
9074     }
9075   else
9076     {
9077       dynamic_relocs = rel_dyn;
9078       ext_size = bed->s->sizeof_rel;
9079       swap_in = bed->s->swap_reloc_in;
9080       swap_out = bed->s->swap_reloc_out;
9081     }
9082
9083   size = 0;
9084   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9085     if (lo->type == bfd_indirect_link_order)
9086       size += lo->u.indirect.section->size;
9087
9088   if (size != dynamic_relocs->size)
9089     return 0;
9090
9091   sort_elt = (sizeof (struct elf_link_sort_rela)
9092               + (i2e - 1) * sizeof (Elf_Internal_Rela));
9093
9094   count = dynamic_relocs->size / ext_size;
9095   if (count == 0)
9096     return 0;
9097   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
9098
9099   if (sort == NULL)
9100     {
9101       (*info->callbacks->warning)
9102         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
9103       return 0;
9104     }
9105
9106   if (bed->s->arch_size == 32)
9107     r_sym_mask = ~(bfd_vma) 0xff;
9108   else
9109     r_sym_mask = ~(bfd_vma) 0xffffffff;
9110
9111   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9112     if (lo->type == bfd_indirect_link_order)
9113       {
9114         bfd_byte *erel, *erelend;
9115         asection *o = lo->u.indirect.section;
9116
9117         if (o->contents == NULL && o->size != 0)
9118           {
9119             /* This is a reloc section that is being handled as a normal
9120                section.  See bfd_section_from_shdr.  We can't combine
9121                relocs in this case.  */
9122             free (sort);
9123             return 0;
9124           }
9125         erel = o->contents;
9126         erelend = o->contents + o->size;
9127         p = sort + o->output_offset * opb / ext_size * sort_elt;
9128
9129         while (erel < erelend)
9130           {
9131             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9132
9133             (*swap_in) (abfd, erel, s->rela);
9134             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
9135             s->u.sym_mask = r_sym_mask;
9136             p += sort_elt;
9137             erel += ext_size;
9138           }
9139       }
9140
9141   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
9142
9143   for (i = 0, p = sort; i < count; i++, p += sort_elt)
9144     {
9145       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9146       if (s->type != reloc_class_relative)
9147         break;
9148     }
9149   ret = i;
9150   s_non_relative = p;
9151
9152   sq = (struct elf_link_sort_rela *) s_non_relative;
9153   for (; i < count; i++, p += sort_elt)
9154     {
9155       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
9156       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
9157         sq = sp;
9158       sp->u.offset = sq->rela->r_offset;
9159     }
9160
9161   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
9162
9163   struct elf_link_hash_table *htab = elf_hash_table (info);
9164   if (htab->srelplt && htab->srelplt->output_section == dynamic_relocs)
9165     {
9166       /* We have plt relocs in .rela.dyn.  */
9167       sq = (struct elf_link_sort_rela *) sort;
9168       for (i = 0; i < count; i++)
9169         if (sq[count - i - 1].type != reloc_class_plt)
9170           break;
9171       if (i != 0 && htab->srelplt->size == i * ext_size)
9172         {
9173           struct bfd_link_order **plo;
9174           /* Put srelplt link_order last.  This is so the output_offset
9175              set in the next loop is correct for DT_JMPREL.  */
9176           for (plo = &dynamic_relocs->map_head.link_order; *plo != NULL; )
9177             if ((*plo)->type == bfd_indirect_link_order
9178                 && (*plo)->u.indirect.section == htab->srelplt)
9179               {
9180                 lo = *plo;
9181                 *plo = lo->next;
9182               }
9183             else
9184               plo = &(*plo)->next;
9185           *plo = lo;
9186           lo->next = NULL;
9187           dynamic_relocs->map_tail.link_order = lo;
9188         }
9189     }
9190
9191   p = sort;
9192   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9193     if (lo->type == bfd_indirect_link_order)
9194       {
9195         bfd_byte *erel, *erelend;
9196         asection *o = lo->u.indirect.section;
9197
9198         erel = o->contents;
9199         erelend = o->contents + o->size;
9200         o->output_offset = (p - sort) / sort_elt * ext_size / opb;
9201         while (erel < erelend)
9202           {
9203             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9204             (*swap_out) (abfd, s->rela, erel);
9205             p += sort_elt;
9206             erel += ext_size;
9207           }
9208       }
9209
9210   free (sort);
9211   *psec = dynamic_relocs;
9212   return ret;
9213 }
9214
9215 /* Add a symbol to the output symbol string table.  */
9216
9217 static int
9218 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
9219                            const char *name,
9220                            Elf_Internal_Sym *elfsym,
9221                            asection *input_sec,
9222                            struct elf_link_hash_entry *h)
9223 {
9224   int (*output_symbol_hook)
9225     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
9226      struct elf_link_hash_entry *);
9227   struct elf_link_hash_table *hash_table;
9228   const struct elf_backend_data *bed;
9229   bfd_size_type strtabsize;
9230
9231   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9232
9233   bed = get_elf_backend_data (flinfo->output_bfd);
9234   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
9235   if (output_symbol_hook != NULL)
9236     {
9237       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
9238       if (ret != 1)
9239         return ret;
9240     }
9241
9242   if (name == NULL
9243       || *name == '\0'
9244       || (input_sec->flags & SEC_EXCLUDE))
9245     elfsym->st_name = (unsigned long) -1;
9246   else
9247     {
9248       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
9249          to get the final offset for st_name.  */
9250       elfsym->st_name
9251         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
9252                                                name, FALSE);
9253       if (elfsym->st_name == (unsigned long) -1)
9254         return 0;
9255     }
9256
9257   hash_table = elf_hash_table (flinfo->info);
9258   strtabsize = hash_table->strtabsize;
9259   if (strtabsize <= hash_table->strtabcount)
9260     {
9261       strtabsize += strtabsize;
9262       hash_table->strtabsize = strtabsize;
9263       strtabsize *= sizeof (*hash_table->strtab);
9264       hash_table->strtab
9265         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
9266                                                  strtabsize);
9267       if (hash_table->strtab == NULL)
9268         return 0;
9269     }
9270   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
9271   hash_table->strtab[hash_table->strtabcount].dest_index
9272     = hash_table->strtabcount;
9273   hash_table->strtab[hash_table->strtabcount].destshndx_index
9274     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
9275
9276   bfd_get_symcount (flinfo->output_bfd) += 1;
9277   hash_table->strtabcount += 1;
9278
9279   return 1;
9280 }
9281
9282 /* Swap symbols out to the symbol table and flush the output symbols to
9283    the file.  */
9284
9285 static bfd_boolean
9286 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
9287 {
9288   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
9289   bfd_size_type amt;
9290   size_t i;
9291   const struct elf_backend_data *bed;
9292   bfd_byte *symbuf;
9293   Elf_Internal_Shdr *hdr;
9294   file_ptr pos;
9295   bfd_boolean ret;
9296
9297   if (!hash_table->strtabcount)
9298     return TRUE;
9299
9300   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9301
9302   bed = get_elf_backend_data (flinfo->output_bfd);
9303
9304   amt = bed->s->sizeof_sym * hash_table->strtabcount;
9305   symbuf = (bfd_byte *) bfd_malloc (amt);
9306   if (symbuf == NULL)
9307     return FALSE;
9308
9309   if (flinfo->symshndxbuf)
9310     {
9311       amt = sizeof (Elf_External_Sym_Shndx);
9312       amt *= bfd_get_symcount (flinfo->output_bfd);
9313       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
9314       if (flinfo->symshndxbuf == NULL)
9315         {
9316           free (symbuf);
9317           return FALSE;
9318         }
9319     }
9320
9321   for (i = 0; i < hash_table->strtabcount; i++)
9322     {
9323       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
9324       if (elfsym->sym.st_name == (unsigned long) -1)
9325         elfsym->sym.st_name = 0;
9326       else
9327         elfsym->sym.st_name
9328           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
9329                                                     elfsym->sym.st_name);
9330       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
9331                                ((bfd_byte *) symbuf
9332                                 + (elfsym->dest_index
9333                                    * bed->s->sizeof_sym)),
9334                                (flinfo->symshndxbuf
9335                                 + elfsym->destshndx_index));
9336     }
9337
9338   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
9339   pos = hdr->sh_offset + hdr->sh_size;
9340   amt = hash_table->strtabcount * bed->s->sizeof_sym;
9341   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
9342       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
9343     {
9344       hdr->sh_size += amt;
9345       ret = TRUE;
9346     }
9347   else
9348     ret = FALSE;
9349
9350   free (symbuf);
9351
9352   free (hash_table->strtab);
9353   hash_table->strtab = NULL;
9354
9355   return ret;
9356 }
9357
9358 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
9359
9360 static bfd_boolean
9361 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
9362 {
9363   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
9364       && sym->st_shndx < SHN_LORESERVE)
9365     {
9366       /* The gABI doesn't support dynamic symbols in output sections
9367          beyond 64k.  */
9368       _bfd_error_handler
9369         /* xgettext:c-format */
9370         (_("%pB: Too many sections: %d (>= %d)"),
9371          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
9372       bfd_set_error (bfd_error_nonrepresentable_section);
9373       return FALSE;
9374     }
9375   return TRUE;
9376 }
9377
9378 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
9379    allowing an unsatisfied unversioned symbol in the DSO to match a
9380    versioned symbol that would normally require an explicit version.
9381    We also handle the case that a DSO references a hidden symbol
9382    which may be satisfied by a versioned symbol in another DSO.  */
9383
9384 static bfd_boolean
9385 elf_link_check_versioned_symbol (struct bfd_link_info *info,
9386                                  const struct elf_backend_data *bed,
9387                                  struct elf_link_hash_entry *h)
9388 {
9389   bfd *abfd;
9390   struct elf_link_loaded_list *loaded;
9391
9392   if (!is_elf_hash_table (info->hash))
9393     return FALSE;
9394
9395   /* Check indirect symbol.  */
9396   while (h->root.type == bfd_link_hash_indirect)
9397     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9398
9399   switch (h->root.type)
9400     {
9401     default:
9402       abfd = NULL;
9403       break;
9404
9405     case bfd_link_hash_undefined:
9406     case bfd_link_hash_undefweak:
9407       abfd = h->root.u.undef.abfd;
9408       if (abfd == NULL
9409           || (abfd->flags & DYNAMIC) == 0
9410           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
9411         return FALSE;
9412       break;
9413
9414     case bfd_link_hash_defined:
9415     case bfd_link_hash_defweak:
9416       abfd = h->root.u.def.section->owner;
9417       break;
9418
9419     case bfd_link_hash_common:
9420       abfd = h->root.u.c.p->section->owner;
9421       break;
9422     }
9423   BFD_ASSERT (abfd != NULL);
9424
9425   for (loaded = elf_hash_table (info)->loaded;
9426        loaded != NULL;
9427        loaded = loaded->next)
9428     {
9429       bfd *input;
9430       Elf_Internal_Shdr *hdr;
9431       size_t symcount;
9432       size_t extsymcount;
9433       size_t extsymoff;
9434       Elf_Internal_Shdr *versymhdr;
9435       Elf_Internal_Sym *isym;
9436       Elf_Internal_Sym *isymend;
9437       Elf_Internal_Sym *isymbuf;
9438       Elf_External_Versym *ever;
9439       Elf_External_Versym *extversym;
9440
9441       input = loaded->abfd;
9442
9443       /* We check each DSO for a possible hidden versioned definition.  */
9444       if (input == abfd
9445           || (input->flags & DYNAMIC) == 0
9446           || elf_dynversym (input) == 0)
9447         continue;
9448
9449       hdr = &elf_tdata (input)->dynsymtab_hdr;
9450
9451       symcount = hdr->sh_size / bed->s->sizeof_sym;
9452       if (elf_bad_symtab (input))
9453         {
9454           extsymcount = symcount;
9455           extsymoff = 0;
9456         }
9457       else
9458         {
9459           extsymcount = symcount - hdr->sh_info;
9460           extsymoff = hdr->sh_info;
9461         }
9462
9463       if (extsymcount == 0)
9464         continue;
9465
9466       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
9467                                       NULL, NULL, NULL);
9468       if (isymbuf == NULL)
9469         return FALSE;
9470
9471       /* Read in any version definitions.  */
9472       versymhdr = &elf_tdata (input)->dynversym_hdr;
9473       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
9474       if (extversym == NULL)
9475         goto error_ret;
9476
9477       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
9478           || (bfd_bread (extversym, versymhdr->sh_size, input)
9479               != versymhdr->sh_size))
9480         {
9481           free (extversym);
9482         error_ret:
9483           free (isymbuf);
9484           return FALSE;
9485         }
9486
9487       ever = extversym + extsymoff;
9488       isymend = isymbuf + extsymcount;
9489       for (isym = isymbuf; isym < isymend; isym++, ever++)
9490         {
9491           const char *name;
9492           Elf_Internal_Versym iver;
9493           unsigned short version_index;
9494
9495           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
9496               || isym->st_shndx == SHN_UNDEF)
9497             continue;
9498
9499           name = bfd_elf_string_from_elf_section (input,
9500                                                   hdr->sh_link,
9501                                                   isym->st_name);
9502           if (strcmp (name, h->root.root.string) != 0)
9503             continue;
9504
9505           _bfd_elf_swap_versym_in (input, ever, &iver);
9506
9507           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
9508               && !(h->def_regular
9509                    && h->forced_local))
9510             {
9511               /* If we have a non-hidden versioned sym, then it should
9512                  have provided a definition for the undefined sym unless
9513                  it is defined in a non-shared object and forced local.
9514                */
9515               abort ();
9516             }
9517
9518           version_index = iver.vs_vers & VERSYM_VERSION;
9519           if (version_index == 1 || version_index == 2)
9520             {
9521               /* This is the base or first version.  We can use it.  */
9522               free (extversym);
9523               free (isymbuf);
9524               return TRUE;
9525             }
9526         }
9527
9528       free (extversym);
9529       free (isymbuf);
9530     }
9531
9532   return FALSE;
9533 }
9534
9535 /* Convert ELF common symbol TYPE.  */
9536
9537 static int
9538 elf_link_convert_common_type (struct bfd_link_info *info, int type)
9539 {
9540   /* Commom symbol can only appear in relocatable link.  */
9541   if (!bfd_link_relocatable (info))
9542     abort ();
9543   switch (info->elf_stt_common)
9544     {
9545     case unchanged:
9546       break;
9547     case elf_stt_common:
9548       type = STT_COMMON;
9549       break;
9550     case no_elf_stt_common:
9551       type = STT_OBJECT;
9552       break;
9553     }
9554   return type;
9555 }
9556
9557 /* Add an external symbol to the symbol table.  This is called from
9558    the hash table traversal routine.  When generating a shared object,
9559    we go through the symbol table twice.  The first time we output
9560    anything that might have been forced to local scope in a version
9561    script.  The second time we output the symbols that are still
9562    global symbols.  */
9563
9564 static bfd_boolean
9565 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
9566 {
9567   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
9568   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
9569   struct elf_final_link_info *flinfo = eoinfo->flinfo;
9570   bfd_boolean strip;
9571   Elf_Internal_Sym sym;
9572   asection *input_sec;
9573   const struct elf_backend_data *bed;
9574   long indx;
9575   int ret;
9576   unsigned int type;
9577
9578   if (h->root.type == bfd_link_hash_warning)
9579     {
9580       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9581       if (h->root.type == bfd_link_hash_new)
9582         return TRUE;
9583     }
9584
9585   /* Decide whether to output this symbol in this pass.  */
9586   if (eoinfo->localsyms)
9587     {
9588       if (!h->forced_local)
9589         return TRUE;
9590     }
9591   else
9592     {
9593       if (h->forced_local)
9594         return TRUE;
9595     }
9596
9597   bed = get_elf_backend_data (flinfo->output_bfd);
9598
9599   if (h->root.type == bfd_link_hash_undefined)
9600     {
9601       /* If we have an undefined symbol reference here then it must have
9602          come from a shared library that is being linked in.  (Undefined
9603          references in regular files have already been handled unless
9604          they are in unreferenced sections which are removed by garbage
9605          collection).  */
9606       bfd_boolean ignore_undef = FALSE;
9607
9608       /* Some symbols may be special in that the fact that they're
9609          undefined can be safely ignored - let backend determine that.  */
9610       if (bed->elf_backend_ignore_undef_symbol)
9611         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9612
9613       /* If we are reporting errors for this situation then do so now.  */
9614       if (!ignore_undef
9615           && h->ref_dynamic
9616           && (!h->ref_regular || flinfo->info->gc_sections)
9617           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9618           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9619         (*flinfo->info->callbacks->undefined_symbol)
9620           (flinfo->info, h->root.root.string,
9621            h->ref_regular ? NULL : h->root.u.undef.abfd,
9622            NULL, 0,
9623            flinfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR);
9624
9625       /* Strip a global symbol defined in a discarded section.  */
9626       if (h->indx == -3)
9627         return TRUE;
9628     }
9629
9630   /* We should also warn if a forced local symbol is referenced from
9631      shared libraries.  */
9632   if (bfd_link_executable (flinfo->info)
9633       && h->forced_local
9634       && h->ref_dynamic
9635       && h->def_regular
9636       && !h->dynamic_def
9637       && h->ref_dynamic_nonweak
9638       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9639     {
9640       bfd *def_bfd;
9641       const char *msg;
9642       struct elf_link_hash_entry *hi = h;
9643
9644       /* Check indirect symbol.  */
9645       while (hi->root.type == bfd_link_hash_indirect)
9646         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9647
9648       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9649         /* xgettext:c-format */
9650         msg = _("%pB: internal symbol `%s' in %pB is referenced by DSO");
9651       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9652         /* xgettext:c-format */
9653         msg = _("%pB: hidden symbol `%s' in %pB is referenced by DSO");
9654       else
9655         /* xgettext:c-format */
9656         msg = _("%pB: local symbol `%s' in %pB is referenced by DSO");
9657       def_bfd = flinfo->output_bfd;
9658       if (hi->root.u.def.section != bfd_abs_section_ptr)
9659         def_bfd = hi->root.u.def.section->owner;
9660       _bfd_error_handler (msg, flinfo->output_bfd,
9661                           h->root.root.string, def_bfd);
9662       bfd_set_error (bfd_error_bad_value);
9663       eoinfo->failed = TRUE;
9664       return FALSE;
9665     }
9666
9667   /* We don't want to output symbols that have never been mentioned by
9668      a regular file, or that we have been told to strip.  However, if
9669      h->indx is set to -2, the symbol is used by a reloc and we must
9670      output it.  */
9671   strip = FALSE;
9672   if (h->indx == -2)
9673     ;
9674   else if ((h->def_dynamic
9675             || h->ref_dynamic
9676             || h->root.type == bfd_link_hash_new)
9677            && !h->def_regular
9678            && !h->ref_regular)
9679     strip = TRUE;
9680   else if (flinfo->info->strip == strip_all)
9681     strip = TRUE;
9682   else if (flinfo->info->strip == strip_some
9683            && bfd_hash_lookup (flinfo->info->keep_hash,
9684                                h->root.root.string, FALSE, FALSE) == NULL)
9685     strip = TRUE;
9686   else if ((h->root.type == bfd_link_hash_defined
9687             || h->root.type == bfd_link_hash_defweak)
9688            && ((flinfo->info->strip_discarded
9689                 && discarded_section (h->root.u.def.section))
9690                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9691                    && h->root.u.def.section->owner != NULL
9692                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9693     strip = TRUE;
9694   else if ((h->root.type == bfd_link_hash_undefined
9695             || h->root.type == bfd_link_hash_undefweak)
9696            && h->root.u.undef.abfd != NULL
9697            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9698     strip = TRUE;
9699
9700   type = h->type;
9701
9702   /* If we're stripping it, and it's not a dynamic symbol, there's
9703      nothing else to do.   However, if it is a forced local symbol or
9704      an ifunc symbol we need to give the backend finish_dynamic_symbol
9705      function a chance to make it dynamic.  */
9706   if (strip
9707       && h->dynindx == -1
9708       && type != STT_GNU_IFUNC
9709       && !h->forced_local)
9710     return TRUE;
9711
9712   sym.st_value = 0;
9713   sym.st_size = h->size;
9714   sym.st_other = h->other;
9715   switch (h->root.type)
9716     {
9717     default:
9718     case bfd_link_hash_new:
9719     case bfd_link_hash_warning:
9720       abort ();
9721       return FALSE;
9722
9723     case bfd_link_hash_undefined:
9724     case bfd_link_hash_undefweak:
9725       input_sec = bfd_und_section_ptr;
9726       sym.st_shndx = SHN_UNDEF;
9727       break;
9728
9729     case bfd_link_hash_defined:
9730     case bfd_link_hash_defweak:
9731       {
9732         input_sec = h->root.u.def.section;
9733         if (input_sec->output_section != NULL)
9734           {
9735             sym.st_shndx =
9736               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9737                                                  input_sec->output_section);
9738             if (sym.st_shndx == SHN_BAD)
9739               {
9740                 _bfd_error_handler
9741                   /* xgettext:c-format */
9742                   (_("%pB: could not find output section %pA for input section %pA"),
9743                    flinfo->output_bfd, input_sec->output_section, input_sec);
9744                 bfd_set_error (bfd_error_nonrepresentable_section);
9745                 eoinfo->failed = TRUE;
9746                 return FALSE;
9747               }
9748
9749             /* ELF symbols in relocatable files are section relative,
9750                but in nonrelocatable files they are virtual
9751                addresses.  */
9752             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9753             if (!bfd_link_relocatable (flinfo->info))
9754               {
9755                 sym.st_value += input_sec->output_section->vma;
9756                 if (h->type == STT_TLS)
9757                   {
9758                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9759                     if (tls_sec != NULL)
9760                       sym.st_value -= tls_sec->vma;
9761                   }
9762               }
9763           }
9764         else
9765           {
9766             BFD_ASSERT (input_sec->owner == NULL
9767                         || (input_sec->owner->flags & DYNAMIC) != 0);
9768             sym.st_shndx = SHN_UNDEF;
9769             input_sec = bfd_und_section_ptr;
9770           }
9771       }
9772       break;
9773
9774     case bfd_link_hash_common:
9775       input_sec = h->root.u.c.p->section;
9776       sym.st_shndx = bed->common_section_index (input_sec);
9777       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9778       break;
9779
9780     case bfd_link_hash_indirect:
9781       /* These symbols are created by symbol versioning.  They point
9782          to the decorated version of the name.  For example, if the
9783          symbol foo@@GNU_1.2 is the default, which should be used when
9784          foo is used with no version, then we add an indirect symbol
9785          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9786          since the indirected symbol is already in the hash table.  */
9787       return TRUE;
9788     }
9789
9790   if (type == STT_COMMON || type == STT_OBJECT)
9791     switch (h->root.type)
9792       {
9793       case bfd_link_hash_common:
9794         type = elf_link_convert_common_type (flinfo->info, type);
9795         break;
9796       case bfd_link_hash_defined:
9797       case bfd_link_hash_defweak:
9798         if (bed->common_definition (&sym))
9799           type = elf_link_convert_common_type (flinfo->info, type);
9800         else
9801           type = STT_OBJECT;
9802         break;
9803       case bfd_link_hash_undefined:
9804       case bfd_link_hash_undefweak:
9805         break;
9806       default:
9807         abort ();
9808       }
9809
9810   if (h->forced_local)
9811     {
9812       sym.st_info = ELF_ST_INFO (STB_LOCAL, type);
9813       /* Turn off visibility on local symbol.  */
9814       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9815     }
9816   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9817   else if (h->unique_global && h->def_regular)
9818     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, type);
9819   else if (h->root.type == bfd_link_hash_undefweak
9820            || h->root.type == bfd_link_hash_defweak)
9821     sym.st_info = ELF_ST_INFO (STB_WEAK, type);
9822   else
9823     sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9824   sym.st_target_internal = h->target_internal;
9825
9826   /* Give the processor backend a chance to tweak the symbol value,
9827      and also to finish up anything that needs to be done for this
9828      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9829      forced local syms when non-shared is due to a historical quirk.
9830      STT_GNU_IFUNC symbol must go through PLT.  */
9831   if ((h->type == STT_GNU_IFUNC
9832        && h->def_regular
9833        && !bfd_link_relocatable (flinfo->info))
9834       || ((h->dynindx != -1
9835            || h->forced_local)
9836           && ((bfd_link_pic (flinfo->info)
9837                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9838                    || h->root.type != bfd_link_hash_undefweak))
9839               || !h->forced_local)
9840           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9841     {
9842       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9843              (flinfo->output_bfd, flinfo->info, h, &sym)))
9844         {
9845           eoinfo->failed = TRUE;
9846           return FALSE;
9847         }
9848     }
9849
9850   /* If we are marking the symbol as undefined, and there are no
9851      non-weak references to this symbol from a regular object, then
9852      mark the symbol as weak undefined; if there are non-weak
9853      references, mark the symbol as strong.  We can't do this earlier,
9854      because it might not be marked as undefined until the
9855      finish_dynamic_symbol routine gets through with it.  */
9856   if (sym.st_shndx == SHN_UNDEF
9857       && h->ref_regular
9858       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9859           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9860     {
9861       int bindtype;
9862       type = ELF_ST_TYPE (sym.st_info);
9863
9864       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9865       if (type == STT_GNU_IFUNC)
9866         type = STT_FUNC;
9867
9868       if (h->ref_regular_nonweak)
9869         bindtype = STB_GLOBAL;
9870       else
9871         bindtype = STB_WEAK;
9872       sym.st_info = ELF_ST_INFO (bindtype, type);
9873     }
9874
9875   /* If this is a symbol defined in a dynamic library, don't use the
9876      symbol size from the dynamic library.  Relinking an executable
9877      against a new library may introduce gratuitous changes in the
9878      executable's symbols if we keep the size.  */
9879   if (sym.st_shndx == SHN_UNDEF
9880       && !h->def_regular
9881       && h->def_dynamic)
9882     sym.st_size = 0;
9883
9884   /* If a non-weak symbol with non-default visibility is not defined
9885      locally, it is a fatal error.  */
9886   if (!bfd_link_relocatable (flinfo->info)
9887       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9888       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9889       && h->root.type == bfd_link_hash_undefined
9890       && !h->def_regular)
9891     {
9892       const char *msg;
9893
9894       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9895         /* xgettext:c-format */
9896         msg = _("%pB: protected symbol `%s' isn't defined");
9897       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9898         /* xgettext:c-format */
9899         msg = _("%pB: internal symbol `%s' isn't defined");
9900       else
9901         /* xgettext:c-format */
9902         msg = _("%pB: hidden symbol `%s' isn't defined");
9903       _bfd_error_handler (msg, flinfo->output_bfd, h->root.root.string);
9904       bfd_set_error (bfd_error_bad_value);
9905       eoinfo->failed = TRUE;
9906       return FALSE;
9907     }
9908
9909   /* If this symbol should be put in the .dynsym section, then put it
9910      there now.  We already know the symbol index.  We also fill in
9911      the entry in the .hash section.  */
9912   if (elf_hash_table (flinfo->info)->dynsym != NULL
9913       && h->dynindx != -1
9914       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9915     {
9916       bfd_byte *esym;
9917
9918       /* Since there is no version information in the dynamic string,
9919          if there is no version info in symbol version section, we will
9920          have a run-time problem if not linking executable, referenced
9921          by shared library, or not bound locally.  */
9922       if (h->verinfo.verdef == NULL
9923           && (!bfd_link_executable (flinfo->info)
9924               || h->ref_dynamic
9925               || !h->def_regular))
9926         {
9927           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9928
9929           if (p && p [1] != '\0')
9930             {
9931               _bfd_error_handler
9932                 /* xgettext:c-format */
9933                 (_("%pB: No symbol version section for versioned symbol `%s'"),
9934                  flinfo->output_bfd, h->root.root.string);
9935               eoinfo->failed = TRUE;
9936               return FALSE;
9937             }
9938         }
9939
9940       sym.st_name = h->dynstr_index;
9941       esym = (elf_hash_table (flinfo->info)->dynsym->contents
9942               + h->dynindx * bed->s->sizeof_sym);
9943       if (!check_dynsym (flinfo->output_bfd, &sym))
9944         {
9945           eoinfo->failed = TRUE;
9946           return FALSE;
9947         }
9948       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9949
9950       if (flinfo->hash_sec != NULL)
9951         {
9952           size_t hash_entry_size;
9953           bfd_byte *bucketpos;
9954           bfd_vma chain;
9955           size_t bucketcount;
9956           size_t bucket;
9957
9958           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9959           bucket = h->u.elf_hash_value % bucketcount;
9960
9961           hash_entry_size
9962             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9963           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9964                        + (bucket + 2) * hash_entry_size);
9965           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9966           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9967                    bucketpos);
9968           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9969                    ((bfd_byte *) flinfo->hash_sec->contents
9970                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9971         }
9972
9973       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9974         {
9975           Elf_Internal_Versym iversym;
9976           Elf_External_Versym *eversym;
9977
9978           if (!h->def_regular)
9979             {
9980               if (h->verinfo.verdef == NULL
9981                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9982                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9983                 iversym.vs_vers = 0;
9984               else
9985                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9986             }
9987           else
9988             {
9989               if (h->verinfo.vertree == NULL)
9990                 iversym.vs_vers = 1;
9991               else
9992                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9993               if (flinfo->info->create_default_symver)
9994                 iversym.vs_vers++;
9995             }
9996
9997           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
9998              defined locally.  */
9999           if (h->versioned == versioned_hidden && h->def_regular)
10000             iversym.vs_vers |= VERSYM_HIDDEN;
10001
10002           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
10003           eversym += h->dynindx;
10004           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
10005         }
10006     }
10007
10008   /* If the symbol is undefined, and we didn't output it to .dynsym,
10009      strip it from .symtab too.  Obviously we can't do this for
10010      relocatable output or when needed for --emit-relocs.  */
10011   else if (input_sec == bfd_und_section_ptr
10012            && h->indx != -2
10013            /* PR 22319 Do not strip global undefined symbols marked as being needed.  */
10014            && (h->mark != 1 || ELF_ST_BIND (sym.st_info) != STB_GLOBAL)
10015            && !bfd_link_relocatable (flinfo->info))
10016     return TRUE;
10017
10018   /* Also strip others that we couldn't earlier due to dynamic symbol
10019      processing.  */
10020   if (strip)
10021     return TRUE;
10022   if ((input_sec->flags & SEC_EXCLUDE) != 0)
10023     return TRUE;
10024
10025   /* Output a FILE symbol so that following locals are not associated
10026      with the wrong input file.  We need one for forced local symbols
10027      if we've seen more than one FILE symbol or when we have exactly
10028      one FILE symbol but global symbols are present in a file other
10029      than the one with the FILE symbol.  We also need one if linker
10030      defined symbols are present.  In practice these conditions are
10031      always met, so just emit the FILE symbol unconditionally.  */
10032   if (eoinfo->localsyms
10033       && !eoinfo->file_sym_done
10034       && eoinfo->flinfo->filesym_count != 0)
10035     {
10036       Elf_Internal_Sym fsym;
10037
10038       memset (&fsym, 0, sizeof (fsym));
10039       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10040       fsym.st_shndx = SHN_ABS;
10041       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
10042                                       bfd_und_section_ptr, NULL))
10043         return FALSE;
10044
10045       eoinfo->file_sym_done = TRUE;
10046     }
10047
10048   indx = bfd_get_symcount (flinfo->output_bfd);
10049   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
10050                                    input_sec, h);
10051   if (ret == 0)
10052     {
10053       eoinfo->failed = TRUE;
10054       return FALSE;
10055     }
10056   else if (ret == 1)
10057     h->indx = indx;
10058   else if (h->indx == -2)
10059     abort();
10060
10061   return TRUE;
10062 }
10063
10064 /* Return TRUE if special handling is done for relocs in SEC against
10065    symbols defined in discarded sections.  */
10066
10067 static bfd_boolean
10068 elf_section_ignore_discarded_relocs (asection *sec)
10069 {
10070   const struct elf_backend_data *bed;
10071
10072   switch (sec->sec_info_type)
10073     {
10074     case SEC_INFO_TYPE_STABS:
10075     case SEC_INFO_TYPE_EH_FRAME:
10076     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10077       return TRUE;
10078     default:
10079       break;
10080     }
10081
10082   bed = get_elf_backend_data (sec->owner);
10083   if (bed->elf_backend_ignore_discarded_relocs != NULL
10084       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
10085     return TRUE;
10086
10087   return FALSE;
10088 }
10089
10090 /* Return a mask saying how ld should treat relocations in SEC against
10091    symbols defined in discarded sections.  If this function returns
10092    COMPLAIN set, ld will issue a warning message.  If this function
10093    returns PRETEND set, and the discarded section was link-once and the
10094    same size as the kept link-once section, ld will pretend that the
10095    symbol was actually defined in the kept section.  Otherwise ld will
10096    zero the reloc (at least that is the intent, but some cooperation by
10097    the target dependent code is needed, particularly for REL targets).  */
10098
10099 unsigned int
10100 _bfd_elf_default_action_discarded (asection *sec)
10101 {
10102   if (sec->flags & SEC_DEBUGGING)
10103     return PRETEND;
10104
10105   if (strcmp (".eh_frame", sec->name) == 0)
10106     return 0;
10107
10108   if (strcmp (".gcc_except_table", sec->name) == 0)
10109     return 0;
10110
10111   return COMPLAIN | PRETEND;
10112 }
10113
10114 /* Find a match between a section and a member of a section group.  */
10115
10116 static asection *
10117 match_group_member (asection *sec, asection *group,
10118                     struct bfd_link_info *info)
10119 {
10120   asection *first = elf_next_in_group (group);
10121   asection *s = first;
10122
10123   while (s != NULL)
10124     {
10125       if (bfd_elf_match_symbols_in_sections (s, sec, info))
10126         return s;
10127
10128       s = elf_next_in_group (s);
10129       if (s == first)
10130         break;
10131     }
10132
10133   return NULL;
10134 }
10135
10136 /* Check if the kept section of a discarded section SEC can be used
10137    to replace it.  Return the replacement if it is OK.  Otherwise return
10138    NULL.  */
10139
10140 asection *
10141 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
10142 {
10143   asection *kept;
10144
10145   kept = sec->kept_section;
10146   if (kept != NULL)
10147     {
10148       if ((kept->flags & SEC_GROUP) != 0)
10149         kept = match_group_member (sec, kept, info);
10150       if (kept != NULL
10151           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
10152               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
10153         kept = NULL;
10154       sec->kept_section = kept;
10155     }
10156   return kept;
10157 }
10158
10159 /* Link an input file into the linker output file.  This function
10160    handles all the sections and relocations of the input file at once.
10161    This is so that we only have to read the local symbols once, and
10162    don't have to keep them in memory.  */
10163
10164 static bfd_boolean
10165 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
10166 {
10167   int (*relocate_section)
10168     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
10169      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
10170   bfd *output_bfd;
10171   Elf_Internal_Shdr *symtab_hdr;
10172   size_t locsymcount;
10173   size_t extsymoff;
10174   Elf_Internal_Sym *isymbuf;
10175   Elf_Internal_Sym *isym;
10176   Elf_Internal_Sym *isymend;
10177   long *pindex;
10178   asection **ppsection;
10179   asection *o;
10180   const struct elf_backend_data *bed;
10181   struct elf_link_hash_entry **sym_hashes;
10182   bfd_size_type address_size;
10183   bfd_vma r_type_mask;
10184   int r_sym_shift;
10185   bfd_boolean have_file_sym = FALSE;
10186
10187   output_bfd = flinfo->output_bfd;
10188   bed = get_elf_backend_data (output_bfd);
10189   relocate_section = bed->elf_backend_relocate_section;
10190
10191   /* If this is a dynamic object, we don't want to do anything here:
10192      we don't want the local symbols, and we don't want the section
10193      contents.  */
10194   if ((input_bfd->flags & DYNAMIC) != 0)
10195     return TRUE;
10196
10197   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
10198   if (elf_bad_symtab (input_bfd))
10199     {
10200       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
10201       extsymoff = 0;
10202     }
10203   else
10204     {
10205       locsymcount = symtab_hdr->sh_info;
10206       extsymoff = symtab_hdr->sh_info;
10207     }
10208
10209   /* Read the local symbols.  */
10210   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
10211   if (isymbuf == NULL && locsymcount != 0)
10212     {
10213       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
10214                                       flinfo->internal_syms,
10215                                       flinfo->external_syms,
10216                                       flinfo->locsym_shndx);
10217       if (isymbuf == NULL)
10218         return FALSE;
10219     }
10220
10221   /* Find local symbol sections and adjust values of symbols in
10222      SEC_MERGE sections.  Write out those local symbols we know are
10223      going into the output file.  */
10224   isymend = isymbuf + locsymcount;
10225   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
10226        isym < isymend;
10227        isym++, pindex++, ppsection++)
10228     {
10229       asection *isec;
10230       const char *name;
10231       Elf_Internal_Sym osym;
10232       long indx;
10233       int ret;
10234
10235       *pindex = -1;
10236
10237       if (elf_bad_symtab (input_bfd))
10238         {
10239           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
10240             {
10241               *ppsection = NULL;
10242               continue;
10243             }
10244         }
10245
10246       if (isym->st_shndx == SHN_UNDEF)
10247         isec = bfd_und_section_ptr;
10248       else if (isym->st_shndx == SHN_ABS)
10249         isec = bfd_abs_section_ptr;
10250       else if (isym->st_shndx == SHN_COMMON)
10251         isec = bfd_com_section_ptr;
10252       else
10253         {
10254           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
10255           if (isec == NULL)
10256             {
10257               /* Don't attempt to output symbols with st_shnx in the
10258                  reserved range other than SHN_ABS and SHN_COMMON.  */
10259               *ppsection = NULL;
10260               continue;
10261             }
10262           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
10263                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
10264             isym->st_value =
10265               _bfd_merged_section_offset (output_bfd, &isec,
10266                                           elf_section_data (isec)->sec_info,
10267                                           isym->st_value);
10268         }
10269
10270       *ppsection = isec;
10271
10272       /* Don't output the first, undefined, symbol.  In fact, don't
10273          output any undefined local symbol.  */
10274       if (isec == bfd_und_section_ptr)
10275         continue;
10276
10277       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
10278         {
10279           /* We never output section symbols.  Instead, we use the
10280              section symbol of the corresponding section in the output
10281              file.  */
10282           continue;
10283         }
10284
10285       /* If we are stripping all symbols, we don't want to output this
10286          one.  */
10287       if (flinfo->info->strip == strip_all)
10288         continue;
10289
10290       /* If we are discarding all local symbols, we don't want to
10291          output this one.  If we are generating a relocatable output
10292          file, then some of the local symbols may be required by
10293          relocs; we output them below as we discover that they are
10294          needed.  */
10295       if (flinfo->info->discard == discard_all)
10296         continue;
10297
10298       /* If this symbol is defined in a section which we are
10299          discarding, we don't need to keep it.  */
10300       if (isym->st_shndx != SHN_UNDEF
10301           && isym->st_shndx < SHN_LORESERVE
10302           && bfd_section_removed_from_list (output_bfd,
10303                                             isec->output_section))
10304         continue;
10305
10306       /* Get the name of the symbol.  */
10307       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
10308                                               isym->st_name);
10309       if (name == NULL)
10310         return FALSE;
10311
10312       /* See if we are discarding symbols with this name.  */
10313       if ((flinfo->info->strip == strip_some
10314            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
10315                == NULL))
10316           || (((flinfo->info->discard == discard_sec_merge
10317                 && (isec->flags & SEC_MERGE)
10318                 && !bfd_link_relocatable (flinfo->info))
10319                || flinfo->info->discard == discard_l)
10320               && bfd_is_local_label_name (input_bfd, name)))
10321         continue;
10322
10323       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
10324         {
10325           if (input_bfd->lto_output)
10326             /* -flto puts a temp file name here.  This means builds
10327                are not reproducible.  Discard the symbol.  */
10328             continue;
10329           have_file_sym = TRUE;
10330           flinfo->filesym_count += 1;
10331         }
10332       if (!have_file_sym)
10333         {
10334           /* In the absence of debug info, bfd_find_nearest_line uses
10335              FILE symbols to determine the source file for local
10336              function symbols.  Provide a FILE symbol here if input
10337              files lack such, so that their symbols won't be
10338              associated with a previous input file.  It's not the
10339              source file, but the best we can do.  */
10340           have_file_sym = TRUE;
10341           flinfo->filesym_count += 1;
10342           memset (&osym, 0, sizeof (osym));
10343           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10344           osym.st_shndx = SHN_ABS;
10345           if (!elf_link_output_symstrtab (flinfo,
10346                                           (input_bfd->lto_output ? NULL
10347                                            : input_bfd->filename),
10348                                           &osym, bfd_abs_section_ptr,
10349                                           NULL))
10350             return FALSE;
10351         }
10352
10353       osym = *isym;
10354
10355       /* Adjust the section index for the output file.  */
10356       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10357                                                          isec->output_section);
10358       if (osym.st_shndx == SHN_BAD)
10359         return FALSE;
10360
10361       /* ELF symbols in relocatable files are section relative, but
10362          in executable files they are virtual addresses.  Note that
10363          this code assumes that all ELF sections have an associated
10364          BFD section with a reasonable value for output_offset; below
10365          we assume that they also have a reasonable value for
10366          output_section.  Any special sections must be set up to meet
10367          these requirements.  */
10368       osym.st_value += isec->output_offset;
10369       if (!bfd_link_relocatable (flinfo->info))
10370         {
10371           osym.st_value += isec->output_section->vma;
10372           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
10373             {
10374               /* STT_TLS symbols are relative to PT_TLS segment base.  */
10375               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
10376               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
10377             }
10378         }
10379
10380       indx = bfd_get_symcount (output_bfd);
10381       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
10382       if (ret == 0)
10383         return FALSE;
10384       else if (ret == 1)
10385         *pindex = indx;
10386     }
10387
10388   if (bed->s->arch_size == 32)
10389     {
10390       r_type_mask = 0xff;
10391       r_sym_shift = 8;
10392       address_size = 4;
10393     }
10394   else
10395     {
10396       r_type_mask = 0xffffffff;
10397       r_sym_shift = 32;
10398       address_size = 8;
10399     }
10400
10401   /* Relocate the contents of each section.  */
10402   sym_hashes = elf_sym_hashes (input_bfd);
10403   for (o = input_bfd->sections; o != NULL; o = o->next)
10404     {
10405       bfd_byte *contents;
10406
10407       if (! o->linker_mark)
10408         {
10409           /* This section was omitted from the link.  */
10410           continue;
10411         }
10412
10413       if (!flinfo->info->resolve_section_groups
10414           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
10415         {
10416           /* Deal with the group signature symbol.  */
10417           struct bfd_elf_section_data *sec_data = elf_section_data (o);
10418           unsigned long symndx = sec_data->this_hdr.sh_info;
10419           asection *osec = o->output_section;
10420
10421           BFD_ASSERT (bfd_link_relocatable (flinfo->info));
10422           if (symndx >= locsymcount
10423               || (elf_bad_symtab (input_bfd)
10424                   && flinfo->sections[symndx] == NULL))
10425             {
10426               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
10427               while (h->root.type == bfd_link_hash_indirect
10428                      || h->root.type == bfd_link_hash_warning)
10429                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
10430               /* Arrange for symbol to be output.  */
10431               h->indx = -2;
10432               elf_section_data (osec)->this_hdr.sh_info = -2;
10433             }
10434           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
10435             {
10436               /* We'll use the output section target_index.  */
10437               asection *sec = flinfo->sections[symndx]->output_section;
10438               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
10439             }
10440           else
10441             {
10442               if (flinfo->indices[symndx] == -1)
10443                 {
10444                   /* Otherwise output the local symbol now.  */
10445                   Elf_Internal_Sym sym = isymbuf[symndx];
10446                   asection *sec = flinfo->sections[symndx]->output_section;
10447                   const char *name;
10448                   long indx;
10449                   int ret;
10450
10451                   name = bfd_elf_string_from_elf_section (input_bfd,
10452                                                           symtab_hdr->sh_link,
10453                                                           sym.st_name);
10454                   if (name == NULL)
10455                     return FALSE;
10456
10457                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10458                                                                     sec);
10459                   if (sym.st_shndx == SHN_BAD)
10460                     return FALSE;
10461
10462                   sym.st_value += o->output_offset;
10463
10464                   indx = bfd_get_symcount (output_bfd);
10465                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
10466                                                    NULL);
10467                   if (ret == 0)
10468                     return FALSE;
10469                   else if (ret == 1)
10470                     flinfo->indices[symndx] = indx;
10471                   else
10472                     abort ();
10473                 }
10474               elf_section_data (osec)->this_hdr.sh_info
10475                 = flinfo->indices[symndx];
10476             }
10477         }
10478
10479       if ((o->flags & SEC_HAS_CONTENTS) == 0
10480           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
10481         continue;
10482
10483       if ((o->flags & SEC_LINKER_CREATED) != 0)
10484         {
10485           /* Section was created by _bfd_elf_link_create_dynamic_sections
10486              or somesuch.  */
10487           continue;
10488         }
10489
10490       /* Get the contents of the section.  They have been cached by a
10491          relaxation routine.  Note that o is a section in an input
10492          file, so the contents field will not have been set by any of
10493          the routines which work on output files.  */
10494       if (elf_section_data (o)->this_hdr.contents != NULL)
10495         {
10496           contents = elf_section_data (o)->this_hdr.contents;
10497           if (bed->caches_rawsize
10498               && o->rawsize != 0
10499               && o->rawsize < o->size)
10500             {
10501               memcpy (flinfo->contents, contents, o->rawsize);
10502               contents = flinfo->contents;
10503             }
10504         }
10505       else
10506         {
10507           contents = flinfo->contents;
10508           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
10509             return FALSE;
10510         }
10511
10512       if ((o->flags & SEC_RELOC) != 0)
10513         {
10514           Elf_Internal_Rela *internal_relocs;
10515           Elf_Internal_Rela *rel, *relend;
10516           int action_discarded;
10517           int ret;
10518
10519           /* Get the swapped relocs.  */
10520           internal_relocs
10521             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
10522                                          flinfo->internal_relocs, FALSE);
10523           if (internal_relocs == NULL
10524               && o->reloc_count > 0)
10525             return FALSE;
10526
10527           /* We need to reverse-copy input .ctors/.dtors sections if
10528              they are placed in .init_array/.finit_array for output.  */
10529           if (o->size > address_size
10530               && ((strncmp (o->name, ".ctors", 6) == 0
10531                    && strcmp (o->output_section->name,
10532                               ".init_array") == 0)
10533                   || (strncmp (o->name, ".dtors", 6) == 0
10534                       && strcmp (o->output_section->name,
10535                                  ".fini_array") == 0))
10536               && (o->name[6] == 0 || o->name[6] == '.'))
10537             {
10538               if (o->size * bed->s->int_rels_per_ext_rel
10539                   != o->reloc_count * address_size)
10540                 {
10541                   _bfd_error_handler
10542                     /* xgettext:c-format */
10543                     (_("error: %pB: size of section %pA is not "
10544                        "multiple of address size"),
10545                      input_bfd, o);
10546                   bfd_set_error (bfd_error_bad_value);
10547                   return FALSE;
10548                 }
10549               o->flags |= SEC_ELF_REVERSE_COPY;
10550             }
10551
10552           action_discarded = -1;
10553           if (!elf_section_ignore_discarded_relocs (o))
10554             action_discarded = (*bed->action_discarded) (o);
10555
10556           /* Run through the relocs evaluating complex reloc symbols and
10557              looking for relocs against symbols from discarded sections
10558              or section symbols from removed link-once sections.
10559              Complain about relocs against discarded sections.  Zero
10560              relocs against removed link-once sections.  */
10561
10562           rel = internal_relocs;
10563           relend = rel + o->reloc_count;
10564           for ( ; rel < relend; rel++)
10565             {
10566               unsigned long r_symndx = rel->r_info >> r_sym_shift;
10567               unsigned int s_type;
10568               asection **ps, *sec;
10569               struct elf_link_hash_entry *h = NULL;
10570               const char *sym_name;
10571
10572               if (r_symndx == STN_UNDEF)
10573                 continue;
10574
10575               if (r_symndx >= locsymcount
10576                   || (elf_bad_symtab (input_bfd)
10577                       && flinfo->sections[r_symndx] == NULL))
10578                 {
10579                   h = sym_hashes[r_symndx - extsymoff];
10580
10581                   /* Badly formatted input files can contain relocs that
10582                      reference non-existant symbols.  Check here so that
10583                      we do not seg fault.  */
10584                   if (h == NULL)
10585                     {
10586                       _bfd_error_handler
10587                         /* xgettext:c-format */
10588                         (_("error: %pB contains a reloc (%#" PRIx64 ") for section %pA "
10589                            "that references a non-existent global symbol"),
10590                          input_bfd, (uint64_t) rel->r_info, o);
10591                       bfd_set_error (bfd_error_bad_value);
10592                       return FALSE;
10593                     }
10594
10595                   while (h->root.type == bfd_link_hash_indirect
10596                          || h->root.type == bfd_link_hash_warning)
10597                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10598
10599                   s_type = h->type;
10600
10601                   /* If a plugin symbol is referenced from a non-IR file,
10602                      mark the symbol as undefined.  Note that the
10603                      linker may attach linker created dynamic sections
10604                      to the plugin bfd.  Symbols defined in linker
10605                      created sections are not plugin symbols.  */
10606                   if ((h->root.non_ir_ref_regular
10607                        || h->root.non_ir_ref_dynamic)
10608                       && (h->root.type == bfd_link_hash_defined
10609                           || h->root.type == bfd_link_hash_defweak)
10610                       && (h->root.u.def.section->flags
10611                           & SEC_LINKER_CREATED) == 0
10612                       && h->root.u.def.section->owner != NULL
10613                       && (h->root.u.def.section->owner->flags
10614                           & BFD_PLUGIN) != 0)
10615                     {
10616                       h->root.type = bfd_link_hash_undefined;
10617                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10618                     }
10619
10620                   ps = NULL;
10621                   if (h->root.type == bfd_link_hash_defined
10622                       || h->root.type == bfd_link_hash_defweak)
10623                     ps = &h->root.u.def.section;
10624
10625                   sym_name = h->root.root.string;
10626                 }
10627               else
10628                 {
10629                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10630
10631                   s_type = ELF_ST_TYPE (sym->st_info);
10632                   ps = &flinfo->sections[r_symndx];
10633                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10634                                                sym, *ps);
10635                 }
10636
10637               if ((s_type == STT_RELC || s_type == STT_SRELC)
10638                   && !bfd_link_relocatable (flinfo->info))
10639                 {
10640                   bfd_vma val;
10641                   bfd_vma dot = (rel->r_offset
10642                                  + o->output_offset + o->output_section->vma);
10643 #ifdef DEBUG
10644                   printf ("Encountered a complex symbol!");
10645                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10646                           input_bfd->filename, o->name,
10647                           (long) (rel - internal_relocs));
10648                   printf (" symbol: idx  %8.8lx, name %s\n",
10649                           r_symndx, sym_name);
10650                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10651                           (unsigned long) rel->r_info,
10652                           (unsigned long) rel->r_offset);
10653 #endif
10654                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10655                                     isymbuf, locsymcount, s_type == STT_SRELC))
10656                     return FALSE;
10657
10658                   /* Symbol evaluated OK.  Update to absolute value.  */
10659                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10660                                     r_symndx, val);
10661                   continue;
10662                 }
10663
10664               if (action_discarded != -1 && ps != NULL)
10665                 {
10666                   /* Complain if the definition comes from a
10667                      discarded section.  */
10668                   if ((sec = *ps) != NULL && discarded_section (sec))
10669                     {
10670                       BFD_ASSERT (r_symndx != STN_UNDEF);
10671                       if (action_discarded & COMPLAIN)
10672                         (*flinfo->info->callbacks->einfo)
10673                           /* xgettext:c-format */
10674                           (_("%X`%s' referenced in section `%pA' of %pB: "
10675                              "defined in discarded section `%pA' of %pB\n"),
10676                            sym_name, o, input_bfd, sec, sec->owner);
10677
10678                       /* Try to do the best we can to support buggy old
10679                          versions of gcc.  Pretend that the symbol is
10680                          really defined in the kept linkonce section.
10681                          FIXME: This is quite broken.  Modifying the
10682                          symbol here means we will be changing all later
10683                          uses of the symbol, not just in this section.  */
10684                       if (action_discarded & PRETEND)
10685                         {
10686                           asection *kept;
10687
10688                           kept = _bfd_elf_check_kept_section (sec,
10689                                                               flinfo->info);
10690                           if (kept != NULL)
10691                             {
10692                               *ps = kept;
10693                               continue;
10694                             }
10695                         }
10696                     }
10697                 }
10698             }
10699
10700           /* Relocate the section by invoking a back end routine.
10701
10702              The back end routine is responsible for adjusting the
10703              section contents as necessary, and (if using Rela relocs
10704              and generating a relocatable output file) adjusting the
10705              reloc addend as necessary.
10706
10707              The back end routine does not have to worry about setting
10708              the reloc address or the reloc symbol index.
10709
10710              The back end routine is given a pointer to the swapped in
10711              internal symbols, and can access the hash table entries
10712              for the external symbols via elf_sym_hashes (input_bfd).
10713
10714              When generating relocatable output, the back end routine
10715              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10716              output symbol is going to be a section symbol
10717              corresponding to the output section, which will require
10718              the addend to be adjusted.  */
10719
10720           ret = (*relocate_section) (output_bfd, flinfo->info,
10721                                      input_bfd, o, contents,
10722                                      internal_relocs,
10723                                      isymbuf,
10724                                      flinfo->sections);
10725           if (!ret)
10726             return FALSE;
10727
10728           if (ret == 2
10729               || bfd_link_relocatable (flinfo->info)
10730               || flinfo->info->emitrelocations)
10731             {
10732               Elf_Internal_Rela *irela;
10733               Elf_Internal_Rela *irelaend, *irelamid;
10734               bfd_vma last_offset;
10735               struct elf_link_hash_entry **rel_hash;
10736               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10737               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10738               unsigned int next_erel;
10739               bfd_boolean rela_normal;
10740               struct bfd_elf_section_data *esdi, *esdo;
10741
10742               esdi = elf_section_data (o);
10743               esdo = elf_section_data (o->output_section);
10744               rela_normal = FALSE;
10745
10746               /* Adjust the reloc addresses and symbol indices.  */
10747
10748               irela = internal_relocs;
10749               irelaend = irela + o->reloc_count;
10750               rel_hash = esdo->rel.hashes + esdo->rel.count;
10751               /* We start processing the REL relocs, if any.  When we reach
10752                  IRELAMID in the loop, we switch to the RELA relocs.  */
10753               irelamid = irela;
10754               if (esdi->rel.hdr != NULL)
10755                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10756                              * bed->s->int_rels_per_ext_rel);
10757               rel_hash_list = rel_hash;
10758               rela_hash_list = NULL;
10759               last_offset = o->output_offset;
10760               if (!bfd_link_relocatable (flinfo->info))
10761                 last_offset += o->output_section->vma;
10762               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10763                 {
10764                   unsigned long r_symndx;
10765                   asection *sec;
10766                   Elf_Internal_Sym sym;
10767
10768                   if (next_erel == bed->s->int_rels_per_ext_rel)
10769                     {
10770                       rel_hash++;
10771                       next_erel = 0;
10772                     }
10773
10774                   if (irela == irelamid)
10775                     {
10776                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10777                       rela_hash_list = rel_hash;
10778                       rela_normal = bed->rela_normal;
10779                     }
10780
10781                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10782                                                              flinfo->info, o,
10783                                                              irela->r_offset);
10784                   if (irela->r_offset >= (bfd_vma) -2)
10785                     {
10786                       /* This is a reloc for a deleted entry or somesuch.
10787                          Turn it into an R_*_NONE reloc, at the same
10788                          offset as the last reloc.  elf_eh_frame.c and
10789                          bfd_elf_discard_info rely on reloc offsets
10790                          being ordered.  */
10791                       irela->r_offset = last_offset;
10792                       irela->r_info = 0;
10793                       irela->r_addend = 0;
10794                       continue;
10795                     }
10796
10797                   irela->r_offset += o->output_offset;
10798
10799                   /* Relocs in an executable have to be virtual addresses.  */
10800                   if (!bfd_link_relocatable (flinfo->info))
10801                     irela->r_offset += o->output_section->vma;
10802
10803                   last_offset = irela->r_offset;
10804
10805                   r_symndx = irela->r_info >> r_sym_shift;
10806                   if (r_symndx == STN_UNDEF)
10807                     continue;
10808
10809                   if (r_symndx >= locsymcount
10810                       || (elf_bad_symtab (input_bfd)
10811                           && flinfo->sections[r_symndx] == NULL))
10812                     {
10813                       struct elf_link_hash_entry *rh;
10814                       unsigned long indx;
10815
10816                       /* This is a reloc against a global symbol.  We
10817                          have not yet output all the local symbols, so
10818                          we do not know the symbol index of any global
10819                          symbol.  We set the rel_hash entry for this
10820                          reloc to point to the global hash table entry
10821                          for this symbol.  The symbol index is then
10822                          set at the end of bfd_elf_final_link.  */
10823                       indx = r_symndx - extsymoff;
10824                       rh = elf_sym_hashes (input_bfd)[indx];
10825                       while (rh->root.type == bfd_link_hash_indirect
10826                              || rh->root.type == bfd_link_hash_warning)
10827                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10828
10829                       /* Setting the index to -2 tells
10830                          elf_link_output_extsym that this symbol is
10831                          used by a reloc.  */
10832                       BFD_ASSERT (rh->indx < 0);
10833                       rh->indx = -2;
10834                       *rel_hash = rh;
10835
10836                       continue;
10837                     }
10838
10839                   /* This is a reloc against a local symbol.  */
10840
10841                   *rel_hash = NULL;
10842                   sym = isymbuf[r_symndx];
10843                   sec = flinfo->sections[r_symndx];
10844                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10845                     {
10846                       /* I suppose the backend ought to fill in the
10847                          section of any STT_SECTION symbol against a
10848                          processor specific section.  */
10849                       r_symndx = STN_UNDEF;
10850                       if (bfd_is_abs_section (sec))
10851                         ;
10852                       else if (sec == NULL || sec->owner == NULL)
10853                         {
10854                           bfd_set_error (bfd_error_bad_value);
10855                           return FALSE;
10856                         }
10857                       else
10858                         {
10859                           asection *osec = sec->output_section;
10860
10861                           /* If we have discarded a section, the output
10862                              section will be the absolute section.  In
10863                              case of discarded SEC_MERGE sections, use
10864                              the kept section.  relocate_section should
10865                              have already handled discarded linkonce
10866                              sections.  */
10867                           if (bfd_is_abs_section (osec)
10868                               && sec->kept_section != NULL
10869                               && sec->kept_section->output_section != NULL)
10870                             {
10871                               osec = sec->kept_section->output_section;
10872                               irela->r_addend -= osec->vma;
10873                             }
10874
10875                           if (!bfd_is_abs_section (osec))
10876                             {
10877                               r_symndx = osec->target_index;
10878                               if (r_symndx == STN_UNDEF)
10879                                 {
10880                                   irela->r_addend += osec->vma;
10881                                   osec = _bfd_nearby_section (output_bfd, osec,
10882                                                               osec->vma);
10883                                   irela->r_addend -= osec->vma;
10884                                   r_symndx = osec->target_index;
10885                                 }
10886                             }
10887                         }
10888
10889                       /* Adjust the addend according to where the
10890                          section winds up in the output section.  */
10891                       if (rela_normal)
10892                         irela->r_addend += sec->output_offset;
10893                     }
10894                   else
10895                     {
10896                       if (flinfo->indices[r_symndx] == -1)
10897                         {
10898                           unsigned long shlink;
10899                           const char *name;
10900                           asection *osec;
10901                           long indx;
10902
10903                           if (flinfo->info->strip == strip_all)
10904                             {
10905                               /* You can't do ld -r -s.  */
10906                               bfd_set_error (bfd_error_invalid_operation);
10907                               return FALSE;
10908                             }
10909
10910                           /* This symbol was skipped earlier, but
10911                              since it is needed by a reloc, we
10912                              must output it now.  */
10913                           shlink = symtab_hdr->sh_link;
10914                           name = (bfd_elf_string_from_elf_section
10915                                   (input_bfd, shlink, sym.st_name));
10916                           if (name == NULL)
10917                             return FALSE;
10918
10919                           osec = sec->output_section;
10920                           sym.st_shndx =
10921                             _bfd_elf_section_from_bfd_section (output_bfd,
10922                                                                osec);
10923                           if (sym.st_shndx == SHN_BAD)
10924                             return FALSE;
10925
10926                           sym.st_value += sec->output_offset;
10927                           if (!bfd_link_relocatable (flinfo->info))
10928                             {
10929                               sym.st_value += osec->vma;
10930                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10931                                 {
10932                                   /* STT_TLS symbols are relative to PT_TLS
10933                                      segment base.  */
10934                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10935                                               ->tls_sec != NULL);
10936                                   sym.st_value -= (elf_hash_table (flinfo->info)
10937                                                    ->tls_sec->vma);
10938                                 }
10939                             }
10940
10941                           indx = bfd_get_symcount (output_bfd);
10942                           ret = elf_link_output_symstrtab (flinfo, name,
10943                                                            &sym, sec,
10944                                                            NULL);
10945                           if (ret == 0)
10946                             return FALSE;
10947                           else if (ret == 1)
10948                             flinfo->indices[r_symndx] = indx;
10949                           else
10950                             abort ();
10951                         }
10952
10953                       r_symndx = flinfo->indices[r_symndx];
10954                     }
10955
10956                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10957                                    | (irela->r_info & r_type_mask));
10958                 }
10959
10960               /* Swap out the relocs.  */
10961               input_rel_hdr = esdi->rel.hdr;
10962               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10963                 {
10964                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10965                                                      input_rel_hdr,
10966                                                      internal_relocs,
10967                                                      rel_hash_list))
10968                     return FALSE;
10969                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10970                                       * bed->s->int_rels_per_ext_rel);
10971                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10972                 }
10973
10974               input_rela_hdr = esdi->rela.hdr;
10975               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10976                 {
10977                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10978                                                      input_rela_hdr,
10979                                                      internal_relocs,
10980                                                      rela_hash_list))
10981                     return FALSE;
10982                 }
10983             }
10984         }
10985
10986       /* Write out the modified section contents.  */
10987       if (bed->elf_backend_write_section
10988           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10989                                                 contents))
10990         {
10991           /* Section written out.  */
10992         }
10993       else switch (o->sec_info_type)
10994         {
10995         case SEC_INFO_TYPE_STABS:
10996           if (! (_bfd_write_section_stabs
10997                  (output_bfd,
10998                   &elf_hash_table (flinfo->info)->stab_info,
10999                   o, &elf_section_data (o)->sec_info, contents)))
11000             return FALSE;
11001           break;
11002         case SEC_INFO_TYPE_MERGE:
11003           if (! _bfd_write_merged_section (output_bfd, o,
11004                                            elf_section_data (o)->sec_info))
11005             return FALSE;
11006           break;
11007         case SEC_INFO_TYPE_EH_FRAME:
11008           {
11009             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
11010                                                    o, contents))
11011               return FALSE;
11012           }
11013           break;
11014         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
11015           {
11016             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
11017                                                          flinfo->info,
11018                                                          o, contents))
11019               return FALSE;
11020           }
11021           break;
11022         default:
11023           {
11024             if (! (o->flags & SEC_EXCLUDE))
11025               {
11026                 file_ptr offset = (file_ptr) o->output_offset;
11027                 bfd_size_type todo = o->size;
11028
11029                 offset *= bfd_octets_per_byte (output_bfd);
11030
11031                 if ((o->flags & SEC_ELF_REVERSE_COPY))
11032                   {
11033                     /* Reverse-copy input section to output.  */
11034                     do
11035                       {
11036                         todo -= address_size;
11037                         if (! bfd_set_section_contents (output_bfd,
11038                                                         o->output_section,
11039                                                         contents + todo,
11040                                                         offset,
11041                                                         address_size))
11042                           return FALSE;
11043                         if (todo == 0)
11044                           break;
11045                         offset += address_size;
11046                       }
11047                     while (1);
11048                   }
11049                 else if (! bfd_set_section_contents (output_bfd,
11050                                                      o->output_section,
11051                                                      contents,
11052                                                      offset, todo))
11053                   return FALSE;
11054               }
11055           }
11056           break;
11057         }
11058     }
11059
11060   return TRUE;
11061 }
11062
11063 /* Generate a reloc when linking an ELF file.  This is a reloc
11064    requested by the linker, and does not come from any input file.  This
11065    is used to build constructor and destructor tables when linking
11066    with -Ur.  */
11067
11068 static bfd_boolean
11069 elf_reloc_link_order (bfd *output_bfd,
11070                       struct bfd_link_info *info,
11071                       asection *output_section,
11072                       struct bfd_link_order *link_order)
11073 {
11074   reloc_howto_type *howto;
11075   long indx;
11076   bfd_vma offset;
11077   bfd_vma addend;
11078   struct bfd_elf_section_reloc_data *reldata;
11079   struct elf_link_hash_entry **rel_hash_ptr;
11080   Elf_Internal_Shdr *rel_hdr;
11081   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
11082   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
11083   bfd_byte *erel;
11084   unsigned int i;
11085   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
11086
11087   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
11088   if (howto == NULL)
11089     {
11090       bfd_set_error (bfd_error_bad_value);
11091       return FALSE;
11092     }
11093
11094   addend = link_order->u.reloc.p->addend;
11095
11096   if (esdo->rel.hdr)
11097     reldata = &esdo->rel;
11098   else if (esdo->rela.hdr)
11099     reldata = &esdo->rela;
11100   else
11101     {
11102       reldata = NULL;
11103       BFD_ASSERT (0);
11104     }
11105
11106   /* Figure out the symbol index.  */
11107   rel_hash_ptr = reldata->hashes + reldata->count;
11108   if (link_order->type == bfd_section_reloc_link_order)
11109     {
11110       indx = link_order->u.reloc.p->u.section->target_index;
11111       BFD_ASSERT (indx != 0);
11112       *rel_hash_ptr = NULL;
11113     }
11114   else
11115     {
11116       struct elf_link_hash_entry *h;
11117
11118       /* Treat a reloc against a defined symbol as though it were
11119          actually against the section.  */
11120       h = ((struct elf_link_hash_entry *)
11121            bfd_wrapped_link_hash_lookup (output_bfd, info,
11122                                          link_order->u.reloc.p->u.name,
11123                                          FALSE, FALSE, TRUE));
11124       if (h != NULL
11125           && (h->root.type == bfd_link_hash_defined
11126               || h->root.type == bfd_link_hash_defweak))
11127         {
11128           asection *section;
11129
11130           section = h->root.u.def.section;
11131           indx = section->output_section->target_index;
11132           *rel_hash_ptr = NULL;
11133           /* It seems that we ought to add the symbol value to the
11134              addend here, but in practice it has already been added
11135              because it was passed to constructor_callback.  */
11136           addend += section->output_section->vma + section->output_offset;
11137         }
11138       else if (h != NULL)
11139         {
11140           /* Setting the index to -2 tells elf_link_output_extsym that
11141              this symbol is used by a reloc.  */
11142           h->indx = -2;
11143           *rel_hash_ptr = h;
11144           indx = 0;
11145         }
11146       else
11147         {
11148           (*info->callbacks->unattached_reloc)
11149             (info, link_order->u.reloc.p->u.name, NULL, NULL, 0);
11150           indx = 0;
11151         }
11152     }
11153
11154   /* If this is an inplace reloc, we must write the addend into the
11155      object file.  */
11156   if (howto->partial_inplace && addend != 0)
11157     {
11158       bfd_size_type size;
11159       bfd_reloc_status_type rstat;
11160       bfd_byte *buf;
11161       bfd_boolean ok;
11162       const char *sym_name;
11163
11164       size = (bfd_size_type) bfd_get_reloc_size (howto);
11165       buf = (bfd_byte *) bfd_zmalloc (size);
11166       if (buf == NULL && size != 0)
11167         return FALSE;
11168       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
11169       switch (rstat)
11170         {
11171         case bfd_reloc_ok:
11172           break;
11173
11174         default:
11175         case bfd_reloc_outofrange:
11176           abort ();
11177
11178         case bfd_reloc_overflow:
11179           if (link_order->type == bfd_section_reloc_link_order)
11180             sym_name = bfd_section_name (output_bfd,
11181                                          link_order->u.reloc.p->u.section);
11182           else
11183             sym_name = link_order->u.reloc.p->u.name;
11184           (*info->callbacks->reloc_overflow) (info, NULL, sym_name,
11185                                               howto->name, addend, NULL, NULL,
11186                                               (bfd_vma) 0);
11187           break;
11188         }
11189
11190       ok = bfd_set_section_contents (output_bfd, output_section, buf,
11191                                      link_order->offset
11192                                      * bfd_octets_per_byte (output_bfd),
11193                                      size);
11194       free (buf);
11195       if (! ok)
11196         return FALSE;
11197     }
11198
11199   /* The address of a reloc is relative to the section in a
11200      relocatable file, and is a virtual address in an executable
11201      file.  */
11202   offset = link_order->offset;
11203   if (! bfd_link_relocatable (info))
11204     offset += output_section->vma;
11205
11206   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
11207     {
11208       irel[i].r_offset = offset;
11209       irel[i].r_info = 0;
11210       irel[i].r_addend = 0;
11211     }
11212   if (bed->s->arch_size == 32)
11213     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
11214   else
11215     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
11216
11217   rel_hdr = reldata->hdr;
11218   erel = rel_hdr->contents;
11219   if (rel_hdr->sh_type == SHT_REL)
11220     {
11221       erel += reldata->count * bed->s->sizeof_rel;
11222       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
11223     }
11224   else
11225     {
11226       irel[0].r_addend = addend;
11227       erel += reldata->count * bed->s->sizeof_rela;
11228       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
11229     }
11230
11231   ++reldata->count;
11232
11233   return TRUE;
11234 }
11235
11236
11237 /* Get the output vma of the section pointed to by the sh_link field.  */
11238
11239 static bfd_vma
11240 elf_get_linked_section_vma (struct bfd_link_order *p)
11241 {
11242   Elf_Internal_Shdr **elf_shdrp;
11243   asection *s;
11244   int elfsec;
11245
11246   s = p->u.indirect.section;
11247   elf_shdrp = elf_elfsections (s->owner);
11248   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
11249   elfsec = elf_shdrp[elfsec]->sh_link;
11250   /* PR 290:
11251      The Intel C compiler generates SHT_IA_64_UNWIND with
11252      SHF_LINK_ORDER.  But it doesn't set the sh_link or
11253      sh_info fields.  Hence we could get the situation
11254      where elfsec is 0.  */
11255   if (elfsec == 0)
11256     {
11257       const struct elf_backend_data *bed
11258         = get_elf_backend_data (s->owner);
11259       if (bed->link_order_error_handler)
11260         bed->link_order_error_handler
11261           /* xgettext:c-format */
11262           (_("%pB: warning: sh_link not set for section `%pA'"), s->owner, s);
11263       return 0;
11264     }
11265   else
11266     {
11267       s = elf_shdrp[elfsec]->bfd_section;
11268       return s->output_section->vma + s->output_offset;
11269     }
11270 }
11271
11272
11273 /* Compare two sections based on the locations of the sections they are
11274    linked to.  Used by elf_fixup_link_order.  */
11275
11276 static int
11277 compare_link_order (const void * a, const void * b)
11278 {
11279   bfd_vma apos;
11280   bfd_vma bpos;
11281
11282   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
11283   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
11284   if (apos < bpos)
11285     return -1;
11286   return apos > bpos;
11287 }
11288
11289
11290 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
11291    order as their linked sections.  Returns false if this could not be done
11292    because an output section includes both ordered and unordered
11293    sections.  Ideally we'd do this in the linker proper.  */
11294
11295 static bfd_boolean
11296 elf_fixup_link_order (bfd *abfd, asection *o)
11297 {
11298   int seen_linkorder;
11299   int seen_other;
11300   int n;
11301   struct bfd_link_order *p;
11302   bfd *sub;
11303   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11304   unsigned elfsec;
11305   struct bfd_link_order **sections;
11306   asection *s, *other_sec, *linkorder_sec;
11307   bfd_vma offset;
11308
11309   other_sec = NULL;
11310   linkorder_sec = NULL;
11311   seen_other = 0;
11312   seen_linkorder = 0;
11313   for (p = o->map_head.link_order; p != NULL; p = p->next)
11314     {
11315       if (p->type == bfd_indirect_link_order)
11316         {
11317           s = p->u.indirect.section;
11318           sub = s->owner;
11319           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11320               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
11321               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
11322               && elfsec < elf_numsections (sub)
11323               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
11324               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
11325             {
11326               seen_linkorder++;
11327               linkorder_sec = s;
11328             }
11329           else
11330             {
11331               seen_other++;
11332               other_sec = s;
11333             }
11334         }
11335       else
11336         seen_other++;
11337
11338       if (seen_other && seen_linkorder)
11339         {
11340           if (other_sec && linkorder_sec)
11341             _bfd_error_handler
11342               /* xgettext:c-format */
11343               (_("%pA has both ordered [`%pA' in %pB] "
11344                  "and unordered [`%pA' in %pB] sections"),
11345                o, linkorder_sec, linkorder_sec->owner,
11346                other_sec, other_sec->owner);
11347           else
11348             _bfd_error_handler
11349               (_("%pA has both ordered and unordered sections"), o);
11350           bfd_set_error (bfd_error_bad_value);
11351           return FALSE;
11352         }
11353     }
11354
11355   if (!seen_linkorder)
11356     return TRUE;
11357
11358   sections = (struct bfd_link_order **)
11359     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
11360   if (sections == NULL)
11361     return FALSE;
11362   seen_linkorder = 0;
11363
11364   for (p = o->map_head.link_order; p != NULL; p = p->next)
11365     {
11366       sections[seen_linkorder++] = p;
11367     }
11368   /* Sort the input sections in the order of their linked section.  */
11369   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
11370          compare_link_order);
11371
11372   /* Change the offsets of the sections.  */
11373   offset = 0;
11374   for (n = 0; n < seen_linkorder; n++)
11375     {
11376       s = sections[n]->u.indirect.section;
11377       offset &= ~(bfd_vma) 0 << s->alignment_power;
11378       s->output_offset = offset / bfd_octets_per_byte (abfd);
11379       sections[n]->offset = offset;
11380       offset += sections[n]->size;
11381     }
11382
11383   free (sections);
11384   return TRUE;
11385 }
11386
11387 /* Generate an import library in INFO->implib_bfd from symbols in ABFD.
11388    Returns TRUE upon success, FALSE otherwise.  */
11389
11390 static bfd_boolean
11391 elf_output_implib (bfd *abfd, struct bfd_link_info *info)
11392 {
11393   bfd_boolean ret = FALSE;
11394   bfd *implib_bfd;
11395   const struct elf_backend_data *bed;
11396   flagword flags;
11397   enum bfd_architecture arch;
11398   unsigned int mach;
11399   asymbol **sympp = NULL;
11400   long symsize;
11401   long symcount;
11402   long src_count;
11403   elf_symbol_type *osymbuf;
11404
11405   implib_bfd = info->out_implib_bfd;
11406   bed = get_elf_backend_data (abfd);
11407
11408   if (!bfd_set_format (implib_bfd, bfd_object))
11409     return FALSE;
11410
11411   /* Use flag from executable but make it a relocatable object.  */
11412   flags = bfd_get_file_flags (abfd);
11413   flags &= ~HAS_RELOC;
11414   if (!bfd_set_start_address (implib_bfd, 0)
11415       || !bfd_set_file_flags (implib_bfd, flags & ~EXEC_P))
11416     return FALSE;
11417
11418   /* Copy architecture of output file to import library file.  */
11419   arch = bfd_get_arch (abfd);
11420   mach = bfd_get_mach (abfd);
11421   if (!bfd_set_arch_mach (implib_bfd, arch, mach)
11422       && (abfd->target_defaulted
11423           || bfd_get_arch (abfd) != bfd_get_arch (implib_bfd)))
11424     return FALSE;
11425
11426   /* Get symbol table size.  */
11427   symsize = bfd_get_symtab_upper_bound (abfd);
11428   if (symsize < 0)
11429     return FALSE;
11430
11431   /* Read in the symbol table.  */
11432   sympp = (asymbol **) xmalloc (symsize);
11433   symcount = bfd_canonicalize_symtab (abfd, sympp);
11434   if (symcount < 0)
11435     goto free_sym_buf;
11436
11437   /* Allow the BFD backend to copy any private header data it
11438      understands from the output BFD to the import library BFD.  */
11439   if (! bfd_copy_private_header_data (abfd, implib_bfd))
11440     goto free_sym_buf;
11441
11442   /* Filter symbols to appear in the import library.  */
11443   if (bed->elf_backend_filter_implib_symbols)
11444     symcount = bed->elf_backend_filter_implib_symbols (abfd, info, sympp,
11445                                                        symcount);
11446   else
11447     symcount = _bfd_elf_filter_global_symbols (abfd, info, sympp, symcount);
11448   if (symcount == 0)
11449     {
11450       bfd_set_error (bfd_error_no_symbols);
11451       _bfd_error_handler (_("%pB: no symbol found for import library"),
11452                           implib_bfd);
11453       goto free_sym_buf;
11454     }
11455
11456
11457   /* Make symbols absolute.  */
11458   osymbuf = (elf_symbol_type *) bfd_alloc2 (implib_bfd, symcount,
11459                                             sizeof (*osymbuf));
11460   for (src_count = 0; src_count < symcount; src_count++)
11461     {
11462       memcpy (&osymbuf[src_count], (elf_symbol_type *) sympp[src_count],
11463               sizeof (*osymbuf));
11464       osymbuf[src_count].symbol.section = bfd_abs_section_ptr;
11465       osymbuf[src_count].internal_elf_sym.st_shndx = SHN_ABS;
11466       osymbuf[src_count].symbol.value += sympp[src_count]->section->vma;
11467       osymbuf[src_count].internal_elf_sym.st_value =
11468         osymbuf[src_count].symbol.value;
11469       sympp[src_count] = &osymbuf[src_count].symbol;
11470     }
11471
11472   bfd_set_symtab (implib_bfd, sympp, symcount);
11473
11474   /* Allow the BFD backend to copy any private data it understands
11475      from the output BFD to the import library BFD.  This is done last
11476      to permit the routine to look at the filtered symbol table.  */
11477   if (! bfd_copy_private_bfd_data (abfd, implib_bfd))
11478     goto free_sym_buf;
11479
11480   if (!bfd_close (implib_bfd))
11481     goto free_sym_buf;
11482
11483   ret = TRUE;
11484
11485 free_sym_buf:
11486   free (sympp);
11487   return ret;
11488 }
11489
11490 static void
11491 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
11492 {
11493   asection *o;
11494
11495   if (flinfo->symstrtab != NULL)
11496     _bfd_elf_strtab_free (flinfo->symstrtab);
11497   if (flinfo->contents != NULL)
11498     free (flinfo->contents);
11499   if (flinfo->external_relocs != NULL)
11500     free (flinfo->external_relocs);
11501   if (flinfo->internal_relocs != NULL)
11502     free (flinfo->internal_relocs);
11503   if (flinfo->external_syms != NULL)
11504     free (flinfo->external_syms);
11505   if (flinfo->locsym_shndx != NULL)
11506     free (flinfo->locsym_shndx);
11507   if (flinfo->internal_syms != NULL)
11508     free (flinfo->internal_syms);
11509   if (flinfo->indices != NULL)
11510     free (flinfo->indices);
11511   if (flinfo->sections != NULL)
11512     free (flinfo->sections);
11513   if (flinfo->symshndxbuf != NULL)
11514     free (flinfo->symshndxbuf);
11515   for (o = obfd->sections; o != NULL; o = o->next)
11516     {
11517       struct bfd_elf_section_data *esdo = elf_section_data (o);
11518       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11519         free (esdo->rel.hashes);
11520       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11521         free (esdo->rela.hashes);
11522     }
11523 }
11524
11525 /* Do the final step of an ELF link.  */
11526
11527 bfd_boolean
11528 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
11529 {
11530   bfd_boolean dynamic;
11531   bfd_boolean emit_relocs;
11532   bfd *dynobj;
11533   struct elf_final_link_info flinfo;
11534   asection *o;
11535   struct bfd_link_order *p;
11536   bfd *sub;
11537   bfd_size_type max_contents_size;
11538   bfd_size_type max_external_reloc_size;
11539   bfd_size_type max_internal_reloc_count;
11540   bfd_size_type max_sym_count;
11541   bfd_size_type max_sym_shndx_count;
11542   Elf_Internal_Sym elfsym;
11543   unsigned int i;
11544   Elf_Internal_Shdr *symtab_hdr;
11545   Elf_Internal_Shdr *symtab_shndx_hdr;
11546   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11547   struct elf_outext_info eoinfo;
11548   bfd_boolean merged;
11549   size_t relativecount = 0;
11550   asection *reldyn = 0;
11551   bfd_size_type amt;
11552   asection *attr_section = NULL;
11553   bfd_vma attr_size = 0;
11554   const char *std_attrs_section;
11555   struct elf_link_hash_table *htab = elf_hash_table (info);
11556
11557   if (!is_elf_hash_table (htab))
11558     return FALSE;
11559
11560   if (bfd_link_pic (info))
11561     abfd->flags |= DYNAMIC;
11562
11563   dynamic = htab->dynamic_sections_created;
11564   dynobj = htab->dynobj;
11565
11566   emit_relocs = (bfd_link_relocatable (info)
11567                  || info->emitrelocations);
11568
11569   flinfo.info = info;
11570   flinfo.output_bfd = abfd;
11571   flinfo.symstrtab = _bfd_elf_strtab_init ();
11572   if (flinfo.symstrtab == NULL)
11573     return FALSE;
11574
11575   if (! dynamic)
11576     {
11577       flinfo.hash_sec = NULL;
11578       flinfo.symver_sec = NULL;
11579     }
11580   else
11581     {
11582       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
11583       /* Note that dynsym_sec can be NULL (on VMS).  */
11584       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
11585       /* Note that it is OK if symver_sec is NULL.  */
11586     }
11587
11588   flinfo.contents = NULL;
11589   flinfo.external_relocs = NULL;
11590   flinfo.internal_relocs = NULL;
11591   flinfo.external_syms = NULL;
11592   flinfo.locsym_shndx = NULL;
11593   flinfo.internal_syms = NULL;
11594   flinfo.indices = NULL;
11595   flinfo.sections = NULL;
11596   flinfo.symshndxbuf = NULL;
11597   flinfo.filesym_count = 0;
11598
11599   /* The object attributes have been merged.  Remove the input
11600      sections from the link, and set the contents of the output
11601      secton.  */
11602   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
11603   for (o = abfd->sections; o != NULL; o = o->next)
11604     {
11605       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
11606           || strcmp (o->name, ".gnu.attributes") == 0)
11607         {
11608           for (p = o->map_head.link_order; p != NULL; p = p->next)
11609             {
11610               asection *input_section;
11611
11612               if (p->type != bfd_indirect_link_order)
11613                 continue;
11614               input_section = p->u.indirect.section;
11615               /* Hack: reset the SEC_HAS_CONTENTS flag so that
11616                  elf_link_input_bfd ignores this section.  */
11617               input_section->flags &= ~SEC_HAS_CONTENTS;
11618             }
11619
11620           attr_size = bfd_elf_obj_attr_size (abfd);
11621           if (attr_size)
11622             {
11623               bfd_set_section_size (abfd, o, attr_size);
11624               attr_section = o;
11625               /* Skip this section later on.  */
11626               o->map_head.link_order = NULL;
11627             }
11628           else
11629             o->flags |= SEC_EXCLUDE;
11630         }
11631       else if ((o->flags & SEC_GROUP) != 0 && o->size == 0)
11632         {
11633           /* Remove empty group section from linker output.  */
11634           o->flags |= SEC_EXCLUDE;
11635           bfd_section_list_remove (abfd, o);
11636           abfd->section_count--;
11637         }
11638     }
11639
11640   /* Count up the number of relocations we will output for each output
11641      section, so that we know the sizes of the reloc sections.  We
11642      also figure out some maximum sizes.  */
11643   max_contents_size = 0;
11644   max_external_reloc_size = 0;
11645   max_internal_reloc_count = 0;
11646   max_sym_count = 0;
11647   max_sym_shndx_count = 0;
11648   merged = FALSE;
11649   for (o = abfd->sections; o != NULL; o = o->next)
11650     {
11651       struct bfd_elf_section_data *esdo = elf_section_data (o);
11652       o->reloc_count = 0;
11653
11654       for (p = o->map_head.link_order; p != NULL; p = p->next)
11655         {
11656           unsigned int reloc_count = 0;
11657           unsigned int additional_reloc_count = 0;
11658           struct bfd_elf_section_data *esdi = NULL;
11659
11660           if (p->type == bfd_section_reloc_link_order
11661               || p->type == bfd_symbol_reloc_link_order)
11662             reloc_count = 1;
11663           else if (p->type == bfd_indirect_link_order)
11664             {
11665               asection *sec;
11666
11667               sec = p->u.indirect.section;
11668
11669               /* Mark all sections which are to be included in the
11670                  link.  This will normally be every section.  We need
11671                  to do this so that we can identify any sections which
11672                  the linker has decided to not include.  */
11673               sec->linker_mark = TRUE;
11674
11675               if (sec->flags & SEC_MERGE)
11676                 merged = TRUE;
11677
11678               if (sec->rawsize > max_contents_size)
11679                 max_contents_size = sec->rawsize;
11680               if (sec->size > max_contents_size)
11681                 max_contents_size = sec->size;
11682
11683               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
11684                   && (sec->owner->flags & DYNAMIC) == 0)
11685                 {
11686                   size_t sym_count;
11687
11688                   /* We are interested in just local symbols, not all
11689                      symbols.  */
11690                   if (elf_bad_symtab (sec->owner))
11691                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
11692                                  / bed->s->sizeof_sym);
11693                   else
11694                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
11695
11696                   if (sym_count > max_sym_count)
11697                     max_sym_count = sym_count;
11698
11699                   if (sym_count > max_sym_shndx_count
11700                       && elf_symtab_shndx_list (sec->owner) != NULL)
11701                     max_sym_shndx_count = sym_count;
11702
11703                   if (esdo->this_hdr.sh_type == SHT_REL
11704                       || esdo->this_hdr.sh_type == SHT_RELA)
11705                     /* Some backends use reloc_count in relocation sections
11706                        to count particular types of relocs.  Of course,
11707                        reloc sections themselves can't have relocations.  */
11708                     ;
11709                   else if (emit_relocs)
11710                     {
11711                       reloc_count = sec->reloc_count;
11712                       if (bed->elf_backend_count_additional_relocs)
11713                         {
11714                           int c;
11715                           c = (*bed->elf_backend_count_additional_relocs) (sec);
11716                           additional_reloc_count += c;
11717                         }
11718                     }
11719                   else if (bed->elf_backend_count_relocs)
11720                     reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
11721
11722                   esdi = elf_section_data (sec);
11723
11724                   if ((sec->flags & SEC_RELOC) != 0)
11725                     {
11726                       size_t ext_size = 0;
11727
11728                       if (esdi->rel.hdr != NULL)
11729                         ext_size = esdi->rel.hdr->sh_size;
11730                       if (esdi->rela.hdr != NULL)
11731                         ext_size += esdi->rela.hdr->sh_size;
11732
11733                       if (ext_size > max_external_reloc_size)
11734                         max_external_reloc_size = ext_size;
11735                       if (sec->reloc_count > max_internal_reloc_count)
11736                         max_internal_reloc_count = sec->reloc_count;
11737                     }
11738                 }
11739             }
11740
11741           if (reloc_count == 0)
11742             continue;
11743
11744           reloc_count += additional_reloc_count;
11745           o->reloc_count += reloc_count;
11746
11747           if (p->type == bfd_indirect_link_order && emit_relocs)
11748             {
11749               if (esdi->rel.hdr)
11750                 {
11751                   esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11752                   esdo->rel.count += additional_reloc_count;
11753                 }
11754               if (esdi->rela.hdr)
11755                 {
11756                   esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11757                   esdo->rela.count += additional_reloc_count;
11758                 }
11759             }
11760           else
11761             {
11762               if (o->use_rela_p)
11763                 esdo->rela.count += reloc_count;
11764               else
11765                 esdo->rel.count += reloc_count;
11766             }
11767         }
11768
11769       if (o->reloc_count > 0)
11770         o->flags |= SEC_RELOC;
11771       else
11772         {
11773           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11774              set it (this is probably a bug) and if it is set
11775              assign_section_numbers will create a reloc section.  */
11776           o->flags &=~ SEC_RELOC;
11777         }
11778
11779       /* If the SEC_ALLOC flag is not set, force the section VMA to
11780          zero.  This is done in elf_fake_sections as well, but forcing
11781          the VMA to 0 here will ensure that relocs against these
11782          sections are handled correctly.  */
11783       if ((o->flags & SEC_ALLOC) == 0
11784           && ! o->user_set_vma)
11785         o->vma = 0;
11786     }
11787
11788   if (! bfd_link_relocatable (info) && merged)
11789     elf_link_hash_traverse (htab, _bfd_elf_link_sec_merge_syms, abfd);
11790
11791   /* Figure out the file positions for everything but the symbol table
11792      and the relocs.  We set symcount to force assign_section_numbers
11793      to create a symbol table.  */
11794   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11795   BFD_ASSERT (! abfd->output_has_begun);
11796   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11797     goto error_return;
11798
11799   /* Set sizes, and assign file positions for reloc sections.  */
11800   for (o = abfd->sections; o != NULL; o = o->next)
11801     {
11802       struct bfd_elf_section_data *esdo = elf_section_data (o);
11803       if ((o->flags & SEC_RELOC) != 0)
11804         {
11805           if (esdo->rel.hdr
11806               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11807             goto error_return;
11808
11809           if (esdo->rela.hdr
11810               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11811             goto error_return;
11812         }
11813
11814       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
11815          to count upwards while actually outputting the relocations.  */
11816       esdo->rel.count = 0;
11817       esdo->rela.count = 0;
11818
11819       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
11820         {
11821           /* Cache the section contents so that they can be compressed
11822              later.  Use bfd_malloc since it will be freed by
11823              bfd_compress_section_contents.  */
11824           unsigned char *contents = esdo->this_hdr.contents;
11825           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
11826             abort ();
11827           contents
11828             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
11829           if (contents == NULL)
11830             goto error_return;
11831           esdo->this_hdr.contents = contents;
11832         }
11833     }
11834
11835   /* We have now assigned file positions for all the sections except
11836      .symtab, .strtab, and non-loaded reloc sections.  We start the
11837      .symtab section at the current file position, and write directly
11838      to it.  We build the .strtab section in memory.  */
11839   bfd_get_symcount (abfd) = 0;
11840   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11841   /* sh_name is set in prep_headers.  */
11842   symtab_hdr->sh_type = SHT_SYMTAB;
11843   /* sh_flags, sh_addr and sh_size all start off zero.  */
11844   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
11845   /* sh_link is set in assign_section_numbers.  */
11846   /* sh_info is set below.  */
11847   /* sh_offset is set just below.  */
11848   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
11849
11850   if (max_sym_count < 20)
11851     max_sym_count = 20;
11852   htab->strtabsize = max_sym_count;
11853   amt = max_sym_count * sizeof (struct elf_sym_strtab);
11854   htab->strtab = (struct elf_sym_strtab *) bfd_malloc (amt);
11855   if (htab->strtab == NULL)
11856     goto error_return;
11857   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
11858   flinfo.symshndxbuf
11859     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
11860        ? (Elf_External_Sym_Shndx *) -1 : NULL);
11861
11862   if (info->strip != strip_all || emit_relocs)
11863     {
11864       file_ptr off = elf_next_file_pos (abfd);
11865
11866       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
11867
11868       /* Note that at this point elf_next_file_pos (abfd) is
11869          incorrect.  We do not yet know the size of the .symtab section.
11870          We correct next_file_pos below, after we do know the size.  */
11871
11872       /* Start writing out the symbol table.  The first symbol is always a
11873          dummy symbol.  */
11874       elfsym.st_value = 0;
11875       elfsym.st_size = 0;
11876       elfsym.st_info = 0;
11877       elfsym.st_other = 0;
11878       elfsym.st_shndx = SHN_UNDEF;
11879       elfsym.st_target_internal = 0;
11880       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
11881                                      bfd_und_section_ptr, NULL) != 1)
11882         goto error_return;
11883
11884       /* Output a symbol for each section.  We output these even if we are
11885          discarding local symbols, since they are used for relocs.  These
11886          symbols have no names.  We store the index of each one in the
11887          index field of the section, so that we can find it again when
11888          outputting relocs.  */
11889
11890       elfsym.st_size = 0;
11891       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11892       elfsym.st_other = 0;
11893       elfsym.st_value = 0;
11894       elfsym.st_target_internal = 0;
11895       for (i = 1; i < elf_numsections (abfd); i++)
11896         {
11897           o = bfd_section_from_elf_index (abfd, i);
11898           if (o != NULL)
11899             {
11900               o->target_index = bfd_get_symcount (abfd);
11901               elfsym.st_shndx = i;
11902               if (!bfd_link_relocatable (info))
11903                 elfsym.st_value = o->vma;
11904               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
11905                                              NULL) != 1)
11906                 goto error_return;
11907             }
11908         }
11909     }
11910
11911   /* Allocate some memory to hold information read in from the input
11912      files.  */
11913   if (max_contents_size != 0)
11914     {
11915       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
11916       if (flinfo.contents == NULL)
11917         goto error_return;
11918     }
11919
11920   if (max_external_reloc_size != 0)
11921     {
11922       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
11923       if (flinfo.external_relocs == NULL)
11924         goto error_return;
11925     }
11926
11927   if (max_internal_reloc_count != 0)
11928     {
11929       amt = max_internal_reloc_count * sizeof (Elf_Internal_Rela);
11930       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
11931       if (flinfo.internal_relocs == NULL)
11932         goto error_return;
11933     }
11934
11935   if (max_sym_count != 0)
11936     {
11937       amt = max_sym_count * bed->s->sizeof_sym;
11938       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
11939       if (flinfo.external_syms == NULL)
11940         goto error_return;
11941
11942       amt = max_sym_count * sizeof (Elf_Internal_Sym);
11943       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
11944       if (flinfo.internal_syms == NULL)
11945         goto error_return;
11946
11947       amt = max_sym_count * sizeof (long);
11948       flinfo.indices = (long int *) bfd_malloc (amt);
11949       if (flinfo.indices == NULL)
11950         goto error_return;
11951
11952       amt = max_sym_count * sizeof (asection *);
11953       flinfo.sections = (asection **) bfd_malloc (amt);
11954       if (flinfo.sections == NULL)
11955         goto error_return;
11956     }
11957
11958   if (max_sym_shndx_count != 0)
11959     {
11960       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
11961       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
11962       if (flinfo.locsym_shndx == NULL)
11963         goto error_return;
11964     }
11965
11966   if (htab->tls_sec)
11967     {
11968       bfd_vma base, end = 0;
11969       asection *sec;
11970
11971       for (sec = htab->tls_sec;
11972            sec && (sec->flags & SEC_THREAD_LOCAL);
11973            sec = sec->next)
11974         {
11975           bfd_size_type size = sec->size;
11976
11977           if (size == 0
11978               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11979             {
11980               struct bfd_link_order *ord = sec->map_tail.link_order;
11981
11982               if (ord != NULL)
11983                 size = ord->offset + ord->size;
11984             }
11985           end = sec->vma + size;
11986         }
11987       base = htab->tls_sec->vma;
11988       /* Only align end of TLS section if static TLS doesn't have special
11989          alignment requirements.  */
11990       if (bed->static_tls_alignment == 1)
11991         end = align_power (end, htab->tls_sec->alignment_power);
11992       htab->tls_size = end - base;
11993     }
11994
11995   /* Reorder SHF_LINK_ORDER sections.  */
11996   for (o = abfd->sections; o != NULL; o = o->next)
11997     {
11998       if (!elf_fixup_link_order (abfd, o))
11999         return FALSE;
12000     }
12001
12002   if (!_bfd_elf_fixup_eh_frame_hdr (info))
12003     return FALSE;
12004
12005   /* Since ELF permits relocations to be against local symbols, we
12006      must have the local symbols available when we do the relocations.
12007      Since we would rather only read the local symbols once, and we
12008      would rather not keep them in memory, we handle all the
12009      relocations for a single input file at the same time.
12010
12011      Unfortunately, there is no way to know the total number of local
12012      symbols until we have seen all of them, and the local symbol
12013      indices precede the global symbol indices.  This means that when
12014      we are generating relocatable output, and we see a reloc against
12015      a global symbol, we can not know the symbol index until we have
12016      finished examining all the local symbols to see which ones we are
12017      going to output.  To deal with this, we keep the relocations in
12018      memory, and don't output them until the end of the link.  This is
12019      an unfortunate waste of memory, but I don't see a good way around
12020      it.  Fortunately, it only happens when performing a relocatable
12021      link, which is not the common case.  FIXME: If keep_memory is set
12022      we could write the relocs out and then read them again; I don't
12023      know how bad the memory loss will be.  */
12024
12025   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12026     sub->output_has_begun = FALSE;
12027   for (o = abfd->sections; o != NULL; o = o->next)
12028     {
12029       for (p = o->map_head.link_order; p != NULL; p = p->next)
12030         {
12031           if (p->type == bfd_indirect_link_order
12032               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
12033                   == bfd_target_elf_flavour)
12034               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
12035             {
12036               if (! sub->output_has_begun)
12037                 {
12038                   if (! elf_link_input_bfd (&flinfo, sub))
12039                     goto error_return;
12040                   sub->output_has_begun = TRUE;
12041                 }
12042             }
12043           else if (p->type == bfd_section_reloc_link_order
12044                    || p->type == bfd_symbol_reloc_link_order)
12045             {
12046               if (! elf_reloc_link_order (abfd, info, o, p))
12047                 goto error_return;
12048             }
12049           else
12050             {
12051               if (! _bfd_default_link_order (abfd, info, o, p))
12052                 {
12053                   if (p->type == bfd_indirect_link_order
12054                       && (bfd_get_flavour (sub)
12055                           == bfd_target_elf_flavour)
12056                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
12057                           != bed->s->elfclass))
12058                     {
12059                       const char *iclass, *oclass;
12060
12061                       switch (bed->s->elfclass)
12062                         {
12063                         case ELFCLASS64: oclass = "ELFCLASS64"; break;
12064                         case ELFCLASS32: oclass = "ELFCLASS32"; break;
12065                         case ELFCLASSNONE: oclass = "ELFCLASSNONE"; break;
12066                         default: abort ();
12067                         }
12068
12069                       switch (elf_elfheader (sub)->e_ident[EI_CLASS])
12070                         {
12071                         case ELFCLASS64: iclass = "ELFCLASS64"; break;
12072                         case ELFCLASS32: iclass = "ELFCLASS32"; break;
12073                         case ELFCLASSNONE: iclass = "ELFCLASSNONE"; break;
12074                         default: abort ();
12075                         }
12076
12077                       bfd_set_error (bfd_error_wrong_format);
12078                       _bfd_error_handler
12079                         /* xgettext:c-format */
12080                         (_("%pB: file class %s incompatible with %s"),
12081                          sub, iclass, oclass);
12082                     }
12083
12084                   goto error_return;
12085                 }
12086             }
12087         }
12088     }
12089
12090   /* Free symbol buffer if needed.  */
12091   if (!info->reduce_memory_overheads)
12092     {
12093       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12094         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
12095             && elf_tdata (sub)->symbuf)
12096           {
12097             free (elf_tdata (sub)->symbuf);
12098             elf_tdata (sub)->symbuf = NULL;
12099           }
12100     }
12101
12102   /* Output any global symbols that got converted to local in a
12103      version script or due to symbol visibility.  We do this in a
12104      separate step since ELF requires all local symbols to appear
12105      prior to any global symbols.  FIXME: We should only do this if
12106      some global symbols were, in fact, converted to become local.
12107      FIXME: Will this work correctly with the Irix 5 linker?  */
12108   eoinfo.failed = FALSE;
12109   eoinfo.flinfo = &flinfo;
12110   eoinfo.localsyms = TRUE;
12111   eoinfo.file_sym_done = FALSE;
12112   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12113   if (eoinfo.failed)
12114     return FALSE;
12115
12116   /* If backend needs to output some local symbols not present in the hash
12117      table, do it now.  */
12118   if (bed->elf_backend_output_arch_local_syms
12119       && (info->strip != strip_all || emit_relocs))
12120     {
12121       typedef int (*out_sym_func)
12122         (void *, const char *, Elf_Internal_Sym *, asection *,
12123          struct elf_link_hash_entry *);
12124
12125       if (! ((*bed->elf_backend_output_arch_local_syms)
12126              (abfd, info, &flinfo,
12127               (out_sym_func) elf_link_output_symstrtab)))
12128         return FALSE;
12129     }
12130
12131   /* That wrote out all the local symbols.  Finish up the symbol table
12132      with the global symbols. Even if we want to strip everything we
12133      can, we still need to deal with those global symbols that got
12134      converted to local in a version script.  */
12135
12136   /* The sh_info field records the index of the first non local symbol.  */
12137   symtab_hdr->sh_info = bfd_get_symcount (abfd);
12138
12139   if (dynamic
12140       && htab->dynsym != NULL
12141       && htab->dynsym->output_section != bfd_abs_section_ptr)
12142     {
12143       Elf_Internal_Sym sym;
12144       bfd_byte *dynsym = htab->dynsym->contents;
12145
12146       o = htab->dynsym->output_section;
12147       elf_section_data (o)->this_hdr.sh_info = htab->local_dynsymcount + 1;
12148
12149       /* Write out the section symbols for the output sections.  */
12150       if (bfd_link_pic (info)
12151           || htab->is_relocatable_executable)
12152         {
12153           asection *s;
12154
12155           sym.st_size = 0;
12156           sym.st_name = 0;
12157           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
12158           sym.st_other = 0;
12159           sym.st_target_internal = 0;
12160
12161           for (s = abfd->sections; s != NULL; s = s->next)
12162             {
12163               int indx;
12164               bfd_byte *dest;
12165               long dynindx;
12166
12167               dynindx = elf_section_data (s)->dynindx;
12168               if (dynindx <= 0)
12169                 continue;
12170               indx = elf_section_data (s)->this_idx;
12171               BFD_ASSERT (indx > 0);
12172               sym.st_shndx = indx;
12173               if (! check_dynsym (abfd, &sym))
12174                 return FALSE;
12175               sym.st_value = s->vma;
12176               dest = dynsym + dynindx * bed->s->sizeof_sym;
12177               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12178             }
12179         }
12180
12181       /* Write out the local dynsyms.  */
12182       if (htab->dynlocal)
12183         {
12184           struct elf_link_local_dynamic_entry *e;
12185           for (e = htab->dynlocal; e ; e = e->next)
12186             {
12187               asection *s;
12188               bfd_byte *dest;
12189
12190               /* Copy the internal symbol and turn off visibility.
12191                  Note that we saved a word of storage and overwrote
12192                  the original st_name with the dynstr_index.  */
12193               sym = e->isym;
12194               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
12195
12196               s = bfd_section_from_elf_index (e->input_bfd,
12197                                               e->isym.st_shndx);
12198               if (s != NULL)
12199                 {
12200                   sym.st_shndx =
12201                     elf_section_data (s->output_section)->this_idx;
12202                   if (! check_dynsym (abfd, &sym))
12203                     return FALSE;
12204                   sym.st_value = (s->output_section->vma
12205                                   + s->output_offset
12206                                   + e->isym.st_value);
12207                 }
12208
12209               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
12210               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12211             }
12212         }
12213     }
12214
12215   /* We get the global symbols from the hash table.  */
12216   eoinfo.failed = FALSE;
12217   eoinfo.localsyms = FALSE;
12218   eoinfo.flinfo = &flinfo;
12219   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12220   if (eoinfo.failed)
12221     return FALSE;
12222
12223   /* If backend needs to output some symbols not present in the hash
12224      table, do it now.  */
12225   if (bed->elf_backend_output_arch_syms
12226       && (info->strip != strip_all || emit_relocs))
12227     {
12228       typedef int (*out_sym_func)
12229         (void *, const char *, Elf_Internal_Sym *, asection *,
12230          struct elf_link_hash_entry *);
12231
12232       if (! ((*bed->elf_backend_output_arch_syms)
12233              (abfd, info, &flinfo,
12234               (out_sym_func) elf_link_output_symstrtab)))
12235         return FALSE;
12236     }
12237
12238   /* Finalize the .strtab section.  */
12239   _bfd_elf_strtab_finalize (flinfo.symstrtab);
12240
12241   /* Swap out the .strtab section. */
12242   if (!elf_link_swap_symbols_out (&flinfo))
12243     return FALSE;
12244
12245   /* Now we know the size of the symtab section.  */
12246   if (bfd_get_symcount (abfd) > 0)
12247     {
12248       /* Finish up and write out the symbol string table (.strtab)
12249          section.  */
12250       Elf_Internal_Shdr *symstrtab_hdr = NULL;
12251       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
12252
12253       if (elf_symtab_shndx_list (abfd))
12254         {
12255           symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
12256
12257           if (symtab_shndx_hdr != NULL && symtab_shndx_hdr->sh_name != 0)
12258             {
12259               symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
12260               symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
12261               symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
12262               amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
12263               symtab_shndx_hdr->sh_size = amt;
12264
12265               off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
12266                                                                off, TRUE);
12267
12268               if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
12269                   || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
12270                 return FALSE;
12271             }
12272         }
12273
12274       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
12275       /* sh_name was set in prep_headers.  */
12276       symstrtab_hdr->sh_type = SHT_STRTAB;
12277       symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
12278       symstrtab_hdr->sh_addr = 0;
12279       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
12280       symstrtab_hdr->sh_entsize = 0;
12281       symstrtab_hdr->sh_link = 0;
12282       symstrtab_hdr->sh_info = 0;
12283       /* sh_offset is set just below.  */
12284       symstrtab_hdr->sh_addralign = 1;
12285
12286       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
12287                                                        off, TRUE);
12288       elf_next_file_pos (abfd) = off;
12289
12290       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
12291           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
12292         return FALSE;
12293     }
12294
12295   if (info->out_implib_bfd && !elf_output_implib (abfd, info))
12296     {
12297       _bfd_error_handler (_("%pB: failed to generate import library"),
12298                           info->out_implib_bfd);
12299       return FALSE;
12300     }
12301
12302   /* Adjust the relocs to have the correct symbol indices.  */
12303   for (o = abfd->sections; o != NULL; o = o->next)
12304     {
12305       struct bfd_elf_section_data *esdo = elf_section_data (o);
12306       bfd_boolean sort;
12307
12308       if ((o->flags & SEC_RELOC) == 0)
12309         continue;
12310
12311       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
12312       if (esdo->rel.hdr != NULL
12313           && !elf_link_adjust_relocs (abfd, o, &esdo->rel, sort, info))
12314         return FALSE;
12315       if (esdo->rela.hdr != NULL
12316           && !elf_link_adjust_relocs (abfd, o, &esdo->rela, sort, info))
12317         return FALSE;
12318
12319       /* Set the reloc_count field to 0 to prevent write_relocs from
12320          trying to swap the relocs out itself.  */
12321       o->reloc_count = 0;
12322     }
12323
12324   if (dynamic && info->combreloc && dynobj != NULL)
12325     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
12326
12327   /* If we are linking against a dynamic object, or generating a
12328      shared library, finish up the dynamic linking information.  */
12329   if (dynamic)
12330     {
12331       bfd_byte *dyncon, *dynconend;
12332
12333       /* Fix up .dynamic entries.  */
12334       o = bfd_get_linker_section (dynobj, ".dynamic");
12335       BFD_ASSERT (o != NULL);
12336
12337       dyncon = o->contents;
12338       dynconend = o->contents + o->size;
12339       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12340         {
12341           Elf_Internal_Dyn dyn;
12342           const char *name;
12343           unsigned int type;
12344           bfd_size_type sh_size;
12345           bfd_vma sh_addr;
12346
12347           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12348
12349           switch (dyn.d_tag)
12350             {
12351             default:
12352               continue;
12353             case DT_NULL:
12354               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
12355                 {
12356                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
12357                     {
12358                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
12359                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
12360                     default: continue;
12361                     }
12362                   dyn.d_un.d_val = relativecount;
12363                   relativecount = 0;
12364                   break;
12365                 }
12366               continue;
12367
12368             case DT_INIT:
12369               name = info->init_function;
12370               goto get_sym;
12371             case DT_FINI:
12372               name = info->fini_function;
12373             get_sym:
12374               {
12375                 struct elf_link_hash_entry *h;
12376
12377                 h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
12378                 if (h != NULL
12379                     && (h->root.type == bfd_link_hash_defined
12380                         || h->root.type == bfd_link_hash_defweak))
12381                   {
12382                     dyn.d_un.d_ptr = h->root.u.def.value;
12383                     o = h->root.u.def.section;
12384                     if (o->output_section != NULL)
12385                       dyn.d_un.d_ptr += (o->output_section->vma
12386                                          + o->output_offset);
12387                     else
12388                       {
12389                         /* The symbol is imported from another shared
12390                            library and does not apply to this one.  */
12391                         dyn.d_un.d_ptr = 0;
12392                       }
12393                     break;
12394                   }
12395               }
12396               continue;
12397
12398             case DT_PREINIT_ARRAYSZ:
12399               name = ".preinit_array";
12400               goto get_out_size;
12401             case DT_INIT_ARRAYSZ:
12402               name = ".init_array";
12403               goto get_out_size;
12404             case DT_FINI_ARRAYSZ:
12405               name = ".fini_array";
12406             get_out_size:
12407               o = bfd_get_section_by_name (abfd, name);
12408               if (o == NULL)
12409                 {
12410                   _bfd_error_handler
12411                     (_("could not find section %s"), name);
12412                   goto error_return;
12413                 }
12414               if (o->size == 0)
12415                 _bfd_error_handler
12416                   (_("warning: %s section has zero size"), name);
12417               dyn.d_un.d_val = o->size;
12418               break;
12419
12420             case DT_PREINIT_ARRAY:
12421               name = ".preinit_array";
12422               goto get_out_vma;
12423             case DT_INIT_ARRAY:
12424               name = ".init_array";
12425               goto get_out_vma;
12426             case DT_FINI_ARRAY:
12427               name = ".fini_array";
12428             get_out_vma:
12429               o = bfd_get_section_by_name (abfd, name);
12430               goto do_vma;
12431
12432             case DT_HASH:
12433               name = ".hash";
12434               goto get_vma;
12435             case DT_GNU_HASH:
12436               name = ".gnu.hash";
12437               goto get_vma;
12438             case DT_STRTAB:
12439               name = ".dynstr";
12440               goto get_vma;
12441             case DT_SYMTAB:
12442               name = ".dynsym";
12443               goto get_vma;
12444             case DT_VERDEF:
12445               name = ".gnu.version_d";
12446               goto get_vma;
12447             case DT_VERNEED:
12448               name = ".gnu.version_r";
12449               goto get_vma;
12450             case DT_VERSYM:
12451               name = ".gnu.version";
12452             get_vma:
12453               o = bfd_get_linker_section (dynobj, name);
12454             do_vma:
12455               if (o == NULL || bfd_is_abs_section (o->output_section))
12456                 {
12457                   _bfd_error_handler
12458                     (_("could not find section %s"), name);
12459                   goto error_return;
12460                 }
12461               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
12462                 {
12463                   _bfd_error_handler
12464                     (_("warning: section '%s' is being made into a note"), name);
12465                   bfd_set_error (bfd_error_nonrepresentable_section);
12466                   goto error_return;
12467                 }
12468               dyn.d_un.d_ptr = o->output_section->vma + o->output_offset;
12469               break;
12470
12471             case DT_REL:
12472             case DT_RELA:
12473             case DT_RELSZ:
12474             case DT_RELASZ:
12475               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
12476                 type = SHT_REL;
12477               else
12478                 type = SHT_RELA;
12479               sh_size = 0;
12480               sh_addr = 0;
12481               for (i = 1; i < elf_numsections (abfd); i++)
12482                 {
12483                   Elf_Internal_Shdr *hdr;
12484
12485                   hdr = elf_elfsections (abfd)[i];
12486                   if (hdr->sh_type == type
12487                       && (hdr->sh_flags & SHF_ALLOC) != 0)
12488                     {
12489                       sh_size += hdr->sh_size;
12490                       if (sh_addr == 0
12491                           || sh_addr > hdr->sh_addr)
12492                         sh_addr = hdr->sh_addr;
12493                     }
12494                 }
12495
12496               if (bed->dtrel_excludes_plt && htab->srelplt != NULL)
12497                 {
12498                   /* Don't count procedure linkage table relocs in the
12499                      overall reloc count.  */
12500                   sh_size -= htab->srelplt->size;
12501                   if (sh_size == 0)
12502                     /* If the size is zero, make the address zero too.
12503                        This is to avoid a glibc bug.  If the backend
12504                        emits DT_RELA/DT_RELASZ even when DT_RELASZ is
12505                        zero, then we'll put DT_RELA at the end of
12506                        DT_JMPREL.  glibc will interpret the end of
12507                        DT_RELA matching the end of DT_JMPREL as the
12508                        case where DT_RELA includes DT_JMPREL, and for
12509                        LD_BIND_NOW will decide that processing DT_RELA
12510                        will process the PLT relocs too.  Net result:
12511                        No PLT relocs applied.  */
12512                     sh_addr = 0;
12513
12514                   /* If .rela.plt is the first .rela section, exclude
12515                      it from DT_RELA.  */
12516                   else if (sh_addr == (htab->srelplt->output_section->vma
12517                                        + htab->srelplt->output_offset))
12518                     sh_addr += htab->srelplt->size;
12519                 }
12520
12521               if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
12522                 dyn.d_un.d_val = sh_size;
12523               else
12524                 dyn.d_un.d_ptr = sh_addr;
12525               break;
12526             }
12527           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
12528         }
12529     }
12530
12531   /* If we have created any dynamic sections, then output them.  */
12532   if (dynobj != NULL)
12533     {
12534       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
12535         goto error_return;
12536
12537       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
12538       if (((info->warn_shared_textrel && bfd_link_pic (info))
12539            || info->error_textrel)
12540           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
12541         {
12542           bfd_byte *dyncon, *dynconend;
12543
12544           dyncon = o->contents;
12545           dynconend = o->contents + o->size;
12546           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12547             {
12548               Elf_Internal_Dyn dyn;
12549
12550               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12551
12552               if (dyn.d_tag == DT_TEXTREL)
12553                 {
12554                   if (info->error_textrel)
12555                     info->callbacks->einfo
12556                       (_("%P%X: read-only segment has dynamic relocations.\n"));
12557                   else
12558                     info->callbacks->einfo
12559                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
12560                   break;
12561                 }
12562             }
12563         }
12564
12565       for (o = dynobj->sections; o != NULL; o = o->next)
12566         {
12567           if ((o->flags & SEC_HAS_CONTENTS) == 0
12568               || o->size == 0
12569               || o->output_section == bfd_abs_section_ptr)
12570             continue;
12571           if ((o->flags & SEC_LINKER_CREATED) == 0)
12572             {
12573               /* At this point, we are only interested in sections
12574                  created by _bfd_elf_link_create_dynamic_sections.  */
12575               continue;
12576             }
12577           if (htab->stab_info.stabstr == o)
12578             continue;
12579           if (htab->eh_info.hdr_sec == o)
12580             continue;
12581           if (strcmp (o->name, ".dynstr") != 0)
12582             {
12583               if (! bfd_set_section_contents (abfd, o->output_section,
12584                                               o->contents,
12585                                               (file_ptr) o->output_offset
12586                                               * bfd_octets_per_byte (abfd),
12587                                               o->size))
12588                 goto error_return;
12589             }
12590           else
12591             {
12592               /* The contents of the .dynstr section are actually in a
12593                  stringtab.  */
12594               file_ptr off;
12595
12596               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
12597               if (bfd_seek (abfd, off, SEEK_SET) != 0
12598                   || !_bfd_elf_strtab_emit (abfd, htab->dynstr))
12599                 goto error_return;
12600             }
12601         }
12602     }
12603
12604   if (!info->resolve_section_groups)
12605     {
12606       bfd_boolean failed = FALSE;
12607
12608       BFD_ASSERT (bfd_link_relocatable (info));
12609       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
12610       if (failed)
12611         goto error_return;
12612     }
12613
12614   /* If we have optimized stabs strings, output them.  */
12615   if (htab->stab_info.stabstr != NULL)
12616     {
12617       if (!_bfd_write_stab_strings (abfd, &htab->stab_info))
12618         goto error_return;
12619     }
12620
12621   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
12622     goto error_return;
12623
12624   elf_final_link_free (abfd, &flinfo);
12625
12626   elf_linker (abfd) = TRUE;
12627
12628   if (attr_section)
12629     {
12630       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
12631       if (contents == NULL)
12632         return FALSE;   /* Bail out and fail.  */
12633       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
12634       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
12635       free (contents);
12636     }
12637
12638   return TRUE;
12639
12640  error_return:
12641   elf_final_link_free (abfd, &flinfo);
12642   return FALSE;
12643 }
12644 \f
12645 /* Initialize COOKIE for input bfd ABFD.  */
12646
12647 static bfd_boolean
12648 init_reloc_cookie (struct elf_reloc_cookie *cookie,
12649                    struct bfd_link_info *info, bfd *abfd)
12650 {
12651   Elf_Internal_Shdr *symtab_hdr;
12652   const struct elf_backend_data *bed;
12653
12654   bed = get_elf_backend_data (abfd);
12655   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12656
12657   cookie->abfd = abfd;
12658   cookie->sym_hashes = elf_sym_hashes (abfd);
12659   cookie->bad_symtab = elf_bad_symtab (abfd);
12660   if (cookie->bad_symtab)
12661     {
12662       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12663       cookie->extsymoff = 0;
12664     }
12665   else
12666     {
12667       cookie->locsymcount = symtab_hdr->sh_info;
12668       cookie->extsymoff = symtab_hdr->sh_info;
12669     }
12670
12671   if (bed->s->arch_size == 32)
12672     cookie->r_sym_shift = 8;
12673   else
12674     cookie->r_sym_shift = 32;
12675
12676   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
12677   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
12678     {
12679       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12680                                               cookie->locsymcount, 0,
12681                                               NULL, NULL, NULL);
12682       if (cookie->locsyms == NULL)
12683         {
12684           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
12685           return FALSE;
12686         }
12687       if (info->keep_memory)
12688         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
12689     }
12690   return TRUE;
12691 }
12692
12693 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
12694
12695 static void
12696 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
12697 {
12698   Elf_Internal_Shdr *symtab_hdr;
12699
12700   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12701   if (cookie->locsyms != NULL
12702       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
12703     free (cookie->locsyms);
12704 }
12705
12706 /* Initialize the relocation information in COOKIE for input section SEC
12707    of input bfd ABFD.  */
12708
12709 static bfd_boolean
12710 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12711                         struct bfd_link_info *info, bfd *abfd,
12712                         asection *sec)
12713 {
12714   if (sec->reloc_count == 0)
12715     {
12716       cookie->rels = NULL;
12717       cookie->relend = NULL;
12718     }
12719   else
12720     {
12721       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
12722                                                 info->keep_memory);
12723       if (cookie->rels == NULL)
12724         return FALSE;
12725       cookie->rel = cookie->rels;
12726       cookie->relend = cookie->rels + sec->reloc_count;
12727     }
12728   cookie->rel = cookie->rels;
12729   return TRUE;
12730 }
12731
12732 /* Free the memory allocated by init_reloc_cookie_rels,
12733    if appropriate.  */
12734
12735 static void
12736 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12737                         asection *sec)
12738 {
12739   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
12740     free (cookie->rels);
12741 }
12742
12743 /* Initialize the whole of COOKIE for input section SEC.  */
12744
12745 static bfd_boolean
12746 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12747                                struct bfd_link_info *info,
12748                                asection *sec)
12749 {
12750   if (!init_reloc_cookie (cookie, info, sec->owner))
12751     goto error1;
12752   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
12753     goto error2;
12754   return TRUE;
12755
12756  error2:
12757   fini_reloc_cookie (cookie, sec->owner);
12758  error1:
12759   return FALSE;
12760 }
12761
12762 /* Free the memory allocated by init_reloc_cookie_for_section,
12763    if appropriate.  */
12764
12765 static void
12766 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12767                                asection *sec)
12768 {
12769   fini_reloc_cookie_rels (cookie, sec);
12770   fini_reloc_cookie (cookie, sec->owner);
12771 }
12772 \f
12773 /* Garbage collect unused sections.  */
12774
12775 /* Default gc_mark_hook.  */
12776
12777 asection *
12778 _bfd_elf_gc_mark_hook (asection *sec,
12779                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12780                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12781                        struct elf_link_hash_entry *h,
12782                        Elf_Internal_Sym *sym)
12783 {
12784   if (h != NULL)
12785     {
12786       switch (h->root.type)
12787         {
12788         case bfd_link_hash_defined:
12789         case bfd_link_hash_defweak:
12790           return h->root.u.def.section;
12791
12792         case bfd_link_hash_common:
12793           return h->root.u.c.p->section;
12794
12795         default:
12796           break;
12797         }
12798     }
12799   else
12800     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12801
12802   return NULL;
12803 }
12804
12805 /* Return the global debug definition section.  */
12806
12807 static asection *
12808 elf_gc_mark_debug_section (asection *sec ATTRIBUTE_UNUSED,
12809                            struct bfd_link_info *info ATTRIBUTE_UNUSED,
12810                            Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12811                            struct elf_link_hash_entry *h,
12812                            Elf_Internal_Sym *sym ATTRIBUTE_UNUSED)
12813 {
12814   if (h != NULL
12815       && (h->root.type == bfd_link_hash_defined
12816           || h->root.type == bfd_link_hash_defweak)
12817       && (h->root.u.def.section->flags & SEC_DEBUGGING) != 0)
12818     return h->root.u.def.section;
12819
12820   return NULL;
12821 }
12822
12823 /* COOKIE->rel describes a relocation against section SEC, which is
12824    a section we've decided to keep.  Return the section that contains
12825    the relocation symbol, or NULL if no section contains it.  */
12826
12827 asection *
12828 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
12829                        elf_gc_mark_hook_fn gc_mark_hook,
12830                        struct elf_reloc_cookie *cookie,
12831                        bfd_boolean *start_stop)
12832 {
12833   unsigned long r_symndx;
12834   struct elf_link_hash_entry *h;
12835
12836   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
12837   if (r_symndx == STN_UNDEF)
12838     return NULL;
12839
12840   if (r_symndx >= cookie->locsymcount
12841       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12842     {
12843       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
12844       if (h == NULL)
12845         {
12846           info->callbacks->einfo (_("%F%P: corrupt input: %pB\n"),
12847                                   sec->owner);
12848           return NULL;
12849         }
12850       while (h->root.type == bfd_link_hash_indirect
12851              || h->root.type == bfd_link_hash_warning)
12852         h = (struct elf_link_hash_entry *) h->root.u.i.link;
12853       h->mark = 1;
12854       /* If this symbol is weak and there is a non-weak definition, we
12855          keep the non-weak definition because many backends put
12856          dynamic reloc info on the non-weak definition for code
12857          handling copy relocs.  */
12858       if (h->is_weakalias)
12859         weakdef (h)->mark = 1;
12860
12861       if (start_stop != NULL)
12862         {
12863           /* To work around a glibc bug, mark XXX input sections
12864              when there is a reference to __start_XXX or __stop_XXX
12865              symbols.  */
12866           if (h->start_stop)
12867             {
12868               asection *s = h->u2.start_stop_section;
12869               *start_stop = !s->gc_mark;
12870               return s;
12871             }
12872         }
12873
12874       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
12875     }
12876
12877   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
12878                           &cookie->locsyms[r_symndx]);
12879 }
12880
12881 /* COOKIE->rel describes a relocation against section SEC, which is
12882    a section we've decided to keep.  Mark the section that contains
12883    the relocation symbol.  */
12884
12885 bfd_boolean
12886 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
12887                         asection *sec,
12888                         elf_gc_mark_hook_fn gc_mark_hook,
12889                         struct elf_reloc_cookie *cookie)
12890 {
12891   asection *rsec;
12892   bfd_boolean start_stop = FALSE;
12893
12894   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie, &start_stop);
12895   while (rsec != NULL)
12896     {
12897       if (!rsec->gc_mark)
12898         {
12899           if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
12900               || (rsec->owner->flags & DYNAMIC) != 0)
12901             rsec->gc_mark = 1;
12902           else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
12903             return FALSE;
12904         }
12905       if (!start_stop)
12906         break;
12907       rsec = bfd_get_next_section_by_name (rsec->owner, rsec);
12908     }
12909   return TRUE;
12910 }
12911
12912 /* The mark phase of garbage collection.  For a given section, mark
12913    it and any sections in this section's group, and all the sections
12914    which define symbols to which it refers.  */
12915
12916 bfd_boolean
12917 _bfd_elf_gc_mark (struct bfd_link_info *info,
12918                   asection *sec,
12919                   elf_gc_mark_hook_fn gc_mark_hook)
12920 {
12921   bfd_boolean ret;
12922   asection *group_sec, *eh_frame;
12923
12924   sec->gc_mark = 1;
12925
12926   /* Mark all the sections in the group.  */
12927   group_sec = elf_section_data (sec)->next_in_group;
12928   if (group_sec && !group_sec->gc_mark)
12929     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
12930       return FALSE;
12931
12932   /* Look through the section relocs.  */
12933   ret = TRUE;
12934   eh_frame = elf_eh_frame_section (sec->owner);
12935   if ((sec->flags & SEC_RELOC) != 0
12936       && sec->reloc_count > 0
12937       && sec != eh_frame)
12938     {
12939       struct elf_reloc_cookie cookie;
12940
12941       if (!init_reloc_cookie_for_section (&cookie, info, sec))
12942         ret = FALSE;
12943       else
12944         {
12945           for (; cookie.rel < cookie.relend; cookie.rel++)
12946             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
12947               {
12948                 ret = FALSE;
12949                 break;
12950               }
12951           fini_reloc_cookie_for_section (&cookie, sec);
12952         }
12953     }
12954
12955   if (ret && eh_frame && elf_fde_list (sec))
12956     {
12957       struct elf_reloc_cookie cookie;
12958
12959       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
12960         ret = FALSE;
12961       else
12962         {
12963           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
12964                                       gc_mark_hook, &cookie))
12965             ret = FALSE;
12966           fini_reloc_cookie_for_section (&cookie, eh_frame);
12967         }
12968     }
12969
12970   eh_frame = elf_section_eh_frame_entry (sec);
12971   if (ret && eh_frame && !eh_frame->gc_mark)
12972     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
12973       ret = FALSE;
12974
12975   return ret;
12976 }
12977
12978 /* Scan and mark sections in a special or debug section group.  */
12979
12980 static void
12981 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
12982 {
12983   /* Point to first section of section group.  */
12984   asection *ssec;
12985   /* Used to iterate the section group.  */
12986   asection *msec;
12987
12988   bfd_boolean is_special_grp = TRUE;
12989   bfd_boolean is_debug_grp = TRUE;
12990
12991   /* First scan to see if group contains any section other than debug
12992      and special section.  */
12993   ssec = msec = elf_next_in_group (grp);
12994   do
12995     {
12996       if ((msec->flags & SEC_DEBUGGING) == 0)
12997         is_debug_grp = FALSE;
12998
12999       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
13000         is_special_grp = FALSE;
13001
13002       msec = elf_next_in_group (msec);
13003     }
13004   while (msec != ssec);
13005
13006   /* If this is a pure debug section group or pure special section group,
13007      keep all sections in this group.  */
13008   if (is_debug_grp || is_special_grp)
13009     {
13010       do
13011         {
13012           msec->gc_mark = 1;
13013           msec = elf_next_in_group (msec);
13014         }
13015       while (msec != ssec);
13016     }
13017 }
13018
13019 /* Keep debug and special sections.  */
13020
13021 bfd_boolean
13022 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
13023                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
13024 {
13025   bfd *ibfd;
13026
13027   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13028     {
13029       asection *isec;
13030       bfd_boolean some_kept;
13031       bfd_boolean debug_frag_seen;
13032       bfd_boolean has_kept_debug_info;
13033
13034       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13035         continue;
13036       isec = ibfd->sections;
13037       if (isec == NULL || isec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13038         continue;
13039
13040       /* Ensure all linker created sections are kept,
13041          see if any other section is already marked,
13042          and note if we have any fragmented debug sections.  */
13043       debug_frag_seen = some_kept = has_kept_debug_info = FALSE;
13044       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13045         {
13046           if ((isec->flags & SEC_LINKER_CREATED) != 0)
13047             isec->gc_mark = 1;
13048           else if (isec->gc_mark
13049                    && (isec->flags & SEC_ALLOC) != 0
13050                    && elf_section_type (isec) != SHT_NOTE)
13051             some_kept = TRUE;
13052
13053           if (!debug_frag_seen
13054               && (isec->flags & SEC_DEBUGGING)
13055               && CONST_STRNEQ (isec->name, ".debug_line."))
13056             debug_frag_seen = TRUE;
13057         }
13058
13059       /* If no non-note alloc section in this file will be kept, then
13060          we can toss out the debug and special sections.  */
13061       if (!some_kept)
13062         continue;
13063
13064       /* Keep debug and special sections like .comment when they are
13065          not part of a group.  Also keep section groups that contain
13066          just debug sections or special sections.  */
13067       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13068         {
13069           if ((isec->flags & SEC_GROUP) != 0)
13070             _bfd_elf_gc_mark_debug_special_section_group (isec);
13071           else if (((isec->flags & SEC_DEBUGGING) != 0
13072                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
13073                    && elf_next_in_group (isec) == NULL)
13074             isec->gc_mark = 1;
13075           if (isec->gc_mark && (isec->flags & SEC_DEBUGGING) != 0)
13076             has_kept_debug_info = TRUE;
13077         }
13078
13079       /* Look for CODE sections which are going to be discarded,
13080          and find and discard any fragmented debug sections which
13081          are associated with that code section.  */
13082       if (debug_frag_seen)
13083         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13084           if ((isec->flags & SEC_CODE) != 0
13085               && isec->gc_mark == 0)
13086             {
13087               unsigned int ilen;
13088               asection *dsec;
13089
13090               ilen = strlen (isec->name);
13091
13092               /* Association is determined by the name of the debug
13093                  section containing the name of the code section as
13094                  a suffix.  For example .debug_line.text.foo is a
13095                  debug section associated with .text.foo.  */
13096               for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
13097                 {
13098                   unsigned int dlen;
13099
13100                   if (dsec->gc_mark == 0
13101                       || (dsec->flags & SEC_DEBUGGING) == 0)
13102                     continue;
13103
13104                   dlen = strlen (dsec->name);
13105
13106                   if (dlen > ilen
13107                       && strncmp (dsec->name + (dlen - ilen),
13108                                   isec->name, ilen) == 0)
13109                     dsec->gc_mark = 0;
13110                 }
13111           }
13112
13113       /* Mark debug sections referenced by kept debug sections.  */
13114       if (has_kept_debug_info)
13115         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13116           if (isec->gc_mark
13117               && (isec->flags & SEC_DEBUGGING) != 0)
13118             if (!_bfd_elf_gc_mark (info, isec,
13119                                    elf_gc_mark_debug_section))
13120               return FALSE;
13121     }
13122   return TRUE;
13123 }
13124
13125 static bfd_boolean
13126 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
13127 {
13128   bfd *sub;
13129   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13130
13131   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13132     {
13133       asection *o;
13134
13135       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13136           || elf_object_id (sub) != elf_hash_table_id (elf_hash_table (info))
13137           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13138         continue;
13139       o = sub->sections;
13140       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13141         continue;
13142
13143       for (o = sub->sections; o != NULL; o = o->next)
13144         {
13145           /* When any section in a section group is kept, we keep all
13146              sections in the section group.  If the first member of
13147              the section group is excluded, we will also exclude the
13148              group section.  */
13149           if (o->flags & SEC_GROUP)
13150             {
13151               asection *first = elf_next_in_group (o);
13152               o->gc_mark = first->gc_mark;
13153             }
13154
13155           if (o->gc_mark)
13156             continue;
13157
13158           /* Skip sweeping sections already excluded.  */
13159           if (o->flags & SEC_EXCLUDE)
13160             continue;
13161
13162           /* Since this is early in the link process, it is simple
13163              to remove a section from the output.  */
13164           o->flags |= SEC_EXCLUDE;
13165
13166           if (info->print_gc_sections && o->size != 0)
13167             /* xgettext:c-format */
13168             _bfd_error_handler (_("Removing unused section '%pA' in file '%pB'"),
13169                                 o, sub);
13170         }
13171     }
13172
13173   return TRUE;
13174 }
13175
13176 /* Propagate collected vtable information.  This is called through
13177    elf_link_hash_traverse.  */
13178
13179 static bfd_boolean
13180 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
13181 {
13182   /* Those that are not vtables.  */
13183   if (h->start_stop
13184       || h->u2.vtable == NULL
13185       || h->u2.vtable->parent == NULL)
13186     return TRUE;
13187
13188   /* Those vtables that do not have parents, we cannot merge.  */
13189   if (h->u2.vtable->parent == (struct elf_link_hash_entry *) -1)
13190     return TRUE;
13191
13192   /* If we've already been done, exit.  */
13193   if (h->u2.vtable->used && h->u2.vtable->used[-1])
13194     return TRUE;
13195
13196   /* Make sure the parent's table is up to date.  */
13197   elf_gc_propagate_vtable_entries_used (h->u2.vtable->parent, okp);
13198
13199   if (h->u2.vtable->used == NULL)
13200     {
13201       /* None of this table's entries were referenced.  Re-use the
13202          parent's table.  */
13203       h->u2.vtable->used = h->u2.vtable->parent->u2.vtable->used;
13204       h->u2.vtable->size = h->u2.vtable->parent->u2.vtable->size;
13205     }
13206   else
13207     {
13208       size_t n;
13209       bfd_boolean *cu, *pu;
13210
13211       /* Or the parent's entries into ours.  */
13212       cu = h->u2.vtable->used;
13213       cu[-1] = TRUE;
13214       pu = h->u2.vtable->parent->u2.vtable->used;
13215       if (pu != NULL)
13216         {
13217           const struct elf_backend_data *bed;
13218           unsigned int log_file_align;
13219
13220           bed = get_elf_backend_data (h->root.u.def.section->owner);
13221           log_file_align = bed->s->log_file_align;
13222           n = h->u2.vtable->parent->u2.vtable->size >> log_file_align;
13223           while (n--)
13224             {
13225               if (*pu)
13226                 *cu = TRUE;
13227               pu++;
13228               cu++;
13229             }
13230         }
13231     }
13232
13233   return TRUE;
13234 }
13235
13236 static bfd_boolean
13237 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
13238 {
13239   asection *sec;
13240   bfd_vma hstart, hend;
13241   Elf_Internal_Rela *relstart, *relend, *rel;
13242   const struct elf_backend_data *bed;
13243   unsigned int log_file_align;
13244
13245   /* Take care of both those symbols that do not describe vtables as
13246      well as those that are not loaded.  */
13247   if (h->start_stop
13248       || h->u2.vtable == NULL
13249       || h->u2.vtable->parent == NULL)
13250     return TRUE;
13251
13252   BFD_ASSERT (h->root.type == bfd_link_hash_defined
13253               || h->root.type == bfd_link_hash_defweak);
13254
13255   sec = h->root.u.def.section;
13256   hstart = h->root.u.def.value;
13257   hend = hstart + h->size;
13258
13259   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
13260   if (!relstart)
13261     return *(bfd_boolean *) okp = FALSE;
13262   bed = get_elf_backend_data (sec->owner);
13263   log_file_align = bed->s->log_file_align;
13264
13265   relend = relstart + sec->reloc_count;
13266
13267   for (rel = relstart; rel < relend; ++rel)
13268     if (rel->r_offset >= hstart && rel->r_offset < hend)
13269       {
13270         /* If the entry is in use, do nothing.  */
13271         if (h->u2.vtable->used
13272             && (rel->r_offset - hstart) < h->u2.vtable->size)
13273           {
13274             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
13275             if (h->u2.vtable->used[entry])
13276               continue;
13277           }
13278         /* Otherwise, kill it.  */
13279         rel->r_offset = rel->r_info = rel->r_addend = 0;
13280       }
13281
13282   return TRUE;
13283 }
13284
13285 /* Mark sections containing dynamically referenced symbols.  When
13286    building shared libraries, we must assume that any visible symbol is
13287    referenced.  */
13288
13289 bfd_boolean
13290 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
13291 {
13292   struct bfd_link_info *info = (struct bfd_link_info *) inf;
13293   struct bfd_elf_dynamic_list *d = info->dynamic_list;
13294
13295   if ((h->root.type == bfd_link_hash_defined
13296        || h->root.type == bfd_link_hash_defweak)
13297       && ((h->ref_dynamic && !h->forced_local)
13298           || ((h->def_regular || ELF_COMMON_DEF_P (h))
13299               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
13300               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
13301               && (!bfd_link_executable (info)
13302                   || info->gc_keep_exported
13303                   || info->export_dynamic
13304                   || (h->dynamic
13305                       && d != NULL
13306                       && (*d->match) (&d->head, NULL, h->root.root.string)))
13307               && (h->versioned >= versioned
13308                   || !bfd_hide_sym_by_version (info->version_info,
13309                                                h->root.root.string)))))
13310     h->root.u.def.section->flags |= SEC_KEEP;
13311
13312   return TRUE;
13313 }
13314
13315 /* Keep all sections containing symbols undefined on the command-line,
13316    and the section containing the entry symbol.  */
13317
13318 void
13319 _bfd_elf_gc_keep (struct bfd_link_info *info)
13320 {
13321   struct bfd_sym_chain *sym;
13322
13323   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
13324     {
13325       struct elf_link_hash_entry *h;
13326
13327       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
13328                                 FALSE, FALSE, FALSE);
13329
13330       if (h != NULL
13331           && (h->root.type == bfd_link_hash_defined
13332               || h->root.type == bfd_link_hash_defweak)
13333           && !bfd_is_abs_section (h->root.u.def.section)
13334           && !bfd_is_und_section (h->root.u.def.section))
13335         h->root.u.def.section->flags |= SEC_KEEP;
13336     }
13337 }
13338
13339 bfd_boolean
13340 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
13341                                 struct bfd_link_info *info)
13342 {
13343   bfd *ibfd = info->input_bfds;
13344
13345   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13346     {
13347       asection *sec;
13348       struct elf_reloc_cookie cookie;
13349
13350       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13351         continue;
13352       sec = ibfd->sections;
13353       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13354         continue;
13355
13356       if (!init_reloc_cookie (&cookie, info, ibfd))
13357         return FALSE;
13358
13359       for (sec = ibfd->sections; sec; sec = sec->next)
13360         {
13361           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
13362               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
13363             {
13364               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
13365               fini_reloc_cookie_rels (&cookie, sec);
13366             }
13367         }
13368     }
13369   return TRUE;
13370 }
13371
13372 /* Do mark and sweep of unused sections.  */
13373
13374 bfd_boolean
13375 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
13376 {
13377   bfd_boolean ok = TRUE;
13378   bfd *sub;
13379   elf_gc_mark_hook_fn gc_mark_hook;
13380   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13381   struct elf_link_hash_table *htab;
13382
13383   if (!bed->can_gc_sections
13384       || !is_elf_hash_table (info->hash))
13385     {
13386       _bfd_error_handler(_("Warning: gc-sections option ignored"));
13387       return TRUE;
13388     }
13389
13390   bed->gc_keep (info);
13391   htab = elf_hash_table (info);
13392
13393   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
13394      at the .eh_frame section if we can mark the FDEs individually.  */
13395   for (sub = info->input_bfds;
13396        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
13397        sub = sub->link.next)
13398     {
13399       asection *sec;
13400       struct elf_reloc_cookie cookie;
13401
13402       sec = sub->sections;
13403       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13404         continue;
13405       sec = bfd_get_section_by_name (sub, ".eh_frame");
13406       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
13407         {
13408           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
13409           if (elf_section_data (sec)->sec_info
13410               && (sec->flags & SEC_LINKER_CREATED) == 0)
13411             elf_eh_frame_section (sub) = sec;
13412           fini_reloc_cookie_for_section (&cookie, sec);
13413           sec = bfd_get_next_section_by_name (NULL, sec);
13414         }
13415     }
13416
13417   /* Apply transitive closure to the vtable entry usage info.  */
13418   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
13419   if (!ok)
13420     return FALSE;
13421
13422   /* Kill the vtable relocations that were not used.  */
13423   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
13424   if (!ok)
13425     return FALSE;
13426
13427   /* Mark dynamically referenced symbols.  */
13428   if (htab->dynamic_sections_created || info->gc_keep_exported)
13429     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
13430
13431   /* Grovel through relocs to find out who stays ...  */
13432   gc_mark_hook = bed->gc_mark_hook;
13433   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13434     {
13435       asection *o;
13436
13437       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13438           || elf_object_id (sub) != elf_hash_table_id (htab)
13439           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13440         continue;
13441
13442       o = sub->sections;
13443       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13444         continue;
13445
13446       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
13447          Also treat note sections as a root, if the section is not part
13448          of a group.  We must keep all PREINIT_ARRAY, INIT_ARRAY as
13449          well as FINI_ARRAY sections for ld -r.  */
13450       for (o = sub->sections; o != NULL; o = o->next)
13451         if (!o->gc_mark
13452             && (o->flags & SEC_EXCLUDE) == 0
13453             && ((o->flags & SEC_KEEP) != 0
13454                 || (bfd_link_relocatable (info)
13455                     && ((elf_section_data (o)->this_hdr.sh_type
13456                          == SHT_PREINIT_ARRAY)
13457                         || (elf_section_data (o)->this_hdr.sh_type
13458                             == SHT_INIT_ARRAY)
13459                         || (elf_section_data (o)->this_hdr.sh_type
13460                             == SHT_FINI_ARRAY)))
13461                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
13462                     && elf_next_in_group (o) == NULL )))
13463           {
13464             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
13465               return FALSE;
13466           }
13467     }
13468
13469   /* Allow the backend to mark additional target specific sections.  */
13470   bed->gc_mark_extra_sections (info, gc_mark_hook);
13471
13472   /* ... and mark SEC_EXCLUDE for those that go.  */
13473   return elf_gc_sweep (abfd, info);
13474 }
13475 \f
13476 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
13477
13478 bfd_boolean
13479 bfd_elf_gc_record_vtinherit (bfd *abfd,
13480                              asection *sec,
13481                              struct elf_link_hash_entry *h,
13482                              bfd_vma offset)
13483 {
13484   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
13485   struct elf_link_hash_entry **search, *child;
13486   size_t extsymcount;
13487   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13488
13489   /* The sh_info field of the symtab header tells us where the
13490      external symbols start.  We don't care about the local symbols at
13491      this point.  */
13492   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
13493   if (!elf_bad_symtab (abfd))
13494     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
13495
13496   sym_hashes = elf_sym_hashes (abfd);
13497   sym_hashes_end = sym_hashes + extsymcount;
13498
13499   /* Hunt down the child symbol, which is in this section at the same
13500      offset as the relocation.  */
13501   for (search = sym_hashes; search != sym_hashes_end; ++search)
13502     {
13503       if ((child = *search) != NULL
13504           && (child->root.type == bfd_link_hash_defined
13505               || child->root.type == bfd_link_hash_defweak)
13506           && child->root.u.def.section == sec
13507           && child->root.u.def.value == offset)
13508         goto win;
13509     }
13510
13511   /* xgettext:c-format */
13512   _bfd_error_handler (_("%pB: %pA+%#" PRIx64 ": No symbol found for INHERIT"),
13513                       abfd, sec, (uint64_t) offset);
13514   bfd_set_error (bfd_error_invalid_operation);
13515   return FALSE;
13516
13517  win:
13518   if (!child->u2.vtable)
13519     {
13520       child->u2.vtable = ((struct elf_link_virtual_table_entry *)
13521                           bfd_zalloc (abfd, sizeof (*child->u2.vtable)));
13522       if (!child->u2.vtable)
13523         return FALSE;
13524     }
13525   if (!h)
13526     {
13527       /* This *should* only be the absolute section.  It could potentially
13528          be that someone has defined a non-global vtable though, which
13529          would be bad.  It isn't worth paging in the local symbols to be
13530          sure though; that case should simply be handled by the assembler.  */
13531
13532       child->u2.vtable->parent = (struct elf_link_hash_entry *) -1;
13533     }
13534   else
13535     child->u2.vtable->parent = h;
13536
13537   return TRUE;
13538 }
13539
13540 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
13541
13542 bfd_boolean
13543 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
13544                            asection *sec ATTRIBUTE_UNUSED,
13545                            struct elf_link_hash_entry *h,
13546                            bfd_vma addend)
13547 {
13548   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13549   unsigned int log_file_align = bed->s->log_file_align;
13550
13551   if (!h->u2.vtable)
13552     {
13553       h->u2.vtable = ((struct elf_link_virtual_table_entry *)
13554                       bfd_zalloc (abfd, sizeof (*h->u2.vtable)));
13555       if (!h->u2.vtable)
13556         return FALSE;
13557     }
13558
13559   if (addend >= h->u2.vtable->size)
13560     {
13561       size_t size, bytes, file_align;
13562       bfd_boolean *ptr = h->u2.vtable->used;
13563
13564       /* While the symbol is undefined, we have to be prepared to handle
13565          a zero size.  */
13566       file_align = 1 << log_file_align;
13567       if (h->root.type == bfd_link_hash_undefined)
13568         size = addend + file_align;
13569       else
13570         {
13571           size = h->size;
13572           if (addend >= size)
13573             {
13574               /* Oops!  We've got a reference past the defined end of
13575                  the table.  This is probably a bug -- shall we warn?  */
13576               size = addend + file_align;
13577             }
13578         }
13579       size = (size + file_align - 1) & -file_align;
13580
13581       /* Allocate one extra entry for use as a "done" flag for the
13582          consolidation pass.  */
13583       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
13584
13585       if (ptr)
13586         {
13587           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
13588
13589           if (ptr != NULL)
13590             {
13591               size_t oldbytes;
13592
13593               oldbytes = (((h->u2.vtable->size >> log_file_align) + 1)
13594                           * sizeof (bfd_boolean));
13595               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
13596             }
13597         }
13598       else
13599         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
13600
13601       if (ptr == NULL)
13602         return FALSE;
13603
13604       /* And arrange for that done flag to be at index -1.  */
13605       h->u2.vtable->used = ptr + 1;
13606       h->u2.vtable->size = size;
13607     }
13608
13609   h->u2.vtable->used[addend >> log_file_align] = TRUE;
13610
13611   return TRUE;
13612 }
13613
13614 /* Map an ELF section header flag to its corresponding string.  */
13615 typedef struct
13616 {
13617   char *flag_name;
13618   flagword flag_value;
13619 } elf_flags_to_name_table;
13620
13621 static elf_flags_to_name_table elf_flags_to_names [] =
13622 {
13623   { "SHF_WRITE", SHF_WRITE },
13624   { "SHF_ALLOC", SHF_ALLOC },
13625   { "SHF_EXECINSTR", SHF_EXECINSTR },
13626   { "SHF_MERGE", SHF_MERGE },
13627   { "SHF_STRINGS", SHF_STRINGS },
13628   { "SHF_INFO_LINK", SHF_INFO_LINK},
13629   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
13630   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
13631   { "SHF_GROUP", SHF_GROUP },
13632   { "SHF_TLS", SHF_TLS },
13633   { "SHF_MASKOS", SHF_MASKOS },
13634   { "SHF_EXCLUDE", SHF_EXCLUDE },
13635 };
13636
13637 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
13638 bfd_boolean
13639 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
13640                               struct flag_info *flaginfo,
13641                               asection *section)
13642 {
13643   const bfd_vma sh_flags = elf_section_flags (section);
13644
13645   if (!flaginfo->flags_initialized)
13646     {
13647       bfd *obfd = info->output_bfd;
13648       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13649       struct flag_info_list *tf = flaginfo->flag_list;
13650       int with_hex = 0;
13651       int without_hex = 0;
13652
13653       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
13654         {
13655           unsigned i;
13656           flagword (*lookup) (char *);
13657
13658           lookup = bed->elf_backend_lookup_section_flags_hook;
13659           if (lookup != NULL)
13660             {
13661               flagword hexval = (*lookup) ((char *) tf->name);
13662
13663               if (hexval != 0)
13664                 {
13665                   if (tf->with == with_flags)
13666                     with_hex |= hexval;
13667                   else if (tf->with == without_flags)
13668                     without_hex |= hexval;
13669                   tf->valid = TRUE;
13670                   continue;
13671                 }
13672             }
13673           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
13674             {
13675               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
13676                 {
13677                   if (tf->with == with_flags)
13678                     with_hex |= elf_flags_to_names[i].flag_value;
13679                   else if (tf->with == without_flags)
13680                     without_hex |= elf_flags_to_names[i].flag_value;
13681                   tf->valid = TRUE;
13682                   break;
13683                 }
13684             }
13685           if (!tf->valid)
13686             {
13687               info->callbacks->einfo
13688                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
13689               return FALSE;
13690             }
13691         }
13692       flaginfo->flags_initialized = TRUE;
13693       flaginfo->only_with_flags |= with_hex;
13694       flaginfo->not_with_flags |= without_hex;
13695     }
13696
13697   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
13698     return FALSE;
13699
13700   if ((flaginfo->not_with_flags & sh_flags) != 0)
13701     return FALSE;
13702
13703   return TRUE;
13704 }
13705
13706 struct alloc_got_off_arg {
13707   bfd_vma gotoff;
13708   struct bfd_link_info *info;
13709 };
13710
13711 /* We need a special top-level link routine to convert got reference counts
13712    to real got offsets.  */
13713
13714 static bfd_boolean
13715 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
13716 {
13717   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
13718   bfd *obfd = gofarg->info->output_bfd;
13719   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13720
13721   if (h->got.refcount > 0)
13722     {
13723       h->got.offset = gofarg->gotoff;
13724       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
13725     }
13726   else
13727     h->got.offset = (bfd_vma) -1;
13728
13729   return TRUE;
13730 }
13731
13732 /* And an accompanying bit to work out final got entry offsets once
13733    we're done.  Should be called from final_link.  */
13734
13735 bfd_boolean
13736 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
13737                                         struct bfd_link_info *info)
13738 {
13739   bfd *i;
13740   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13741   bfd_vma gotoff;
13742   struct alloc_got_off_arg gofarg;
13743
13744   BFD_ASSERT (abfd == info->output_bfd);
13745
13746   if (! is_elf_hash_table (info->hash))
13747     return FALSE;
13748
13749   /* The GOT offset is relative to the .got section, but the GOT header is
13750      put into the .got.plt section, if the backend uses it.  */
13751   if (bed->want_got_plt)
13752     gotoff = 0;
13753   else
13754     gotoff = bed->got_header_size;
13755
13756   /* Do the local .got entries first.  */
13757   for (i = info->input_bfds; i; i = i->link.next)
13758     {
13759       bfd_signed_vma *local_got;
13760       size_t j, locsymcount;
13761       Elf_Internal_Shdr *symtab_hdr;
13762
13763       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13764         continue;
13765
13766       local_got = elf_local_got_refcounts (i);
13767       if (!local_got)
13768         continue;
13769
13770       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13771       if (elf_bad_symtab (i))
13772         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13773       else
13774         locsymcount = symtab_hdr->sh_info;
13775
13776       for (j = 0; j < locsymcount; ++j)
13777         {
13778           if (local_got[j] > 0)
13779             {
13780               local_got[j] = gotoff;
13781               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13782             }
13783           else
13784             local_got[j] = (bfd_vma) -1;
13785         }
13786     }
13787
13788   /* Then the global .got entries.  .plt refcounts are handled by
13789      adjust_dynamic_symbol  */
13790   gofarg.gotoff = gotoff;
13791   gofarg.info = info;
13792   elf_link_hash_traverse (elf_hash_table (info),
13793                           elf_gc_allocate_got_offsets,
13794                           &gofarg);
13795   return TRUE;
13796 }
13797
13798 /* Many folk need no more in the way of final link than this, once
13799    got entry reference counting is enabled.  */
13800
13801 bfd_boolean
13802 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
13803 {
13804   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
13805     return FALSE;
13806
13807   /* Invoke the regular ELF backend linker to do all the work.  */
13808   return bfd_elf_final_link (abfd, info);
13809 }
13810
13811 bfd_boolean
13812 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
13813 {
13814   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
13815
13816   if (rcookie->bad_symtab)
13817     rcookie->rel = rcookie->rels;
13818
13819   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
13820     {
13821       unsigned long r_symndx;
13822
13823       if (! rcookie->bad_symtab)
13824         if (rcookie->rel->r_offset > offset)
13825           return FALSE;
13826       if (rcookie->rel->r_offset != offset)
13827         continue;
13828
13829       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
13830       if (r_symndx == STN_UNDEF)
13831         return TRUE;
13832
13833       if (r_symndx >= rcookie->locsymcount
13834           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13835         {
13836           struct elf_link_hash_entry *h;
13837
13838           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
13839
13840           while (h->root.type == bfd_link_hash_indirect
13841                  || h->root.type == bfd_link_hash_warning)
13842             h = (struct elf_link_hash_entry *) h->root.u.i.link;
13843
13844           if ((h->root.type == bfd_link_hash_defined
13845                || h->root.type == bfd_link_hash_defweak)
13846               && (h->root.u.def.section->owner != rcookie->abfd
13847                   || h->root.u.def.section->kept_section != NULL
13848                   || discarded_section (h->root.u.def.section)))
13849             return TRUE;
13850         }
13851       else
13852         {
13853           /* It's not a relocation against a global symbol,
13854              but it could be a relocation against a local
13855              symbol for a discarded section.  */
13856           asection *isec;
13857           Elf_Internal_Sym *isym;
13858
13859           /* Need to: get the symbol; get the section.  */
13860           isym = &rcookie->locsyms[r_symndx];
13861           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
13862           if (isec != NULL
13863               && (isec->kept_section != NULL
13864                   || discarded_section (isec)))
13865             return TRUE;
13866         }
13867       return FALSE;
13868     }
13869   return FALSE;
13870 }
13871
13872 /* Discard unneeded references to discarded sections.
13873    Returns -1 on error, 1 if any section's size was changed, 0 if
13874    nothing changed.  This function assumes that the relocations are in
13875    sorted order, which is true for all known assemblers.  */
13876
13877 int
13878 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
13879 {
13880   struct elf_reloc_cookie cookie;
13881   asection *o;
13882   bfd *abfd;
13883   int changed = 0;
13884
13885   if (info->traditional_format
13886       || !is_elf_hash_table (info->hash))
13887     return 0;
13888
13889   o = bfd_get_section_by_name (output_bfd, ".stab");
13890   if (o != NULL)
13891     {
13892       asection *i;
13893
13894       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13895         {
13896           if (i->size == 0
13897               || i->reloc_count == 0
13898               || i->sec_info_type != SEC_INFO_TYPE_STABS)
13899             continue;
13900
13901           abfd = i->owner;
13902           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13903             continue;
13904
13905           if (!init_reloc_cookie_for_section (&cookie, info, i))
13906             return -1;
13907
13908           if (_bfd_discard_section_stabs (abfd, i,
13909                                           elf_section_data (i)->sec_info,
13910                                           bfd_elf_reloc_symbol_deleted_p,
13911                                           &cookie))
13912             changed = 1;
13913
13914           fini_reloc_cookie_for_section (&cookie, i);
13915         }
13916     }
13917
13918   o = NULL;
13919   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
13920     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
13921   if (o != NULL)
13922     {
13923       asection *i;
13924       int eh_changed = 0;
13925       unsigned int eh_alignment;
13926
13927       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13928         {
13929           if (i->size == 0)
13930             continue;
13931
13932           abfd = i->owner;
13933           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13934             continue;
13935
13936           if (!init_reloc_cookie_for_section (&cookie, info, i))
13937             return -1;
13938
13939           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
13940           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
13941                                                  bfd_elf_reloc_symbol_deleted_p,
13942                                                  &cookie))
13943             {
13944               eh_changed = 1;
13945               if (i->size != i->rawsize)
13946                 changed = 1;
13947             }
13948
13949           fini_reloc_cookie_for_section (&cookie, i);
13950         }
13951
13952       eh_alignment = 1 << o->alignment_power;
13953       /* Skip over zero terminator, and prevent empty sections from
13954          adding alignment padding at the end.  */
13955       for (i = o->map_tail.s; i != NULL; i = i->map_tail.s)
13956         if (i->size == 0)
13957           i->flags |= SEC_EXCLUDE;
13958         else if (i->size > 4)
13959           break;
13960       /* The last non-empty eh_frame section doesn't need padding.  */
13961       if (i != NULL)
13962         i = i->map_tail.s;
13963       /* Any prior sections must pad the last FDE out to the output
13964          section alignment.  Otherwise we might have zero padding
13965          between sections, which would be seen as a terminator.  */
13966       for (; i != NULL; i = i->map_tail.s)
13967         if (i->size == 4)
13968           /* All but the last zero terminator should have been removed.  */
13969           BFD_FAIL ();
13970         else
13971           {
13972             bfd_size_type size
13973               = (i->size + eh_alignment - 1) & -eh_alignment;
13974             if (i->size != size)
13975               {
13976                 i->size = size;
13977                 changed = 1;
13978                 eh_changed = 1;
13979               }
13980           }
13981       if (eh_changed)
13982         elf_link_hash_traverse (elf_hash_table (info),
13983                                 _bfd_elf_adjust_eh_frame_global_symbol, NULL);
13984     }
13985
13986   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
13987     {
13988       const struct elf_backend_data *bed;
13989       asection *s;
13990
13991       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13992         continue;
13993       s = abfd->sections;
13994       if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13995         continue;
13996
13997       bed = get_elf_backend_data (abfd);
13998
13999       if (bed->elf_backend_discard_info != NULL)
14000         {
14001           if (!init_reloc_cookie (&cookie, info, abfd))
14002             return -1;
14003
14004           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
14005             changed = 1;
14006
14007           fini_reloc_cookie (&cookie, abfd);
14008         }
14009     }
14010
14011   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
14012     _bfd_elf_end_eh_frame_parsing (info);
14013
14014   if (info->eh_frame_hdr_type
14015       && !bfd_link_relocatable (info)
14016       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
14017     changed = 1;
14018
14019   return changed;
14020 }
14021
14022 bfd_boolean
14023 _bfd_elf_section_already_linked (bfd *abfd,
14024                                  asection *sec,
14025                                  struct bfd_link_info *info)
14026 {
14027   flagword flags;
14028   const char *name, *key;
14029   struct bfd_section_already_linked *l;
14030   struct bfd_section_already_linked_hash_entry *already_linked_list;
14031
14032   if (sec->output_section == bfd_abs_section_ptr)
14033     return FALSE;
14034
14035   flags = sec->flags;
14036
14037   /* Return if it isn't a linkonce section.  A comdat group section
14038      also has SEC_LINK_ONCE set.  */
14039   if ((flags & SEC_LINK_ONCE) == 0)
14040     return FALSE;
14041
14042   /* Don't put group member sections on our list of already linked
14043      sections.  They are handled as a group via their group section.  */
14044   if (elf_sec_group (sec) != NULL)
14045     return FALSE;
14046
14047   /* For a SHT_GROUP section, use the group signature as the key.  */
14048   name = sec->name;
14049   if ((flags & SEC_GROUP) != 0
14050       && elf_next_in_group (sec) != NULL
14051       && elf_group_name (elf_next_in_group (sec)) != NULL)
14052     key = elf_group_name (elf_next_in_group (sec));
14053   else
14054     {
14055       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
14056       if (CONST_STRNEQ (name, ".gnu.linkonce.")
14057           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
14058         key++;
14059       else
14060         /* Must be a user linkonce section that doesn't follow gcc's
14061            naming convention.  In this case we won't be matching
14062            single member groups.  */
14063         key = name;
14064     }
14065
14066   already_linked_list = bfd_section_already_linked_table_lookup (key);
14067
14068   for (l = already_linked_list->entry; l != NULL; l = l->next)
14069     {
14070       /* We may have 2 different types of sections on the list: group
14071          sections with a signature of <key> (<key> is some string),
14072          and linkonce sections named .gnu.linkonce.<type>.<key>.
14073          Match like sections.  LTO plugin sections are an exception.
14074          They are always named .gnu.linkonce.t.<key> and match either
14075          type of section.  */
14076       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
14077            && ((flags & SEC_GROUP) != 0
14078                || strcmp (name, l->sec->name) == 0))
14079           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
14080         {
14081           /* The section has already been linked.  See if we should
14082              issue a warning.  */
14083           if (!_bfd_handle_already_linked (sec, l, info))
14084             return FALSE;
14085
14086           if (flags & SEC_GROUP)
14087             {
14088               asection *first = elf_next_in_group (sec);
14089               asection *s = first;
14090
14091               while (s != NULL)
14092                 {
14093                   s->output_section = bfd_abs_section_ptr;
14094                   /* Record which group discards it.  */
14095                   s->kept_section = l->sec;
14096                   s = elf_next_in_group (s);
14097                   /* These lists are circular.  */
14098                   if (s == first)
14099                     break;
14100                 }
14101             }
14102
14103           return TRUE;
14104         }
14105     }
14106
14107   /* A single member comdat group section may be discarded by a
14108      linkonce section and vice versa.  */
14109   if ((flags & SEC_GROUP) != 0)
14110     {
14111       asection *first = elf_next_in_group (sec);
14112
14113       if (first != NULL && elf_next_in_group (first) == first)
14114         /* Check this single member group against linkonce sections.  */
14115         for (l = already_linked_list->entry; l != NULL; l = l->next)
14116           if ((l->sec->flags & SEC_GROUP) == 0
14117               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
14118             {
14119               first->output_section = bfd_abs_section_ptr;
14120               first->kept_section = l->sec;
14121               sec->output_section = bfd_abs_section_ptr;
14122               break;
14123             }
14124     }
14125   else
14126     /* Check this linkonce section against single member groups.  */
14127     for (l = already_linked_list->entry; l != NULL; l = l->next)
14128       if (l->sec->flags & SEC_GROUP)
14129         {
14130           asection *first = elf_next_in_group (l->sec);
14131
14132           if (first != NULL
14133               && elf_next_in_group (first) == first
14134               && bfd_elf_match_symbols_in_sections (first, sec, info))
14135             {
14136               sec->output_section = bfd_abs_section_ptr;
14137               sec->kept_section = first;
14138               break;
14139             }
14140         }
14141
14142   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
14143      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
14144      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
14145      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
14146      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
14147      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
14148      `.gnu.linkonce.t.F' section from a different bfd not requiring any
14149      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
14150      The reverse order cannot happen as there is never a bfd with only the
14151      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
14152      matter as here were are looking only for cross-bfd sections.  */
14153
14154   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
14155     for (l = already_linked_list->entry; l != NULL; l = l->next)
14156       if ((l->sec->flags & SEC_GROUP) == 0
14157           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
14158         {
14159           if (abfd != l->sec->owner)
14160             sec->output_section = bfd_abs_section_ptr;
14161           break;
14162         }
14163
14164   /* This is the first section with this name.  Record it.  */
14165   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
14166     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
14167   return sec->output_section == bfd_abs_section_ptr;
14168 }
14169
14170 bfd_boolean
14171 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
14172 {
14173   return sym->st_shndx == SHN_COMMON;
14174 }
14175
14176 unsigned int
14177 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
14178 {
14179   return SHN_COMMON;
14180 }
14181
14182 asection *
14183 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
14184 {
14185   return bfd_com_section_ptr;
14186 }
14187
14188 bfd_vma
14189 _bfd_elf_default_got_elt_size (bfd *abfd,
14190                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
14191                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
14192                                bfd *ibfd ATTRIBUTE_UNUSED,
14193                                unsigned long symndx ATTRIBUTE_UNUSED)
14194 {
14195   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14196   return bed->s->arch_size / 8;
14197 }
14198
14199 /* Routines to support the creation of dynamic relocs.  */
14200
14201 /* Returns the name of the dynamic reloc section associated with SEC.  */
14202
14203 static const char *
14204 get_dynamic_reloc_section_name (bfd *       abfd,
14205                                 asection *  sec,
14206                                 bfd_boolean is_rela)
14207 {
14208   char *name;
14209   const char *old_name = bfd_get_section_name (NULL, sec);
14210   const char *prefix = is_rela ? ".rela" : ".rel";
14211
14212   if (old_name == NULL)
14213     return NULL;
14214
14215   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
14216   sprintf (name, "%s%s", prefix, old_name);
14217
14218   return name;
14219 }
14220
14221 /* Returns the dynamic reloc section associated with SEC.
14222    If necessary compute the name of the dynamic reloc section based
14223    on SEC's name (looked up in ABFD's string table) and the setting
14224    of IS_RELA.  */
14225
14226 asection *
14227 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
14228                                     asection *  sec,
14229                                     bfd_boolean is_rela)
14230 {
14231   asection * reloc_sec = elf_section_data (sec)->sreloc;
14232
14233   if (reloc_sec == NULL)
14234     {
14235       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14236
14237       if (name != NULL)
14238         {
14239           reloc_sec = bfd_get_linker_section (abfd, name);
14240
14241           if (reloc_sec != NULL)
14242             elf_section_data (sec)->sreloc = reloc_sec;
14243         }
14244     }
14245
14246   return reloc_sec;
14247 }
14248
14249 /* Returns the dynamic reloc section associated with SEC.  If the
14250    section does not exist it is created and attached to the DYNOBJ
14251    bfd and stored in the SRELOC field of SEC's elf_section_data
14252    structure.
14253
14254    ALIGNMENT is the alignment for the newly created section and
14255    IS_RELA defines whether the name should be .rela.<SEC's name>
14256    or .rel.<SEC's name>.  The section name is looked up in the
14257    string table associated with ABFD.  */
14258
14259 asection *
14260 _bfd_elf_make_dynamic_reloc_section (asection *sec,
14261                                      bfd *dynobj,
14262                                      unsigned int alignment,
14263                                      bfd *abfd,
14264                                      bfd_boolean is_rela)
14265 {
14266   asection * reloc_sec = elf_section_data (sec)->sreloc;
14267
14268   if (reloc_sec == NULL)
14269     {
14270       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14271
14272       if (name == NULL)
14273         return NULL;
14274
14275       reloc_sec = bfd_get_linker_section (dynobj, name);
14276
14277       if (reloc_sec == NULL)
14278         {
14279           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
14280                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
14281           if ((sec->flags & SEC_ALLOC) != 0)
14282             flags |= SEC_ALLOC | SEC_LOAD;
14283
14284           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
14285           if (reloc_sec != NULL)
14286             {
14287               /* _bfd_elf_get_sec_type_attr chooses a section type by
14288                  name.  Override as it may be wrong, eg. for a user
14289                  section named "auto" we'll get ".relauto" which is
14290                  seen to be a .rela section.  */
14291               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
14292               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
14293                 reloc_sec = NULL;
14294             }
14295         }
14296
14297       elf_section_data (sec)->sreloc = reloc_sec;
14298     }
14299
14300   return reloc_sec;
14301 }
14302
14303 /* Copy the ELF symbol type and other attributes for a linker script
14304    assignment from HSRC to HDEST.  Generally this should be treated as
14305    if we found a strong non-dynamic definition for HDEST (except that
14306    ld ignores multiple definition errors).  */
14307 void
14308 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
14309                                      struct bfd_link_hash_entry *hdest,
14310                                      struct bfd_link_hash_entry *hsrc)
14311 {
14312   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
14313   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
14314   Elf_Internal_Sym isym;
14315
14316   ehdest->type = ehsrc->type;
14317   ehdest->target_internal = ehsrc->target_internal;
14318
14319   isym.st_other = ehsrc->other;
14320   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
14321 }
14322
14323 /* Append a RELA relocation REL to section S in BFD.  */
14324
14325 void
14326 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14327 {
14328   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14329   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
14330   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
14331   bed->s->swap_reloca_out (abfd, rel, loc);
14332 }
14333
14334 /* Append a REL relocation REL to section S in BFD.  */
14335
14336 void
14337 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14338 {
14339   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14340   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
14341   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
14342   bed->s->swap_reloc_out (abfd, rel, loc);
14343 }
14344
14345 /* Define __start, __stop, .startof. or .sizeof. symbol.  */
14346
14347 struct bfd_link_hash_entry *
14348 bfd_elf_define_start_stop (struct bfd_link_info *info,
14349                            const char *symbol, asection *sec)
14350 {
14351   struct elf_link_hash_entry *h;
14352
14353   h = elf_link_hash_lookup (elf_hash_table (info), symbol,
14354                             FALSE, FALSE, TRUE);
14355   if (h != NULL
14356       && (h->root.type == bfd_link_hash_undefined
14357           || h->root.type == bfd_link_hash_undefweak
14358           || ((h->ref_regular || h->def_dynamic) && !h->def_regular)))
14359     {
14360       bfd_boolean was_dynamic = h->ref_dynamic || h->def_dynamic;
14361       h->root.type = bfd_link_hash_defined;
14362       h->root.u.def.section = sec;
14363       h->root.u.def.value = 0;
14364       h->def_regular = 1;
14365       h->def_dynamic = 0;
14366       h->start_stop = 1;
14367       h->u2.start_stop_section = sec;
14368       if (symbol[0] == '.')
14369         {
14370           /* .startof. and .sizeof. symbols are local.  */
14371           const struct elf_backend_data *bed;
14372           bed = get_elf_backend_data (info->output_bfd);
14373           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
14374         }
14375       else
14376         {
14377           if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
14378             h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_PROTECTED;
14379           if (was_dynamic)
14380             bfd_elf_link_record_dynamic_symbol (info, h);
14381         }
14382       return &h->root;
14383     }
14384   return NULL;
14385 }