Remove sh5 and sh64 support
[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     {
590       h->dynamic = 1;
591       /* NB: If a symbol is made dynamic by --dynamic-list, it has
592          non-IR reference.  */
593       h->root.non_ir_ref_dynamic = 1;
594     }
595 }
596
597 /* Record an assignment to a symbol made by a linker script.  We need
598    this in case some dynamic object refers to this symbol.  */
599
600 bfd_boolean
601 bfd_elf_record_link_assignment (bfd *output_bfd,
602                                 struct bfd_link_info *info,
603                                 const char *name,
604                                 bfd_boolean provide,
605                                 bfd_boolean hidden)
606 {
607   struct elf_link_hash_entry *h, *hv;
608   struct elf_link_hash_table *htab;
609   const struct elf_backend_data *bed;
610
611   if (!is_elf_hash_table (info->hash))
612     return TRUE;
613
614   htab = elf_hash_table (info);
615   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
616   if (h == NULL)
617     return provide;
618
619   if (h->root.type == bfd_link_hash_warning)
620     h = (struct elf_link_hash_entry *) h->root.u.i.link;
621
622   if (h->versioned == unknown)
623     {
624       /* Set versioned if symbol version is unknown.  */
625       char *version = strrchr (name, ELF_VER_CHR);
626       if (version)
627         {
628           if (version > name && version[-1] != ELF_VER_CHR)
629             h->versioned = versioned_hidden;
630           else
631             h->versioned = versioned;
632         }
633     }
634
635   /* Symbols defined in a linker script but not referenced anywhere
636      else will have non_elf set.  */
637   if (h->non_elf)
638     {
639       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
640       h->non_elf = 0;
641     }
642
643   switch (h->root.type)
644     {
645     case bfd_link_hash_defined:
646     case bfd_link_hash_defweak:
647     case bfd_link_hash_common:
648       break;
649     case bfd_link_hash_undefweak:
650     case bfd_link_hash_undefined:
651       /* Since we're defining the symbol, don't let it seem to have not
652          been defined.  record_dynamic_symbol and size_dynamic_sections
653          may depend on this.  */
654       h->root.type = bfd_link_hash_new;
655       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
656         bfd_link_repair_undef_list (&htab->root);
657       break;
658     case bfd_link_hash_new:
659       break;
660     case bfd_link_hash_indirect:
661       /* We had a versioned symbol in a dynamic library.  We make the
662          the versioned symbol point to this one.  */
663       bed = get_elf_backend_data (output_bfd);
664       hv = h;
665       while (hv->root.type == bfd_link_hash_indirect
666              || hv->root.type == bfd_link_hash_warning)
667         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
668       /* We don't need to update h->root.u since linker will set them
669          later.  */
670       h->root.type = bfd_link_hash_undefined;
671       hv->root.type = bfd_link_hash_indirect;
672       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
673       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
674       break;
675     default:
676       BFD_FAIL ();
677       return FALSE;
678     }
679
680   /* If this symbol is being provided by the linker script, and it is
681      currently defined by a dynamic object, but not by a regular
682      object, then mark it as undefined so that the generic linker will
683      force the correct value.  */
684   if (provide
685       && h->def_dynamic
686       && !h->def_regular)
687     h->root.type = bfd_link_hash_undefined;
688
689   /* If this symbol is not being provided by the linker script, and it is
690      currently defined by a dynamic object, but not by a regular object,
691      then clear out any version information because the symbol will not be
692      associated with the dynamic object any more.  */
693   if (!provide
694       && h->def_dynamic
695       && !h->def_regular)
696     h->verinfo.verdef = NULL;
697
698   /* Make sure this symbol is not garbage collected.  */
699   h->mark = 1;
700
701   h->def_regular = 1;
702
703   if (hidden)
704     {
705       bed = get_elf_backend_data (output_bfd);
706       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
707         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
708       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
709     }
710
711   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
712      and executables.  */
713   if (!bfd_link_relocatable (info)
714       && h->dynindx != -1
715       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
716           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
717     h->forced_local = 1;
718
719   if ((h->def_dynamic
720        || h->ref_dynamic
721        || bfd_link_dll (info)
722        || elf_hash_table (info)->is_relocatable_executable)
723       && h->dynindx == -1)
724     {
725       if (! bfd_elf_link_record_dynamic_symbol (info, h))
726         return FALSE;
727
728       /* If this is a weak defined symbol, and we know a corresponding
729          real symbol from the same dynamic object, make sure the real
730          symbol is also made into a dynamic symbol.  */
731       if (h->is_weakalias)
732         {
733           struct elf_link_hash_entry *def = weakdef (h);
734
735           if (def->dynindx == -1
736               && !bfd_elf_link_record_dynamic_symbol (info, def))
737             return FALSE;
738         }
739     }
740
741   return TRUE;
742 }
743
744 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
745    success, and 2 on a failure caused by attempting to record a symbol
746    in a discarded section, eg. a discarded link-once section symbol.  */
747
748 int
749 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
750                                           bfd *input_bfd,
751                                           long input_indx)
752 {
753   bfd_size_type amt;
754   struct elf_link_local_dynamic_entry *entry;
755   struct elf_link_hash_table *eht;
756   struct elf_strtab_hash *dynstr;
757   size_t dynstr_index;
758   char *name;
759   Elf_External_Sym_Shndx eshndx;
760   char esym[sizeof (Elf64_External_Sym)];
761
762   if (! is_elf_hash_table (info->hash))
763     return 0;
764
765   /* See if the entry exists already.  */
766   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
767     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
768       return 1;
769
770   amt = sizeof (*entry);
771   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
772   if (entry == NULL)
773     return 0;
774
775   /* Go find the symbol, so that we can find it's name.  */
776   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
777                              1, input_indx, &entry->isym, esym, &eshndx))
778     {
779       bfd_release (input_bfd, entry);
780       return 0;
781     }
782
783   if (entry->isym.st_shndx != SHN_UNDEF
784       && entry->isym.st_shndx < SHN_LORESERVE)
785     {
786       asection *s;
787
788       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
789       if (s == NULL || bfd_is_abs_section (s->output_section))
790         {
791           /* We can still bfd_release here as nothing has done another
792              bfd_alloc.  We can't do this later in this function.  */
793           bfd_release (input_bfd, entry);
794           return 2;
795         }
796     }
797
798   name = (bfd_elf_string_from_elf_section
799           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
800            entry->isym.st_name));
801
802   dynstr = elf_hash_table (info)->dynstr;
803   if (dynstr == NULL)
804     {
805       /* Create a strtab to hold the dynamic symbol names.  */
806       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
807       if (dynstr == NULL)
808         return 0;
809     }
810
811   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
812   if (dynstr_index == (size_t) -1)
813     return 0;
814   entry->isym.st_name = dynstr_index;
815
816   eht = elf_hash_table (info);
817
818   entry->next = eht->dynlocal;
819   eht->dynlocal = entry;
820   entry->input_bfd = input_bfd;
821   entry->input_indx = input_indx;
822   eht->dynsymcount++;
823
824   /* Whatever binding the symbol had before, it's now local.  */
825   entry->isym.st_info
826     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
827
828   /* The dynindx will be set at the end of size_dynamic_sections.  */
829
830   return 1;
831 }
832
833 /* Return the dynindex of a local dynamic symbol.  */
834
835 long
836 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
837                                     bfd *input_bfd,
838                                     long input_indx)
839 {
840   struct elf_link_local_dynamic_entry *e;
841
842   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
843     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
844       return e->dynindx;
845   return -1;
846 }
847
848 /* This function is used to renumber the dynamic symbols, if some of
849    them are removed because they are marked as local.  This is called
850    via elf_link_hash_traverse.  */
851
852 static bfd_boolean
853 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
854                                       void *data)
855 {
856   size_t *count = (size_t *) data;
857
858   if (h->forced_local)
859     return TRUE;
860
861   if (h->dynindx != -1)
862     h->dynindx = ++(*count);
863
864   return TRUE;
865 }
866
867
868 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
869    STB_LOCAL binding.  */
870
871 static bfd_boolean
872 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
873                                             void *data)
874 {
875   size_t *count = (size_t *) data;
876
877   if (!h->forced_local)
878     return TRUE;
879
880   if (h->dynindx != -1)
881     h->dynindx = ++(*count);
882
883   return TRUE;
884 }
885
886 /* Return true if the dynamic symbol for a given section should be
887    omitted when creating a shared library.  */
888 bfd_boolean
889 _bfd_elf_omit_section_dynsym_default (bfd *output_bfd ATTRIBUTE_UNUSED,
890                                       struct bfd_link_info *info,
891                                       asection *p)
892 {
893   struct elf_link_hash_table *htab;
894   asection *ip;
895
896   switch (elf_section_data (p)->this_hdr.sh_type)
897     {
898     case SHT_PROGBITS:
899     case SHT_NOBITS:
900       /* If sh_type is yet undecided, assume it could be
901          SHT_PROGBITS/SHT_NOBITS.  */
902     case SHT_NULL:
903       htab = elf_hash_table (info);
904       if (p == htab->tls_sec)
905         return FALSE;
906
907       if (htab->text_index_section != NULL)
908         return p != htab->text_index_section && p != htab->data_index_section;
909
910       return (htab->dynobj != NULL
911               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
912               && ip->output_section == p);
913
914       /* There shouldn't be section relative relocations
915          against any other section.  */
916     default:
917       return TRUE;
918     }
919 }
920
921 bfd_boolean
922 _bfd_elf_omit_section_dynsym_all
923     (bfd *output_bfd ATTRIBUTE_UNUSED,
924      struct bfd_link_info *info ATTRIBUTE_UNUSED,
925      asection *p ATTRIBUTE_UNUSED)
926 {
927   return TRUE;
928 }
929
930 /* Assign dynsym indices.  In a shared library we generate a section
931    symbol for each output section, which come first.  Next come symbols
932    which have been forced to local binding.  Then all of the back-end
933    allocated local dynamic syms, followed by the rest of the global
934    symbols.  If SECTION_SYM_COUNT is NULL, section dynindx is not set.
935    (This prevents the early call before elf_backend_init_index_section
936    and strip_excluded_output_sections setting dynindx for sections
937    that are stripped.)  */
938
939 static unsigned long
940 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
941                                 struct bfd_link_info *info,
942                                 unsigned long *section_sym_count)
943 {
944   unsigned long dynsymcount = 0;
945   bfd_boolean do_sec = section_sym_count != NULL;
946
947   if (bfd_link_pic (info)
948       || elf_hash_table (info)->is_relocatable_executable)
949     {
950       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
951       asection *p;
952       for (p = output_bfd->sections; p ; p = p->next)
953         if ((p->flags & SEC_EXCLUDE) == 0
954             && (p->flags & SEC_ALLOC) != 0
955             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
956           {
957             ++dynsymcount;
958             if (do_sec)
959               elf_section_data (p)->dynindx = dynsymcount;
960           }
961         else if (do_sec)
962           elf_section_data (p)->dynindx = 0;
963     }
964   if (do_sec)
965     *section_sym_count = dynsymcount;
966
967   elf_link_hash_traverse (elf_hash_table (info),
968                           elf_link_renumber_local_hash_table_dynsyms,
969                           &dynsymcount);
970
971   if (elf_hash_table (info)->dynlocal)
972     {
973       struct elf_link_local_dynamic_entry *p;
974       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
975         p->dynindx = ++dynsymcount;
976     }
977   elf_hash_table (info)->local_dynsymcount = dynsymcount;
978
979   elf_link_hash_traverse (elf_hash_table (info),
980                           elf_link_renumber_hash_table_dynsyms,
981                           &dynsymcount);
982
983   /* There is an unused NULL entry at the head of the table which we
984      must account for in our count even if the table is empty since it
985      is intended for the mandatory DT_SYMTAB tag (.dynsym section) in
986      .dynamic section.  */
987   dynsymcount++;
988
989   elf_hash_table (info)->dynsymcount = dynsymcount;
990   return dynsymcount;
991 }
992
993 /* Merge st_other field.  */
994
995 static void
996 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
997                     const Elf_Internal_Sym *isym, asection *sec,
998                     bfd_boolean definition, bfd_boolean dynamic)
999 {
1000   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
1001
1002   /* If st_other has a processor-specific meaning, specific
1003      code might be needed here.  */
1004   if (bed->elf_backend_merge_symbol_attribute)
1005     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
1006                                                 dynamic);
1007
1008   if (!dynamic)
1009     {
1010       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
1011       unsigned hvis = ELF_ST_VISIBILITY (h->other);
1012
1013       /* Keep the most constraining visibility.  Leave the remainder
1014          of the st_other field to elf_backend_merge_symbol_attribute.  */
1015       if (symvis - 1 < hvis - 1)
1016         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
1017     }
1018   else if (definition
1019            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
1020            && (sec->flags & SEC_READONLY) == 0)
1021     h->protected_def = 1;
1022 }
1023
1024 /* This function is called when we want to merge a new symbol with an
1025    existing symbol.  It handles the various cases which arise when we
1026    find a definition in a dynamic object, or when there is already a
1027    definition in a dynamic object.  The new symbol is described by
1028    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
1029    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
1030    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
1031    of an old common symbol.  We set OVERRIDE if the old symbol is
1032    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
1033    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
1034    to change.  By OK to change, we mean that we shouldn't warn if the
1035    type or size does change.  */
1036
1037 static bfd_boolean
1038 _bfd_elf_merge_symbol (bfd *abfd,
1039                        struct bfd_link_info *info,
1040                        const char *name,
1041                        Elf_Internal_Sym *sym,
1042                        asection **psec,
1043                        bfd_vma *pvalue,
1044                        struct elf_link_hash_entry **sym_hash,
1045                        bfd **poldbfd,
1046                        bfd_boolean *pold_weak,
1047                        unsigned int *pold_alignment,
1048                        bfd_boolean *skip,
1049                        bfd_boolean *override,
1050                        bfd_boolean *type_change_ok,
1051                        bfd_boolean *size_change_ok,
1052                        bfd_boolean *matched)
1053 {
1054   asection *sec, *oldsec;
1055   struct elf_link_hash_entry *h;
1056   struct elf_link_hash_entry *hi;
1057   struct elf_link_hash_entry *flip;
1058   int bind;
1059   bfd *oldbfd;
1060   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
1061   bfd_boolean newweak, oldweak, newfunc, oldfunc;
1062   const struct elf_backend_data *bed;
1063   char *new_version;
1064   bfd_boolean default_sym = *matched;
1065
1066   *skip = FALSE;
1067   *override = FALSE;
1068
1069   sec = *psec;
1070   bind = ELF_ST_BIND (sym->st_info);
1071
1072   if (! bfd_is_und_section (sec))
1073     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
1074   else
1075     h = ((struct elf_link_hash_entry *)
1076          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
1077   if (h == NULL)
1078     return FALSE;
1079   *sym_hash = h;
1080
1081   bed = get_elf_backend_data (abfd);
1082
1083   /* NEW_VERSION is the symbol version of the new symbol.  */
1084   if (h->versioned != unversioned)
1085     {
1086       /* Symbol version is unknown or versioned.  */
1087       new_version = strrchr (name, ELF_VER_CHR);
1088       if (new_version)
1089         {
1090           if (h->versioned == unknown)
1091             {
1092               if (new_version > name && new_version[-1] != ELF_VER_CHR)
1093                 h->versioned = versioned_hidden;
1094               else
1095                 h->versioned = versioned;
1096             }
1097           new_version += 1;
1098           if (new_version[0] == '\0')
1099             new_version = NULL;
1100         }
1101       else
1102         h->versioned = unversioned;
1103     }
1104   else
1105     new_version = NULL;
1106
1107   /* For merging, we only care about real symbols.  But we need to make
1108      sure that indirect symbol dynamic flags are updated.  */
1109   hi = h;
1110   while (h->root.type == bfd_link_hash_indirect
1111          || h->root.type == bfd_link_hash_warning)
1112     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1113
1114   if (!*matched)
1115     {
1116       if (hi == h || h->root.type == bfd_link_hash_new)
1117         *matched = TRUE;
1118       else
1119         {
1120           /* OLD_HIDDEN is true if the existing symbol is only visible
1121              to the symbol with the same symbol version.  NEW_HIDDEN is
1122              true if the new symbol is only visible to the symbol with
1123              the same symbol version.  */
1124           bfd_boolean old_hidden = h->versioned == versioned_hidden;
1125           bfd_boolean new_hidden = hi->versioned == versioned_hidden;
1126           if (!old_hidden && !new_hidden)
1127             /* The new symbol matches the existing symbol if both
1128                aren't hidden.  */
1129             *matched = TRUE;
1130           else
1131             {
1132               /* OLD_VERSION is the symbol version of the existing
1133                  symbol. */
1134               char *old_version;
1135
1136               if (h->versioned >= versioned)
1137                 old_version = strrchr (h->root.root.string,
1138                                        ELF_VER_CHR) + 1;
1139               else
1140                  old_version = NULL;
1141
1142               /* The new symbol matches the existing symbol if they
1143                  have the same symbol version.  */
1144               *matched = (old_version == new_version
1145                           || (old_version != NULL
1146                               && new_version != NULL
1147                               && strcmp (old_version, new_version) == 0));
1148             }
1149         }
1150     }
1151
1152   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
1153      existing symbol.  */
1154
1155   oldbfd = NULL;
1156   oldsec = NULL;
1157   switch (h->root.type)
1158     {
1159     default:
1160       break;
1161
1162     case bfd_link_hash_undefined:
1163     case bfd_link_hash_undefweak:
1164       oldbfd = h->root.u.undef.abfd;
1165       break;
1166
1167     case bfd_link_hash_defined:
1168     case bfd_link_hash_defweak:
1169       oldbfd = h->root.u.def.section->owner;
1170       oldsec = h->root.u.def.section;
1171       break;
1172
1173     case bfd_link_hash_common:
1174       oldbfd = h->root.u.c.p->section->owner;
1175       oldsec = h->root.u.c.p->section;
1176       if (pold_alignment)
1177         *pold_alignment = h->root.u.c.p->alignment_power;
1178       break;
1179     }
1180   if (poldbfd && *poldbfd == NULL)
1181     *poldbfd = oldbfd;
1182
1183   /* Differentiate strong and weak symbols.  */
1184   newweak = bind == STB_WEAK;
1185   oldweak = (h->root.type == bfd_link_hash_defweak
1186              || h->root.type == bfd_link_hash_undefweak);
1187   if (pold_weak)
1188     *pold_weak = oldweak;
1189
1190   /* We have to check it for every instance since the first few may be
1191      references and not all compilers emit symbol type for undefined
1192      symbols.  */
1193   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
1194
1195   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1196      respectively, is from a dynamic object.  */
1197
1198   newdyn = (abfd->flags & DYNAMIC) != 0;
1199
1200   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
1201      syms and defined syms in dynamic libraries respectively.
1202      ref_dynamic on the other hand can be set for a symbol defined in
1203      a dynamic library, and def_dynamic may not be set;  When the
1204      definition in a dynamic lib is overridden by a definition in the
1205      executable use of the symbol in the dynamic lib becomes a
1206      reference to the executable symbol.  */
1207   if (newdyn)
1208     {
1209       if (bfd_is_und_section (sec))
1210         {
1211           if (bind != STB_WEAK)
1212             {
1213               h->ref_dynamic_nonweak = 1;
1214               hi->ref_dynamic_nonweak = 1;
1215             }
1216         }
1217       else
1218         {
1219           /* Update the existing symbol only if they match. */
1220           if (*matched)
1221             h->dynamic_def = 1;
1222           hi->dynamic_def = 1;
1223         }
1224     }
1225
1226   /* If we just created the symbol, mark it as being an ELF symbol.
1227      Other than that, there is nothing to do--there is no merge issue
1228      with a newly defined symbol--so we just return.  */
1229
1230   if (h->root.type == bfd_link_hash_new)
1231     {
1232       h->non_elf = 0;
1233       return TRUE;
1234     }
1235
1236   /* In cases involving weak versioned symbols, we may wind up trying
1237      to merge a symbol with itself.  Catch that here, to avoid the
1238      confusion that results if we try to override a symbol with
1239      itself.  The additional tests catch cases like
1240      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1241      dynamic object, which we do want to handle here.  */
1242   if (abfd == oldbfd
1243       && (newweak || oldweak)
1244       && ((abfd->flags & DYNAMIC) == 0
1245           || !h->def_regular))
1246     return TRUE;
1247
1248   olddyn = FALSE;
1249   if (oldbfd != NULL)
1250     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1251   else if (oldsec != NULL)
1252     {
1253       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1254          indices used by MIPS ELF.  */
1255       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1256     }
1257
1258   /* Handle a case where plugin_notice won't be called and thus won't
1259      set the non_ir_ref flags on the first pass over symbols.  */
1260   if (oldbfd != NULL
1261       && (oldbfd->flags & BFD_PLUGIN) != (abfd->flags & BFD_PLUGIN)
1262       && newdyn != olddyn)
1263     {
1264       h->root.non_ir_ref_dynamic = TRUE;
1265       hi->root.non_ir_ref_dynamic = TRUE;
1266     }
1267
1268   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1269      respectively, appear to be a definition rather than reference.  */
1270
1271   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1272
1273   olddef = (h->root.type != bfd_link_hash_undefined
1274             && h->root.type != bfd_link_hash_undefweak
1275             && h->root.type != bfd_link_hash_common);
1276
1277   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1278      respectively, appear to be a function.  */
1279
1280   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1281              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1282
1283   oldfunc = (h->type != STT_NOTYPE
1284              && bed->is_function_type (h->type));
1285
1286   if (!(newfunc && oldfunc)
1287       && ELF_ST_TYPE (sym->st_info) != h->type
1288       && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1289       && h->type != STT_NOTYPE
1290       && (newdef || bfd_is_com_section (sec))
1291       && (olddef || h->root.type == bfd_link_hash_common))
1292     {
1293       /* If creating a default indirect symbol ("foo" or "foo@") from
1294          a dynamic versioned definition ("foo@@") skip doing so if
1295          there is an existing regular definition with a different
1296          type.  We don't want, for example, a "time" variable in the
1297          executable overriding a "time" function in a shared library.  */
1298       if (newdyn
1299           && !olddyn)
1300         {
1301           *skip = TRUE;
1302           return TRUE;
1303         }
1304
1305       /* When adding a symbol from a regular object file after we have
1306          created indirect symbols, undo the indirection and any
1307          dynamic state.  */
1308       if (hi != h
1309           && !newdyn
1310           && olddyn)
1311         {
1312           h = hi;
1313           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1314           h->forced_local = 0;
1315           h->ref_dynamic = 0;
1316           h->def_dynamic = 0;
1317           h->dynamic_def = 0;
1318           if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1319             {
1320               h->root.type = bfd_link_hash_undefined;
1321               h->root.u.undef.abfd = abfd;
1322             }
1323           else
1324             {
1325               h->root.type = bfd_link_hash_new;
1326               h->root.u.undef.abfd = NULL;
1327             }
1328           return TRUE;
1329         }
1330     }
1331
1332   /* Check TLS symbols.  We don't check undefined symbols introduced
1333      by "ld -u" which have no type (and oldbfd NULL), and we don't
1334      check symbols from plugins because they also have no type.  */
1335   if (oldbfd != NULL
1336       && (oldbfd->flags & BFD_PLUGIN) == 0
1337       && (abfd->flags & BFD_PLUGIN) == 0
1338       && ELF_ST_TYPE (sym->st_info) != h->type
1339       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1340     {
1341       bfd *ntbfd, *tbfd;
1342       bfd_boolean ntdef, tdef;
1343       asection *ntsec, *tsec;
1344
1345       if (h->type == STT_TLS)
1346         {
1347           ntbfd = abfd;
1348           ntsec = sec;
1349           ntdef = newdef;
1350           tbfd = oldbfd;
1351           tsec = oldsec;
1352           tdef = olddef;
1353         }
1354       else
1355         {
1356           ntbfd = oldbfd;
1357           ntsec = oldsec;
1358           ntdef = olddef;
1359           tbfd = abfd;
1360           tsec = sec;
1361           tdef = newdef;
1362         }
1363
1364       if (tdef && ntdef)
1365         _bfd_error_handler
1366           /* xgettext:c-format */
1367           (_("%s: TLS definition in %pB section %pA "
1368              "mismatches non-TLS definition in %pB section %pA"),
1369            h->root.root.string, tbfd, tsec, ntbfd, ntsec);
1370       else if (!tdef && !ntdef)
1371         _bfd_error_handler
1372           /* xgettext:c-format */
1373           (_("%s: TLS reference in %pB "
1374              "mismatches non-TLS reference in %pB"),
1375            h->root.root.string, tbfd, ntbfd);
1376       else if (tdef)
1377         _bfd_error_handler
1378           /* xgettext:c-format */
1379           (_("%s: TLS definition in %pB section %pA "
1380              "mismatches non-TLS reference in %pB"),
1381            h->root.root.string, tbfd, tsec, ntbfd);
1382       else
1383         _bfd_error_handler
1384           /* xgettext:c-format */
1385           (_("%s: TLS reference in %pB "
1386              "mismatches non-TLS definition in %pB section %pA"),
1387            h->root.root.string, tbfd, ntbfd, ntsec);
1388
1389       bfd_set_error (bfd_error_bad_value);
1390       return FALSE;
1391     }
1392
1393   /* If the old symbol has non-default visibility, we ignore the new
1394      definition from a dynamic object.  */
1395   if (newdyn
1396       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1397       && !bfd_is_und_section (sec))
1398     {
1399       *skip = TRUE;
1400       /* Make sure this symbol is dynamic.  */
1401       h->ref_dynamic = 1;
1402       hi->ref_dynamic = 1;
1403       /* A protected symbol has external availability. Make sure it is
1404          recorded as dynamic.
1405
1406          FIXME: Should we check type and size for protected symbol?  */
1407       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1408         return bfd_elf_link_record_dynamic_symbol (info, h);
1409       else
1410         return TRUE;
1411     }
1412   else if (!newdyn
1413            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1414            && h->def_dynamic)
1415     {
1416       /* If the new symbol with non-default visibility comes from a
1417          relocatable file and the old definition comes from a dynamic
1418          object, we remove the old definition.  */
1419       if (hi->root.type == bfd_link_hash_indirect)
1420         {
1421           /* Handle the case where the old dynamic definition is
1422              default versioned.  We need to copy the symbol info from
1423              the symbol with default version to the normal one if it
1424              was referenced before.  */
1425           if (h->ref_regular)
1426             {
1427               hi->root.type = h->root.type;
1428               h->root.type = bfd_link_hash_indirect;
1429               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1430
1431               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1432               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1433                 {
1434                   /* If the new symbol is hidden or internal, completely undo
1435                      any dynamic link state.  */
1436                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1437                   h->forced_local = 0;
1438                   h->ref_dynamic = 0;
1439                 }
1440               else
1441                 h->ref_dynamic = 1;
1442
1443               h->def_dynamic = 0;
1444               /* FIXME: Should we check type and size for protected symbol?  */
1445               h->size = 0;
1446               h->type = 0;
1447
1448               h = hi;
1449             }
1450           else
1451             h = hi;
1452         }
1453
1454       /* If the old symbol was undefined before, then it will still be
1455          on the undefs list.  If the new symbol is undefined or
1456          common, we can't make it bfd_link_hash_new here, because new
1457          undefined or common symbols will be added to the undefs list
1458          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1459          added twice to the undefs list.  Also, if the new symbol is
1460          undefweak then we don't want to lose the strong undef.  */
1461       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1462         {
1463           h->root.type = bfd_link_hash_undefined;
1464           h->root.u.undef.abfd = abfd;
1465         }
1466       else
1467         {
1468           h->root.type = bfd_link_hash_new;
1469           h->root.u.undef.abfd = NULL;
1470         }
1471
1472       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1473         {
1474           /* If the new symbol is hidden or internal, completely undo
1475              any dynamic link state.  */
1476           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1477           h->forced_local = 0;
1478           h->ref_dynamic = 0;
1479         }
1480       else
1481         h->ref_dynamic = 1;
1482       h->def_dynamic = 0;
1483       /* FIXME: Should we check type and size for protected symbol?  */
1484       h->size = 0;
1485       h->type = 0;
1486       return TRUE;
1487     }
1488
1489   /* If a new weak symbol definition comes from a regular file and the
1490      old symbol comes from a dynamic library, we treat the new one as
1491      strong.  Similarly, an old weak symbol definition from a regular
1492      file is treated as strong when the new symbol comes from a dynamic
1493      library.  Further, an old weak symbol from a dynamic library is
1494      treated as strong if the new symbol is from a dynamic library.
1495      This reflects the way glibc's ld.so works.
1496
1497      Also allow a weak symbol to override a linker script symbol
1498      defined by an early pass over the script.  This is done so the
1499      linker knows the symbol is defined in an object file, for the
1500      DEFINED script function.
1501
1502      Do this before setting *type_change_ok or *size_change_ok so that
1503      we warn properly when dynamic library symbols are overridden.  */
1504
1505   if (newdef && !newdyn && (olddyn || h->root.ldscript_def))
1506     newweak = FALSE;
1507   if (olddef && newdyn)
1508     oldweak = FALSE;
1509
1510   /* Allow changes between different types of function symbol.  */
1511   if (newfunc && oldfunc)
1512     *type_change_ok = TRUE;
1513
1514   /* It's OK to change the type if either the existing symbol or the
1515      new symbol is weak.  A type change is also OK if the old symbol
1516      is undefined and the new symbol is defined.  */
1517
1518   if (oldweak
1519       || newweak
1520       || (newdef
1521           && h->root.type == bfd_link_hash_undefined))
1522     *type_change_ok = TRUE;
1523
1524   /* It's OK to change the size if either the existing symbol or the
1525      new symbol is weak, or if the old symbol is undefined.  */
1526
1527   if (*type_change_ok
1528       || h->root.type == bfd_link_hash_undefined)
1529     *size_change_ok = TRUE;
1530
1531   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1532      symbol, respectively, appears to be a common symbol in a dynamic
1533      object.  If a symbol appears in an uninitialized section, and is
1534      not weak, and is not a function, then it may be a common symbol
1535      which was resolved when the dynamic object was created.  We want
1536      to treat such symbols specially, because they raise special
1537      considerations when setting the symbol size: if the symbol
1538      appears as a common symbol in a regular object, and the size in
1539      the regular object is larger, we must make sure that we use the
1540      larger size.  This problematic case can always be avoided in C,
1541      but it must be handled correctly when using Fortran shared
1542      libraries.
1543
1544      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1545      likewise for OLDDYNCOMMON and OLDDEF.
1546
1547      Note that this test is just a heuristic, and that it is quite
1548      possible to have an uninitialized symbol in a shared object which
1549      is really a definition, rather than a common symbol.  This could
1550      lead to some minor confusion when the symbol really is a common
1551      symbol in some regular object.  However, I think it will be
1552      harmless.  */
1553
1554   if (newdyn
1555       && newdef
1556       && !newweak
1557       && (sec->flags & SEC_ALLOC) != 0
1558       && (sec->flags & SEC_LOAD) == 0
1559       && sym->st_size > 0
1560       && !newfunc)
1561     newdyncommon = TRUE;
1562   else
1563     newdyncommon = FALSE;
1564
1565   if (olddyn
1566       && olddef
1567       && h->root.type == bfd_link_hash_defined
1568       && h->def_dynamic
1569       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1570       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1571       && h->size > 0
1572       && !oldfunc)
1573     olddyncommon = TRUE;
1574   else
1575     olddyncommon = FALSE;
1576
1577   /* We now know everything about the old and new symbols.  We ask the
1578      backend to check if we can merge them.  */
1579   if (bed->merge_symbol != NULL)
1580     {
1581       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1582         return FALSE;
1583       sec = *psec;
1584     }
1585
1586   /* There are multiple definitions of a normal symbol.  Skip the
1587      default symbol as well as definition from an IR object.  */
1588   if (olddef && !olddyn && !oldweak && newdef && !newdyn && !newweak
1589       && !default_sym && h->def_regular
1590       && !(oldbfd != NULL
1591            && (oldbfd->flags & BFD_PLUGIN) != 0
1592            && (abfd->flags & BFD_PLUGIN) == 0))
1593     {
1594       /* Handle a multiple definition.  */
1595       (*info->callbacks->multiple_definition) (info, &h->root,
1596                                                abfd, sec, *pvalue);
1597       *skip = TRUE;
1598       return TRUE;
1599     }
1600
1601   /* If both the old and the new symbols look like common symbols in a
1602      dynamic object, set the size of the symbol to the larger of the
1603      two.  */
1604
1605   if (olddyncommon
1606       && newdyncommon
1607       && sym->st_size != h->size)
1608     {
1609       /* Since we think we have two common symbols, issue a multiple
1610          common warning if desired.  Note that we only warn if the
1611          size is different.  If the size is the same, we simply let
1612          the old symbol override the new one as normally happens with
1613          symbols defined in dynamic objects.  */
1614
1615       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1616                                            bfd_link_hash_common, sym->st_size);
1617       if (sym->st_size > h->size)
1618         h->size = sym->st_size;
1619
1620       *size_change_ok = TRUE;
1621     }
1622
1623   /* If we are looking at a dynamic object, and we have found a
1624      definition, we need to see if the symbol was already defined by
1625      some other object.  If so, we want to use the existing
1626      definition, and we do not want to report a multiple symbol
1627      definition error; we do this by clobbering *PSEC to be
1628      bfd_und_section_ptr.
1629
1630      We treat a common symbol as a definition if the symbol in the
1631      shared library is a function, since common symbols always
1632      represent variables; this can cause confusion in principle, but
1633      any such confusion would seem to indicate an erroneous program or
1634      shared library.  We also permit a common symbol in a regular
1635      object to override a weak symbol in a shared object.  */
1636
1637   if (newdyn
1638       && newdef
1639       && (olddef
1640           || (h->root.type == bfd_link_hash_common
1641               && (newweak || newfunc))))
1642     {
1643       *override = TRUE;
1644       newdef = FALSE;
1645       newdyncommon = FALSE;
1646
1647       *psec = sec = bfd_und_section_ptr;
1648       *size_change_ok = TRUE;
1649
1650       /* If we get here when the old symbol is a common symbol, then
1651          we are explicitly letting it override a weak symbol or
1652          function in a dynamic object, and we don't want to warn about
1653          a type change.  If the old symbol is a defined symbol, a type
1654          change warning may still be appropriate.  */
1655
1656       if (h->root.type == bfd_link_hash_common)
1657         *type_change_ok = TRUE;
1658     }
1659
1660   /* Handle the special case of an old common symbol merging with a
1661      new symbol which looks like a common symbol in a shared object.
1662      We change *PSEC and *PVALUE to make the new symbol look like a
1663      common symbol, and let _bfd_generic_link_add_one_symbol do the
1664      right thing.  */
1665
1666   if (newdyncommon
1667       && h->root.type == bfd_link_hash_common)
1668     {
1669       *override = TRUE;
1670       newdef = FALSE;
1671       newdyncommon = FALSE;
1672       *pvalue = sym->st_size;
1673       *psec = sec = bed->common_section (oldsec);
1674       *size_change_ok = TRUE;
1675     }
1676
1677   /* Skip weak definitions of symbols that are already defined.  */
1678   if (newdef && olddef && newweak)
1679     {
1680       /* Don't skip new non-IR weak syms.  */
1681       if (!(oldbfd != NULL
1682             && (oldbfd->flags & BFD_PLUGIN) != 0
1683             && (abfd->flags & BFD_PLUGIN) == 0))
1684         {
1685           newdef = FALSE;
1686           *skip = TRUE;
1687         }
1688
1689       /* Merge st_other.  If the symbol already has a dynamic index,
1690          but visibility says it should not be visible, turn it into a
1691          local symbol.  */
1692       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1693       if (h->dynindx != -1)
1694         switch (ELF_ST_VISIBILITY (h->other))
1695           {
1696           case STV_INTERNAL:
1697           case STV_HIDDEN:
1698             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1699             break;
1700           }
1701     }
1702
1703   /* If the old symbol is from a dynamic object, and the new symbol is
1704      a definition which is not from a dynamic object, then the new
1705      symbol overrides the old symbol.  Symbols from regular files
1706      always take precedence over symbols from dynamic objects, even if
1707      they are defined after the dynamic object in the link.
1708
1709      As above, we again permit a common symbol in a regular object to
1710      override a definition in a shared object if the shared object
1711      symbol is a function or is weak.  */
1712
1713   flip = NULL;
1714   if (!newdyn
1715       && (newdef
1716           || (bfd_is_com_section (sec)
1717               && (oldweak || oldfunc)))
1718       && olddyn
1719       && olddef
1720       && h->def_dynamic)
1721     {
1722       /* Change the hash table entry to undefined, and let
1723          _bfd_generic_link_add_one_symbol do the right thing with the
1724          new definition.  */
1725
1726       h->root.type = bfd_link_hash_undefined;
1727       h->root.u.undef.abfd = h->root.u.def.section->owner;
1728       *size_change_ok = TRUE;
1729
1730       olddef = FALSE;
1731       olddyncommon = FALSE;
1732
1733       /* We again permit a type change when a common symbol may be
1734          overriding a function.  */
1735
1736       if (bfd_is_com_section (sec))
1737         {
1738           if (oldfunc)
1739             {
1740               /* If a common symbol overrides a function, make sure
1741                  that it isn't defined dynamically nor has type
1742                  function.  */
1743               h->def_dynamic = 0;
1744               h->type = STT_NOTYPE;
1745             }
1746           *type_change_ok = TRUE;
1747         }
1748
1749       if (hi->root.type == bfd_link_hash_indirect)
1750         flip = hi;
1751       else
1752         /* This union may have been set to be non-NULL when this symbol
1753            was seen in a dynamic object.  We must force the union to be
1754            NULL, so that it is correct for a regular symbol.  */
1755         h->verinfo.vertree = NULL;
1756     }
1757
1758   /* Handle the special case of a new common symbol merging with an
1759      old symbol that looks like it might be a common symbol defined in
1760      a shared object.  Note that we have already handled the case in
1761      which a new common symbol should simply override the definition
1762      in the shared library.  */
1763
1764   if (! newdyn
1765       && bfd_is_com_section (sec)
1766       && olddyncommon)
1767     {
1768       /* It would be best if we could set the hash table entry to a
1769          common symbol, but we don't know what to use for the section
1770          or the alignment.  */
1771       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1772                                            bfd_link_hash_common, sym->st_size);
1773
1774       /* If the presumed common symbol in the dynamic object is
1775          larger, pretend that the new symbol has its size.  */
1776
1777       if (h->size > *pvalue)
1778         *pvalue = h->size;
1779
1780       /* We need to remember the alignment required by the symbol
1781          in the dynamic object.  */
1782       BFD_ASSERT (pold_alignment);
1783       *pold_alignment = h->root.u.def.section->alignment_power;
1784
1785       olddef = FALSE;
1786       olddyncommon = FALSE;
1787
1788       h->root.type = bfd_link_hash_undefined;
1789       h->root.u.undef.abfd = h->root.u.def.section->owner;
1790
1791       *size_change_ok = TRUE;
1792       *type_change_ok = TRUE;
1793
1794       if (hi->root.type == bfd_link_hash_indirect)
1795         flip = hi;
1796       else
1797         h->verinfo.vertree = NULL;
1798     }
1799
1800   if (flip != NULL)
1801     {
1802       /* Handle the case where we had a versioned symbol in a dynamic
1803          library and now find a definition in a normal object.  In this
1804          case, we make the versioned symbol point to the normal one.  */
1805       flip->root.type = h->root.type;
1806       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1807       h->root.type = bfd_link_hash_indirect;
1808       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1809       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1810       if (h->def_dynamic)
1811         {
1812           h->def_dynamic = 0;
1813           flip->ref_dynamic = 1;
1814         }
1815     }
1816
1817   return TRUE;
1818 }
1819
1820 /* This function is called to create an indirect symbol from the
1821    default for the symbol with the default version if needed. The
1822    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1823    set DYNSYM if the new indirect symbol is dynamic.  */
1824
1825 static bfd_boolean
1826 _bfd_elf_add_default_symbol (bfd *abfd,
1827                              struct bfd_link_info *info,
1828                              struct elf_link_hash_entry *h,
1829                              const char *name,
1830                              Elf_Internal_Sym *sym,
1831                              asection *sec,
1832                              bfd_vma value,
1833                              bfd **poldbfd,
1834                              bfd_boolean *dynsym)
1835 {
1836   bfd_boolean type_change_ok;
1837   bfd_boolean size_change_ok;
1838   bfd_boolean skip;
1839   char *shortname;
1840   struct elf_link_hash_entry *hi;
1841   struct bfd_link_hash_entry *bh;
1842   const struct elf_backend_data *bed;
1843   bfd_boolean collect;
1844   bfd_boolean dynamic;
1845   bfd_boolean override;
1846   char *p;
1847   size_t len, shortlen;
1848   asection *tmp_sec;
1849   bfd_boolean matched;
1850
1851   if (h->versioned == unversioned || h->versioned == versioned_hidden)
1852     return TRUE;
1853
1854   /* If this symbol has a version, and it is the default version, we
1855      create an indirect symbol from the default name to the fully
1856      decorated name.  This will cause external references which do not
1857      specify a version to be bound to this version of the symbol.  */
1858   p = strchr (name, ELF_VER_CHR);
1859   if (h->versioned == unknown)
1860     {
1861       if (p == NULL)
1862         {
1863           h->versioned = unversioned;
1864           return TRUE;
1865         }
1866       else
1867         {
1868           if (p[1] != ELF_VER_CHR)
1869             {
1870               h->versioned = versioned_hidden;
1871               return TRUE;
1872             }
1873           else
1874             h->versioned = versioned;
1875         }
1876     }
1877   else
1878     {
1879       /* PR ld/19073: We may see an unversioned definition after the
1880          default version.  */
1881       if (p == NULL)
1882         return TRUE;
1883     }
1884
1885   bed = get_elf_backend_data (abfd);
1886   collect = bed->collect;
1887   dynamic = (abfd->flags & DYNAMIC) != 0;
1888
1889   shortlen = p - name;
1890   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1891   if (shortname == NULL)
1892     return FALSE;
1893   memcpy (shortname, name, shortlen);
1894   shortname[shortlen] = '\0';
1895
1896   /* We are going to create a new symbol.  Merge it with any existing
1897      symbol with this name.  For the purposes of the merge, act as
1898      though we were defining the symbol we just defined, although we
1899      actually going to define an indirect symbol.  */
1900   type_change_ok = FALSE;
1901   size_change_ok = FALSE;
1902   matched = TRUE;
1903   tmp_sec = sec;
1904   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1905                               &hi, poldbfd, NULL, NULL, &skip, &override,
1906                               &type_change_ok, &size_change_ok, &matched))
1907     return FALSE;
1908
1909   if (skip)
1910     goto nondefault;
1911
1912   if (hi->def_regular)
1913     {
1914       /* If the undecorated symbol will have a version added by a
1915          script different to H, then don't indirect to/from the
1916          undecorated symbol.  This isn't ideal because we may not yet
1917          have seen symbol versions, if given by a script on the
1918          command line rather than via --version-script.  */
1919       if (hi->verinfo.vertree == NULL && info->version_info != NULL)
1920         {
1921           bfd_boolean hide;
1922
1923           hi->verinfo.vertree
1924             = bfd_find_version_for_sym (info->version_info,
1925                                         hi->root.root.string, &hide);
1926           if (hi->verinfo.vertree != NULL && hide)
1927             {
1928               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
1929               goto nondefault;
1930             }
1931         }
1932       if (hi->verinfo.vertree != NULL
1933           && strcmp (p + 1 + (p[1] == '@'), hi->verinfo.vertree->name) != 0)
1934         goto nondefault;
1935     }
1936
1937   if (! override)
1938     {
1939       /* Add the default symbol if not performing a relocatable link.  */
1940       if (! bfd_link_relocatable (info))
1941         {
1942           bh = &hi->root;
1943           if (! (_bfd_generic_link_add_one_symbol
1944                  (info, abfd, shortname, BSF_INDIRECT,
1945                   bfd_ind_section_ptr,
1946                   0, name, FALSE, collect, &bh)))
1947             return FALSE;
1948           hi = (struct elf_link_hash_entry *) bh;
1949         }
1950     }
1951   else
1952     {
1953       /* In this case the symbol named SHORTNAME is overriding the
1954          indirect symbol we want to add.  We were planning on making
1955          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1956          is the name without a version.  NAME is the fully versioned
1957          name, and it is the default version.
1958
1959          Overriding means that we already saw a definition for the
1960          symbol SHORTNAME in a regular object, and it is overriding
1961          the symbol defined in the dynamic object.
1962
1963          When this happens, we actually want to change NAME, the
1964          symbol we just added, to refer to SHORTNAME.  This will cause
1965          references to NAME in the shared object to become references
1966          to SHORTNAME in the regular object.  This is what we expect
1967          when we override a function in a shared object: that the
1968          references in the shared object will be mapped to the
1969          definition in the regular object.  */
1970
1971       while (hi->root.type == bfd_link_hash_indirect
1972              || hi->root.type == bfd_link_hash_warning)
1973         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1974
1975       h->root.type = bfd_link_hash_indirect;
1976       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1977       if (h->def_dynamic)
1978         {
1979           h->def_dynamic = 0;
1980           hi->ref_dynamic = 1;
1981           if (hi->ref_regular
1982               || hi->def_regular)
1983             {
1984               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1985                 return FALSE;
1986             }
1987         }
1988
1989       /* Now set HI to H, so that the following code will set the
1990          other fields correctly.  */
1991       hi = h;
1992     }
1993
1994   /* Check if HI is a warning symbol.  */
1995   if (hi->root.type == bfd_link_hash_warning)
1996     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1997
1998   /* If there is a duplicate definition somewhere, then HI may not
1999      point to an indirect symbol.  We will have reported an error to
2000      the user in that case.  */
2001
2002   if (hi->root.type == bfd_link_hash_indirect)
2003     {
2004       struct elf_link_hash_entry *ht;
2005
2006       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
2007       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
2008
2009       /* A reference to the SHORTNAME symbol from a dynamic library
2010          will be satisfied by the versioned symbol at runtime.  In
2011          effect, we have a reference to the versioned symbol.  */
2012       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
2013       hi->dynamic_def |= ht->dynamic_def;
2014
2015       /* See if the new flags lead us to realize that the symbol must
2016          be dynamic.  */
2017       if (! *dynsym)
2018         {
2019           if (! dynamic)
2020             {
2021               if (! bfd_link_executable (info)
2022                   || hi->def_dynamic
2023                   || hi->ref_dynamic)
2024                 *dynsym = TRUE;
2025             }
2026           else
2027             {
2028               if (hi->ref_regular)
2029                 *dynsym = TRUE;
2030             }
2031         }
2032     }
2033
2034   /* We also need to define an indirection from the nondefault version
2035      of the symbol.  */
2036
2037 nondefault:
2038   len = strlen (name);
2039   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
2040   if (shortname == NULL)
2041     return FALSE;
2042   memcpy (shortname, name, shortlen);
2043   memcpy (shortname + shortlen, p + 1, len - shortlen);
2044
2045   /* Once again, merge with any existing symbol.  */
2046   type_change_ok = FALSE;
2047   size_change_ok = FALSE;
2048   tmp_sec = sec;
2049   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
2050                               &hi, poldbfd, NULL, NULL, &skip, &override,
2051                               &type_change_ok, &size_change_ok, &matched))
2052     return FALSE;
2053
2054   if (skip)
2055     return TRUE;
2056
2057   if (override)
2058     {
2059       /* Here SHORTNAME is a versioned name, so we don't expect to see
2060          the type of override we do in the case above unless it is
2061          overridden by a versioned definition.  */
2062       if (hi->root.type != bfd_link_hash_defined
2063           && hi->root.type != bfd_link_hash_defweak)
2064         _bfd_error_handler
2065           /* xgettext:c-format */
2066           (_("%pB: unexpected redefinition of indirect versioned symbol `%s'"),
2067            abfd, shortname);
2068     }
2069   else
2070     {
2071       bh = &hi->root;
2072       if (! (_bfd_generic_link_add_one_symbol
2073              (info, abfd, shortname, BSF_INDIRECT,
2074               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
2075         return FALSE;
2076       hi = (struct elf_link_hash_entry *) bh;
2077
2078       /* If there is a duplicate definition somewhere, then HI may not
2079          point to an indirect symbol.  We will have reported an error
2080          to the user in that case.  */
2081
2082       if (hi->root.type == bfd_link_hash_indirect)
2083         {
2084           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
2085           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
2086           hi->dynamic_def |= h->dynamic_def;
2087
2088           /* See if the new flags lead us to realize that the symbol
2089              must be dynamic.  */
2090           if (! *dynsym)
2091             {
2092               if (! dynamic)
2093                 {
2094                   if (! bfd_link_executable (info)
2095                       || hi->ref_dynamic)
2096                     *dynsym = TRUE;
2097                 }
2098               else
2099                 {
2100                   if (hi->ref_regular)
2101                     *dynsym = TRUE;
2102                 }
2103             }
2104         }
2105     }
2106
2107   return TRUE;
2108 }
2109 \f
2110 /* This routine is used to export all defined symbols into the dynamic
2111    symbol table.  It is called via elf_link_hash_traverse.  */
2112
2113 static bfd_boolean
2114 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
2115 {
2116   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2117
2118   /* Ignore indirect symbols.  These are added by the versioning code.  */
2119   if (h->root.type == bfd_link_hash_indirect)
2120     return TRUE;
2121
2122   /* Ignore this if we won't export it.  */
2123   if (!eif->info->export_dynamic && !h->dynamic)
2124     return TRUE;
2125
2126   if (h->dynindx == -1
2127       && (h->def_regular || h->ref_regular)
2128       && ! bfd_hide_sym_by_version (eif->info->version_info,
2129                                     h->root.root.string))
2130     {
2131       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2132         {
2133           eif->failed = TRUE;
2134           return FALSE;
2135         }
2136     }
2137
2138   return TRUE;
2139 }
2140 \f
2141 /* Look through the symbols which are defined in other shared
2142    libraries and referenced here.  Update the list of version
2143    dependencies.  This will be put into the .gnu.version_r section.
2144    This function is called via elf_link_hash_traverse.  */
2145
2146 static bfd_boolean
2147 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
2148                                          void *data)
2149 {
2150   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
2151   Elf_Internal_Verneed *t;
2152   Elf_Internal_Vernaux *a;
2153   bfd_size_type amt;
2154
2155   /* We only care about symbols defined in shared objects with version
2156      information.  */
2157   if (!h->def_dynamic
2158       || h->def_regular
2159       || h->dynindx == -1
2160       || h->verinfo.verdef == NULL
2161       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
2162           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
2163     return TRUE;
2164
2165   /* See if we already know about this version.  */
2166   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
2167        t != NULL;
2168        t = t->vn_nextref)
2169     {
2170       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
2171         continue;
2172
2173       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
2174         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
2175           return TRUE;
2176
2177       break;
2178     }
2179
2180   /* This is a new version.  Add it to tree we are building.  */
2181
2182   if (t == NULL)
2183     {
2184       amt = sizeof *t;
2185       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
2186       if (t == NULL)
2187         {
2188           rinfo->failed = TRUE;
2189           return FALSE;
2190         }
2191
2192       t->vn_bfd = h->verinfo.verdef->vd_bfd;
2193       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
2194       elf_tdata (rinfo->info->output_bfd)->verref = t;
2195     }
2196
2197   amt = sizeof *a;
2198   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
2199   if (a == NULL)
2200     {
2201       rinfo->failed = TRUE;
2202       return FALSE;
2203     }
2204
2205   /* Note that we are copying a string pointer here, and testing it
2206      above.  If bfd_elf_string_from_elf_section is ever changed to
2207      discard the string data when low in memory, this will have to be
2208      fixed.  */
2209   a->vna_nodename = h->verinfo.verdef->vd_nodename;
2210
2211   a->vna_flags = h->verinfo.verdef->vd_flags;
2212   a->vna_nextptr = t->vn_auxptr;
2213
2214   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
2215   ++rinfo->vers;
2216
2217   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
2218
2219   t->vn_auxptr = a;
2220
2221   return TRUE;
2222 }
2223
2224 /* Figure out appropriate versions for all the symbols.  We may not
2225    have the version number script until we have read all of the input
2226    files, so until that point we don't know which symbols should be
2227    local.  This function is called via elf_link_hash_traverse.  */
2228
2229 static bfd_boolean
2230 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2231 {
2232   struct elf_info_failed *sinfo;
2233   struct bfd_link_info *info;
2234   const struct elf_backend_data *bed;
2235   struct elf_info_failed eif;
2236   char *p;
2237
2238   sinfo = (struct elf_info_failed *) data;
2239   info = sinfo->info;
2240
2241   /* Fix the symbol flags.  */
2242   eif.failed = FALSE;
2243   eif.info = info;
2244   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2245     {
2246       if (eif.failed)
2247         sinfo->failed = TRUE;
2248       return FALSE;
2249     }
2250
2251   /* We only need version numbers for symbols defined in regular
2252      objects.  */
2253   if (!h->def_regular)
2254     return TRUE;
2255
2256   bed = get_elf_backend_data (info->output_bfd);
2257   p = strchr (h->root.root.string, ELF_VER_CHR);
2258   if (p != NULL && h->verinfo.vertree == NULL)
2259     {
2260       struct bfd_elf_version_tree *t;
2261
2262       ++p;
2263       if (*p == ELF_VER_CHR)
2264         ++p;
2265
2266       /* If there is no version string, we can just return out.  */
2267       if (*p == '\0')
2268         return TRUE;
2269
2270       /* Look for the version.  If we find it, it is no longer weak.  */
2271       for (t = sinfo->info->version_info; t != NULL; t = t->next)
2272         {
2273           if (strcmp (t->name, p) == 0)
2274             {
2275               size_t len;
2276               char *alc;
2277               struct bfd_elf_version_expr *d;
2278
2279               len = p - h->root.root.string;
2280               alc = (char *) bfd_malloc (len);
2281               if (alc == NULL)
2282                 {
2283                   sinfo->failed = TRUE;
2284                   return FALSE;
2285                 }
2286               memcpy (alc, h->root.root.string, len - 1);
2287               alc[len - 1] = '\0';
2288               if (alc[len - 2] == ELF_VER_CHR)
2289                 alc[len - 2] = '\0';
2290
2291               h->verinfo.vertree = t;
2292               t->used = TRUE;
2293               d = NULL;
2294
2295               if (t->globals.list != NULL)
2296                 d = (*t->match) (&t->globals, NULL, alc);
2297
2298               /* See if there is anything to force this symbol to
2299                  local scope.  */
2300               if (d == NULL && t->locals.list != NULL)
2301                 {
2302                   d = (*t->match) (&t->locals, NULL, alc);
2303                   if (d != NULL
2304                       && h->dynindx != -1
2305                       && ! info->export_dynamic)
2306                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2307                 }
2308
2309               free (alc);
2310               break;
2311             }
2312         }
2313
2314       /* If we are building an application, we need to create a
2315          version node for this version.  */
2316       if (t == NULL && bfd_link_executable (info))
2317         {
2318           struct bfd_elf_version_tree **pp;
2319           int version_index;
2320
2321           /* If we aren't going to export this symbol, we don't need
2322              to worry about it.  */
2323           if (h->dynindx == -1)
2324             return TRUE;
2325
2326           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd,
2327                                                           sizeof *t);
2328           if (t == NULL)
2329             {
2330               sinfo->failed = TRUE;
2331               return FALSE;
2332             }
2333
2334           t->name = p;
2335           t->name_indx = (unsigned int) -1;
2336           t->used = TRUE;
2337
2338           version_index = 1;
2339           /* Don't count anonymous version tag.  */
2340           if (sinfo->info->version_info != NULL
2341               && sinfo->info->version_info->vernum == 0)
2342             version_index = 0;
2343           for (pp = &sinfo->info->version_info;
2344                *pp != NULL;
2345                pp = &(*pp)->next)
2346             ++version_index;
2347           t->vernum = version_index;
2348
2349           *pp = t;
2350
2351           h->verinfo.vertree = t;
2352         }
2353       else if (t == NULL)
2354         {
2355           /* We could not find the version for a symbol when
2356              generating a shared archive.  Return an error.  */
2357           _bfd_error_handler
2358             /* xgettext:c-format */
2359             (_("%pB: version node not found for symbol %s"),
2360              info->output_bfd, h->root.root.string);
2361           bfd_set_error (bfd_error_bad_value);
2362           sinfo->failed = TRUE;
2363           return FALSE;
2364         }
2365     }
2366
2367   /* If we don't have a version for this symbol, see if we can find
2368      something.  */
2369   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2370     {
2371       bfd_boolean hide;
2372
2373       h->verinfo.vertree
2374         = bfd_find_version_for_sym (sinfo->info->version_info,
2375                                     h->root.root.string, &hide);
2376       if (h->verinfo.vertree != NULL && hide)
2377         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2378     }
2379
2380   return TRUE;
2381 }
2382 \f
2383 /* Read and swap the relocs from the section indicated by SHDR.  This
2384    may be either a REL or a RELA section.  The relocations are
2385    translated into RELA relocations and stored in INTERNAL_RELOCS,
2386    which should have already been allocated to contain enough space.
2387    The EXTERNAL_RELOCS are a buffer where the external form of the
2388    relocations should be stored.
2389
2390    Returns FALSE if something goes wrong.  */
2391
2392 static bfd_boolean
2393 elf_link_read_relocs_from_section (bfd *abfd,
2394                                    asection *sec,
2395                                    Elf_Internal_Shdr *shdr,
2396                                    void *external_relocs,
2397                                    Elf_Internal_Rela *internal_relocs)
2398 {
2399   const struct elf_backend_data *bed;
2400   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2401   const bfd_byte *erela;
2402   const bfd_byte *erelaend;
2403   Elf_Internal_Rela *irela;
2404   Elf_Internal_Shdr *symtab_hdr;
2405   size_t nsyms;
2406
2407   /* Position ourselves at the start of the section.  */
2408   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2409     return FALSE;
2410
2411   /* Read the relocations.  */
2412   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2413     return FALSE;
2414
2415   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2416   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2417
2418   bed = get_elf_backend_data (abfd);
2419
2420   /* Convert the external relocations to the internal format.  */
2421   if (shdr->sh_entsize == bed->s->sizeof_rel)
2422     swap_in = bed->s->swap_reloc_in;
2423   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2424     swap_in = bed->s->swap_reloca_in;
2425   else
2426     {
2427       bfd_set_error (bfd_error_wrong_format);
2428       return FALSE;
2429     }
2430
2431   erela = (const bfd_byte *) external_relocs;
2432   erelaend = erela + shdr->sh_size;
2433   irela = internal_relocs;
2434   while (erela < erelaend)
2435     {
2436       bfd_vma r_symndx;
2437
2438       (*swap_in) (abfd, erela, irela);
2439       r_symndx = ELF32_R_SYM (irela->r_info);
2440       if (bed->s->arch_size == 64)
2441         r_symndx >>= 24;
2442       if (nsyms > 0)
2443         {
2444           if ((size_t) r_symndx >= nsyms)
2445             {
2446               _bfd_error_handler
2447                 /* xgettext:c-format */
2448                 (_("%pB: bad reloc symbol index (%#" PRIx64 " >= %#lx)"
2449                    " for offset %#" PRIx64 " in section `%pA'"),
2450                  abfd, (uint64_t) r_symndx, (unsigned long) nsyms,
2451                  (uint64_t) irela->r_offset, sec);
2452               bfd_set_error (bfd_error_bad_value);
2453               return FALSE;
2454             }
2455         }
2456       else if (r_symndx != STN_UNDEF)
2457         {
2458           _bfd_error_handler
2459             /* xgettext:c-format */
2460             (_("%pB: non-zero symbol index (%#" PRIx64 ")"
2461                " for offset %#" PRIx64 " in section `%pA'"
2462                " when the object file has no symbol table"),
2463              abfd, (uint64_t) r_symndx,
2464              (uint64_t) irela->r_offset, sec);
2465           bfd_set_error (bfd_error_bad_value);
2466           return FALSE;
2467         }
2468       irela += bed->s->int_rels_per_ext_rel;
2469       erela += shdr->sh_entsize;
2470     }
2471
2472   return TRUE;
2473 }
2474
2475 /* Read and swap the relocs for a section O.  They may have been
2476    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2477    not NULL, they are used as buffers to read into.  They are known to
2478    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2479    the return value is allocated using either malloc or bfd_alloc,
2480    according to the KEEP_MEMORY argument.  If O has two relocation
2481    sections (both REL and RELA relocations), then the REL_HDR
2482    relocations will appear first in INTERNAL_RELOCS, followed by the
2483    RELA_HDR relocations.  */
2484
2485 Elf_Internal_Rela *
2486 _bfd_elf_link_read_relocs (bfd *abfd,
2487                            asection *o,
2488                            void *external_relocs,
2489                            Elf_Internal_Rela *internal_relocs,
2490                            bfd_boolean keep_memory)
2491 {
2492   void *alloc1 = NULL;
2493   Elf_Internal_Rela *alloc2 = NULL;
2494   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2495   struct bfd_elf_section_data *esdo = elf_section_data (o);
2496   Elf_Internal_Rela *internal_rela_relocs;
2497
2498   if (esdo->relocs != NULL)
2499     return esdo->relocs;
2500
2501   if (o->reloc_count == 0)
2502     return NULL;
2503
2504   if (internal_relocs == NULL)
2505     {
2506       bfd_size_type size;
2507
2508       size = (bfd_size_type) o->reloc_count * sizeof (Elf_Internal_Rela);
2509       if (keep_memory)
2510         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2511       else
2512         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2513       if (internal_relocs == NULL)
2514         goto error_return;
2515     }
2516
2517   if (external_relocs == NULL)
2518     {
2519       bfd_size_type size = 0;
2520
2521       if (esdo->rel.hdr)
2522         size += esdo->rel.hdr->sh_size;
2523       if (esdo->rela.hdr)
2524         size += esdo->rela.hdr->sh_size;
2525
2526       alloc1 = bfd_malloc (size);
2527       if (alloc1 == NULL)
2528         goto error_return;
2529       external_relocs = alloc1;
2530     }
2531
2532   internal_rela_relocs = internal_relocs;
2533   if (esdo->rel.hdr)
2534     {
2535       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2536                                               external_relocs,
2537                                               internal_relocs))
2538         goto error_return;
2539       external_relocs = (((bfd_byte *) external_relocs)
2540                          + esdo->rel.hdr->sh_size);
2541       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2542                                * bed->s->int_rels_per_ext_rel);
2543     }
2544
2545   if (esdo->rela.hdr
2546       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2547                                               external_relocs,
2548                                               internal_rela_relocs)))
2549     goto error_return;
2550
2551   /* Cache the results for next time, if we can.  */
2552   if (keep_memory)
2553     esdo->relocs = internal_relocs;
2554
2555   if (alloc1 != NULL)
2556     free (alloc1);
2557
2558   /* Don't free alloc2, since if it was allocated we are passing it
2559      back (under the name of internal_relocs).  */
2560
2561   return internal_relocs;
2562
2563  error_return:
2564   if (alloc1 != NULL)
2565     free (alloc1);
2566   if (alloc2 != NULL)
2567     {
2568       if (keep_memory)
2569         bfd_release (abfd, alloc2);
2570       else
2571         free (alloc2);
2572     }
2573   return NULL;
2574 }
2575
2576 /* Compute the size of, and allocate space for, REL_HDR which is the
2577    section header for a section containing relocations for O.  */
2578
2579 static bfd_boolean
2580 _bfd_elf_link_size_reloc_section (bfd *abfd,
2581                                   struct bfd_elf_section_reloc_data *reldata)
2582 {
2583   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2584
2585   /* That allows us to calculate the size of the section.  */
2586   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2587
2588   /* The contents field must last into write_object_contents, so we
2589      allocate it with bfd_alloc rather than malloc.  Also since we
2590      cannot be sure that the contents will actually be filled in,
2591      we zero the allocated space.  */
2592   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2593   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2594     return FALSE;
2595
2596   if (reldata->hashes == NULL && reldata->count)
2597     {
2598       struct elf_link_hash_entry **p;
2599
2600       p = ((struct elf_link_hash_entry **)
2601            bfd_zmalloc (reldata->count * sizeof (*p)));
2602       if (p == NULL)
2603         return FALSE;
2604
2605       reldata->hashes = p;
2606     }
2607
2608   return TRUE;
2609 }
2610
2611 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2612    originated from the section given by INPUT_REL_HDR) to the
2613    OUTPUT_BFD.  */
2614
2615 bfd_boolean
2616 _bfd_elf_link_output_relocs (bfd *output_bfd,
2617                              asection *input_section,
2618                              Elf_Internal_Shdr *input_rel_hdr,
2619                              Elf_Internal_Rela *internal_relocs,
2620                              struct elf_link_hash_entry **rel_hash
2621                                ATTRIBUTE_UNUSED)
2622 {
2623   Elf_Internal_Rela *irela;
2624   Elf_Internal_Rela *irelaend;
2625   bfd_byte *erel;
2626   struct bfd_elf_section_reloc_data *output_reldata;
2627   asection *output_section;
2628   const struct elf_backend_data *bed;
2629   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2630   struct bfd_elf_section_data *esdo;
2631
2632   output_section = input_section->output_section;
2633
2634   bed = get_elf_backend_data (output_bfd);
2635   esdo = elf_section_data (output_section);
2636   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2637     {
2638       output_reldata = &esdo->rel;
2639       swap_out = bed->s->swap_reloc_out;
2640     }
2641   else if (esdo->rela.hdr
2642            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2643     {
2644       output_reldata = &esdo->rela;
2645       swap_out = bed->s->swap_reloca_out;
2646     }
2647   else
2648     {
2649       _bfd_error_handler
2650         /* xgettext:c-format */
2651         (_("%pB: relocation size mismatch in %pB section %pA"),
2652          output_bfd, input_section->owner, input_section);
2653       bfd_set_error (bfd_error_wrong_format);
2654       return FALSE;
2655     }
2656
2657   erel = output_reldata->hdr->contents;
2658   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2659   irela = internal_relocs;
2660   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2661                       * bed->s->int_rels_per_ext_rel);
2662   while (irela < irelaend)
2663     {
2664       (*swap_out) (output_bfd, irela, erel);
2665       irela += bed->s->int_rels_per_ext_rel;
2666       erel += input_rel_hdr->sh_entsize;
2667     }
2668
2669   /* Bump the counter, so that we know where to add the next set of
2670      relocations.  */
2671   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2672
2673   return TRUE;
2674 }
2675 \f
2676 /* Make weak undefined symbols in PIE dynamic.  */
2677
2678 bfd_boolean
2679 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2680                                  struct elf_link_hash_entry *h)
2681 {
2682   if (bfd_link_pie (info)
2683       && h->dynindx == -1
2684       && h->root.type == bfd_link_hash_undefweak)
2685     return bfd_elf_link_record_dynamic_symbol (info, h);
2686
2687   return TRUE;
2688 }
2689
2690 /* Fix up the flags for a symbol.  This handles various cases which
2691    can only be fixed after all the input files are seen.  This is
2692    currently called by both adjust_dynamic_symbol and
2693    assign_sym_version, which is unnecessary but perhaps more robust in
2694    the face of future changes.  */
2695
2696 static bfd_boolean
2697 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2698                            struct elf_info_failed *eif)
2699 {
2700   const struct elf_backend_data *bed;
2701
2702   /* If this symbol was mentioned in a non-ELF file, try to set
2703      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2704      permit a non-ELF file to correctly refer to a symbol defined in
2705      an ELF dynamic object.  */
2706   if (h->non_elf)
2707     {
2708       while (h->root.type == bfd_link_hash_indirect)
2709         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2710
2711       if (h->root.type != bfd_link_hash_defined
2712           && h->root.type != bfd_link_hash_defweak)
2713         {
2714           h->ref_regular = 1;
2715           h->ref_regular_nonweak = 1;
2716         }
2717       else
2718         {
2719           if (h->root.u.def.section->owner != NULL
2720               && (bfd_get_flavour (h->root.u.def.section->owner)
2721                   == bfd_target_elf_flavour))
2722             {
2723               h->ref_regular = 1;
2724               h->ref_regular_nonweak = 1;
2725             }
2726           else
2727             h->def_regular = 1;
2728         }
2729
2730       if (h->dynindx == -1
2731           && (h->def_dynamic
2732               || h->ref_dynamic))
2733         {
2734           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2735             {
2736               eif->failed = TRUE;
2737               return FALSE;
2738             }
2739         }
2740     }
2741   else
2742     {
2743       /* Unfortunately, NON_ELF is only correct if the symbol
2744          was first seen in a non-ELF file.  Fortunately, if the symbol
2745          was first seen in an ELF file, we're probably OK unless the
2746          symbol was defined in a non-ELF file.  Catch that case here.
2747          FIXME: We're still in trouble if the symbol was first seen in
2748          a dynamic object, and then later in a non-ELF regular object.  */
2749       if ((h->root.type == bfd_link_hash_defined
2750            || h->root.type == bfd_link_hash_defweak)
2751           && !h->def_regular
2752           && (h->root.u.def.section->owner != NULL
2753               ? (bfd_get_flavour (h->root.u.def.section->owner)
2754                  != bfd_target_elf_flavour)
2755               : (bfd_is_abs_section (h->root.u.def.section)
2756                  && !h->def_dynamic)))
2757         h->def_regular = 1;
2758     }
2759
2760   /* Backend specific symbol fixup.  */
2761   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2762   if (bed->elf_backend_fixup_symbol
2763       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2764     return FALSE;
2765
2766   /* If this is a final link, and the symbol was defined as a common
2767      symbol in a regular object file, and there was no definition in
2768      any dynamic object, then the linker will have allocated space for
2769      the symbol in a common section but the DEF_REGULAR
2770      flag will not have been set.  */
2771   if (h->root.type == bfd_link_hash_defined
2772       && !h->def_regular
2773       && h->ref_regular
2774       && !h->def_dynamic
2775       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2776     h->def_regular = 1;
2777
2778   /* If a weak undefined symbol has non-default visibility, we also
2779      hide it from the dynamic linker.  */
2780   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2781       && h->root.type == bfd_link_hash_undefweak)
2782     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2783
2784   /* A hidden versioned symbol in executable should be forced local if
2785      it is is locally defined, not referenced by shared library and not
2786      exported.  */
2787   else if (bfd_link_executable (eif->info)
2788            && h->versioned == versioned_hidden
2789            && !eif->info->export_dynamic
2790            && !h->dynamic
2791            && !h->ref_dynamic
2792            && h->def_regular)
2793     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2794
2795   /* If -Bsymbolic was used (which means to bind references to global
2796      symbols to the definition within the shared object), and this
2797      symbol was defined in a regular object, then it actually doesn't
2798      need a PLT entry.  Likewise, if the symbol has non-default
2799      visibility.  If the symbol has hidden or internal visibility, we
2800      will force it local.  */
2801   else if (h->needs_plt
2802            && bfd_link_pic (eif->info)
2803            && is_elf_hash_table (eif->info->hash)
2804            && (SYMBOLIC_BIND (eif->info, h)
2805                || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2806            && h->def_regular)
2807     {
2808       bfd_boolean force_local;
2809
2810       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2811                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2812       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2813     }
2814
2815   /* If this is a weak defined symbol in a dynamic object, and we know
2816      the real definition in the dynamic object, copy interesting flags
2817      over to the real definition.  */
2818   if (h->is_weakalias)
2819     {
2820       struct elf_link_hash_entry *def = weakdef (h);
2821
2822       /* If the real definition is defined by a regular object file,
2823          don't do anything special.  See the longer description in
2824          _bfd_elf_adjust_dynamic_symbol, below.  */
2825       if (def->def_regular)
2826         {
2827           h = def;
2828           while ((h = h->u.alias) != def)
2829             h->is_weakalias = 0;
2830         }
2831       else
2832         {
2833           while (h->root.type == bfd_link_hash_indirect)
2834             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2835           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2836                       || h->root.type == bfd_link_hash_defweak);
2837           BFD_ASSERT (def->def_dynamic);
2838           BFD_ASSERT (def->root.type == bfd_link_hash_defined);
2839           (*bed->elf_backend_copy_indirect_symbol) (eif->info, def, h);
2840         }
2841     }
2842
2843   return TRUE;
2844 }
2845
2846 /* Make the backend pick a good value for a dynamic symbol.  This is
2847    called via elf_link_hash_traverse, and also calls itself
2848    recursively.  */
2849
2850 static bfd_boolean
2851 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2852 {
2853   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2854   struct elf_link_hash_table *htab;
2855   const struct elf_backend_data *bed;
2856
2857   if (! is_elf_hash_table (eif->info->hash))
2858     return FALSE;
2859
2860   /* Ignore indirect symbols.  These are added by the versioning code.  */
2861   if (h->root.type == bfd_link_hash_indirect)
2862     return TRUE;
2863
2864   /* Fix the symbol flags.  */
2865   if (! _bfd_elf_fix_symbol_flags (h, eif))
2866     return FALSE;
2867
2868   htab = elf_hash_table (eif->info);
2869   bed = get_elf_backend_data (htab->dynobj);
2870
2871   if (h->root.type == bfd_link_hash_undefweak)
2872     {
2873       if (eif->info->dynamic_undefined_weak == 0)
2874         (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2875       else if (eif->info->dynamic_undefined_weak > 0
2876                && h->ref_regular
2877                && ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2878                && !bfd_hide_sym_by_version (eif->info->version_info,
2879                                             h->root.root.string))
2880         {
2881           if (!bfd_elf_link_record_dynamic_symbol (eif->info, h))
2882             {
2883               eif->failed = TRUE;
2884               return FALSE;
2885             }
2886         }
2887     }
2888
2889   /* If this symbol does not require a PLT entry, and it is not
2890      defined by a dynamic object, or is not referenced by a regular
2891      object, ignore it.  We do have to handle a weak defined symbol,
2892      even if no regular object refers to it, if we decided to add it
2893      to the dynamic symbol table.  FIXME: Do we normally need to worry
2894      about symbols which are defined by one dynamic object and
2895      referenced by another one?  */
2896   if (!h->needs_plt
2897       && h->type != STT_GNU_IFUNC
2898       && (h->def_regular
2899           || !h->def_dynamic
2900           || (!h->ref_regular
2901               && (!h->is_weakalias || weakdef (h)->dynindx == -1))))
2902     {
2903       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2904       return TRUE;
2905     }
2906
2907   /* If we've already adjusted this symbol, don't do it again.  This
2908      can happen via a recursive call.  */
2909   if (h->dynamic_adjusted)
2910     return TRUE;
2911
2912   /* Don't look at this symbol again.  Note that we must set this
2913      after checking the above conditions, because we may look at a
2914      symbol once, decide not to do anything, and then get called
2915      recursively later after REF_REGULAR is set below.  */
2916   h->dynamic_adjusted = 1;
2917
2918   /* If this is a weak definition, and we know a real definition, and
2919      the real symbol is not itself defined by a regular object file,
2920      then get a good value for the real definition.  We handle the
2921      real symbol first, for the convenience of the backend routine.
2922
2923      Note that there is a confusing case here.  If the real definition
2924      is defined by a regular object file, we don't get the real symbol
2925      from the dynamic object, but we do get the weak symbol.  If the
2926      processor backend uses a COPY reloc, then if some routine in the
2927      dynamic object changes the real symbol, we will not see that
2928      change in the corresponding weak symbol.  This is the way other
2929      ELF linkers work as well, and seems to be a result of the shared
2930      library model.
2931
2932      I will clarify this issue.  Most SVR4 shared libraries define the
2933      variable _timezone and define timezone as a weak synonym.  The
2934      tzset call changes _timezone.  If you write
2935        extern int timezone;
2936        int _timezone = 5;
2937        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2938      you might expect that, since timezone is a synonym for _timezone,
2939      the same number will print both times.  However, if the processor
2940      backend uses a COPY reloc, then actually timezone will be copied
2941      into your process image, and, since you define _timezone
2942      yourself, _timezone will not.  Thus timezone and _timezone will
2943      wind up at different memory locations.  The tzset call will set
2944      _timezone, leaving timezone unchanged.  */
2945
2946   if (h->is_weakalias)
2947     {
2948       struct elf_link_hash_entry *def = weakdef (h);
2949
2950       /* If we get to this point, there is an implicit reference to
2951          the alias by a regular object file via the weak symbol H.  */
2952       def->ref_regular = 1;
2953
2954       /* Ensure that the backend adjust_dynamic_symbol function sees
2955          the strong alias before H by recursively calling ourselves.  */
2956       if (!_bfd_elf_adjust_dynamic_symbol (def, eif))
2957         return FALSE;
2958     }
2959
2960   /* If a symbol has no type and no size and does not require a PLT
2961      entry, then we are probably about to do the wrong thing here: we
2962      are probably going to create a COPY reloc for an empty object.
2963      This case can arise when a shared object is built with assembly
2964      code, and the assembly code fails to set the symbol type.  */
2965   if (h->size == 0
2966       && h->type == STT_NOTYPE
2967       && !h->needs_plt)
2968     _bfd_error_handler
2969       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2970        h->root.root.string);
2971
2972   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2973     {
2974       eif->failed = TRUE;
2975       return FALSE;
2976     }
2977
2978   return TRUE;
2979 }
2980
2981 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2982    DYNBSS.  */
2983
2984 bfd_boolean
2985 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
2986                               struct elf_link_hash_entry *h,
2987                               asection *dynbss)
2988 {
2989   unsigned int power_of_two;
2990   bfd_vma mask;
2991   asection *sec = h->root.u.def.section;
2992
2993   /* The section alignment of the definition is the maximum alignment
2994      requirement of symbols defined in the section.  Since we don't
2995      know the symbol alignment requirement, we start with the
2996      maximum alignment and check low bits of the symbol address
2997      for the minimum alignment.  */
2998   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2999   mask = ((bfd_vma) 1 << power_of_two) - 1;
3000   while ((h->root.u.def.value & mask) != 0)
3001     {
3002        mask >>= 1;
3003        --power_of_two;
3004     }
3005
3006   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
3007                                                 dynbss))
3008     {
3009       /* Adjust the section alignment if needed.  */
3010       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
3011                                        power_of_two))
3012         return FALSE;
3013     }
3014
3015   /* We make sure that the symbol will be aligned properly.  */
3016   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
3017
3018   /* Define the symbol as being at this point in DYNBSS.  */
3019   h->root.u.def.section = dynbss;
3020   h->root.u.def.value = dynbss->size;
3021
3022   /* Increment the size of DYNBSS to make room for the symbol.  */
3023   dynbss->size += h->size;
3024
3025   /* No error if extern_protected_data is true.  */
3026   if (h->protected_def
3027       && (!info->extern_protected_data
3028           || (info->extern_protected_data < 0
3029               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
3030     info->callbacks->einfo
3031       (_("%P: copy reloc against protected `%pT' is dangerous\n"),
3032        h->root.root.string);
3033
3034   return TRUE;
3035 }
3036
3037 /* Adjust all external symbols pointing into SEC_MERGE sections
3038    to reflect the object merging within the sections.  */
3039
3040 static bfd_boolean
3041 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
3042 {
3043   asection *sec;
3044
3045   if ((h->root.type == bfd_link_hash_defined
3046        || h->root.type == bfd_link_hash_defweak)
3047       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
3048       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
3049     {
3050       bfd *output_bfd = (bfd *) data;
3051
3052       h->root.u.def.value =
3053         _bfd_merged_section_offset (output_bfd,
3054                                     &h->root.u.def.section,
3055                                     elf_section_data (sec)->sec_info,
3056                                     h->root.u.def.value);
3057     }
3058
3059   return TRUE;
3060 }
3061
3062 /* Returns false if the symbol referred to by H should be considered
3063    to resolve local to the current module, and true if it should be
3064    considered to bind dynamically.  */
3065
3066 bfd_boolean
3067 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
3068                            struct bfd_link_info *info,
3069                            bfd_boolean not_local_protected)
3070 {
3071   bfd_boolean binding_stays_local_p;
3072   const struct elf_backend_data *bed;
3073   struct elf_link_hash_table *hash_table;
3074
3075   if (h == NULL)
3076     return FALSE;
3077
3078   while (h->root.type == bfd_link_hash_indirect
3079          || h->root.type == bfd_link_hash_warning)
3080     h = (struct elf_link_hash_entry *) h->root.u.i.link;
3081
3082   /* If it was forced local, then clearly it's not dynamic.  */
3083   if (h->dynindx == -1)
3084     return FALSE;
3085   if (h->forced_local)
3086     return FALSE;
3087
3088   /* Identify the cases where name binding rules say that a
3089      visible symbol resolves locally.  */
3090   binding_stays_local_p = (bfd_link_executable (info)
3091                            || SYMBOLIC_BIND (info, h));
3092
3093   switch (ELF_ST_VISIBILITY (h->other))
3094     {
3095     case STV_INTERNAL:
3096     case STV_HIDDEN:
3097       return FALSE;
3098
3099     case STV_PROTECTED:
3100       hash_table = elf_hash_table (info);
3101       if (!is_elf_hash_table (hash_table))
3102         return FALSE;
3103
3104       bed = get_elf_backend_data (hash_table->dynobj);
3105
3106       /* Proper resolution for function pointer equality may require
3107          that these symbols perhaps be resolved dynamically, even though
3108          we should be resolving them to the current module.  */
3109       if (!not_local_protected || !bed->is_function_type (h->type))
3110         binding_stays_local_p = TRUE;
3111       break;
3112
3113     default:
3114       break;
3115     }
3116
3117   /* If it isn't defined locally, then clearly it's dynamic.  */
3118   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
3119     return TRUE;
3120
3121   /* Otherwise, the symbol is dynamic if binding rules don't tell
3122      us that it remains local.  */
3123   return !binding_stays_local_p;
3124 }
3125
3126 /* Return true if the symbol referred to by H should be considered
3127    to resolve local to the current module, and false otherwise.  Differs
3128    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
3129    undefined symbols.  The two functions are virtually identical except
3130    for the place where dynindx == -1 is tested.  If that test is true,
3131    _bfd_elf_dynamic_symbol_p will say the symbol is local, while
3132    _bfd_elf_symbol_refs_local_p will say the symbol is local only for
3133    defined symbols.
3134    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
3135    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
3136    treatment of undefined weak symbols.  For those that do not make
3137    undefined weak symbols dynamic, both functions may return false.  */
3138
3139 bfd_boolean
3140 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
3141                               struct bfd_link_info *info,
3142                               bfd_boolean local_protected)
3143 {
3144   const struct elf_backend_data *bed;
3145   struct elf_link_hash_table *hash_table;
3146
3147   /* If it's a local sym, of course we resolve locally.  */
3148   if (h == NULL)
3149     return TRUE;
3150
3151   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
3152   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
3153       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
3154     return TRUE;
3155
3156   /* Forced local symbols resolve locally.  */
3157   if (h->forced_local)
3158     return TRUE;
3159
3160   /* Common symbols that become definitions don't get the DEF_REGULAR
3161      flag set, so test it first, and don't bail out.  */
3162   if (ELF_COMMON_DEF_P (h))
3163     /* Do nothing.  */;
3164   /* If we don't have a definition in a regular file, then we can't
3165      resolve locally.  The sym is either undefined or dynamic.  */
3166   else if (!h->def_regular)
3167     return FALSE;
3168
3169   /* Non-dynamic symbols resolve locally.  */
3170   if (h->dynindx == -1)
3171     return TRUE;
3172
3173   /* At this point, we know the symbol is defined and dynamic.  In an
3174      executable it must resolve locally, likewise when building symbolic
3175      shared libraries.  */
3176   if (bfd_link_executable (info) || SYMBOLIC_BIND (info, h))
3177     return TRUE;
3178
3179   /* Now deal with defined dynamic symbols in shared libraries.  Ones
3180      with default visibility might not resolve locally.  */
3181   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
3182     return FALSE;
3183
3184   hash_table = elf_hash_table (info);
3185   if (!is_elf_hash_table (hash_table))
3186     return TRUE;
3187
3188   bed = get_elf_backend_data (hash_table->dynobj);
3189
3190   /* If extern_protected_data is false, STV_PROTECTED non-function
3191      symbols are local.  */
3192   if ((!info->extern_protected_data
3193        || (info->extern_protected_data < 0
3194            && !bed->extern_protected_data))
3195       && !bed->is_function_type (h->type))
3196     return TRUE;
3197
3198   /* Function pointer equality tests may require that STV_PROTECTED
3199      symbols be treated as dynamic symbols.  If the address of a
3200      function not defined in an executable is set to that function's
3201      plt entry in the executable, then the address of the function in
3202      a shared library must also be the plt entry in the executable.  */
3203   return local_protected;
3204 }
3205
3206 /* Caches some TLS segment info, and ensures that the TLS segment vma is
3207    aligned.  Returns the first TLS output section.  */
3208
3209 struct bfd_section *
3210 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
3211 {
3212   struct bfd_section *sec, *tls;
3213   unsigned int align = 0;
3214
3215   for (sec = obfd->sections; sec != NULL; sec = sec->next)
3216     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
3217       break;
3218   tls = sec;
3219
3220   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
3221     if (sec->alignment_power > align)
3222       align = sec->alignment_power;
3223
3224   elf_hash_table (info)->tls_sec = tls;
3225
3226   /* Ensure the alignment of the first section is the largest alignment,
3227      so that the tls segment starts aligned.  */
3228   if (tls != NULL)
3229     tls->alignment_power = align;
3230
3231   return tls;
3232 }
3233
3234 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
3235 static bfd_boolean
3236 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
3237                                   Elf_Internal_Sym *sym)
3238 {
3239   const struct elf_backend_data *bed;
3240
3241   /* Local symbols do not count, but target specific ones might.  */
3242   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
3243       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
3244     return FALSE;
3245
3246   bed = get_elf_backend_data (abfd);
3247   /* Function symbols do not count.  */
3248   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
3249     return FALSE;
3250
3251   /* If the section is undefined, then so is the symbol.  */
3252   if (sym->st_shndx == SHN_UNDEF)
3253     return FALSE;
3254
3255   /* If the symbol is defined in the common section, then
3256      it is a common definition and so does not count.  */
3257   if (bed->common_definition (sym))
3258     return FALSE;
3259
3260   /* If the symbol is in a target specific section then we
3261      must rely upon the backend to tell us what it is.  */
3262   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3263     /* FIXME - this function is not coded yet:
3264
3265        return _bfd_is_global_symbol_definition (abfd, sym);
3266
3267        Instead for now assume that the definition is not global,
3268        Even if this is wrong, at least the linker will behave
3269        in the same way that it used to do.  */
3270     return FALSE;
3271
3272   return TRUE;
3273 }
3274
3275 /* Search the symbol table of the archive element of the archive ABFD
3276    whose archive map contains a mention of SYMDEF, and determine if
3277    the symbol is defined in this element.  */
3278 static bfd_boolean
3279 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3280 {
3281   Elf_Internal_Shdr * hdr;
3282   size_t symcount;
3283   size_t extsymcount;
3284   size_t extsymoff;
3285   Elf_Internal_Sym *isymbuf;
3286   Elf_Internal_Sym *isym;
3287   Elf_Internal_Sym *isymend;
3288   bfd_boolean result;
3289
3290   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3291   if (abfd == NULL)
3292     return FALSE;
3293
3294   if (! bfd_check_format (abfd, bfd_object))
3295     return FALSE;
3296
3297   /* Select the appropriate symbol table.  If we don't know if the
3298      object file is an IR object, give linker LTO plugin a chance to
3299      get the correct symbol table.  */
3300   if (abfd->plugin_format == bfd_plugin_yes
3301 #if BFD_SUPPORTS_PLUGINS
3302       || (abfd->plugin_format == bfd_plugin_unknown
3303           && bfd_link_plugin_object_p (abfd))
3304 #endif
3305       )
3306     {
3307       /* Use the IR symbol table if the object has been claimed by
3308          plugin.  */
3309       abfd = abfd->plugin_dummy_bfd;
3310       hdr = &elf_tdata (abfd)->symtab_hdr;
3311     }
3312   else if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3313     hdr = &elf_tdata (abfd)->symtab_hdr;
3314   else
3315     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3316
3317   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3318
3319   /* The sh_info field of the symtab header tells us where the
3320      external symbols start.  We don't care about the local symbols.  */
3321   if (elf_bad_symtab (abfd))
3322     {
3323       extsymcount = symcount;
3324       extsymoff = 0;
3325     }
3326   else
3327     {
3328       extsymcount = symcount - hdr->sh_info;
3329       extsymoff = hdr->sh_info;
3330     }
3331
3332   if (extsymcount == 0)
3333     return FALSE;
3334
3335   /* Read in the symbol table.  */
3336   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3337                                   NULL, NULL, NULL);
3338   if (isymbuf == NULL)
3339     return FALSE;
3340
3341   /* Scan the symbol table looking for SYMDEF.  */
3342   result = FALSE;
3343   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3344     {
3345       const char *name;
3346
3347       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3348                                               isym->st_name);
3349       if (name == NULL)
3350         break;
3351
3352       if (strcmp (name, symdef->name) == 0)
3353         {
3354           result = is_global_data_symbol_definition (abfd, isym);
3355           break;
3356         }
3357     }
3358
3359   free (isymbuf);
3360
3361   return result;
3362 }
3363 \f
3364 /* Add an entry to the .dynamic table.  */
3365
3366 bfd_boolean
3367 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3368                             bfd_vma tag,
3369                             bfd_vma val)
3370 {
3371   struct elf_link_hash_table *hash_table;
3372   const struct elf_backend_data *bed;
3373   asection *s;
3374   bfd_size_type newsize;
3375   bfd_byte *newcontents;
3376   Elf_Internal_Dyn dyn;
3377
3378   hash_table = elf_hash_table (info);
3379   if (! is_elf_hash_table (hash_table))
3380     return FALSE;
3381
3382   bed = get_elf_backend_data (hash_table->dynobj);
3383   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3384   BFD_ASSERT (s != NULL);
3385
3386   newsize = s->size + bed->s->sizeof_dyn;
3387   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3388   if (newcontents == NULL)
3389     return FALSE;
3390
3391   dyn.d_tag = tag;
3392   dyn.d_un.d_val = val;
3393   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3394
3395   s->size = newsize;
3396   s->contents = newcontents;
3397
3398   return TRUE;
3399 }
3400
3401 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3402    otherwise just check whether one already exists.  Returns -1 on error,
3403    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3404
3405 static int
3406 elf_add_dt_needed_tag (bfd *abfd,
3407                        struct bfd_link_info *info,
3408                        const char *soname,
3409                        bfd_boolean do_it)
3410 {
3411   struct elf_link_hash_table *hash_table;
3412   size_t strindex;
3413
3414   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3415     return -1;
3416
3417   hash_table = elf_hash_table (info);
3418   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3419   if (strindex == (size_t) -1)
3420     return -1;
3421
3422   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3423     {
3424       asection *sdyn;
3425       const struct elf_backend_data *bed;
3426       bfd_byte *extdyn;
3427
3428       bed = get_elf_backend_data (hash_table->dynobj);
3429       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3430       if (sdyn != NULL)
3431         for (extdyn = sdyn->contents;
3432              extdyn < sdyn->contents + sdyn->size;
3433              extdyn += bed->s->sizeof_dyn)
3434           {
3435             Elf_Internal_Dyn dyn;
3436
3437             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3438             if (dyn.d_tag == DT_NEEDED
3439                 && dyn.d_un.d_val == strindex)
3440               {
3441                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3442                 return 1;
3443               }
3444           }
3445     }
3446
3447   if (do_it)
3448     {
3449       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3450         return -1;
3451
3452       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3453         return -1;
3454     }
3455   else
3456     /* We were just checking for existence of the tag.  */
3457     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3458
3459   return 0;
3460 }
3461
3462 /* Return true if SONAME is on the needed list between NEEDED and STOP
3463    (or the end of list if STOP is NULL), and needed by a library that
3464    will be loaded.  */
3465
3466 static bfd_boolean
3467 on_needed_list (const char *soname,
3468                 struct bfd_link_needed_list *needed,
3469                 struct bfd_link_needed_list *stop)
3470 {
3471   struct bfd_link_needed_list *look;
3472   for (look = needed; look != stop; look = look->next)
3473     if (strcmp (soname, look->name) == 0
3474         && ((elf_dyn_lib_class (look->by) & DYN_AS_NEEDED) == 0
3475             /* If needed by a library that itself is not directly
3476                needed, recursively check whether that library is
3477                indirectly needed.  Since we add DT_NEEDED entries to
3478                the end of the list, library dependencies appear after
3479                the library.  Therefore search prior to the current
3480                LOOK, preventing possible infinite recursion.  */
3481             || on_needed_list (elf_dt_name (look->by), needed, look)))
3482       return TRUE;
3483
3484   return FALSE;
3485 }
3486
3487 /* Sort symbol by value, section, and size.  */
3488 static int
3489 elf_sort_symbol (const void *arg1, const void *arg2)
3490 {
3491   const struct elf_link_hash_entry *h1;
3492   const struct elf_link_hash_entry *h2;
3493   bfd_signed_vma vdiff;
3494
3495   h1 = *(const struct elf_link_hash_entry **) arg1;
3496   h2 = *(const struct elf_link_hash_entry **) arg2;
3497   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3498   if (vdiff != 0)
3499     return vdiff > 0 ? 1 : -1;
3500   else
3501     {
3502       int sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3503       if (sdiff != 0)
3504         return sdiff > 0 ? 1 : -1;
3505     }
3506   vdiff = h1->size - h2->size;
3507   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3508 }
3509
3510 /* This function is used to adjust offsets into .dynstr for
3511    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3512
3513 static bfd_boolean
3514 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3515 {
3516   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3517
3518   if (h->dynindx != -1)
3519     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3520   return TRUE;
3521 }
3522
3523 /* Assign string offsets in .dynstr, update all structures referencing
3524    them.  */
3525
3526 static bfd_boolean
3527 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3528 {
3529   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3530   struct elf_link_local_dynamic_entry *entry;
3531   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3532   bfd *dynobj = hash_table->dynobj;
3533   asection *sdyn;
3534   bfd_size_type size;
3535   const struct elf_backend_data *bed;
3536   bfd_byte *extdyn;
3537
3538   _bfd_elf_strtab_finalize (dynstr);
3539   size = _bfd_elf_strtab_size (dynstr);
3540
3541   bed = get_elf_backend_data (dynobj);
3542   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3543   BFD_ASSERT (sdyn != NULL);
3544
3545   /* Update all .dynamic entries referencing .dynstr strings.  */
3546   for (extdyn = sdyn->contents;
3547        extdyn < sdyn->contents + sdyn->size;
3548        extdyn += bed->s->sizeof_dyn)
3549     {
3550       Elf_Internal_Dyn dyn;
3551
3552       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3553       switch (dyn.d_tag)
3554         {
3555         case DT_STRSZ:
3556           dyn.d_un.d_val = size;
3557           break;
3558         case DT_NEEDED:
3559         case DT_SONAME:
3560         case DT_RPATH:
3561         case DT_RUNPATH:
3562         case DT_FILTER:
3563         case DT_AUXILIARY:
3564         case DT_AUDIT:
3565         case DT_DEPAUDIT:
3566           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3567           break;
3568         default:
3569           continue;
3570         }
3571       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3572     }
3573
3574   /* Now update local dynamic symbols.  */
3575   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3576     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3577                                                   entry->isym.st_name);
3578
3579   /* And the rest of dynamic symbols.  */
3580   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3581
3582   /* Adjust version definitions.  */
3583   if (elf_tdata (output_bfd)->cverdefs)
3584     {
3585       asection *s;
3586       bfd_byte *p;
3587       size_t i;
3588       Elf_Internal_Verdef def;
3589       Elf_Internal_Verdaux defaux;
3590
3591       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3592       p = s->contents;
3593       do
3594         {
3595           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3596                                    &def);
3597           p += sizeof (Elf_External_Verdef);
3598           if (def.vd_aux != sizeof (Elf_External_Verdef))
3599             continue;
3600           for (i = 0; i < def.vd_cnt; ++i)
3601             {
3602               _bfd_elf_swap_verdaux_in (output_bfd,
3603                                         (Elf_External_Verdaux *) p, &defaux);
3604               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3605                                                         defaux.vda_name);
3606               _bfd_elf_swap_verdaux_out (output_bfd,
3607                                          &defaux, (Elf_External_Verdaux *) p);
3608               p += sizeof (Elf_External_Verdaux);
3609             }
3610         }
3611       while (def.vd_next);
3612     }
3613
3614   /* Adjust version references.  */
3615   if (elf_tdata (output_bfd)->verref)
3616     {
3617       asection *s;
3618       bfd_byte *p;
3619       size_t i;
3620       Elf_Internal_Verneed need;
3621       Elf_Internal_Vernaux needaux;
3622
3623       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3624       p = s->contents;
3625       do
3626         {
3627           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3628                                     &need);
3629           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3630           _bfd_elf_swap_verneed_out (output_bfd, &need,
3631                                      (Elf_External_Verneed *) p);
3632           p += sizeof (Elf_External_Verneed);
3633           for (i = 0; i < need.vn_cnt; ++i)
3634             {
3635               _bfd_elf_swap_vernaux_in (output_bfd,
3636                                         (Elf_External_Vernaux *) p, &needaux);
3637               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3638                                                          needaux.vna_name);
3639               _bfd_elf_swap_vernaux_out (output_bfd,
3640                                          &needaux,
3641                                          (Elf_External_Vernaux *) p);
3642               p += sizeof (Elf_External_Vernaux);
3643             }
3644         }
3645       while (need.vn_next);
3646     }
3647
3648   return TRUE;
3649 }
3650 \f
3651 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3652    The default is to only match when the INPUT and OUTPUT are exactly
3653    the same target.  */
3654
3655 bfd_boolean
3656 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3657                                     const bfd_target *output)
3658 {
3659   return input == output;
3660 }
3661
3662 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3663    This version is used when different targets for the same architecture
3664    are virtually identical.  */
3665
3666 bfd_boolean
3667 _bfd_elf_relocs_compatible (const bfd_target *input,
3668                             const bfd_target *output)
3669 {
3670   const struct elf_backend_data *obed, *ibed;
3671
3672   if (input == output)
3673     return TRUE;
3674
3675   ibed = xvec_get_elf_backend_data (input);
3676   obed = xvec_get_elf_backend_data (output);
3677
3678   if (ibed->arch != obed->arch)
3679     return FALSE;
3680
3681   /* If both backends are using this function, deem them compatible.  */
3682   return ibed->relocs_compatible == obed->relocs_compatible;
3683 }
3684
3685 /* Make a special call to the linker "notice" function to tell it that
3686    we are about to handle an as-needed lib, or have finished
3687    processing the lib.  */
3688
3689 bfd_boolean
3690 _bfd_elf_notice_as_needed (bfd *ibfd,
3691                            struct bfd_link_info *info,
3692                            enum notice_asneeded_action act)
3693 {
3694   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3695 }
3696
3697 /* Check relocations an ELF object file.  */
3698
3699 bfd_boolean
3700 _bfd_elf_link_check_relocs (bfd *abfd, struct bfd_link_info *info)
3701 {
3702   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3703   struct elf_link_hash_table *htab = elf_hash_table (info);
3704
3705   /* If this object is the same format as the output object, and it is
3706      not a shared library, then let the backend look through the
3707      relocs.
3708
3709      This is required to build global offset table entries and to
3710      arrange for dynamic relocs.  It is not required for the
3711      particular common case of linking non PIC code, even when linking
3712      against shared libraries, but unfortunately there is no way of
3713      knowing whether an object file has been compiled PIC or not.
3714      Looking through the relocs is not particularly time consuming.
3715      The problem is that we must either (1) keep the relocs in memory,
3716      which causes the linker to require additional runtime memory or
3717      (2) read the relocs twice from the input file, which wastes time.
3718      This would be a good case for using mmap.
3719
3720      I have no idea how to handle linking PIC code into a file of a
3721      different format.  It probably can't be done.  */
3722   if ((abfd->flags & DYNAMIC) == 0
3723       && is_elf_hash_table (htab)
3724       && bed->check_relocs != NULL
3725       && elf_object_id (abfd) == elf_hash_table_id (htab)
3726       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
3727     {
3728       asection *o;
3729
3730       for (o = abfd->sections; o != NULL; o = o->next)
3731         {
3732           Elf_Internal_Rela *internal_relocs;
3733           bfd_boolean ok;
3734
3735           /* Don't check relocations in excluded sections.  */
3736           if ((o->flags & SEC_RELOC) == 0
3737               || (o->flags & SEC_EXCLUDE) != 0
3738               || o->reloc_count == 0
3739               || ((info->strip == strip_all || info->strip == strip_debugger)
3740                   && (o->flags & SEC_DEBUGGING) != 0)
3741               || bfd_is_abs_section (o->output_section))
3742             continue;
3743
3744           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
3745                                                        info->keep_memory);
3746           if (internal_relocs == NULL)
3747             return FALSE;
3748
3749           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
3750
3751           if (elf_section_data (o)->relocs != internal_relocs)
3752             free (internal_relocs);
3753
3754           if (! ok)
3755             return FALSE;
3756         }
3757     }
3758
3759   return TRUE;
3760 }
3761
3762 /* Add symbols from an ELF object file to the linker hash table.  */
3763
3764 static bfd_boolean
3765 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3766 {
3767   Elf_Internal_Ehdr *ehdr;
3768   Elf_Internal_Shdr *hdr;
3769   size_t symcount;
3770   size_t extsymcount;
3771   size_t extsymoff;
3772   struct elf_link_hash_entry **sym_hash;
3773   bfd_boolean dynamic;
3774   Elf_External_Versym *extversym = NULL;
3775   Elf_External_Versym *ever;
3776   struct elf_link_hash_entry *weaks;
3777   struct elf_link_hash_entry **nondeflt_vers = NULL;
3778   size_t nondeflt_vers_cnt = 0;
3779   Elf_Internal_Sym *isymbuf = NULL;
3780   Elf_Internal_Sym *isym;
3781   Elf_Internal_Sym *isymend;
3782   const struct elf_backend_data *bed;
3783   bfd_boolean add_needed;
3784   struct elf_link_hash_table *htab;
3785   bfd_size_type amt;
3786   void *alloc_mark = NULL;
3787   struct bfd_hash_entry **old_table = NULL;
3788   unsigned int old_size = 0;
3789   unsigned int old_count = 0;
3790   void *old_tab = NULL;
3791   void *old_ent;
3792   struct bfd_link_hash_entry *old_undefs = NULL;
3793   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3794   void *old_strtab = NULL;
3795   size_t tabsize = 0;
3796   asection *s;
3797   bfd_boolean just_syms;
3798
3799   htab = elf_hash_table (info);
3800   bed = get_elf_backend_data (abfd);
3801
3802   if ((abfd->flags & DYNAMIC) == 0)
3803     dynamic = FALSE;
3804   else
3805     {
3806       dynamic = TRUE;
3807
3808       /* You can't use -r against a dynamic object.  Also, there's no
3809          hope of using a dynamic object which does not exactly match
3810          the format of the output file.  */
3811       if (bfd_link_relocatable (info)
3812           || !is_elf_hash_table (htab)
3813           || info->output_bfd->xvec != abfd->xvec)
3814         {
3815           if (bfd_link_relocatable (info))
3816             bfd_set_error (bfd_error_invalid_operation);
3817           else
3818             bfd_set_error (bfd_error_wrong_format);
3819           goto error_return;
3820         }
3821     }
3822
3823   ehdr = elf_elfheader (abfd);
3824   if (info->warn_alternate_em
3825       && bed->elf_machine_code != ehdr->e_machine
3826       && ((bed->elf_machine_alt1 != 0
3827            && ehdr->e_machine == bed->elf_machine_alt1)
3828           || (bed->elf_machine_alt2 != 0
3829               && ehdr->e_machine == bed->elf_machine_alt2)))
3830     _bfd_error_handler
3831       /* xgettext:c-format */
3832       (_("alternate ELF machine code found (%d) in %pB, expecting %d"),
3833        ehdr->e_machine, abfd, bed->elf_machine_code);
3834
3835   /* As a GNU extension, any input sections which are named
3836      .gnu.warning.SYMBOL are treated as warning symbols for the given
3837      symbol.  This differs from .gnu.warning sections, which generate
3838      warnings when they are included in an output file.  */
3839   /* PR 12761: Also generate this warning when building shared libraries.  */
3840   for (s = abfd->sections; s != NULL; s = s->next)
3841     {
3842       const char *name;
3843
3844       name = bfd_get_section_name (abfd, s);
3845       if (CONST_STRNEQ (name, ".gnu.warning."))
3846         {
3847           char *msg;
3848           bfd_size_type sz;
3849
3850           name += sizeof ".gnu.warning." - 1;
3851
3852           /* If this is a shared object, then look up the symbol
3853              in the hash table.  If it is there, and it is already
3854              been defined, then we will not be using the entry
3855              from this shared object, so we don't need to warn.
3856              FIXME: If we see the definition in a regular object
3857              later on, we will warn, but we shouldn't.  The only
3858              fix is to keep track of what warnings we are supposed
3859              to emit, and then handle them all at the end of the
3860              link.  */
3861           if (dynamic)
3862             {
3863               struct elf_link_hash_entry *h;
3864
3865               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3866
3867               /* FIXME: What about bfd_link_hash_common?  */
3868               if (h != NULL
3869                   && (h->root.type == bfd_link_hash_defined
3870                       || h->root.type == bfd_link_hash_defweak))
3871                 continue;
3872             }
3873
3874           sz = s->size;
3875           msg = (char *) bfd_alloc (abfd, sz + 1);
3876           if (msg == NULL)
3877             goto error_return;
3878
3879           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3880             goto error_return;
3881
3882           msg[sz] = '\0';
3883
3884           if (! (_bfd_generic_link_add_one_symbol
3885                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3886                   FALSE, bed->collect, NULL)))
3887             goto error_return;
3888
3889           if (bfd_link_executable (info))
3890             {
3891               /* Clobber the section size so that the warning does
3892                  not get copied into the output file.  */
3893               s->size = 0;
3894
3895               /* Also set SEC_EXCLUDE, so that symbols defined in
3896                  the warning section don't get copied to the output.  */
3897               s->flags |= SEC_EXCLUDE;
3898             }
3899         }
3900     }
3901
3902   just_syms = ((s = abfd->sections) != NULL
3903                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3904
3905   add_needed = TRUE;
3906   if (! dynamic)
3907     {
3908       /* If we are creating a shared library, create all the dynamic
3909          sections immediately.  We need to attach them to something,
3910          so we attach them to this BFD, provided it is the right
3911          format and is not from ld --just-symbols.  Always create the
3912          dynamic sections for -E/--dynamic-list.  FIXME: If there
3913          are no input BFD's of the same format as the output, we can't
3914          make a shared library.  */
3915       if (!just_syms
3916           && (bfd_link_pic (info)
3917               || (!bfd_link_relocatable (info)
3918                   && info->nointerp
3919                   && (info->export_dynamic || info->dynamic)))
3920           && is_elf_hash_table (htab)
3921           && info->output_bfd->xvec == abfd->xvec
3922           && !htab->dynamic_sections_created)
3923         {
3924           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3925             goto error_return;
3926         }
3927     }
3928   else if (!is_elf_hash_table (htab))
3929     goto error_return;
3930   else
3931     {
3932       const char *soname = NULL;
3933       char *audit = NULL;
3934       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3935       const Elf_Internal_Phdr *phdr;
3936       int ret;
3937
3938       /* ld --just-symbols and dynamic objects don't mix very well.
3939          ld shouldn't allow it.  */
3940       if (just_syms)
3941         abort ();
3942
3943       /* If this dynamic lib was specified on the command line with
3944          --as-needed in effect, then we don't want to add a DT_NEEDED
3945          tag unless the lib is actually used.  Similary for libs brought
3946          in by another lib's DT_NEEDED.  When --no-add-needed is used
3947          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3948          any dynamic library in DT_NEEDED tags in the dynamic lib at
3949          all.  */
3950       add_needed = (elf_dyn_lib_class (abfd)
3951                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3952                        | DYN_NO_NEEDED)) == 0;
3953
3954       s = bfd_get_section_by_name (abfd, ".dynamic");
3955       if (s != NULL)
3956         {
3957           bfd_byte *dynbuf;
3958           bfd_byte *extdyn;
3959           unsigned int elfsec;
3960           unsigned long shlink;
3961
3962           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3963             {
3964 error_free_dyn:
3965               free (dynbuf);
3966               goto error_return;
3967             }
3968
3969           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3970           if (elfsec == SHN_BAD)
3971             goto error_free_dyn;
3972           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3973
3974           for (extdyn = dynbuf;
3975                extdyn < dynbuf + s->size;
3976                extdyn += bed->s->sizeof_dyn)
3977             {
3978               Elf_Internal_Dyn dyn;
3979
3980               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3981               if (dyn.d_tag == DT_SONAME)
3982                 {
3983                   unsigned int tagv = dyn.d_un.d_val;
3984                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3985                   if (soname == NULL)
3986                     goto error_free_dyn;
3987                 }
3988               if (dyn.d_tag == DT_NEEDED)
3989                 {
3990                   struct bfd_link_needed_list *n, **pn;
3991                   char *fnm, *anm;
3992                   unsigned int tagv = dyn.d_un.d_val;
3993
3994                   amt = sizeof (struct bfd_link_needed_list);
3995                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3996                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3997                   if (n == NULL || fnm == NULL)
3998                     goto error_free_dyn;
3999                   amt = strlen (fnm) + 1;
4000                   anm = (char *) bfd_alloc (abfd, amt);
4001                   if (anm == NULL)
4002                     goto error_free_dyn;
4003                   memcpy (anm, fnm, amt);
4004                   n->name = anm;
4005                   n->by = abfd;
4006                   n->next = NULL;
4007                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
4008                     ;
4009                   *pn = n;
4010                 }
4011               if (dyn.d_tag == DT_RUNPATH)
4012                 {
4013                   struct bfd_link_needed_list *n, **pn;
4014                   char *fnm, *anm;
4015                   unsigned int tagv = dyn.d_un.d_val;
4016
4017                   amt = sizeof (struct bfd_link_needed_list);
4018                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
4019                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4020                   if (n == NULL || fnm == NULL)
4021                     goto error_free_dyn;
4022                   amt = strlen (fnm) + 1;
4023                   anm = (char *) bfd_alloc (abfd, amt);
4024                   if (anm == NULL)
4025                     goto error_free_dyn;
4026                   memcpy (anm, fnm, amt);
4027                   n->name = anm;
4028                   n->by = abfd;
4029                   n->next = NULL;
4030                   for (pn = & runpath;
4031                        *pn != NULL;
4032                        pn = &(*pn)->next)
4033                     ;
4034                   *pn = n;
4035                 }
4036               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
4037               if (!runpath && dyn.d_tag == DT_RPATH)
4038                 {
4039                   struct bfd_link_needed_list *n, **pn;
4040                   char *fnm, *anm;
4041                   unsigned int tagv = dyn.d_un.d_val;
4042
4043                   amt = sizeof (struct bfd_link_needed_list);
4044                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
4045                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4046                   if (n == NULL || fnm == NULL)
4047                     goto error_free_dyn;
4048                   amt = strlen (fnm) + 1;
4049                   anm = (char *) bfd_alloc (abfd, amt);
4050                   if (anm == NULL)
4051                     goto error_free_dyn;
4052                   memcpy (anm, fnm, amt);
4053                   n->name = anm;
4054                   n->by = abfd;
4055                   n->next = NULL;
4056                   for (pn = & rpath;
4057                        *pn != NULL;
4058                        pn = &(*pn)->next)
4059                     ;
4060                   *pn = n;
4061                 }
4062               if (dyn.d_tag == DT_AUDIT)
4063                 {
4064                   unsigned int tagv = dyn.d_un.d_val;
4065                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4066                 }
4067             }
4068
4069           free (dynbuf);
4070         }
4071
4072       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
4073          frees all more recently bfd_alloc'd blocks as well.  */
4074       if (runpath)
4075         rpath = runpath;
4076
4077       if (rpath)
4078         {
4079           struct bfd_link_needed_list **pn;
4080           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
4081             ;
4082           *pn = rpath;
4083         }
4084
4085       /* If we have a PT_GNU_RELRO program header, mark as read-only
4086          all sections contained fully therein.  This makes relro
4087          shared library sections appear as they will at run-time.  */
4088       phdr = elf_tdata (abfd)->phdr + elf_elfheader (abfd)->e_phnum;
4089       while (--phdr >= elf_tdata (abfd)->phdr)
4090         if (phdr->p_type == PT_GNU_RELRO)
4091           {
4092             for (s = abfd->sections; s != NULL; s = s->next)
4093               if ((s->flags & SEC_ALLOC) != 0
4094                   && s->vma >= phdr->p_vaddr
4095                   && s->vma + s->size <= phdr->p_vaddr + phdr->p_memsz)
4096                 s->flags |= SEC_READONLY;
4097             break;
4098           }
4099
4100       /* We do not want to include any of the sections in a dynamic
4101          object in the output file.  We hack by simply clobbering the
4102          list of sections in the BFD.  This could be handled more
4103          cleanly by, say, a new section flag; the existing
4104          SEC_NEVER_LOAD flag is not the one we want, because that one
4105          still implies that the section takes up space in the output
4106          file.  */
4107       bfd_section_list_clear (abfd);
4108
4109       /* Find the name to use in a DT_NEEDED entry that refers to this
4110          object.  If the object has a DT_SONAME entry, we use it.
4111          Otherwise, if the generic linker stuck something in
4112          elf_dt_name, we use that.  Otherwise, we just use the file
4113          name.  */
4114       if (soname == NULL || *soname == '\0')
4115         {
4116           soname = elf_dt_name (abfd);
4117           if (soname == NULL || *soname == '\0')
4118             soname = bfd_get_filename (abfd);
4119         }
4120
4121       /* Save the SONAME because sometimes the linker emulation code
4122          will need to know it.  */
4123       elf_dt_name (abfd) = soname;
4124
4125       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4126       if (ret < 0)
4127         goto error_return;
4128
4129       /* If we have already included this dynamic object in the
4130          link, just ignore it.  There is no reason to include a
4131          particular dynamic object more than once.  */
4132       if (ret > 0)
4133         return TRUE;
4134
4135       /* Save the DT_AUDIT entry for the linker emulation code. */
4136       elf_dt_audit (abfd) = audit;
4137     }
4138
4139   /* If this is a dynamic object, we always link against the .dynsym
4140      symbol table, not the .symtab symbol table.  The dynamic linker
4141      will only see the .dynsym symbol table, so there is no reason to
4142      look at .symtab for a dynamic object.  */
4143
4144   if (! dynamic || elf_dynsymtab (abfd) == 0)
4145     hdr = &elf_tdata (abfd)->symtab_hdr;
4146   else
4147     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
4148
4149   symcount = hdr->sh_size / bed->s->sizeof_sym;
4150
4151   /* The sh_info field of the symtab header tells us where the
4152      external symbols start.  We don't care about the local symbols at
4153      this point.  */
4154   if (elf_bad_symtab (abfd))
4155     {
4156       extsymcount = symcount;
4157       extsymoff = 0;
4158     }
4159   else
4160     {
4161       extsymcount = symcount - hdr->sh_info;
4162       extsymoff = hdr->sh_info;
4163     }
4164
4165   sym_hash = elf_sym_hashes (abfd);
4166   if (extsymcount != 0)
4167     {
4168       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
4169                                       NULL, NULL, NULL);
4170       if (isymbuf == NULL)
4171         goto error_return;
4172
4173       if (sym_hash == NULL)
4174         {
4175           /* We store a pointer to the hash table entry for each
4176              external symbol.  */
4177           amt = extsymcount;
4178           amt *= sizeof (struct elf_link_hash_entry *);
4179           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
4180           if (sym_hash == NULL)
4181             goto error_free_sym;
4182           elf_sym_hashes (abfd) = sym_hash;
4183         }
4184     }
4185
4186   if (dynamic)
4187     {
4188       /* Read in any version definitions.  */
4189       if (!_bfd_elf_slurp_version_tables (abfd,
4190                                           info->default_imported_symver))
4191         goto error_free_sym;
4192
4193       /* Read in the symbol versions, but don't bother to convert them
4194          to internal format.  */
4195       if (elf_dynversym (abfd) != 0)
4196         {
4197           Elf_Internal_Shdr *versymhdr;
4198
4199           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
4200           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
4201           if (extversym == NULL)
4202             goto error_free_sym;
4203           amt = versymhdr->sh_size;
4204           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
4205               || bfd_bread (extversym, amt, abfd) != amt)
4206             goto error_free_vers;
4207         }
4208     }
4209
4210   /* If we are loading an as-needed shared lib, save the symbol table
4211      state before we start adding symbols.  If the lib turns out
4212      to be unneeded, restore the state.  */
4213   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4214     {
4215       unsigned int i;
4216       size_t entsize;
4217
4218       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
4219         {
4220           struct bfd_hash_entry *p;
4221           struct elf_link_hash_entry *h;
4222
4223           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4224             {
4225               h = (struct elf_link_hash_entry *) p;
4226               entsize += htab->root.table.entsize;
4227               if (h->root.type == bfd_link_hash_warning)
4228                 entsize += htab->root.table.entsize;
4229             }
4230         }
4231
4232       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
4233       old_tab = bfd_malloc (tabsize + entsize);
4234       if (old_tab == NULL)
4235         goto error_free_vers;
4236
4237       /* Remember the current objalloc pointer, so that all mem for
4238          symbols added can later be reclaimed.  */
4239       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
4240       if (alloc_mark == NULL)
4241         goto error_free_vers;
4242
4243       /* Make a special call to the linker "notice" function to
4244          tell it that we are about to handle an as-needed lib.  */
4245       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
4246         goto error_free_vers;
4247
4248       /* Clone the symbol table.  Remember some pointers into the
4249          symbol table, and dynamic symbol count.  */
4250       old_ent = (char *) old_tab + tabsize;
4251       memcpy (old_tab, htab->root.table.table, tabsize);
4252       old_undefs = htab->root.undefs;
4253       old_undefs_tail = htab->root.undefs_tail;
4254       old_table = htab->root.table.table;
4255       old_size = htab->root.table.size;
4256       old_count = htab->root.table.count;
4257       old_strtab = _bfd_elf_strtab_save (htab->dynstr);
4258       if (old_strtab == NULL)
4259         goto error_free_vers;
4260
4261       for (i = 0; i < htab->root.table.size; i++)
4262         {
4263           struct bfd_hash_entry *p;
4264           struct elf_link_hash_entry *h;
4265
4266           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4267             {
4268               memcpy (old_ent, p, htab->root.table.entsize);
4269               old_ent = (char *) old_ent + htab->root.table.entsize;
4270               h = (struct elf_link_hash_entry *) p;
4271               if (h->root.type == bfd_link_hash_warning)
4272                 {
4273                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
4274                   old_ent = (char *) old_ent + htab->root.table.entsize;
4275                 }
4276             }
4277         }
4278     }
4279
4280   weaks = NULL;
4281   ever = extversym != NULL ? extversym + extsymoff : NULL;
4282   for (isym = isymbuf, isymend = isymbuf + extsymcount;
4283        isym < isymend;
4284        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
4285     {
4286       int bind;
4287       bfd_vma value;
4288       asection *sec, *new_sec;
4289       flagword flags;
4290       const char *name;
4291       struct elf_link_hash_entry *h;
4292       struct elf_link_hash_entry *hi;
4293       bfd_boolean definition;
4294       bfd_boolean size_change_ok;
4295       bfd_boolean type_change_ok;
4296       bfd_boolean new_weak;
4297       bfd_boolean old_weak;
4298       bfd_boolean override;
4299       bfd_boolean common;
4300       bfd_boolean discarded;
4301       unsigned int old_alignment;
4302       bfd *old_bfd;
4303       bfd_boolean matched;
4304
4305       override = FALSE;
4306
4307       flags = BSF_NO_FLAGS;
4308       sec = NULL;
4309       value = isym->st_value;
4310       common = bed->common_definition (isym);
4311       if (common && info->inhibit_common_definition)
4312         {
4313           /* Treat common symbol as undefined for --no-define-common.  */
4314           isym->st_shndx = SHN_UNDEF;
4315           common = FALSE;
4316         }
4317       discarded = FALSE;
4318
4319       bind = ELF_ST_BIND (isym->st_info);
4320       switch (bind)
4321         {
4322         case STB_LOCAL:
4323           /* This should be impossible, since ELF requires that all
4324              global symbols follow all local symbols, and that sh_info
4325              point to the first global symbol.  Unfortunately, Irix 5
4326              screws this up.  */
4327           continue;
4328
4329         case STB_GLOBAL:
4330           if (isym->st_shndx != SHN_UNDEF && !common)
4331             flags = BSF_GLOBAL;
4332           break;
4333
4334         case STB_WEAK:
4335           flags = BSF_WEAK;
4336           break;
4337
4338         case STB_GNU_UNIQUE:
4339           flags = BSF_GNU_UNIQUE;
4340           break;
4341
4342         default:
4343           /* Leave it up to the processor backend.  */
4344           break;
4345         }
4346
4347       if (isym->st_shndx == SHN_UNDEF)
4348         sec = bfd_und_section_ptr;
4349       else if (isym->st_shndx == SHN_ABS)
4350         sec = bfd_abs_section_ptr;
4351       else if (isym->st_shndx == SHN_COMMON)
4352         {
4353           sec = bfd_com_section_ptr;
4354           /* What ELF calls the size we call the value.  What ELF
4355              calls the value we call the alignment.  */
4356           value = isym->st_size;
4357         }
4358       else
4359         {
4360           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
4361           if (sec == NULL)
4362             sec = bfd_abs_section_ptr;
4363           else if (discarded_section (sec))
4364             {
4365               /* Symbols from discarded section are undefined.  We keep
4366                  its visibility.  */
4367               sec = bfd_und_section_ptr;
4368               discarded = TRUE;
4369               isym->st_shndx = SHN_UNDEF;
4370             }
4371           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
4372             value -= sec->vma;
4373         }
4374
4375       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4376                                               isym->st_name);
4377       if (name == NULL)
4378         goto error_free_vers;
4379
4380       if (isym->st_shndx == SHN_COMMON
4381           && (abfd->flags & BFD_PLUGIN) != 0)
4382         {
4383           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4384
4385           if (xc == NULL)
4386             {
4387               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4388                                  | SEC_EXCLUDE);
4389               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4390               if (xc == NULL)
4391                 goto error_free_vers;
4392             }
4393           sec = xc;
4394         }
4395       else if (isym->st_shndx == SHN_COMMON
4396                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4397                && !bfd_link_relocatable (info))
4398         {
4399           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4400
4401           if (tcomm == NULL)
4402             {
4403               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4404                                  | SEC_LINKER_CREATED);
4405               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4406               if (tcomm == NULL)
4407                 goto error_free_vers;
4408             }
4409           sec = tcomm;
4410         }
4411       else if (bed->elf_add_symbol_hook)
4412         {
4413           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4414                                              &sec, &value))
4415             goto error_free_vers;
4416
4417           /* The hook function sets the name to NULL if this symbol
4418              should be skipped for some reason.  */
4419           if (name == NULL)
4420             continue;
4421         }
4422
4423       /* Sanity check that all possibilities were handled.  */
4424       if (sec == NULL)
4425         {
4426           bfd_set_error (bfd_error_bad_value);
4427           goto error_free_vers;
4428         }
4429
4430       /* Silently discard TLS symbols from --just-syms.  There's
4431          no way to combine a static TLS block with a new TLS block
4432          for this executable.  */
4433       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4434           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4435         continue;
4436
4437       if (bfd_is_und_section (sec)
4438           || bfd_is_com_section (sec))
4439         definition = FALSE;
4440       else
4441         definition = TRUE;
4442
4443       size_change_ok = FALSE;
4444       type_change_ok = bed->type_change_ok;
4445       old_weak = FALSE;
4446       matched = FALSE;
4447       old_alignment = 0;
4448       old_bfd = NULL;
4449       new_sec = sec;
4450
4451       if (is_elf_hash_table (htab))
4452         {
4453           Elf_Internal_Versym iver;
4454           unsigned int vernum = 0;
4455           bfd_boolean skip;
4456
4457           if (ever == NULL)
4458             {
4459               if (info->default_imported_symver)
4460                 /* Use the default symbol version created earlier.  */
4461                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4462               else
4463                 iver.vs_vers = 0;
4464             }
4465           else
4466             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4467
4468           vernum = iver.vs_vers & VERSYM_VERSION;
4469
4470           /* If this is a hidden symbol, or if it is not version
4471              1, we append the version name to the symbol name.
4472              However, we do not modify a non-hidden absolute symbol
4473              if it is not a function, because it might be the version
4474              symbol itself.  FIXME: What if it isn't?  */
4475           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4476               || (vernum > 1
4477                   && (!bfd_is_abs_section (sec)
4478                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4479             {
4480               const char *verstr;
4481               size_t namelen, verlen, newlen;
4482               char *newname, *p;
4483
4484               if (isym->st_shndx != SHN_UNDEF)
4485                 {
4486                   if (vernum > elf_tdata (abfd)->cverdefs)
4487                     verstr = NULL;
4488                   else if (vernum > 1)
4489                     verstr =
4490                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4491                   else
4492                     verstr = "";
4493
4494                   if (verstr == NULL)
4495                     {
4496                       _bfd_error_handler
4497                         /* xgettext:c-format */
4498                         (_("%pB: %s: invalid version %u (max %d)"),
4499                          abfd, name, vernum,
4500                          elf_tdata (abfd)->cverdefs);
4501                       bfd_set_error (bfd_error_bad_value);
4502                       goto error_free_vers;
4503                     }
4504                 }
4505               else
4506                 {
4507                   /* We cannot simply test for the number of
4508                      entries in the VERNEED section since the
4509                      numbers for the needed versions do not start
4510                      at 0.  */
4511                   Elf_Internal_Verneed *t;
4512
4513                   verstr = NULL;
4514                   for (t = elf_tdata (abfd)->verref;
4515                        t != NULL;
4516                        t = t->vn_nextref)
4517                     {
4518                       Elf_Internal_Vernaux *a;
4519
4520                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4521                         {
4522                           if (a->vna_other == vernum)
4523                             {
4524                               verstr = a->vna_nodename;
4525                               break;
4526                             }
4527                         }
4528                       if (a != NULL)
4529                         break;
4530                     }
4531                   if (verstr == NULL)
4532                     {
4533                       _bfd_error_handler
4534                         /* xgettext:c-format */
4535                         (_("%pB: %s: invalid needed version %d"),
4536                          abfd, name, vernum);
4537                       bfd_set_error (bfd_error_bad_value);
4538                       goto error_free_vers;
4539                     }
4540                 }
4541
4542               namelen = strlen (name);
4543               verlen = strlen (verstr);
4544               newlen = namelen + verlen + 2;
4545               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4546                   && isym->st_shndx != SHN_UNDEF)
4547                 ++newlen;
4548
4549               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4550               if (newname == NULL)
4551                 goto error_free_vers;
4552               memcpy (newname, name, namelen);
4553               p = newname + namelen;
4554               *p++ = ELF_VER_CHR;
4555               /* If this is a defined non-hidden version symbol,
4556                  we add another @ to the name.  This indicates the
4557                  default version of the symbol.  */
4558               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4559                   && isym->st_shndx != SHN_UNDEF)
4560                 *p++ = ELF_VER_CHR;
4561               memcpy (p, verstr, verlen + 1);
4562
4563               name = newname;
4564             }
4565
4566           /* If this symbol has default visibility and the user has
4567              requested we not re-export it, then mark it as hidden.  */
4568           if (!bfd_is_und_section (sec)
4569               && !dynamic
4570               && abfd->no_export
4571               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4572             isym->st_other = (STV_HIDDEN
4573                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4574
4575           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4576                                       sym_hash, &old_bfd, &old_weak,
4577                                       &old_alignment, &skip, &override,
4578                                       &type_change_ok, &size_change_ok,
4579                                       &matched))
4580             goto error_free_vers;
4581
4582           if (skip)
4583             continue;
4584
4585           /* Override a definition only if the new symbol matches the
4586              existing one.  */
4587           if (override && matched)
4588             definition = FALSE;
4589
4590           h = *sym_hash;
4591           while (h->root.type == bfd_link_hash_indirect
4592                  || h->root.type == bfd_link_hash_warning)
4593             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4594
4595           if (elf_tdata (abfd)->verdef != NULL
4596               && vernum > 1
4597               && definition)
4598             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4599         }
4600
4601       if (! (_bfd_generic_link_add_one_symbol
4602              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4603               (struct bfd_link_hash_entry **) sym_hash)))
4604         goto error_free_vers;
4605
4606       if ((flags & BSF_GNU_UNIQUE)
4607           && (abfd->flags & DYNAMIC) == 0
4608           && bfd_get_flavour (info->output_bfd) == bfd_target_elf_flavour)
4609         elf_tdata (info->output_bfd)->has_gnu_symbols |= elf_gnu_symbol_unique;
4610
4611       h = *sym_hash;
4612       /* We need to make sure that indirect symbol dynamic flags are
4613          updated.  */
4614       hi = h;
4615       while (h->root.type == bfd_link_hash_indirect
4616              || h->root.type == bfd_link_hash_warning)
4617         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4618
4619       /* Setting the index to -3 tells elf_link_output_extsym that
4620          this symbol is defined in a discarded section.  */
4621       if (discarded)
4622         h->indx = -3;
4623
4624       *sym_hash = h;
4625
4626       new_weak = (flags & BSF_WEAK) != 0;
4627       if (dynamic
4628           && definition
4629           && new_weak
4630           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4631           && is_elf_hash_table (htab)
4632           && h->u.alias == NULL)
4633         {
4634           /* Keep a list of all weak defined non function symbols from
4635              a dynamic object, using the alias field.  Later in this
4636              function we will set the alias field to the correct
4637              value.  We only put non-function symbols from dynamic
4638              objects on this list, because that happens to be the only
4639              time we need to know the normal symbol corresponding to a
4640              weak symbol, and the information is time consuming to
4641              figure out.  If the alias field is not already NULL,
4642              then this symbol was already defined by some previous
4643              dynamic object, and we will be using that previous
4644              definition anyhow.  */
4645
4646           h->u.alias = weaks;
4647           weaks = h;
4648         }
4649
4650       /* Set the alignment of a common symbol.  */
4651       if ((common || bfd_is_com_section (sec))
4652           && h->root.type == bfd_link_hash_common)
4653         {
4654           unsigned int align;
4655
4656           if (common)
4657             align = bfd_log2 (isym->st_value);
4658           else
4659             {
4660               /* The new symbol is a common symbol in a shared object.
4661                  We need to get the alignment from the section.  */
4662               align = new_sec->alignment_power;
4663             }
4664           if (align > old_alignment)
4665             h->root.u.c.p->alignment_power = align;
4666           else
4667             h->root.u.c.p->alignment_power = old_alignment;
4668         }
4669
4670       if (is_elf_hash_table (htab))
4671         {
4672           /* Set a flag in the hash table entry indicating the type of
4673              reference or definition we just found.  A dynamic symbol
4674              is one which is referenced or defined by both a regular
4675              object and a shared object.  */
4676           bfd_boolean dynsym = FALSE;
4677
4678           /* Plugin symbols aren't normal.  Don't set def_regular or
4679              ref_regular for them, or make them dynamic.  */
4680           if ((abfd->flags & BFD_PLUGIN) != 0)
4681             ;
4682           else if (! dynamic)
4683             {
4684               if (! definition)
4685                 {
4686                   h->ref_regular = 1;
4687                   if (bind != STB_WEAK)
4688                     h->ref_regular_nonweak = 1;
4689                 }
4690               else
4691                 {
4692                   h->def_regular = 1;
4693                   if (h->def_dynamic)
4694                     {
4695                       h->def_dynamic = 0;
4696                       h->ref_dynamic = 1;
4697                     }
4698                 }
4699
4700               /* If the indirect symbol has been forced local, don't
4701                  make the real symbol dynamic.  */
4702               if ((h == hi || !hi->forced_local)
4703                   && (bfd_link_dll (info)
4704                       || h->def_dynamic
4705                       || h->ref_dynamic))
4706                 dynsym = TRUE;
4707             }
4708           else
4709             {
4710               if (! definition)
4711                 {
4712                   h->ref_dynamic = 1;
4713                   hi->ref_dynamic = 1;
4714                 }
4715               else
4716                 {
4717                   h->def_dynamic = 1;
4718                   hi->def_dynamic = 1;
4719                 }
4720
4721               /* If the indirect symbol has been forced local, don't
4722                  make the real symbol dynamic.  */
4723               if ((h == hi || !hi->forced_local)
4724                   && (h->def_regular
4725                       || h->ref_regular
4726                       || (h->is_weakalias
4727                           && weakdef (h)->dynindx != -1)))
4728                 dynsym = TRUE;
4729             }
4730
4731           /* Check to see if we need to add an indirect symbol for
4732              the default name.  */
4733           if (definition
4734               || (!override && h->root.type == bfd_link_hash_common))
4735             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4736                                               sec, value, &old_bfd, &dynsym))
4737               goto error_free_vers;
4738
4739           /* Check the alignment when a common symbol is involved. This
4740              can change when a common symbol is overridden by a normal
4741              definition or a common symbol is ignored due to the old
4742              normal definition. We need to make sure the maximum
4743              alignment is maintained.  */
4744           if ((old_alignment || common)
4745               && h->root.type != bfd_link_hash_common)
4746             {
4747               unsigned int common_align;
4748               unsigned int normal_align;
4749               unsigned int symbol_align;
4750               bfd *normal_bfd;
4751               bfd *common_bfd;
4752
4753               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4754                           || h->root.type == bfd_link_hash_defweak);
4755
4756               symbol_align = ffs (h->root.u.def.value) - 1;
4757               if (h->root.u.def.section->owner != NULL
4758                   && (h->root.u.def.section->owner->flags
4759                        & (DYNAMIC | BFD_PLUGIN)) == 0)
4760                 {
4761                   normal_align = h->root.u.def.section->alignment_power;
4762                   if (normal_align > symbol_align)
4763                     normal_align = symbol_align;
4764                 }
4765               else
4766                 normal_align = symbol_align;
4767
4768               if (old_alignment)
4769                 {
4770                   common_align = old_alignment;
4771                   common_bfd = old_bfd;
4772                   normal_bfd = abfd;
4773                 }
4774               else
4775                 {
4776                   common_align = bfd_log2 (isym->st_value);
4777                   common_bfd = abfd;
4778                   normal_bfd = old_bfd;
4779                 }
4780
4781               if (normal_align < common_align)
4782                 {
4783                   /* PR binutils/2735 */
4784                   if (normal_bfd == NULL)
4785                     _bfd_error_handler
4786                       /* xgettext:c-format */
4787                       (_("warning: alignment %u of common symbol `%s' in %pB is"
4788                          " greater than the alignment (%u) of its section %pA"),
4789                        1 << common_align, name, common_bfd,
4790                        1 << normal_align, h->root.u.def.section);
4791                   else
4792                     _bfd_error_handler
4793                       /* xgettext:c-format */
4794                       (_("warning: alignment %u of symbol `%s' in %pB"
4795                          " is smaller than %u in %pB"),
4796                        1 << normal_align, name, normal_bfd,
4797                        1 << common_align, common_bfd);
4798                 }
4799             }
4800
4801           /* Remember the symbol size if it isn't undefined.  */
4802           if (isym->st_size != 0
4803               && isym->st_shndx != SHN_UNDEF
4804               && (definition || h->size == 0))
4805             {
4806               if (h->size != 0
4807                   && h->size != isym->st_size
4808                   && ! size_change_ok)
4809                 _bfd_error_handler
4810                   /* xgettext:c-format */
4811                   (_("warning: size of symbol `%s' changed"
4812                      " from %" PRIu64 " in %pB to %" PRIu64 " in %pB"),
4813                    name, (uint64_t) h->size, old_bfd,
4814                    (uint64_t) isym->st_size, abfd);
4815
4816               h->size = isym->st_size;
4817             }
4818
4819           /* If this is a common symbol, then we always want H->SIZE
4820              to be the size of the common symbol.  The code just above
4821              won't fix the size if a common symbol becomes larger.  We
4822              don't warn about a size change here, because that is
4823              covered by --warn-common.  Allow changes between different
4824              function types.  */
4825           if (h->root.type == bfd_link_hash_common)
4826             h->size = h->root.u.c.size;
4827
4828           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4829               && ((definition && !new_weak)
4830                   || (old_weak && h->root.type == bfd_link_hash_common)
4831                   || h->type == STT_NOTYPE))
4832             {
4833               unsigned int type = ELF_ST_TYPE (isym->st_info);
4834
4835               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4836                  symbol.  */
4837               if (type == STT_GNU_IFUNC
4838                   && (abfd->flags & DYNAMIC) != 0)
4839                 type = STT_FUNC;
4840
4841               if (h->type != type)
4842                 {
4843                   if (h->type != STT_NOTYPE && ! type_change_ok)
4844                     /* xgettext:c-format */
4845                     _bfd_error_handler
4846                       (_("warning: type of symbol `%s' changed"
4847                          " from %d to %d in %pB"),
4848                        name, h->type, type, abfd);
4849
4850                   h->type = type;
4851                 }
4852             }
4853
4854           /* Merge st_other field.  */
4855           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4856
4857           /* We don't want to make debug symbol dynamic.  */
4858           if (definition
4859               && (sec->flags & SEC_DEBUGGING)
4860               && !bfd_link_relocatable (info))
4861             dynsym = FALSE;
4862
4863           /* Nor should we make plugin symbols dynamic.  */
4864           if ((abfd->flags & BFD_PLUGIN) != 0)
4865             dynsym = FALSE;
4866
4867           if (definition)
4868             {
4869               h->target_internal = isym->st_target_internal;
4870               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4871             }
4872
4873           if (definition && !dynamic)
4874             {
4875               char *p = strchr (name, ELF_VER_CHR);
4876               if (p != NULL && p[1] != ELF_VER_CHR)
4877                 {
4878                   /* Queue non-default versions so that .symver x, x@FOO
4879                      aliases can be checked.  */
4880                   if (!nondeflt_vers)
4881                     {
4882                       amt = ((isymend - isym + 1)
4883                              * sizeof (struct elf_link_hash_entry *));
4884                       nondeflt_vers
4885                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
4886                       if (!nondeflt_vers)
4887                         goto error_free_vers;
4888                     }
4889                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4890                 }
4891             }
4892
4893           if (dynsym && h->dynindx == -1)
4894             {
4895               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4896                 goto error_free_vers;
4897               if (h->is_weakalias
4898                   && weakdef (h)->dynindx == -1)
4899                 {
4900                   if (!bfd_elf_link_record_dynamic_symbol (info, weakdef (h)))
4901                     goto error_free_vers;
4902                 }
4903             }
4904           else if (h->dynindx != -1)
4905             /* If the symbol already has a dynamic index, but
4906                visibility says it should not be visible, turn it into
4907                a local symbol.  */
4908             switch (ELF_ST_VISIBILITY (h->other))
4909               {
4910               case STV_INTERNAL:
4911               case STV_HIDDEN:
4912                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4913                 dynsym = FALSE;
4914                 break;
4915               }
4916
4917           /* Don't add DT_NEEDED for references from the dummy bfd nor
4918              for unmatched symbol.  */
4919           if (!add_needed
4920               && matched
4921               && definition
4922               && ((dynsym
4923                    && h->ref_regular_nonweak
4924                    && (old_bfd == NULL
4925                        || (old_bfd->flags & BFD_PLUGIN) == 0))
4926                   || (h->ref_dynamic_nonweak
4927                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4928                       && !on_needed_list (elf_dt_name (abfd),
4929                                           htab->needed, NULL))))
4930             {
4931               int ret;
4932               const char *soname = elf_dt_name (abfd);
4933
4934               info->callbacks->minfo ("%!", soname, old_bfd,
4935                                       h->root.root.string);
4936
4937               /* A symbol from a library loaded via DT_NEEDED of some
4938                  other library is referenced by a regular object.
4939                  Add a DT_NEEDED entry for it.  Issue an error if
4940                  --no-add-needed is used and the reference was not
4941                  a weak one.  */
4942               if (old_bfd != NULL
4943                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4944                 {
4945                   _bfd_error_handler
4946                     /* xgettext:c-format */
4947                     (_("%pB: undefined reference to symbol '%s'"),
4948                      old_bfd, name);
4949                   bfd_set_error (bfd_error_missing_dso);
4950                   goto error_free_vers;
4951                 }
4952
4953               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4954                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4955
4956               add_needed = TRUE;
4957               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4958               if (ret < 0)
4959                 goto error_free_vers;
4960
4961               BFD_ASSERT (ret == 0);
4962             }
4963         }
4964     }
4965
4966   if (info->lto_plugin_active
4967       && !bfd_link_relocatable (info)
4968       && (abfd->flags & BFD_PLUGIN) == 0
4969       && !just_syms
4970       && extsymcount)
4971     {
4972       int r_sym_shift;
4973
4974       if (bed->s->arch_size == 32)
4975         r_sym_shift = 8;
4976       else
4977         r_sym_shift = 32;
4978
4979       /* If linker plugin is enabled, set non_ir_ref_regular on symbols
4980          referenced in regular objects so that linker plugin will get
4981          the correct symbol resolution.  */
4982
4983       sym_hash = elf_sym_hashes (abfd);
4984       for (s = abfd->sections; s != NULL; s = s->next)
4985         {
4986           Elf_Internal_Rela *internal_relocs;
4987           Elf_Internal_Rela *rel, *relend;
4988
4989           /* Don't check relocations in excluded sections.  */
4990           if ((s->flags & SEC_RELOC) == 0
4991               || s->reloc_count == 0
4992               || (s->flags & SEC_EXCLUDE) != 0
4993               || ((info->strip == strip_all
4994                    || info->strip == strip_debugger)
4995                   && (s->flags & SEC_DEBUGGING) != 0))
4996             continue;
4997
4998           internal_relocs = _bfd_elf_link_read_relocs (abfd, s, NULL,
4999                                                        NULL,
5000                                                        info->keep_memory);
5001           if (internal_relocs == NULL)
5002             goto error_free_vers;
5003
5004           rel = internal_relocs;
5005           relend = rel + s->reloc_count;
5006           for ( ; rel < relend; rel++)
5007             {
5008               unsigned long r_symndx = rel->r_info >> r_sym_shift;
5009               struct elf_link_hash_entry *h;
5010
5011               /* Skip local symbols.  */
5012               if (r_symndx < extsymoff)
5013                 continue;
5014
5015               h = sym_hash[r_symndx - extsymoff];
5016               if (h != NULL)
5017                 h->root.non_ir_ref_regular = 1;
5018             }
5019
5020           if (elf_section_data (s)->relocs != internal_relocs)
5021             free (internal_relocs);
5022         }
5023     }
5024
5025   if (extversym != NULL)
5026     {
5027       free (extversym);
5028       extversym = NULL;
5029     }
5030
5031   if (isymbuf != NULL)
5032     {
5033       free (isymbuf);
5034       isymbuf = NULL;
5035     }
5036
5037   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
5038     {
5039       unsigned int i;
5040
5041       /* Restore the symbol table.  */
5042       old_ent = (char *) old_tab + tabsize;
5043       memset (elf_sym_hashes (abfd), 0,
5044               extsymcount * sizeof (struct elf_link_hash_entry *));
5045       htab->root.table.table = old_table;
5046       htab->root.table.size = old_size;
5047       htab->root.table.count = old_count;
5048       memcpy (htab->root.table.table, old_tab, tabsize);
5049       htab->root.undefs = old_undefs;
5050       htab->root.undefs_tail = old_undefs_tail;
5051       _bfd_elf_strtab_restore (htab->dynstr, old_strtab);
5052       free (old_strtab);
5053       old_strtab = NULL;
5054       for (i = 0; i < htab->root.table.size; i++)
5055         {
5056           struct bfd_hash_entry *p;
5057           struct elf_link_hash_entry *h;
5058           bfd_size_type size;
5059           unsigned int alignment_power;
5060           unsigned int non_ir_ref_dynamic;
5061
5062           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
5063             {
5064               h = (struct elf_link_hash_entry *) p;
5065               if (h->root.type == bfd_link_hash_warning)
5066                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
5067
5068               /* Preserve the maximum alignment and size for common
5069                  symbols even if this dynamic lib isn't on DT_NEEDED
5070                  since it can still be loaded at run time by another
5071                  dynamic lib.  */
5072               if (h->root.type == bfd_link_hash_common)
5073                 {
5074                   size = h->root.u.c.size;
5075                   alignment_power = h->root.u.c.p->alignment_power;
5076                 }
5077               else
5078                 {
5079                   size = 0;
5080                   alignment_power = 0;
5081                 }
5082               /* Preserve non_ir_ref_dynamic so that this symbol
5083                  will be exported when the dynamic lib becomes needed
5084                  in the second pass.  */
5085               non_ir_ref_dynamic = h->root.non_ir_ref_dynamic;
5086               memcpy (p, old_ent, htab->root.table.entsize);
5087               old_ent = (char *) old_ent + htab->root.table.entsize;
5088               h = (struct elf_link_hash_entry *) p;
5089               if (h->root.type == bfd_link_hash_warning)
5090                 {
5091                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
5092                   old_ent = (char *) old_ent + htab->root.table.entsize;
5093                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
5094                 }
5095               if (h->root.type == bfd_link_hash_common)
5096                 {
5097                   if (size > h->root.u.c.size)
5098                     h->root.u.c.size = size;
5099                   if (alignment_power > h->root.u.c.p->alignment_power)
5100                     h->root.u.c.p->alignment_power = alignment_power;
5101                 }
5102               h->root.non_ir_ref_dynamic = non_ir_ref_dynamic;
5103             }
5104         }
5105
5106       /* Make a special call to the linker "notice" function to
5107          tell it that symbols added for crefs may need to be removed.  */
5108       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
5109         goto error_free_vers;
5110
5111       free (old_tab);
5112       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
5113                            alloc_mark);
5114       if (nondeflt_vers != NULL)
5115         free (nondeflt_vers);
5116       return TRUE;
5117     }
5118
5119   if (old_tab != NULL)
5120     {
5121       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
5122         goto error_free_vers;
5123       free (old_tab);
5124       old_tab = NULL;
5125     }
5126
5127   /* Now that all the symbols from this input file are created, if
5128      not performing a relocatable link, handle .symver foo, foo@BAR
5129      such that any relocs against foo become foo@BAR.  */
5130   if (!bfd_link_relocatable (info) && nondeflt_vers != NULL)
5131     {
5132       size_t cnt, symidx;
5133
5134       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
5135         {
5136           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
5137           char *shortname, *p;
5138
5139           p = strchr (h->root.root.string, ELF_VER_CHR);
5140           if (p == NULL
5141               || (h->root.type != bfd_link_hash_defined
5142                   && h->root.type != bfd_link_hash_defweak))
5143             continue;
5144
5145           amt = p - h->root.root.string;
5146           shortname = (char *) bfd_malloc (amt + 1);
5147           if (!shortname)
5148             goto error_free_vers;
5149           memcpy (shortname, h->root.root.string, amt);
5150           shortname[amt] = '\0';
5151
5152           hi = (struct elf_link_hash_entry *)
5153                bfd_link_hash_lookup (&htab->root, shortname,
5154                                      FALSE, FALSE, FALSE);
5155           if (hi != NULL
5156               && hi->root.type == h->root.type
5157               && hi->root.u.def.value == h->root.u.def.value
5158               && hi->root.u.def.section == h->root.u.def.section)
5159             {
5160               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
5161               hi->root.type = bfd_link_hash_indirect;
5162               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
5163               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
5164               sym_hash = elf_sym_hashes (abfd);
5165               if (sym_hash)
5166                 for (symidx = 0; symidx < extsymcount; ++symidx)
5167                   if (sym_hash[symidx] == hi)
5168                     {
5169                       sym_hash[symidx] = h;
5170                       break;
5171                     }
5172             }
5173           free (shortname);
5174         }
5175       free (nondeflt_vers);
5176       nondeflt_vers = NULL;
5177     }
5178
5179   /* Now set the alias field correctly for all the weak defined
5180      symbols we found.  The only way to do this is to search all the
5181      symbols.  Since we only need the information for non functions in
5182      dynamic objects, that's the only time we actually put anything on
5183      the list WEAKS.  We need this information so that if a regular
5184      object refers to a symbol defined weakly in a dynamic object, the
5185      real symbol in the dynamic object is also put in the dynamic
5186      symbols; we also must arrange for both symbols to point to the
5187      same memory location.  We could handle the general case of symbol
5188      aliasing, but a general symbol alias can only be generated in
5189      assembler code, handling it correctly would be very time
5190      consuming, and other ELF linkers don't handle general aliasing
5191      either.  */
5192   if (weaks != NULL)
5193     {
5194       struct elf_link_hash_entry **hpp;
5195       struct elf_link_hash_entry **hppend;
5196       struct elf_link_hash_entry **sorted_sym_hash;
5197       struct elf_link_hash_entry *h;
5198       size_t sym_count;
5199
5200       /* Since we have to search the whole symbol list for each weak
5201          defined symbol, search time for N weak defined symbols will be
5202          O(N^2). Binary search will cut it down to O(NlogN).  */
5203       amt = extsymcount;
5204       amt *= sizeof (struct elf_link_hash_entry *);
5205       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
5206       if (sorted_sym_hash == NULL)
5207         goto error_return;
5208       sym_hash = sorted_sym_hash;
5209       hpp = elf_sym_hashes (abfd);
5210       hppend = hpp + extsymcount;
5211       sym_count = 0;
5212       for (; hpp < hppend; hpp++)
5213         {
5214           h = *hpp;
5215           if (h != NULL
5216               && h->root.type == bfd_link_hash_defined
5217               && !bed->is_function_type (h->type))
5218             {
5219               *sym_hash = h;
5220               sym_hash++;
5221               sym_count++;
5222             }
5223         }
5224
5225       qsort (sorted_sym_hash, sym_count,
5226              sizeof (struct elf_link_hash_entry *),
5227              elf_sort_symbol);
5228
5229       while (weaks != NULL)
5230         {
5231           struct elf_link_hash_entry *hlook;
5232           asection *slook;
5233           bfd_vma vlook;
5234           size_t i, j, idx = 0;
5235
5236           hlook = weaks;
5237           weaks = hlook->u.alias;
5238           hlook->u.alias = NULL;
5239
5240           if (hlook->root.type != bfd_link_hash_defined
5241               && hlook->root.type != bfd_link_hash_defweak)
5242             continue;
5243
5244           slook = hlook->root.u.def.section;
5245           vlook = hlook->root.u.def.value;
5246
5247           i = 0;
5248           j = sym_count;
5249           while (i != j)
5250             {
5251               bfd_signed_vma vdiff;
5252               idx = (i + j) / 2;
5253               h = sorted_sym_hash[idx];
5254               vdiff = vlook - h->root.u.def.value;
5255               if (vdiff < 0)
5256                 j = idx;
5257               else if (vdiff > 0)
5258                 i = idx + 1;
5259               else
5260                 {
5261                   int sdiff = slook->id - h->root.u.def.section->id;
5262                   if (sdiff < 0)
5263                     j = idx;
5264                   else if (sdiff > 0)
5265                     i = idx + 1;
5266                   else
5267                     break;
5268                 }
5269             }
5270
5271           /* We didn't find a value/section match.  */
5272           if (i == j)
5273             continue;
5274
5275           /* With multiple aliases, or when the weak symbol is already
5276              strongly defined, we have multiple matching symbols and
5277              the binary search above may land on any of them.  Step
5278              one past the matching symbol(s).  */
5279           while (++idx != j)
5280             {
5281               h = sorted_sym_hash[idx];
5282               if (h->root.u.def.section != slook
5283                   || h->root.u.def.value != vlook)
5284                 break;
5285             }
5286
5287           /* Now look back over the aliases.  Since we sorted by size
5288              as well as value and section, we'll choose the one with
5289              the largest size.  */
5290           while (idx-- != i)
5291             {
5292               h = sorted_sym_hash[idx];
5293
5294               /* Stop if value or section doesn't match.  */
5295               if (h->root.u.def.section != slook
5296                   || h->root.u.def.value != vlook)
5297                 break;
5298               else if (h != hlook)
5299                 {
5300                   struct elf_link_hash_entry *t;
5301
5302                   hlook->u.alias = h;
5303                   hlook->is_weakalias = 1;
5304                   t = h;
5305                   if (t->u.alias != NULL)
5306                     while (t->u.alias != h)
5307                       t = t->u.alias;
5308                   t->u.alias = hlook;
5309
5310                   /* If the weak definition is in the list of dynamic
5311                      symbols, make sure the real definition is put
5312                      there as well.  */
5313                   if (hlook->dynindx != -1 && h->dynindx == -1)
5314                     {
5315                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
5316                         {
5317                         err_free_sym_hash:
5318                           free (sorted_sym_hash);
5319                           goto error_return;
5320                         }
5321                     }
5322
5323                   /* If the real definition is in the list of dynamic
5324                      symbols, make sure the weak definition is put
5325                      there as well.  If we don't do this, then the
5326                      dynamic loader might not merge the entries for the
5327                      real definition and the weak definition.  */
5328                   if (h->dynindx != -1 && hlook->dynindx == -1)
5329                     {
5330                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
5331                         goto err_free_sym_hash;
5332                     }
5333                   break;
5334                 }
5335             }
5336         }
5337
5338       free (sorted_sym_hash);
5339     }
5340
5341   if (bed->check_directives
5342       && !(*bed->check_directives) (abfd, info))
5343     return FALSE;
5344
5345   /* If this is a non-traditional link, try to optimize the handling
5346      of the .stab/.stabstr sections.  */
5347   if (! dynamic
5348       && ! info->traditional_format
5349       && is_elf_hash_table (htab)
5350       && (info->strip != strip_all && info->strip != strip_debugger))
5351     {
5352       asection *stabstr;
5353
5354       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
5355       if (stabstr != NULL)
5356         {
5357           bfd_size_type string_offset = 0;
5358           asection *stab;
5359
5360           for (stab = abfd->sections; stab; stab = stab->next)
5361             if (CONST_STRNEQ (stab->name, ".stab")
5362                 && (!stab->name[5] ||
5363                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
5364                 && (stab->flags & SEC_MERGE) == 0
5365                 && !bfd_is_abs_section (stab->output_section))
5366               {
5367                 struct bfd_elf_section_data *secdata;
5368
5369                 secdata = elf_section_data (stab);
5370                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
5371                                                stabstr, &secdata->sec_info,
5372                                                &string_offset))
5373                   goto error_return;
5374                 if (secdata->sec_info)
5375                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
5376             }
5377         }
5378     }
5379
5380   if (is_elf_hash_table (htab) && add_needed)
5381     {
5382       /* Add this bfd to the loaded list.  */
5383       struct elf_link_loaded_list *n;
5384
5385       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
5386       if (n == NULL)
5387         goto error_return;
5388       n->abfd = abfd;
5389       n->next = htab->loaded;
5390       htab->loaded = n;
5391     }
5392
5393   return TRUE;
5394
5395  error_free_vers:
5396   if (old_tab != NULL)
5397     free (old_tab);
5398   if (old_strtab != NULL)
5399     free (old_strtab);
5400   if (nondeflt_vers != NULL)
5401     free (nondeflt_vers);
5402   if (extversym != NULL)
5403     free (extversym);
5404  error_free_sym:
5405   if (isymbuf != NULL)
5406     free (isymbuf);
5407  error_return:
5408   return FALSE;
5409 }
5410
5411 /* Return the linker hash table entry of a symbol that might be
5412    satisfied by an archive symbol.  Return -1 on error.  */
5413
5414 struct elf_link_hash_entry *
5415 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5416                                 struct bfd_link_info *info,
5417                                 const char *name)
5418 {
5419   struct elf_link_hash_entry *h;
5420   char *p, *copy;
5421   size_t len, first;
5422
5423   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5424   if (h != NULL)
5425     return h;
5426
5427   /* If this is a default version (the name contains @@), look up the
5428      symbol again with only one `@' as well as without the version.
5429      The effect is that references to the symbol with and without the
5430      version will be matched by the default symbol in the archive.  */
5431
5432   p = strchr (name, ELF_VER_CHR);
5433   if (p == NULL || p[1] != ELF_VER_CHR)
5434     return h;
5435
5436   /* First check with only one `@'.  */
5437   len = strlen (name);
5438   copy = (char *) bfd_alloc (abfd, len);
5439   if (copy == NULL)
5440     return (struct elf_link_hash_entry *) -1;
5441
5442   first = p - name + 1;
5443   memcpy (copy, name, first);
5444   memcpy (copy + first, name + first + 1, len - first);
5445
5446   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5447   if (h == NULL)
5448     {
5449       /* We also need to check references to the symbol without the
5450          version.  */
5451       copy[first - 1] = '\0';
5452       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5453                                 FALSE, FALSE, TRUE);
5454     }
5455
5456   bfd_release (abfd, copy);
5457   return h;
5458 }
5459
5460 /* Add symbols from an ELF archive file to the linker hash table.  We
5461    don't use _bfd_generic_link_add_archive_symbols because we need to
5462    handle versioned symbols.
5463
5464    Fortunately, ELF archive handling is simpler than that done by
5465    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5466    oddities.  In ELF, if we find a symbol in the archive map, and the
5467    symbol is currently undefined, we know that we must pull in that
5468    object file.
5469
5470    Unfortunately, we do have to make multiple passes over the symbol
5471    table until nothing further is resolved.  */
5472
5473 static bfd_boolean
5474 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5475 {
5476   symindex c;
5477   unsigned char *included = NULL;
5478   carsym *symdefs;
5479   bfd_boolean loop;
5480   bfd_size_type amt;
5481   const struct elf_backend_data *bed;
5482   struct elf_link_hash_entry * (*archive_symbol_lookup)
5483     (bfd *, struct bfd_link_info *, const char *);
5484
5485   if (! bfd_has_map (abfd))
5486     {
5487       /* An empty archive is a special case.  */
5488       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5489         return TRUE;
5490       bfd_set_error (bfd_error_no_armap);
5491       return FALSE;
5492     }
5493
5494   /* Keep track of all symbols we know to be already defined, and all
5495      files we know to be already included.  This is to speed up the
5496      second and subsequent passes.  */
5497   c = bfd_ardata (abfd)->symdef_count;
5498   if (c == 0)
5499     return TRUE;
5500   amt = c;
5501   amt *= sizeof (*included);
5502   included = (unsigned char *) bfd_zmalloc (amt);
5503   if (included == NULL)
5504     return FALSE;
5505
5506   symdefs = bfd_ardata (abfd)->symdefs;
5507   bed = get_elf_backend_data (abfd);
5508   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5509
5510   do
5511     {
5512       file_ptr last;
5513       symindex i;
5514       carsym *symdef;
5515       carsym *symdefend;
5516
5517       loop = FALSE;
5518       last = -1;
5519
5520       symdef = symdefs;
5521       symdefend = symdef + c;
5522       for (i = 0; symdef < symdefend; symdef++, i++)
5523         {
5524           struct elf_link_hash_entry *h;
5525           bfd *element;
5526           struct bfd_link_hash_entry *undefs_tail;
5527           symindex mark;
5528
5529           if (included[i])
5530             continue;
5531           if (symdef->file_offset == last)
5532             {
5533               included[i] = TRUE;
5534               continue;
5535             }
5536
5537           h = archive_symbol_lookup (abfd, info, symdef->name);
5538           if (h == (struct elf_link_hash_entry *) -1)
5539             goto error_return;
5540
5541           if (h == NULL)
5542             continue;
5543
5544           if (h->root.type == bfd_link_hash_common)
5545             {
5546               /* We currently have a common symbol.  The archive map contains
5547                  a reference to this symbol, so we may want to include it.  We
5548                  only want to include it however, if this archive element
5549                  contains a definition of the symbol, not just another common
5550                  declaration of it.
5551
5552                  Unfortunately some archivers (including GNU ar) will put
5553                  declarations of common symbols into their archive maps, as
5554                  well as real definitions, so we cannot just go by the archive
5555                  map alone.  Instead we must read in the element's symbol
5556                  table and check that to see what kind of symbol definition
5557                  this is.  */
5558               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5559                 continue;
5560             }
5561           else if (h->root.type != bfd_link_hash_undefined)
5562             {
5563               if (h->root.type != bfd_link_hash_undefweak)
5564                 /* Symbol must be defined.  Don't check it again.  */
5565                 included[i] = TRUE;
5566               continue;
5567             }
5568
5569           /* We need to include this archive member.  */
5570           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5571           if (element == NULL)
5572             goto error_return;
5573
5574           if (! bfd_check_format (element, bfd_object))
5575             goto error_return;
5576
5577           undefs_tail = info->hash->undefs_tail;
5578
5579           if (!(*info->callbacks
5580                 ->add_archive_element) (info, element, symdef->name, &element))
5581             continue;
5582           if (!bfd_link_add_symbols (element, info))
5583             goto error_return;
5584
5585           /* If there are any new undefined symbols, we need to make
5586              another pass through the archive in order to see whether
5587              they can be defined.  FIXME: This isn't perfect, because
5588              common symbols wind up on undefs_tail and because an
5589              undefined symbol which is defined later on in this pass
5590              does not require another pass.  This isn't a bug, but it
5591              does make the code less efficient than it could be.  */
5592           if (undefs_tail != info->hash->undefs_tail)
5593             loop = TRUE;
5594
5595           /* Look backward to mark all symbols from this object file
5596              which we have already seen in this pass.  */
5597           mark = i;
5598           do
5599             {
5600               included[mark] = TRUE;
5601               if (mark == 0)
5602                 break;
5603               --mark;
5604             }
5605           while (symdefs[mark].file_offset == symdef->file_offset);
5606
5607           /* We mark subsequent symbols from this object file as we go
5608              on through the loop.  */
5609           last = symdef->file_offset;
5610         }
5611     }
5612   while (loop);
5613
5614   free (included);
5615
5616   return TRUE;
5617
5618  error_return:
5619   if (included != NULL)
5620     free (included);
5621   return FALSE;
5622 }
5623
5624 /* Given an ELF BFD, add symbols to the global hash table as
5625    appropriate.  */
5626
5627 bfd_boolean
5628 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5629 {
5630   switch (bfd_get_format (abfd))
5631     {
5632     case bfd_object:
5633       return elf_link_add_object_symbols (abfd, info);
5634     case bfd_archive:
5635       return elf_link_add_archive_symbols (abfd, info);
5636     default:
5637       bfd_set_error (bfd_error_wrong_format);
5638       return FALSE;
5639     }
5640 }
5641 \f
5642 struct hash_codes_info
5643 {
5644   unsigned long *hashcodes;
5645   bfd_boolean error;
5646 };
5647
5648 /* This function will be called though elf_link_hash_traverse to store
5649    all hash value of the exported symbols in an array.  */
5650
5651 static bfd_boolean
5652 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5653 {
5654   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5655   const char *name;
5656   unsigned long ha;
5657   char *alc = NULL;
5658
5659   /* Ignore indirect symbols.  These are added by the versioning code.  */
5660   if (h->dynindx == -1)
5661     return TRUE;
5662
5663   name = h->root.root.string;
5664   if (h->versioned >= versioned)
5665     {
5666       char *p = strchr (name, ELF_VER_CHR);
5667       if (p != NULL)
5668         {
5669           alc = (char *) bfd_malloc (p - name + 1);
5670           if (alc == NULL)
5671             {
5672               inf->error = TRUE;
5673               return FALSE;
5674             }
5675           memcpy (alc, name, p - name);
5676           alc[p - name] = '\0';
5677           name = alc;
5678         }
5679     }
5680
5681   /* Compute the hash value.  */
5682   ha = bfd_elf_hash (name);
5683
5684   /* Store the found hash value in the array given as the argument.  */
5685   *(inf->hashcodes)++ = ha;
5686
5687   /* And store it in the struct so that we can put it in the hash table
5688      later.  */
5689   h->u.elf_hash_value = ha;
5690
5691   if (alc != NULL)
5692     free (alc);
5693
5694   return TRUE;
5695 }
5696
5697 struct collect_gnu_hash_codes
5698 {
5699   bfd *output_bfd;
5700   const struct elf_backend_data *bed;
5701   unsigned long int nsyms;
5702   unsigned long int maskbits;
5703   unsigned long int *hashcodes;
5704   unsigned long int *hashval;
5705   unsigned long int *indx;
5706   unsigned long int *counts;
5707   bfd_vma *bitmask;
5708   bfd_byte *contents;
5709   long int min_dynindx;
5710   unsigned long int bucketcount;
5711   unsigned long int symindx;
5712   long int local_indx;
5713   long int shift1, shift2;
5714   unsigned long int mask;
5715   bfd_boolean error;
5716 };
5717
5718 /* This function will be called though elf_link_hash_traverse to store
5719    all hash value of the exported symbols in an array.  */
5720
5721 static bfd_boolean
5722 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5723 {
5724   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5725   const char *name;
5726   unsigned long ha;
5727   char *alc = NULL;
5728
5729   /* Ignore indirect symbols.  These are added by the versioning code.  */
5730   if (h->dynindx == -1)
5731     return TRUE;
5732
5733   /* Ignore also local symbols and undefined symbols.  */
5734   if (! (*s->bed->elf_hash_symbol) (h))
5735     return TRUE;
5736
5737   name = h->root.root.string;
5738   if (h->versioned >= versioned)
5739     {
5740       char *p = strchr (name, ELF_VER_CHR);
5741       if (p != NULL)
5742         {
5743           alc = (char *) bfd_malloc (p - name + 1);
5744           if (alc == NULL)
5745             {
5746               s->error = TRUE;
5747               return FALSE;
5748             }
5749           memcpy (alc, name, p - name);
5750           alc[p - name] = '\0';
5751           name = alc;
5752         }
5753     }
5754
5755   /* Compute the hash value.  */
5756   ha = bfd_elf_gnu_hash (name);
5757
5758   /* Store the found hash value in the array for compute_bucket_count,
5759      and also for .dynsym reordering purposes.  */
5760   s->hashcodes[s->nsyms] = ha;
5761   s->hashval[h->dynindx] = ha;
5762   ++s->nsyms;
5763   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5764     s->min_dynindx = h->dynindx;
5765
5766   if (alc != NULL)
5767     free (alc);
5768
5769   return TRUE;
5770 }
5771
5772 /* This function will be called though elf_link_hash_traverse to do
5773    final dynaminc symbol renumbering.  */
5774
5775 static bfd_boolean
5776 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5777 {
5778   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5779   unsigned long int bucket;
5780   unsigned long int val;
5781
5782   /* Ignore indirect symbols.  */
5783   if (h->dynindx == -1)
5784     return TRUE;
5785
5786   /* Ignore also local symbols and undefined symbols.  */
5787   if (! (*s->bed->elf_hash_symbol) (h))
5788     {
5789       if (h->dynindx >= s->min_dynindx)
5790         h->dynindx = s->local_indx++;
5791       return TRUE;
5792     }
5793
5794   bucket = s->hashval[h->dynindx] % s->bucketcount;
5795   val = (s->hashval[h->dynindx] >> s->shift1)
5796         & ((s->maskbits >> s->shift1) - 1);
5797   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5798   s->bitmask[val]
5799     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5800   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5801   if (s->counts[bucket] == 1)
5802     /* Last element terminates the chain.  */
5803     val |= 1;
5804   bfd_put_32 (s->output_bfd, val,
5805               s->contents + (s->indx[bucket] - s->symindx) * 4);
5806   --s->counts[bucket];
5807   h->dynindx = s->indx[bucket]++;
5808   return TRUE;
5809 }
5810
5811 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5812
5813 bfd_boolean
5814 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5815 {
5816   return !(h->forced_local
5817            || h->root.type == bfd_link_hash_undefined
5818            || h->root.type == bfd_link_hash_undefweak
5819            || ((h->root.type == bfd_link_hash_defined
5820                 || h->root.type == bfd_link_hash_defweak)
5821                && h->root.u.def.section->output_section == NULL));
5822 }
5823
5824 /* Array used to determine the number of hash table buckets to use
5825    based on the number of symbols there are.  If there are fewer than
5826    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5827    fewer than 37 we use 17 buckets, and so forth.  We never use more
5828    than 32771 buckets.  */
5829
5830 static const size_t elf_buckets[] =
5831 {
5832   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5833   16411, 32771, 0
5834 };
5835
5836 /* Compute bucket count for hashing table.  We do not use a static set
5837    of possible tables sizes anymore.  Instead we determine for all
5838    possible reasonable sizes of the table the outcome (i.e., the
5839    number of collisions etc) and choose the best solution.  The
5840    weighting functions are not too simple to allow the table to grow
5841    without bounds.  Instead one of the weighting factors is the size.
5842    Therefore the result is always a good payoff between few collisions
5843    (= short chain lengths) and table size.  */
5844 static size_t
5845 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5846                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5847                       unsigned long int nsyms,
5848                       int gnu_hash)
5849 {
5850   size_t best_size = 0;
5851   unsigned long int i;
5852
5853   /* We have a problem here.  The following code to optimize the table
5854      size requires an integer type with more the 32 bits.  If
5855      BFD_HOST_U_64_BIT is set we know about such a type.  */
5856 #ifdef BFD_HOST_U_64_BIT
5857   if (info->optimize)
5858     {
5859       size_t minsize;
5860       size_t maxsize;
5861       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5862       bfd *dynobj = elf_hash_table (info)->dynobj;
5863       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5864       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5865       unsigned long int *counts;
5866       bfd_size_type amt;
5867       unsigned int no_improvement_count = 0;
5868
5869       /* Possible optimization parameters: if we have NSYMS symbols we say
5870          that the hashing table must at least have NSYMS/4 and at most
5871          2*NSYMS buckets.  */
5872       minsize = nsyms / 4;
5873       if (minsize == 0)
5874         minsize = 1;
5875       best_size = maxsize = nsyms * 2;
5876       if (gnu_hash)
5877         {
5878           if (minsize < 2)
5879             minsize = 2;
5880           if ((best_size & 31) == 0)
5881             ++best_size;
5882         }
5883
5884       /* Create array where we count the collisions in.  We must use bfd_malloc
5885          since the size could be large.  */
5886       amt = maxsize;
5887       amt *= sizeof (unsigned long int);
5888       counts = (unsigned long int *) bfd_malloc (amt);
5889       if (counts == NULL)
5890         return 0;
5891
5892       /* Compute the "optimal" size for the hash table.  The criteria is a
5893          minimal chain length.  The minor criteria is (of course) the size
5894          of the table.  */
5895       for (i = minsize; i < maxsize; ++i)
5896         {
5897           /* Walk through the array of hashcodes and count the collisions.  */
5898           BFD_HOST_U_64_BIT max;
5899           unsigned long int j;
5900           unsigned long int fact;
5901
5902           if (gnu_hash && (i & 31) == 0)
5903             continue;
5904
5905           memset (counts, '\0', i * sizeof (unsigned long int));
5906
5907           /* Determine how often each hash bucket is used.  */
5908           for (j = 0; j < nsyms; ++j)
5909             ++counts[hashcodes[j] % i];
5910
5911           /* For the weight function we need some information about the
5912              pagesize on the target.  This is information need not be 100%
5913              accurate.  Since this information is not available (so far) we
5914              define it here to a reasonable default value.  If it is crucial
5915              to have a better value some day simply define this value.  */
5916 # ifndef BFD_TARGET_PAGESIZE
5917 #  define BFD_TARGET_PAGESIZE   (4096)
5918 # endif
5919
5920           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5921              and the chains.  */
5922           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5923
5924 # if 1
5925           /* Variant 1: optimize for short chains.  We add the squares
5926              of all the chain lengths (which favors many small chain
5927              over a few long chains).  */
5928           for (j = 0; j < i; ++j)
5929             max += counts[j] * counts[j];
5930
5931           /* This adds penalties for the overall size of the table.  */
5932           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5933           max *= fact * fact;
5934 # else
5935           /* Variant 2: Optimize a lot more for small table.  Here we
5936              also add squares of the size but we also add penalties for
5937              empty slots (the +1 term).  */
5938           for (j = 0; j < i; ++j)
5939             max += (1 + counts[j]) * (1 + counts[j]);
5940
5941           /* The overall size of the table is considered, but not as
5942              strong as in variant 1, where it is squared.  */
5943           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5944           max *= fact;
5945 # endif
5946
5947           /* Compare with current best results.  */
5948           if (max < best_chlen)
5949             {
5950               best_chlen = max;
5951               best_size = i;
5952               no_improvement_count = 0;
5953             }
5954           /* PR 11843: Avoid futile long searches for the best bucket size
5955              when there are a large number of symbols.  */
5956           else if (++no_improvement_count == 100)
5957             break;
5958         }
5959
5960       free (counts);
5961     }
5962   else
5963 #endif /* defined (BFD_HOST_U_64_BIT) */
5964     {
5965       /* This is the fallback solution if no 64bit type is available or if we
5966          are not supposed to spend much time on optimizations.  We select the
5967          bucket count using a fixed set of numbers.  */
5968       for (i = 0; elf_buckets[i] != 0; i++)
5969         {
5970           best_size = elf_buckets[i];
5971           if (nsyms < elf_buckets[i + 1])
5972             break;
5973         }
5974       if (gnu_hash && best_size < 2)
5975         best_size = 2;
5976     }
5977
5978   return best_size;
5979 }
5980
5981 /* Size any SHT_GROUP section for ld -r.  */
5982
5983 bfd_boolean
5984 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5985 {
5986   bfd *ibfd;
5987   asection *s;
5988
5989   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5990     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5991         && (s = ibfd->sections) != NULL
5992         && s->sec_info_type != SEC_INFO_TYPE_JUST_SYMS
5993         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5994       return FALSE;
5995   return TRUE;
5996 }
5997
5998 /* Set a default stack segment size.  The value in INFO wins.  If it
5999    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
6000    undefined it is initialized.  */
6001
6002 bfd_boolean
6003 bfd_elf_stack_segment_size (bfd *output_bfd,
6004                             struct bfd_link_info *info,
6005                             const char *legacy_symbol,
6006                             bfd_vma default_size)
6007 {
6008   struct elf_link_hash_entry *h = NULL;
6009
6010   /* Look for legacy symbol.  */
6011   if (legacy_symbol)
6012     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
6013                               FALSE, FALSE, FALSE);
6014   if (h && (h->root.type == bfd_link_hash_defined
6015             || h->root.type == bfd_link_hash_defweak)
6016       && h->def_regular
6017       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
6018     {
6019       /* The symbol has no type if specified on the command line.  */
6020       h->type = STT_OBJECT;
6021       if (info->stacksize)
6022         /* xgettext:c-format */
6023         _bfd_error_handler (_("%pB: stack size specified and %s set"),
6024                             output_bfd, legacy_symbol);
6025       else if (h->root.u.def.section != bfd_abs_section_ptr)
6026         /* xgettext:c-format */
6027         _bfd_error_handler (_("%pB: %s not absolute"),
6028                             output_bfd, legacy_symbol);
6029       else
6030         info->stacksize = h->root.u.def.value;
6031     }
6032
6033   if (!info->stacksize)
6034     /* If the user didn't set a size, or explicitly inhibit the
6035        size, set it now.  */
6036     info->stacksize = default_size;
6037
6038   /* Provide the legacy symbol, if it is referenced.  */
6039   if (h && (h->root.type == bfd_link_hash_undefined
6040             || h->root.type == bfd_link_hash_undefweak))
6041     {
6042       struct bfd_link_hash_entry *bh = NULL;
6043
6044       if (!(_bfd_generic_link_add_one_symbol
6045             (info, output_bfd, legacy_symbol,
6046              BSF_GLOBAL, bfd_abs_section_ptr,
6047              info->stacksize >= 0 ? info->stacksize : 0,
6048              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
6049         return FALSE;
6050
6051       h = (struct elf_link_hash_entry *) bh;
6052       h->def_regular = 1;
6053       h->type = STT_OBJECT;
6054     }
6055
6056   return TRUE;
6057 }
6058
6059 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
6060
6061 struct elf_gc_sweep_symbol_info
6062 {
6063   struct bfd_link_info *info;
6064   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
6065                        bfd_boolean);
6066 };
6067
6068 static bfd_boolean
6069 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
6070 {
6071   if (!h->mark
6072       && (((h->root.type == bfd_link_hash_defined
6073             || h->root.type == bfd_link_hash_defweak)
6074            && !((h->def_regular || ELF_COMMON_DEF_P (h))
6075                 && h->root.u.def.section->gc_mark))
6076           || h->root.type == bfd_link_hash_undefined
6077           || h->root.type == bfd_link_hash_undefweak))
6078     {
6079       struct elf_gc_sweep_symbol_info *inf;
6080
6081       inf = (struct elf_gc_sweep_symbol_info *) data;
6082       (*inf->hide_symbol) (inf->info, h, TRUE);
6083       h->def_regular = 0;
6084       h->ref_regular = 0;
6085       h->ref_regular_nonweak = 0;
6086     }
6087
6088   return TRUE;
6089 }
6090
6091 /* Set up the sizes and contents of the ELF dynamic sections.  This is
6092    called by the ELF linker emulation before_allocation routine.  We
6093    must set the sizes of the sections before the linker sets the
6094    addresses of the various sections.  */
6095
6096 bfd_boolean
6097 bfd_elf_size_dynamic_sections (bfd *output_bfd,
6098                                const char *soname,
6099                                const char *rpath,
6100                                const char *filter_shlib,
6101                                const char *audit,
6102                                const char *depaudit,
6103                                const char * const *auxiliary_filters,
6104                                struct bfd_link_info *info,
6105                                asection **sinterpptr)
6106 {
6107   bfd *dynobj;
6108   const struct elf_backend_data *bed;
6109
6110   *sinterpptr = NULL;
6111
6112   if (!is_elf_hash_table (info->hash))
6113     return TRUE;
6114
6115   dynobj = elf_hash_table (info)->dynobj;
6116
6117   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6118     {
6119       struct bfd_elf_version_tree *verdefs;
6120       struct elf_info_failed asvinfo;
6121       struct bfd_elf_version_tree *t;
6122       struct bfd_elf_version_expr *d;
6123       asection *s;
6124       size_t soname_indx;
6125
6126       /* If we are supposed to export all symbols into the dynamic symbol
6127          table (this is not the normal case), then do so.  */
6128       if (info->export_dynamic
6129           || (bfd_link_executable (info) && info->dynamic))
6130         {
6131           struct elf_info_failed eif;
6132
6133           eif.info = info;
6134           eif.failed = FALSE;
6135           elf_link_hash_traverse (elf_hash_table (info),
6136                                   _bfd_elf_export_symbol,
6137                                   &eif);
6138           if (eif.failed)
6139             return FALSE;
6140         }
6141
6142       if (soname != NULL)
6143         {
6144           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6145                                              soname, TRUE);
6146           if (soname_indx == (size_t) -1
6147               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
6148             return FALSE;
6149         }
6150       else
6151         soname_indx = (size_t) -1;
6152
6153       /* Make all global versions with definition.  */
6154       for (t = info->version_info; t != NULL; t = t->next)
6155         for (d = t->globals.list; d != NULL; d = d->next)
6156           if (!d->symver && d->literal)
6157             {
6158               const char *verstr, *name;
6159               size_t namelen, verlen, newlen;
6160               char *newname, *p, leading_char;
6161               struct elf_link_hash_entry *newh;
6162
6163               leading_char = bfd_get_symbol_leading_char (output_bfd);
6164               name = d->pattern;
6165               namelen = strlen (name) + (leading_char != '\0');
6166               verstr = t->name;
6167               verlen = strlen (verstr);
6168               newlen = namelen + verlen + 3;
6169
6170               newname = (char *) bfd_malloc (newlen);
6171               if (newname == NULL)
6172                 return FALSE;
6173               newname[0] = leading_char;
6174               memcpy (newname + (leading_char != '\0'), name, namelen);
6175
6176               /* Check the hidden versioned definition.  */
6177               p = newname + namelen;
6178               *p++ = ELF_VER_CHR;
6179               memcpy (p, verstr, verlen + 1);
6180               newh = elf_link_hash_lookup (elf_hash_table (info),
6181                                            newname, FALSE, FALSE,
6182                                            FALSE);
6183               if (newh == NULL
6184                   || (newh->root.type != bfd_link_hash_defined
6185                       && newh->root.type != bfd_link_hash_defweak))
6186                 {
6187                   /* Check the default versioned definition.  */
6188                   *p++ = ELF_VER_CHR;
6189                   memcpy (p, verstr, verlen + 1);
6190                   newh = elf_link_hash_lookup (elf_hash_table (info),
6191                                                newname, FALSE, FALSE,
6192                                                FALSE);
6193                 }
6194               free (newname);
6195
6196               /* Mark this version if there is a definition and it is
6197                  not defined in a shared object.  */
6198               if (newh != NULL
6199                   && !newh->def_dynamic
6200                   && (newh->root.type == bfd_link_hash_defined
6201                       || newh->root.type == bfd_link_hash_defweak))
6202                 d->symver = 1;
6203             }
6204
6205       /* Attach all the symbols to their version information.  */
6206       asvinfo.info = info;
6207       asvinfo.failed = FALSE;
6208
6209       elf_link_hash_traverse (elf_hash_table (info),
6210                               _bfd_elf_link_assign_sym_version,
6211                               &asvinfo);
6212       if (asvinfo.failed)
6213         return FALSE;
6214
6215       if (!info->allow_undefined_version)
6216         {
6217           /* Check if all global versions have a definition.  */
6218           bfd_boolean all_defined = TRUE;
6219           for (t = info->version_info; t != NULL; t = t->next)
6220             for (d = t->globals.list; d != NULL; d = d->next)
6221               if (d->literal && !d->symver && !d->script)
6222                 {
6223                   _bfd_error_handler
6224                     (_("%s: undefined version: %s"),
6225                      d->pattern, t->name);
6226                   all_defined = FALSE;
6227                 }
6228
6229           if (!all_defined)
6230             {
6231               bfd_set_error (bfd_error_bad_value);
6232               return FALSE;
6233             }
6234         }
6235
6236       /* Set up the version definition section.  */
6237       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6238       BFD_ASSERT (s != NULL);
6239
6240       /* We may have created additional version definitions if we are
6241          just linking a regular application.  */
6242       verdefs = info->version_info;
6243
6244       /* Skip anonymous version tag.  */
6245       if (verdefs != NULL && verdefs->vernum == 0)
6246         verdefs = verdefs->next;
6247
6248       if (verdefs == NULL && !info->create_default_symver)
6249         s->flags |= SEC_EXCLUDE;
6250       else
6251         {
6252           unsigned int cdefs;
6253           bfd_size_type size;
6254           bfd_byte *p;
6255           Elf_Internal_Verdef def;
6256           Elf_Internal_Verdaux defaux;
6257           struct bfd_link_hash_entry *bh;
6258           struct elf_link_hash_entry *h;
6259           const char *name;
6260
6261           cdefs = 0;
6262           size = 0;
6263
6264           /* Make space for the base version.  */
6265           size += sizeof (Elf_External_Verdef);
6266           size += sizeof (Elf_External_Verdaux);
6267           ++cdefs;
6268
6269           /* Make space for the default version.  */
6270           if (info->create_default_symver)
6271             {
6272               size += sizeof (Elf_External_Verdef);
6273               ++cdefs;
6274             }
6275
6276           for (t = verdefs; t != NULL; t = t->next)
6277             {
6278               struct bfd_elf_version_deps *n;
6279
6280               /* Don't emit base version twice.  */
6281               if (t->vernum == 0)
6282                 continue;
6283
6284               size += sizeof (Elf_External_Verdef);
6285               size += sizeof (Elf_External_Verdaux);
6286               ++cdefs;
6287
6288               for (n = t->deps; n != NULL; n = n->next)
6289                 size += sizeof (Elf_External_Verdaux);
6290             }
6291
6292           s->size = size;
6293           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6294           if (s->contents == NULL && s->size != 0)
6295             return FALSE;
6296
6297           /* Fill in the version definition section.  */
6298
6299           p = s->contents;
6300
6301           def.vd_version = VER_DEF_CURRENT;
6302           def.vd_flags = VER_FLG_BASE;
6303           def.vd_ndx = 1;
6304           def.vd_cnt = 1;
6305           if (info->create_default_symver)
6306             {
6307               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6308               def.vd_next = sizeof (Elf_External_Verdef);
6309             }
6310           else
6311             {
6312               def.vd_aux = sizeof (Elf_External_Verdef);
6313               def.vd_next = (sizeof (Elf_External_Verdef)
6314                              + sizeof (Elf_External_Verdaux));
6315             }
6316
6317           if (soname_indx != (size_t) -1)
6318             {
6319               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6320                                       soname_indx);
6321               def.vd_hash = bfd_elf_hash (soname);
6322               defaux.vda_name = soname_indx;
6323               name = soname;
6324             }
6325           else
6326             {
6327               size_t indx;
6328
6329               name = lbasename (output_bfd->filename);
6330               def.vd_hash = bfd_elf_hash (name);
6331               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6332                                           name, FALSE);
6333               if (indx == (size_t) -1)
6334                 return FALSE;
6335               defaux.vda_name = indx;
6336             }
6337           defaux.vda_next = 0;
6338
6339           _bfd_elf_swap_verdef_out (output_bfd, &def,
6340                                     (Elf_External_Verdef *) p);
6341           p += sizeof (Elf_External_Verdef);
6342           if (info->create_default_symver)
6343             {
6344               /* Add a symbol representing this version.  */
6345               bh = NULL;
6346               if (! (_bfd_generic_link_add_one_symbol
6347                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6348                       0, NULL, FALSE,
6349                       get_elf_backend_data (dynobj)->collect, &bh)))
6350                 return FALSE;
6351               h = (struct elf_link_hash_entry *) bh;
6352               h->non_elf = 0;
6353               h->def_regular = 1;
6354               h->type = STT_OBJECT;
6355               h->verinfo.vertree = NULL;
6356
6357               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6358                 return FALSE;
6359
6360               /* Create a duplicate of the base version with the same
6361                  aux block, but different flags.  */
6362               def.vd_flags = 0;
6363               def.vd_ndx = 2;
6364               def.vd_aux = sizeof (Elf_External_Verdef);
6365               if (verdefs)
6366                 def.vd_next = (sizeof (Elf_External_Verdef)
6367                                + sizeof (Elf_External_Verdaux));
6368               else
6369                 def.vd_next = 0;
6370               _bfd_elf_swap_verdef_out (output_bfd, &def,
6371                                         (Elf_External_Verdef *) p);
6372               p += sizeof (Elf_External_Verdef);
6373             }
6374           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6375                                      (Elf_External_Verdaux *) p);
6376           p += sizeof (Elf_External_Verdaux);
6377
6378           for (t = verdefs; t != NULL; t = t->next)
6379             {
6380               unsigned int cdeps;
6381               struct bfd_elf_version_deps *n;
6382
6383               /* Don't emit the base version twice.  */
6384               if (t->vernum == 0)
6385                 continue;
6386
6387               cdeps = 0;
6388               for (n = t->deps; n != NULL; n = n->next)
6389                 ++cdeps;
6390
6391               /* Add a symbol representing this version.  */
6392               bh = NULL;
6393               if (! (_bfd_generic_link_add_one_symbol
6394                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6395                       0, NULL, FALSE,
6396                       get_elf_backend_data (dynobj)->collect, &bh)))
6397                 return FALSE;
6398               h = (struct elf_link_hash_entry *) bh;
6399               h->non_elf = 0;
6400               h->def_regular = 1;
6401               h->type = STT_OBJECT;
6402               h->verinfo.vertree = t;
6403
6404               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6405                 return FALSE;
6406
6407               def.vd_version = VER_DEF_CURRENT;
6408               def.vd_flags = 0;
6409               if (t->globals.list == NULL
6410                   && t->locals.list == NULL
6411                   && ! t->used)
6412                 def.vd_flags |= VER_FLG_WEAK;
6413               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6414               def.vd_cnt = cdeps + 1;
6415               def.vd_hash = bfd_elf_hash (t->name);
6416               def.vd_aux = sizeof (Elf_External_Verdef);
6417               def.vd_next = 0;
6418
6419               /* If a basever node is next, it *must* be the last node in
6420                  the chain, otherwise Verdef construction breaks.  */
6421               if (t->next != NULL && t->next->vernum == 0)
6422                 BFD_ASSERT (t->next->next == NULL);
6423
6424               if (t->next != NULL && t->next->vernum != 0)
6425                 def.vd_next = (sizeof (Elf_External_Verdef)
6426                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6427
6428               _bfd_elf_swap_verdef_out (output_bfd, &def,
6429                                         (Elf_External_Verdef *) p);
6430               p += sizeof (Elf_External_Verdef);
6431
6432               defaux.vda_name = h->dynstr_index;
6433               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6434                                       h->dynstr_index);
6435               defaux.vda_next = 0;
6436               if (t->deps != NULL)
6437                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6438               t->name_indx = defaux.vda_name;
6439
6440               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6441                                          (Elf_External_Verdaux *) p);
6442               p += sizeof (Elf_External_Verdaux);
6443
6444               for (n = t->deps; n != NULL; n = n->next)
6445                 {
6446                   if (n->version_needed == NULL)
6447                     {
6448                       /* This can happen if there was an error in the
6449                          version script.  */
6450                       defaux.vda_name = 0;
6451                     }
6452                   else
6453                     {
6454                       defaux.vda_name = n->version_needed->name_indx;
6455                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6456                                               defaux.vda_name);
6457                     }
6458                   if (n->next == NULL)
6459                     defaux.vda_next = 0;
6460                   else
6461                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6462
6463                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6464                                              (Elf_External_Verdaux *) p);
6465                   p += sizeof (Elf_External_Verdaux);
6466                 }
6467             }
6468
6469           elf_tdata (output_bfd)->cverdefs = cdefs;
6470         }
6471     }
6472
6473   bed = get_elf_backend_data (output_bfd);
6474
6475   if (info->gc_sections && bed->can_gc_sections)
6476     {
6477       struct elf_gc_sweep_symbol_info sweep_info;
6478
6479       /* Remove the symbols that were in the swept sections from the
6480          dynamic symbol table.  */
6481       sweep_info.info = info;
6482       sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
6483       elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
6484                               &sweep_info);
6485     }
6486
6487   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6488     {
6489       asection *s;
6490       struct elf_find_verdep_info sinfo;
6491
6492       /* Work out the size of the version reference section.  */
6493
6494       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6495       BFD_ASSERT (s != NULL);
6496
6497       sinfo.info = info;
6498       sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6499       if (sinfo.vers == 0)
6500         sinfo.vers = 1;
6501       sinfo.failed = FALSE;
6502
6503       elf_link_hash_traverse (elf_hash_table (info),
6504                               _bfd_elf_link_find_version_dependencies,
6505                               &sinfo);
6506       if (sinfo.failed)
6507         return FALSE;
6508
6509       if (elf_tdata (output_bfd)->verref == NULL)
6510         s->flags |= SEC_EXCLUDE;
6511       else
6512         {
6513           Elf_Internal_Verneed *vn;
6514           unsigned int size;
6515           unsigned int crefs;
6516           bfd_byte *p;
6517
6518           /* Build the version dependency section.  */
6519           size = 0;
6520           crefs = 0;
6521           for (vn = elf_tdata (output_bfd)->verref;
6522                vn != NULL;
6523                vn = vn->vn_nextref)
6524             {
6525               Elf_Internal_Vernaux *a;
6526
6527               size += sizeof (Elf_External_Verneed);
6528               ++crefs;
6529               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6530                 size += sizeof (Elf_External_Vernaux);
6531             }
6532
6533           s->size = size;
6534           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6535           if (s->contents == NULL)
6536             return FALSE;
6537
6538           p = s->contents;
6539           for (vn = elf_tdata (output_bfd)->verref;
6540                vn != NULL;
6541                vn = vn->vn_nextref)
6542             {
6543               unsigned int caux;
6544               Elf_Internal_Vernaux *a;
6545               size_t indx;
6546
6547               caux = 0;
6548               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6549                 ++caux;
6550
6551               vn->vn_version = VER_NEED_CURRENT;
6552               vn->vn_cnt = caux;
6553               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6554                                           elf_dt_name (vn->vn_bfd) != NULL
6555                                           ? elf_dt_name (vn->vn_bfd)
6556                                           : lbasename (vn->vn_bfd->filename),
6557                                           FALSE);
6558               if (indx == (size_t) -1)
6559                 return FALSE;
6560               vn->vn_file = indx;
6561               vn->vn_aux = sizeof (Elf_External_Verneed);
6562               if (vn->vn_nextref == NULL)
6563                 vn->vn_next = 0;
6564               else
6565                 vn->vn_next = (sizeof (Elf_External_Verneed)
6566                                + caux * sizeof (Elf_External_Vernaux));
6567
6568               _bfd_elf_swap_verneed_out (output_bfd, vn,
6569                                          (Elf_External_Verneed *) p);
6570               p += sizeof (Elf_External_Verneed);
6571
6572               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6573                 {
6574                   a->vna_hash = bfd_elf_hash (a->vna_nodename);
6575                   indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6576                                               a->vna_nodename, FALSE);
6577                   if (indx == (size_t) -1)
6578                     return FALSE;
6579                   a->vna_name = indx;
6580                   if (a->vna_nextptr == NULL)
6581                     a->vna_next = 0;
6582                   else
6583                     a->vna_next = sizeof (Elf_External_Vernaux);
6584
6585                   _bfd_elf_swap_vernaux_out (output_bfd, a,
6586                                              (Elf_External_Vernaux *) p);
6587                   p += sizeof (Elf_External_Vernaux);
6588                 }
6589             }
6590
6591           elf_tdata (output_bfd)->cverrefs = crefs;
6592         }
6593     }
6594
6595   /* Any syms created from now on start with -1 in
6596      got.refcount/offset and plt.refcount/offset.  */
6597   elf_hash_table (info)->init_got_refcount
6598     = elf_hash_table (info)->init_got_offset;
6599   elf_hash_table (info)->init_plt_refcount
6600     = elf_hash_table (info)->init_plt_offset;
6601
6602   if (bfd_link_relocatable (info)
6603       && !_bfd_elf_size_group_sections (info))
6604     return FALSE;
6605
6606   /* The backend may have to create some sections regardless of whether
6607      we're dynamic or not.  */
6608   if (bed->elf_backend_always_size_sections
6609       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
6610     return FALSE;
6611
6612   /* Determine any GNU_STACK segment requirements, after the backend
6613      has had a chance to set a default segment size.  */
6614   if (info->execstack)
6615     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
6616   else if (info->noexecstack)
6617     elf_stack_flags (output_bfd) = PF_R | PF_W;
6618   else
6619     {
6620       bfd *inputobj;
6621       asection *notesec = NULL;
6622       int exec = 0;
6623
6624       for (inputobj = info->input_bfds;
6625            inputobj;
6626            inputobj = inputobj->link.next)
6627         {
6628           asection *s;
6629
6630           if (inputobj->flags
6631               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
6632             continue;
6633           s = inputobj->sections;
6634           if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
6635             continue;
6636
6637           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
6638           if (s)
6639             {
6640               if (s->flags & SEC_CODE)
6641                 exec = PF_X;
6642               notesec = s;
6643             }
6644           else if (bed->default_execstack)
6645             exec = PF_X;
6646         }
6647       if (notesec || info->stacksize > 0)
6648         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
6649       if (notesec && exec && bfd_link_relocatable (info)
6650           && notesec->output_section != bfd_abs_section_ptr)
6651         notesec->output_section->flags |= SEC_CODE;
6652     }
6653
6654   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6655     {
6656       struct elf_info_failed eif;
6657       struct elf_link_hash_entry *h;
6658       asection *dynstr;
6659       asection *s;
6660
6661       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
6662       BFD_ASSERT (*sinterpptr != NULL || !bfd_link_executable (info) || info->nointerp);
6663
6664       if (info->symbolic)
6665         {
6666           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
6667             return FALSE;
6668           info->flags |= DF_SYMBOLIC;
6669         }
6670
6671       if (rpath != NULL)
6672         {
6673           size_t indx;
6674           bfd_vma tag;
6675
6676           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
6677                                       TRUE);
6678           if (indx == (size_t) -1)
6679             return FALSE;
6680
6681           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
6682           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
6683             return FALSE;
6684         }
6685
6686       if (filter_shlib != NULL)
6687         {
6688           size_t indx;
6689
6690           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6691                                       filter_shlib, TRUE);
6692           if (indx == (size_t) -1
6693               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
6694             return FALSE;
6695         }
6696
6697       if (auxiliary_filters != NULL)
6698         {
6699           const char * const *p;
6700
6701           for (p = auxiliary_filters; *p != NULL; p++)
6702             {
6703               size_t indx;
6704
6705               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6706                                           *p, TRUE);
6707               if (indx == (size_t) -1
6708                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
6709                 return FALSE;
6710             }
6711         }
6712
6713       if (audit != NULL)
6714         {
6715           size_t indx;
6716
6717           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
6718                                       TRUE);
6719           if (indx == (size_t) -1
6720               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
6721             return FALSE;
6722         }
6723
6724       if (depaudit != NULL)
6725         {
6726           size_t indx;
6727
6728           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
6729                                       TRUE);
6730           if (indx == (size_t) -1
6731               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
6732             return FALSE;
6733         }
6734
6735       eif.info = info;
6736       eif.failed = FALSE;
6737
6738       /* Find all symbols which were defined in a dynamic object and make
6739          the backend pick a reasonable value for them.  */
6740       elf_link_hash_traverse (elf_hash_table (info),
6741                               _bfd_elf_adjust_dynamic_symbol,
6742                               &eif);
6743       if (eif.failed)
6744         return FALSE;
6745
6746       /* Add some entries to the .dynamic section.  We fill in some of the
6747          values later, in bfd_elf_final_link, but we must add the entries
6748          now so that we know the final size of the .dynamic section.  */
6749
6750       /* If there are initialization and/or finalization functions to
6751          call then add the corresponding DT_INIT/DT_FINI entries.  */
6752       h = (info->init_function
6753            ? elf_link_hash_lookup (elf_hash_table (info),
6754                                    info->init_function, FALSE,
6755                                    FALSE, FALSE)
6756            : NULL);
6757       if (h != NULL
6758           && (h->ref_regular
6759               || h->def_regular))
6760         {
6761           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
6762             return FALSE;
6763         }
6764       h = (info->fini_function
6765            ? elf_link_hash_lookup (elf_hash_table (info),
6766                                    info->fini_function, FALSE,
6767                                    FALSE, FALSE)
6768            : NULL);
6769       if (h != NULL
6770           && (h->ref_regular
6771               || h->def_regular))
6772         {
6773           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
6774             return FALSE;
6775         }
6776
6777       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
6778       if (s != NULL && s->linker_has_input)
6779         {
6780           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
6781           if (! bfd_link_executable (info))
6782             {
6783               bfd *sub;
6784               asection *o;
6785
6786               for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
6787                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour
6788                     && (o = sub->sections) != NULL
6789                     && o->sec_info_type != SEC_INFO_TYPE_JUST_SYMS)
6790                   for (o = sub->sections; o != NULL; o = o->next)
6791                     if (elf_section_data (o)->this_hdr.sh_type
6792                         == SHT_PREINIT_ARRAY)
6793                       {
6794                         _bfd_error_handler
6795                           (_("%pB: .preinit_array section is not allowed in DSO"),
6796                            sub);
6797                         break;
6798                       }
6799
6800               bfd_set_error (bfd_error_nonrepresentable_section);
6801               return FALSE;
6802             }
6803
6804           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6805               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6806             return FALSE;
6807         }
6808       s = bfd_get_section_by_name (output_bfd, ".init_array");
6809       if (s != NULL && s->linker_has_input)
6810         {
6811           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6812               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6813             return FALSE;
6814         }
6815       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6816       if (s != NULL && s->linker_has_input)
6817         {
6818           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6819               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6820             return FALSE;
6821         }
6822
6823       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6824       /* If .dynstr is excluded from the link, we don't want any of
6825          these tags.  Strictly, we should be checking each section
6826          individually;  This quick check covers for the case where
6827          someone does a /DISCARD/ : { *(*) }.  */
6828       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6829         {
6830           bfd_size_type strsize;
6831
6832           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6833           if ((info->emit_hash
6834                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6835               || (info->emit_gnu_hash
6836                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6837               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6838               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6839               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6840               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6841                                               bed->s->sizeof_sym))
6842             return FALSE;
6843         }
6844     }
6845
6846   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6847     return FALSE;
6848
6849   /* The backend must work out the sizes of all the other dynamic
6850      sections.  */
6851   if (dynobj != NULL
6852       && bed->elf_backend_size_dynamic_sections != NULL
6853       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6854     return FALSE;
6855
6856   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6857     {
6858       if (elf_tdata (output_bfd)->cverdefs)
6859         {
6860           unsigned int crefs = elf_tdata (output_bfd)->cverdefs;
6861
6862           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6863               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, crefs))
6864             return FALSE;
6865         }
6866
6867       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6868         {
6869           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6870             return FALSE;
6871         }
6872       else if (info->flags & DF_BIND_NOW)
6873         {
6874           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6875             return FALSE;
6876         }
6877
6878       if (info->flags_1)
6879         {
6880           if (bfd_link_executable (info))
6881             info->flags_1 &= ~ (DF_1_INITFIRST
6882                                 | DF_1_NODELETE
6883                                 | DF_1_NOOPEN);
6884           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6885             return FALSE;
6886         }
6887
6888       if (elf_tdata (output_bfd)->cverrefs)
6889         {
6890           unsigned int crefs = elf_tdata (output_bfd)->cverrefs;
6891
6892           if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6893               || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6894             return FALSE;
6895         }
6896
6897       if ((elf_tdata (output_bfd)->cverrefs == 0
6898            && elf_tdata (output_bfd)->cverdefs == 0)
6899           || _bfd_elf_link_renumber_dynsyms (output_bfd, info, NULL) <= 1)
6900         {
6901           asection *s;
6902
6903           s = bfd_get_linker_section (dynobj, ".gnu.version");
6904           s->flags |= SEC_EXCLUDE;
6905         }
6906     }
6907   return TRUE;
6908 }
6909
6910 /* Find the first non-excluded output section.  We'll use its
6911    section symbol for some emitted relocs.  */
6912 void
6913 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6914 {
6915   asection *s;
6916
6917   for (s = output_bfd->sections; s != NULL; s = s->next)
6918     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6919         && !_bfd_elf_omit_section_dynsym_default (output_bfd, info, s))
6920       {
6921         elf_hash_table (info)->text_index_section = s;
6922         break;
6923       }
6924 }
6925
6926 /* Find two non-excluded output sections, one for code, one for data.
6927    We'll use their section symbols for some emitted relocs.  */
6928 void
6929 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6930 {
6931   asection *s;
6932
6933   /* Data first, since setting text_index_section changes
6934      _bfd_elf_link_omit_section_dynsym.  */
6935   for (s = output_bfd->sections; s != NULL; s = s->next)
6936     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6937         && !_bfd_elf_omit_section_dynsym_default (output_bfd, info, s))
6938       {
6939         elf_hash_table (info)->data_index_section = s;
6940         break;
6941       }
6942
6943   for (s = output_bfd->sections; s != NULL; s = s->next)
6944     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6945          == (SEC_ALLOC | SEC_READONLY))
6946         && !_bfd_elf_omit_section_dynsym_default (output_bfd, info, s))
6947       {
6948         elf_hash_table (info)->text_index_section = s;
6949         break;
6950       }
6951
6952   if (elf_hash_table (info)->text_index_section == NULL)
6953     elf_hash_table (info)->text_index_section
6954       = elf_hash_table (info)->data_index_section;
6955 }
6956
6957 bfd_boolean
6958 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6959 {
6960   const struct elf_backend_data *bed;
6961   unsigned long section_sym_count;
6962   bfd_size_type dynsymcount = 0;
6963
6964   if (!is_elf_hash_table (info->hash))
6965     return TRUE;
6966
6967   bed = get_elf_backend_data (output_bfd);
6968   (*bed->elf_backend_init_index_section) (output_bfd, info);
6969
6970   /* Assign dynsym indices.  In a shared library we generate a section
6971      symbol for each output section, which come first.  Next come all
6972      of the back-end allocated local dynamic syms, followed by the rest
6973      of the global symbols.
6974
6975      This is usually not needed for static binaries, however backends
6976      can request to always do it, e.g. the MIPS backend uses dynamic
6977      symbol counts to lay out GOT, which will be produced in the
6978      presence of GOT relocations even in static binaries (holding fixed
6979      data in that case, to satisfy those relocations).  */
6980
6981   if (elf_hash_table (info)->dynamic_sections_created
6982       || bed->always_renumber_dynsyms)
6983     dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6984                                                   &section_sym_count);
6985
6986   if (elf_hash_table (info)->dynamic_sections_created)
6987     {
6988       bfd *dynobj;
6989       asection *s;
6990       unsigned int dtagcount;
6991
6992       dynobj = elf_hash_table (info)->dynobj;
6993
6994       /* Work out the size of the symbol version section.  */
6995       s = bfd_get_linker_section (dynobj, ".gnu.version");
6996       BFD_ASSERT (s != NULL);
6997       if ((s->flags & SEC_EXCLUDE) == 0)
6998         {
6999           s->size = dynsymcount * sizeof (Elf_External_Versym);
7000           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7001           if (s->contents == NULL)
7002             return FALSE;
7003
7004           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
7005             return FALSE;
7006         }
7007
7008       /* Set the size of the .dynsym and .hash sections.  We counted
7009          the number of dynamic symbols in elf_link_add_object_symbols.
7010          We will build the contents of .dynsym and .hash when we build
7011          the final symbol table, because until then we do not know the
7012          correct value to give the symbols.  We built the .dynstr
7013          section as we went along in elf_link_add_object_symbols.  */
7014       s = elf_hash_table (info)->dynsym;
7015       BFD_ASSERT (s != NULL);
7016       s->size = dynsymcount * bed->s->sizeof_sym;
7017
7018       s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
7019       if (s->contents == NULL)
7020         return FALSE;
7021
7022       /* The first entry in .dynsym is a dummy symbol.  Clear all the
7023          section syms, in case we don't output them all.  */
7024       ++section_sym_count;
7025       memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
7026
7027       elf_hash_table (info)->bucketcount = 0;
7028
7029       /* Compute the size of the hashing table.  As a side effect this
7030          computes the hash values for all the names we export.  */
7031       if (info->emit_hash)
7032         {
7033           unsigned long int *hashcodes;
7034           struct hash_codes_info hashinf;
7035           bfd_size_type amt;
7036           unsigned long int nsyms;
7037           size_t bucketcount;
7038           size_t hash_entry_size;
7039
7040           /* Compute the hash values for all exported symbols.  At the same
7041              time store the values in an array so that we could use them for
7042              optimizations.  */
7043           amt = dynsymcount * sizeof (unsigned long int);
7044           hashcodes = (unsigned long int *) bfd_malloc (amt);
7045           if (hashcodes == NULL)
7046             return FALSE;
7047           hashinf.hashcodes = hashcodes;
7048           hashinf.error = FALSE;
7049
7050           /* Put all hash values in HASHCODES.  */
7051           elf_link_hash_traverse (elf_hash_table (info),
7052                                   elf_collect_hash_codes, &hashinf);
7053           if (hashinf.error)
7054             {
7055               free (hashcodes);
7056               return FALSE;
7057             }
7058
7059           nsyms = hashinf.hashcodes - hashcodes;
7060           bucketcount
7061             = compute_bucket_count (info, hashcodes, nsyms, 0);
7062           free (hashcodes);
7063
7064           if (bucketcount == 0 && nsyms > 0)
7065             return FALSE;
7066
7067           elf_hash_table (info)->bucketcount = bucketcount;
7068
7069           s = bfd_get_linker_section (dynobj, ".hash");
7070           BFD_ASSERT (s != NULL);
7071           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
7072           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
7073           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7074           if (s->contents == NULL)
7075             return FALSE;
7076
7077           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
7078           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
7079                    s->contents + hash_entry_size);
7080         }
7081
7082       if (info->emit_gnu_hash)
7083         {
7084           size_t i, cnt;
7085           unsigned char *contents;
7086           struct collect_gnu_hash_codes cinfo;
7087           bfd_size_type amt;
7088           size_t bucketcount;
7089
7090           memset (&cinfo, 0, sizeof (cinfo));
7091
7092           /* Compute the hash values for all exported symbols.  At the same
7093              time store the values in an array so that we could use them for
7094              optimizations.  */
7095           amt = dynsymcount * 2 * sizeof (unsigned long int);
7096           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
7097           if (cinfo.hashcodes == NULL)
7098             return FALSE;
7099
7100           cinfo.hashval = cinfo.hashcodes + dynsymcount;
7101           cinfo.min_dynindx = -1;
7102           cinfo.output_bfd = output_bfd;
7103           cinfo.bed = bed;
7104
7105           /* Put all hash values in HASHCODES.  */
7106           elf_link_hash_traverse (elf_hash_table (info),
7107                                   elf_collect_gnu_hash_codes, &cinfo);
7108           if (cinfo.error)
7109             {
7110               free (cinfo.hashcodes);
7111               return FALSE;
7112             }
7113
7114           bucketcount
7115             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
7116
7117           if (bucketcount == 0)
7118             {
7119               free (cinfo.hashcodes);
7120               return FALSE;
7121             }
7122
7123           s = bfd_get_linker_section (dynobj, ".gnu.hash");
7124           BFD_ASSERT (s != NULL);
7125
7126           if (cinfo.nsyms == 0)
7127             {
7128               /* Empty .gnu.hash section is special.  */
7129               BFD_ASSERT (cinfo.min_dynindx == -1);
7130               free (cinfo.hashcodes);
7131               s->size = 5 * 4 + bed->s->arch_size / 8;
7132               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7133               if (contents == NULL)
7134                 return FALSE;
7135               s->contents = contents;
7136               /* 1 empty bucket.  */
7137               bfd_put_32 (output_bfd, 1, contents);
7138               /* SYMIDX above the special symbol 0.  */
7139               bfd_put_32 (output_bfd, 1, contents + 4);
7140               /* Just one word for bitmask.  */
7141               bfd_put_32 (output_bfd, 1, contents + 8);
7142               /* Only hash fn bloom filter.  */
7143               bfd_put_32 (output_bfd, 0, contents + 12);
7144               /* No hashes are valid - empty bitmask.  */
7145               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
7146               /* No hashes in the only bucket.  */
7147               bfd_put_32 (output_bfd, 0,
7148                           contents + 16 + bed->s->arch_size / 8);
7149             }
7150           else
7151             {
7152               unsigned long int maskwords, maskbitslog2, x;
7153               BFD_ASSERT (cinfo.min_dynindx != -1);
7154
7155               x = cinfo.nsyms;
7156               maskbitslog2 = 1;
7157               while ((x >>= 1) != 0)
7158                 ++maskbitslog2;
7159               if (maskbitslog2 < 3)
7160                 maskbitslog2 = 5;
7161               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
7162                 maskbitslog2 = maskbitslog2 + 3;
7163               else
7164                 maskbitslog2 = maskbitslog2 + 2;
7165               if (bed->s->arch_size == 64)
7166                 {
7167                   if (maskbitslog2 == 5)
7168                     maskbitslog2 = 6;
7169                   cinfo.shift1 = 6;
7170                 }
7171               else
7172                 cinfo.shift1 = 5;
7173               cinfo.mask = (1 << cinfo.shift1) - 1;
7174               cinfo.shift2 = maskbitslog2;
7175               cinfo.maskbits = 1 << maskbitslog2;
7176               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
7177               amt = bucketcount * sizeof (unsigned long int) * 2;
7178               amt += maskwords * sizeof (bfd_vma);
7179               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
7180               if (cinfo.bitmask == NULL)
7181                 {
7182                   free (cinfo.hashcodes);
7183                   return FALSE;
7184                 }
7185
7186               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
7187               cinfo.indx = cinfo.counts + bucketcount;
7188               cinfo.symindx = dynsymcount - cinfo.nsyms;
7189               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
7190
7191               /* Determine how often each hash bucket is used.  */
7192               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
7193               for (i = 0; i < cinfo.nsyms; ++i)
7194                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
7195
7196               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
7197                 if (cinfo.counts[i] != 0)
7198                   {
7199                     cinfo.indx[i] = cnt;
7200                     cnt += cinfo.counts[i];
7201                   }
7202               BFD_ASSERT (cnt == dynsymcount);
7203               cinfo.bucketcount = bucketcount;
7204               cinfo.local_indx = cinfo.min_dynindx;
7205
7206               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
7207               s->size += cinfo.maskbits / 8;
7208               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7209               if (contents == NULL)
7210                 {
7211                   free (cinfo.bitmask);
7212                   free (cinfo.hashcodes);
7213                   return FALSE;
7214                 }
7215
7216               s->contents = contents;
7217               bfd_put_32 (output_bfd, bucketcount, contents);
7218               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
7219               bfd_put_32 (output_bfd, maskwords, contents + 8);
7220               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
7221               contents += 16 + cinfo.maskbits / 8;
7222
7223               for (i = 0; i < bucketcount; ++i)
7224                 {
7225                   if (cinfo.counts[i] == 0)
7226                     bfd_put_32 (output_bfd, 0, contents);
7227                   else
7228                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
7229                   contents += 4;
7230                 }
7231
7232               cinfo.contents = contents;
7233
7234               /* Renumber dynamic symbols, populate .gnu.hash section.  */
7235               elf_link_hash_traverse (elf_hash_table (info),
7236                                       elf_renumber_gnu_hash_syms, &cinfo);
7237
7238               contents = s->contents + 16;
7239               for (i = 0; i < maskwords; ++i)
7240                 {
7241                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
7242                            contents);
7243                   contents += bed->s->arch_size / 8;
7244                 }
7245
7246               free (cinfo.bitmask);
7247               free (cinfo.hashcodes);
7248             }
7249         }
7250
7251       s = bfd_get_linker_section (dynobj, ".dynstr");
7252       BFD_ASSERT (s != NULL);
7253
7254       elf_finalize_dynstr (output_bfd, info);
7255
7256       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
7257
7258       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
7259         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
7260           return FALSE;
7261     }
7262
7263   return TRUE;
7264 }
7265 \f
7266 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
7267
7268 static void
7269 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
7270                             asection *sec)
7271 {
7272   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
7273   sec->sec_info_type = SEC_INFO_TYPE_NONE;
7274 }
7275
7276 /* Finish SHF_MERGE section merging.  */
7277
7278 bfd_boolean
7279 _bfd_elf_merge_sections (bfd *obfd, struct bfd_link_info *info)
7280 {
7281   bfd *ibfd;
7282   asection *sec;
7283
7284   if (!is_elf_hash_table (info->hash))
7285     return FALSE;
7286
7287   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
7288     if ((ibfd->flags & DYNAMIC) == 0
7289         && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
7290         && (elf_elfheader (ibfd)->e_ident[EI_CLASS]
7291             == get_elf_backend_data (obfd)->s->elfclass))
7292       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
7293         if ((sec->flags & SEC_MERGE) != 0
7294             && !bfd_is_abs_section (sec->output_section))
7295           {
7296             struct bfd_elf_section_data *secdata;
7297
7298             secdata = elf_section_data (sec);
7299             if (! _bfd_add_merge_section (obfd,
7300                                           &elf_hash_table (info)->merge_info,
7301                                           sec, &secdata->sec_info))
7302               return FALSE;
7303             else if (secdata->sec_info)
7304               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
7305           }
7306
7307   if (elf_hash_table (info)->merge_info != NULL)
7308     _bfd_merge_sections (obfd, info, elf_hash_table (info)->merge_info,
7309                          merge_sections_remove_hook);
7310   return TRUE;
7311 }
7312
7313 /* Create an entry in an ELF linker hash table.  */
7314
7315 struct bfd_hash_entry *
7316 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
7317                             struct bfd_hash_table *table,
7318                             const char *string)
7319 {
7320   /* Allocate the structure if it has not already been allocated by a
7321      subclass.  */
7322   if (entry == NULL)
7323     {
7324       entry = (struct bfd_hash_entry *)
7325         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
7326       if (entry == NULL)
7327         return entry;
7328     }
7329
7330   /* Call the allocation method of the superclass.  */
7331   entry = _bfd_link_hash_newfunc (entry, table, string);
7332   if (entry != NULL)
7333     {
7334       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
7335       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
7336
7337       /* Set local fields.  */
7338       ret->indx = -1;
7339       ret->dynindx = -1;
7340       ret->got = htab->init_got_refcount;
7341       ret->plt = htab->init_plt_refcount;
7342       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
7343                               - offsetof (struct elf_link_hash_entry, size)));
7344       /* Assume that we have been called by a non-ELF symbol reader.
7345          This flag is then reset by the code which reads an ELF input
7346          file.  This ensures that a symbol created by a non-ELF symbol
7347          reader will have the flag set correctly.  */
7348       ret->non_elf = 1;
7349     }
7350
7351   return entry;
7352 }
7353
7354 /* Copy data from an indirect symbol to its direct symbol, hiding the
7355    old indirect symbol.  Also used for copying flags to a weakdef.  */
7356
7357 void
7358 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
7359                                   struct elf_link_hash_entry *dir,
7360                                   struct elf_link_hash_entry *ind)
7361 {
7362   struct elf_link_hash_table *htab;
7363
7364   /* Copy down any references that we may have already seen to the
7365      symbol which just became indirect.  */
7366
7367   if (dir->versioned != versioned_hidden)
7368     dir->ref_dynamic |= ind->ref_dynamic;
7369   dir->ref_regular |= ind->ref_regular;
7370   dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
7371   dir->non_got_ref |= ind->non_got_ref;
7372   dir->needs_plt |= ind->needs_plt;
7373   dir->pointer_equality_needed |= ind->pointer_equality_needed;
7374
7375   if (ind->root.type != bfd_link_hash_indirect)
7376     return;
7377
7378   /* Copy over the global and procedure linkage table refcount entries.
7379      These may have been already set up by a check_relocs routine.  */
7380   htab = elf_hash_table (info);
7381   if (ind->got.refcount > htab->init_got_refcount.refcount)
7382     {
7383       if (dir->got.refcount < 0)
7384         dir->got.refcount = 0;
7385       dir->got.refcount += ind->got.refcount;
7386       ind->got.refcount = htab->init_got_refcount.refcount;
7387     }
7388
7389   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
7390     {
7391       if (dir->plt.refcount < 0)
7392         dir->plt.refcount = 0;
7393       dir->plt.refcount += ind->plt.refcount;
7394       ind->plt.refcount = htab->init_plt_refcount.refcount;
7395     }
7396
7397   if (ind->dynindx != -1)
7398     {
7399       if (dir->dynindx != -1)
7400         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
7401       dir->dynindx = ind->dynindx;
7402       dir->dynstr_index = ind->dynstr_index;
7403       ind->dynindx = -1;
7404       ind->dynstr_index = 0;
7405     }
7406 }
7407
7408 void
7409 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
7410                                 struct elf_link_hash_entry *h,
7411                                 bfd_boolean force_local)
7412 {
7413   /* STT_GNU_IFUNC symbol must go through PLT.  */
7414   if (h->type != STT_GNU_IFUNC)
7415     {
7416       h->plt = elf_hash_table (info)->init_plt_offset;
7417       h->needs_plt = 0;
7418     }
7419   if (force_local)
7420     {
7421       h->forced_local = 1;
7422       if (h->dynindx != -1)
7423         {
7424           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
7425                                   h->dynstr_index);
7426           h->dynindx = -1;
7427           h->dynstr_index = 0;
7428         }
7429     }
7430 }
7431
7432 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
7433    caller.  */
7434
7435 bfd_boolean
7436 _bfd_elf_link_hash_table_init
7437   (struct elf_link_hash_table *table,
7438    bfd *abfd,
7439    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
7440                                       struct bfd_hash_table *,
7441                                       const char *),
7442    unsigned int entsize,
7443    enum elf_target_id target_id)
7444 {
7445   bfd_boolean ret;
7446   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
7447
7448   table->init_got_refcount.refcount = can_refcount - 1;
7449   table->init_plt_refcount.refcount = can_refcount - 1;
7450   table->init_got_offset.offset = -(bfd_vma) 1;
7451   table->init_plt_offset.offset = -(bfd_vma) 1;
7452   /* The first dynamic symbol is a dummy.  */
7453   table->dynsymcount = 1;
7454
7455   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
7456
7457   table->root.type = bfd_link_elf_hash_table;
7458   table->hash_table_id = target_id;
7459
7460   return ret;
7461 }
7462
7463 /* Create an ELF linker hash table.  */
7464
7465 struct bfd_link_hash_table *
7466 _bfd_elf_link_hash_table_create (bfd *abfd)
7467 {
7468   struct elf_link_hash_table *ret;
7469   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7470
7471   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7472   if (ret == NULL)
7473     return NULL;
7474
7475   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7476                                        sizeof (struct elf_link_hash_entry),
7477                                        GENERIC_ELF_DATA))
7478     {
7479       free (ret);
7480       return NULL;
7481     }
7482   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7483
7484   return &ret->root;
7485 }
7486
7487 /* Destroy an ELF linker hash table.  */
7488
7489 void
7490 _bfd_elf_link_hash_table_free (bfd *obfd)
7491 {
7492   struct elf_link_hash_table *htab;
7493
7494   htab = (struct elf_link_hash_table *) obfd->link.hash;
7495   if (htab->dynstr != NULL)
7496     _bfd_elf_strtab_free (htab->dynstr);
7497   _bfd_merge_sections_free (htab->merge_info);
7498   _bfd_generic_link_hash_table_free (obfd);
7499 }
7500
7501 /* This is a hook for the ELF emulation code in the generic linker to
7502    tell the backend linker what file name to use for the DT_NEEDED
7503    entry for a dynamic object.  */
7504
7505 void
7506 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7507 {
7508   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7509       && bfd_get_format (abfd) == bfd_object)
7510     elf_dt_name (abfd) = name;
7511 }
7512
7513 int
7514 bfd_elf_get_dyn_lib_class (bfd *abfd)
7515 {
7516   int lib_class;
7517   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7518       && bfd_get_format (abfd) == bfd_object)
7519     lib_class = elf_dyn_lib_class (abfd);
7520   else
7521     lib_class = 0;
7522   return lib_class;
7523 }
7524
7525 void
7526 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7527 {
7528   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7529       && bfd_get_format (abfd) == bfd_object)
7530     elf_dyn_lib_class (abfd) = lib_class;
7531 }
7532
7533 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7534    the linker ELF emulation code.  */
7535
7536 struct bfd_link_needed_list *
7537 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7538                          struct bfd_link_info *info)
7539 {
7540   if (! is_elf_hash_table (info->hash))
7541     return NULL;
7542   return elf_hash_table (info)->needed;
7543 }
7544
7545 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7546    hook for the linker ELF emulation code.  */
7547
7548 struct bfd_link_needed_list *
7549 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7550                           struct bfd_link_info *info)
7551 {
7552   if (! is_elf_hash_table (info->hash))
7553     return NULL;
7554   return elf_hash_table (info)->runpath;
7555 }
7556
7557 /* Get the name actually used for a dynamic object for a link.  This
7558    is the SONAME entry if there is one.  Otherwise, it is the string
7559    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7560
7561 const char *
7562 bfd_elf_get_dt_soname (bfd *abfd)
7563 {
7564   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7565       && bfd_get_format (abfd) == bfd_object)
7566     return elf_dt_name (abfd);
7567   return NULL;
7568 }
7569
7570 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7571    the ELF linker emulation code.  */
7572
7573 bfd_boolean
7574 bfd_elf_get_bfd_needed_list (bfd *abfd,
7575                              struct bfd_link_needed_list **pneeded)
7576 {
7577   asection *s;
7578   bfd_byte *dynbuf = NULL;
7579   unsigned int elfsec;
7580   unsigned long shlink;
7581   bfd_byte *extdyn, *extdynend;
7582   size_t extdynsize;
7583   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7584
7585   *pneeded = NULL;
7586
7587   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7588       || bfd_get_format (abfd) != bfd_object)
7589     return TRUE;
7590
7591   s = bfd_get_section_by_name (abfd, ".dynamic");
7592   if (s == NULL || s->size == 0)
7593     return TRUE;
7594
7595   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7596     goto error_return;
7597
7598   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7599   if (elfsec == SHN_BAD)
7600     goto error_return;
7601
7602   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7603
7604   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7605   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7606
7607   extdyn = dynbuf;
7608   extdynend = extdyn + s->size;
7609   for (; extdyn < extdynend; extdyn += extdynsize)
7610     {
7611       Elf_Internal_Dyn dyn;
7612
7613       (*swap_dyn_in) (abfd, extdyn, &dyn);
7614
7615       if (dyn.d_tag == DT_NULL)
7616         break;
7617
7618       if (dyn.d_tag == DT_NEEDED)
7619         {
7620           const char *string;
7621           struct bfd_link_needed_list *l;
7622           unsigned int tagv = dyn.d_un.d_val;
7623           bfd_size_type amt;
7624
7625           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7626           if (string == NULL)
7627             goto error_return;
7628
7629           amt = sizeof *l;
7630           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7631           if (l == NULL)
7632             goto error_return;
7633
7634           l->by = abfd;
7635           l->name = string;
7636           l->next = *pneeded;
7637           *pneeded = l;
7638         }
7639     }
7640
7641   free (dynbuf);
7642
7643   return TRUE;
7644
7645  error_return:
7646   if (dynbuf != NULL)
7647     free (dynbuf);
7648   return FALSE;
7649 }
7650
7651 struct elf_symbuf_symbol
7652 {
7653   unsigned long st_name;        /* Symbol name, index in string tbl */
7654   unsigned char st_info;        /* Type and binding attributes */
7655   unsigned char st_other;       /* Visibilty, and target specific */
7656 };
7657
7658 struct elf_symbuf_head
7659 {
7660   struct elf_symbuf_symbol *ssym;
7661   size_t count;
7662   unsigned int st_shndx;
7663 };
7664
7665 struct elf_symbol
7666 {
7667   union
7668     {
7669       Elf_Internal_Sym *isym;
7670       struct elf_symbuf_symbol *ssym;
7671     } u;
7672   const char *name;
7673 };
7674
7675 /* Sort references to symbols by ascending section number.  */
7676
7677 static int
7678 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7679 {
7680   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7681   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7682
7683   return s1->st_shndx - s2->st_shndx;
7684 }
7685
7686 static int
7687 elf_sym_name_compare (const void *arg1, const void *arg2)
7688 {
7689   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7690   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7691   return strcmp (s1->name, s2->name);
7692 }
7693
7694 static struct elf_symbuf_head *
7695 elf_create_symbuf (size_t symcount, Elf_Internal_Sym *isymbuf)
7696 {
7697   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7698   struct elf_symbuf_symbol *ssym;
7699   struct elf_symbuf_head *ssymbuf, *ssymhead;
7700   size_t i, shndx_count, total_size;
7701
7702   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7703   if (indbuf == NULL)
7704     return NULL;
7705
7706   for (ind = indbuf, i = 0; i < symcount; i++)
7707     if (isymbuf[i].st_shndx != SHN_UNDEF)
7708       *ind++ = &isymbuf[i];
7709   indbufend = ind;
7710
7711   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7712          elf_sort_elf_symbol);
7713
7714   shndx_count = 0;
7715   if (indbufend > indbuf)
7716     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7717       if (ind[0]->st_shndx != ind[1]->st_shndx)
7718         shndx_count++;
7719
7720   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7721                 + (indbufend - indbuf) * sizeof (*ssym));
7722   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7723   if (ssymbuf == NULL)
7724     {
7725       free (indbuf);
7726       return NULL;
7727     }
7728
7729   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7730   ssymbuf->ssym = NULL;
7731   ssymbuf->count = shndx_count;
7732   ssymbuf->st_shndx = 0;
7733   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7734     {
7735       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7736         {
7737           ssymhead++;
7738           ssymhead->ssym = ssym;
7739           ssymhead->count = 0;
7740           ssymhead->st_shndx = (*ind)->st_shndx;
7741         }
7742       ssym->st_name = (*ind)->st_name;
7743       ssym->st_info = (*ind)->st_info;
7744       ssym->st_other = (*ind)->st_other;
7745       ssymhead->count++;
7746     }
7747   BFD_ASSERT ((size_t) (ssymhead - ssymbuf) == shndx_count
7748               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7749                   == total_size));
7750
7751   free (indbuf);
7752   return ssymbuf;
7753 }
7754
7755 /* Check if 2 sections define the same set of local and global
7756    symbols.  */
7757
7758 static bfd_boolean
7759 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7760                                    struct bfd_link_info *info)
7761 {
7762   bfd *bfd1, *bfd2;
7763   const struct elf_backend_data *bed1, *bed2;
7764   Elf_Internal_Shdr *hdr1, *hdr2;
7765   size_t symcount1, symcount2;
7766   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7767   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7768   Elf_Internal_Sym *isym, *isymend;
7769   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7770   size_t count1, count2, i;
7771   unsigned int shndx1, shndx2;
7772   bfd_boolean result;
7773
7774   bfd1 = sec1->owner;
7775   bfd2 = sec2->owner;
7776
7777   /* Both sections have to be in ELF.  */
7778   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7779       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7780     return FALSE;
7781
7782   if (elf_section_type (sec1) != elf_section_type (sec2))
7783     return FALSE;
7784
7785   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7786   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7787   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7788     return FALSE;
7789
7790   bed1 = get_elf_backend_data (bfd1);
7791   bed2 = get_elf_backend_data (bfd2);
7792   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7793   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7794   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7795   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7796
7797   if (symcount1 == 0 || symcount2 == 0)
7798     return FALSE;
7799
7800   result = FALSE;
7801   isymbuf1 = NULL;
7802   isymbuf2 = NULL;
7803   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7804   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7805
7806   if (ssymbuf1 == NULL)
7807     {
7808       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7809                                        NULL, NULL, NULL);
7810       if (isymbuf1 == NULL)
7811         goto done;
7812
7813       if (!info->reduce_memory_overheads)
7814         elf_tdata (bfd1)->symbuf = ssymbuf1
7815           = elf_create_symbuf (symcount1, isymbuf1);
7816     }
7817
7818   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7819     {
7820       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7821                                        NULL, NULL, NULL);
7822       if (isymbuf2 == NULL)
7823         goto done;
7824
7825       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7826         elf_tdata (bfd2)->symbuf = ssymbuf2
7827           = elf_create_symbuf (symcount2, isymbuf2);
7828     }
7829
7830   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7831     {
7832       /* Optimized faster version.  */
7833       size_t lo, hi, mid;
7834       struct elf_symbol *symp;
7835       struct elf_symbuf_symbol *ssym, *ssymend;
7836
7837       lo = 0;
7838       hi = ssymbuf1->count;
7839       ssymbuf1++;
7840       count1 = 0;
7841       while (lo < hi)
7842         {
7843           mid = (lo + hi) / 2;
7844           if (shndx1 < ssymbuf1[mid].st_shndx)
7845             hi = mid;
7846           else if (shndx1 > ssymbuf1[mid].st_shndx)
7847             lo = mid + 1;
7848           else
7849             {
7850               count1 = ssymbuf1[mid].count;
7851               ssymbuf1 += mid;
7852               break;
7853             }
7854         }
7855
7856       lo = 0;
7857       hi = ssymbuf2->count;
7858       ssymbuf2++;
7859       count2 = 0;
7860       while (lo < hi)
7861         {
7862           mid = (lo + hi) / 2;
7863           if (shndx2 < ssymbuf2[mid].st_shndx)
7864             hi = mid;
7865           else if (shndx2 > ssymbuf2[mid].st_shndx)
7866             lo = mid + 1;
7867           else
7868             {
7869               count2 = ssymbuf2[mid].count;
7870               ssymbuf2 += mid;
7871               break;
7872             }
7873         }
7874
7875       if (count1 == 0 || count2 == 0 || count1 != count2)
7876         goto done;
7877
7878       symtable1
7879         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
7880       symtable2
7881         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
7882       if (symtable1 == NULL || symtable2 == NULL)
7883         goto done;
7884
7885       symp = symtable1;
7886       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7887            ssym < ssymend; ssym++, symp++)
7888         {
7889           symp->u.ssym = ssym;
7890           symp->name = bfd_elf_string_from_elf_section (bfd1,
7891                                                         hdr1->sh_link,
7892                                                         ssym->st_name);
7893         }
7894
7895       symp = symtable2;
7896       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7897            ssym < ssymend; ssym++, symp++)
7898         {
7899           symp->u.ssym = ssym;
7900           symp->name = bfd_elf_string_from_elf_section (bfd2,
7901                                                         hdr2->sh_link,
7902                                                         ssym->st_name);
7903         }
7904
7905       /* Sort symbol by name.  */
7906       qsort (symtable1, count1, sizeof (struct elf_symbol),
7907              elf_sym_name_compare);
7908       qsort (symtable2, count1, sizeof (struct elf_symbol),
7909              elf_sym_name_compare);
7910
7911       for (i = 0; i < count1; i++)
7912         /* Two symbols must have the same binding, type and name.  */
7913         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7914             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7915             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7916           goto done;
7917
7918       result = TRUE;
7919       goto done;
7920     }
7921
7922   symtable1 = (struct elf_symbol *)
7923       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7924   symtable2 = (struct elf_symbol *)
7925       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7926   if (symtable1 == NULL || symtable2 == NULL)
7927     goto done;
7928
7929   /* Count definitions in the section.  */
7930   count1 = 0;
7931   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7932     if (isym->st_shndx == shndx1)
7933       symtable1[count1++].u.isym = isym;
7934
7935   count2 = 0;
7936   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7937     if (isym->st_shndx == shndx2)
7938       symtable2[count2++].u.isym = isym;
7939
7940   if (count1 == 0 || count2 == 0 || count1 != count2)
7941     goto done;
7942
7943   for (i = 0; i < count1; i++)
7944     symtable1[i].name
7945       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7946                                          symtable1[i].u.isym->st_name);
7947
7948   for (i = 0; i < count2; i++)
7949     symtable2[i].name
7950       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7951                                          symtable2[i].u.isym->st_name);
7952
7953   /* Sort symbol by name.  */
7954   qsort (symtable1, count1, sizeof (struct elf_symbol),
7955          elf_sym_name_compare);
7956   qsort (symtable2, count1, sizeof (struct elf_symbol),
7957          elf_sym_name_compare);
7958
7959   for (i = 0; i < count1; i++)
7960     /* Two symbols must have the same binding, type and name.  */
7961     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7962         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7963         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7964       goto done;
7965
7966   result = TRUE;
7967
7968 done:
7969   if (symtable1)
7970     free (symtable1);
7971   if (symtable2)
7972     free (symtable2);
7973   if (isymbuf1)
7974     free (isymbuf1);
7975   if (isymbuf2)
7976     free (isymbuf2);
7977
7978   return result;
7979 }
7980
7981 /* Return TRUE if 2 section types are compatible.  */
7982
7983 bfd_boolean
7984 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7985                                  bfd *bbfd, const asection *bsec)
7986 {
7987   if (asec == NULL
7988       || bsec == NULL
7989       || abfd->xvec->flavour != bfd_target_elf_flavour
7990       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7991     return TRUE;
7992
7993   return elf_section_type (asec) == elf_section_type (bsec);
7994 }
7995 \f
7996 /* Final phase of ELF linker.  */
7997
7998 /* A structure we use to avoid passing large numbers of arguments.  */
7999
8000 struct elf_final_link_info
8001 {
8002   /* General link information.  */
8003   struct bfd_link_info *info;
8004   /* Output BFD.  */
8005   bfd *output_bfd;
8006   /* Symbol string table.  */
8007   struct elf_strtab_hash *symstrtab;
8008   /* .hash section.  */
8009   asection *hash_sec;
8010   /* symbol version section (.gnu.version).  */
8011   asection *symver_sec;
8012   /* Buffer large enough to hold contents of any section.  */
8013   bfd_byte *contents;
8014   /* Buffer large enough to hold external relocs of any section.  */
8015   void *external_relocs;
8016   /* Buffer large enough to hold internal relocs of any section.  */
8017   Elf_Internal_Rela *internal_relocs;
8018   /* Buffer large enough to hold external local symbols of any input
8019      BFD.  */
8020   bfd_byte *external_syms;
8021   /* And a buffer for symbol section indices.  */
8022   Elf_External_Sym_Shndx *locsym_shndx;
8023   /* Buffer large enough to hold internal local symbols of any input
8024      BFD.  */
8025   Elf_Internal_Sym *internal_syms;
8026   /* Array large enough to hold a symbol index for each local symbol
8027      of any input BFD.  */
8028   long *indices;
8029   /* Array large enough to hold a section pointer for each local
8030      symbol of any input BFD.  */
8031   asection **sections;
8032   /* Buffer for SHT_SYMTAB_SHNDX section.  */
8033   Elf_External_Sym_Shndx *symshndxbuf;
8034   /* Number of STT_FILE syms seen.  */
8035   size_t filesym_count;
8036 };
8037
8038 /* This struct is used to pass information to elf_link_output_extsym.  */
8039
8040 struct elf_outext_info
8041 {
8042   bfd_boolean failed;
8043   bfd_boolean localsyms;
8044   bfd_boolean file_sym_done;
8045   struct elf_final_link_info *flinfo;
8046 };
8047
8048
8049 /* Support for evaluating a complex relocation.
8050
8051    Complex relocations are generalized, self-describing relocations.  The
8052    implementation of them consists of two parts: complex symbols, and the
8053    relocations themselves.
8054
8055    The relocations are use a reserved elf-wide relocation type code (R_RELC
8056    external / BFD_RELOC_RELC internal) and an encoding of relocation field
8057    information (start bit, end bit, word width, etc) into the addend.  This
8058    information is extracted from CGEN-generated operand tables within gas.
8059
8060    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
8061    internal) representing prefix-notation expressions, including but not
8062    limited to those sorts of expressions normally encoded as addends in the
8063    addend field.  The symbol mangling format is:
8064
8065    <node> := <literal>
8066           |  <unary-operator> ':' <node>
8067           |  <binary-operator> ':' <node> ':' <node>
8068           ;
8069
8070    <literal> := 's' <digits=N> ':' <N character symbol name>
8071              |  'S' <digits=N> ':' <N character section name>
8072              |  '#' <hexdigits>
8073              ;
8074
8075    <binary-operator> := as in C
8076    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
8077
8078 static void
8079 set_symbol_value (bfd *bfd_with_globals,
8080                   Elf_Internal_Sym *isymbuf,
8081                   size_t locsymcount,
8082                   size_t symidx,
8083                   bfd_vma val)
8084 {
8085   struct elf_link_hash_entry **sym_hashes;
8086   struct elf_link_hash_entry *h;
8087   size_t extsymoff = locsymcount;
8088
8089   if (symidx < locsymcount)
8090     {
8091       Elf_Internal_Sym *sym;
8092
8093       sym = isymbuf + symidx;
8094       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
8095         {
8096           /* It is a local symbol: move it to the
8097              "absolute" section and give it a value.  */
8098           sym->st_shndx = SHN_ABS;
8099           sym->st_value = val;
8100           return;
8101         }
8102       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
8103       extsymoff = 0;
8104     }
8105
8106   /* It is a global symbol: set its link type
8107      to "defined" and give it a value.  */
8108
8109   sym_hashes = elf_sym_hashes (bfd_with_globals);
8110   h = sym_hashes [symidx - extsymoff];
8111   while (h->root.type == bfd_link_hash_indirect
8112          || h->root.type == bfd_link_hash_warning)
8113     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8114   h->root.type = bfd_link_hash_defined;
8115   h->root.u.def.value = val;
8116   h->root.u.def.section = bfd_abs_section_ptr;
8117 }
8118
8119 static bfd_boolean
8120 resolve_symbol (const char *name,
8121                 bfd *input_bfd,
8122                 struct elf_final_link_info *flinfo,
8123                 bfd_vma *result,
8124                 Elf_Internal_Sym *isymbuf,
8125                 size_t locsymcount)
8126 {
8127   Elf_Internal_Sym *sym;
8128   struct bfd_link_hash_entry *global_entry;
8129   const char *candidate = NULL;
8130   Elf_Internal_Shdr *symtab_hdr;
8131   size_t i;
8132
8133   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
8134
8135   for (i = 0; i < locsymcount; ++ i)
8136     {
8137       sym = isymbuf + i;
8138
8139       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
8140         continue;
8141
8142       candidate = bfd_elf_string_from_elf_section (input_bfd,
8143                                                    symtab_hdr->sh_link,
8144                                                    sym->st_name);
8145 #ifdef DEBUG
8146       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
8147               name, candidate, (unsigned long) sym->st_value);
8148 #endif
8149       if (candidate && strcmp (candidate, name) == 0)
8150         {
8151           asection *sec = flinfo->sections [i];
8152
8153           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
8154           *result += sec->output_offset + sec->output_section->vma;
8155 #ifdef DEBUG
8156           printf ("Found symbol with value %8.8lx\n",
8157                   (unsigned long) *result);
8158 #endif
8159           return TRUE;
8160         }
8161     }
8162
8163   /* Hmm, haven't found it yet. perhaps it is a global.  */
8164   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
8165                                        FALSE, FALSE, TRUE);
8166   if (!global_entry)
8167     return FALSE;
8168
8169   if (global_entry->type == bfd_link_hash_defined
8170       || global_entry->type == bfd_link_hash_defweak)
8171     {
8172       *result = (global_entry->u.def.value
8173                  + global_entry->u.def.section->output_section->vma
8174                  + global_entry->u.def.section->output_offset);
8175 #ifdef DEBUG
8176       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
8177               global_entry->root.string, (unsigned long) *result);
8178 #endif
8179       return TRUE;
8180     }
8181
8182   return FALSE;
8183 }
8184
8185 /* Looks up NAME in SECTIONS.  If found sets RESULT to NAME's address (in
8186    bytes) and returns TRUE, otherwise returns FALSE.  Accepts pseudo-section
8187    names like "foo.end" which is the end address of section "foo".  */
8188
8189 static bfd_boolean
8190 resolve_section (const char *name,
8191                  asection *sections,
8192                  bfd_vma *result,
8193                  bfd * abfd)
8194 {
8195   asection *curr;
8196   unsigned int len;
8197
8198   for (curr = sections; curr; curr = curr->next)
8199     if (strcmp (curr->name, name) == 0)
8200       {
8201         *result = curr->vma;
8202         return TRUE;
8203       }
8204
8205   /* Hmm. still haven't found it. try pseudo-section names.  */
8206   /* FIXME: This could be coded more efficiently...  */
8207   for (curr = sections; curr; curr = curr->next)
8208     {
8209       len = strlen (curr->name);
8210       if (len > strlen (name))
8211         continue;
8212
8213       if (strncmp (curr->name, name, len) == 0)
8214         {
8215           if (strncmp (".end", name + len, 4) == 0)
8216             {
8217               *result = curr->vma + curr->size / bfd_octets_per_byte (abfd);
8218               return TRUE;
8219             }
8220
8221           /* Insert more pseudo-section names here, if you like.  */
8222         }
8223     }
8224
8225   return FALSE;
8226 }
8227
8228 static void
8229 undefined_reference (const char *reftype, const char *name)
8230 {
8231   /* xgettext:c-format */
8232   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
8233                       reftype, name);
8234 }
8235
8236 static bfd_boolean
8237 eval_symbol (bfd_vma *result,
8238              const char **symp,
8239              bfd *input_bfd,
8240              struct elf_final_link_info *flinfo,
8241              bfd_vma dot,
8242              Elf_Internal_Sym *isymbuf,
8243              size_t locsymcount,
8244              int signed_p)
8245 {
8246   size_t len;
8247   size_t symlen;
8248   bfd_vma a;
8249   bfd_vma b;
8250   char symbuf[4096];
8251   const char *sym = *symp;
8252   const char *symend;
8253   bfd_boolean symbol_is_section = FALSE;
8254
8255   len = strlen (sym);
8256   symend = sym + len;
8257
8258   if (len < 1 || len > sizeof (symbuf))
8259     {
8260       bfd_set_error (bfd_error_invalid_operation);
8261       return FALSE;
8262     }
8263
8264   switch (* sym)
8265     {
8266     case '.':
8267       *result = dot;
8268       *symp = sym + 1;
8269       return TRUE;
8270
8271     case '#':
8272       ++sym;
8273       *result = strtoul (sym, (char **) symp, 16);
8274       return TRUE;
8275
8276     case 'S':
8277       symbol_is_section = TRUE;
8278       /* Fall through.  */
8279     case 's':
8280       ++sym;
8281       symlen = strtol (sym, (char **) symp, 10);
8282       sym = *symp + 1; /* Skip the trailing ':'.  */
8283
8284       if (symend < sym || symlen + 1 > sizeof (symbuf))
8285         {
8286           bfd_set_error (bfd_error_invalid_operation);
8287           return FALSE;
8288         }
8289
8290       memcpy (symbuf, sym, symlen);
8291       symbuf[symlen] = '\0';
8292       *symp = sym + symlen;
8293
8294       /* Is it always possible, with complex symbols, that gas "mis-guessed"
8295          the symbol as a section, or vice-versa. so we're pretty liberal in our
8296          interpretation here; section means "try section first", not "must be a
8297          section", and likewise with symbol.  */
8298
8299       if (symbol_is_section)
8300         {
8301           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result, input_bfd)
8302               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
8303                                   isymbuf, locsymcount))
8304             {
8305               undefined_reference ("section", symbuf);
8306               return FALSE;
8307             }
8308         }
8309       else
8310         {
8311           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
8312                                isymbuf, locsymcount)
8313               && !resolve_section (symbuf, flinfo->output_bfd->sections,
8314                                    result, input_bfd))
8315             {
8316               undefined_reference ("symbol", symbuf);
8317               return FALSE;
8318             }
8319         }
8320
8321       return TRUE;
8322
8323       /* All that remains are operators.  */
8324
8325 #define UNARY_OP(op)                                            \
8326   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8327     {                                                           \
8328       sym += strlen (#op);                                      \
8329       if (*sym == ':')                                          \
8330         ++sym;                                                  \
8331       *symp = sym;                                              \
8332       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8333                         isymbuf, locsymcount, signed_p))        \
8334         return FALSE;                                           \
8335       if (signed_p)                                             \
8336         *result = op ((bfd_signed_vma) a);                      \
8337       else                                                      \
8338         *result = op a;                                         \
8339       return TRUE;                                              \
8340     }
8341
8342 #define BINARY_OP(op)                                           \
8343   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8344     {                                                           \
8345       sym += strlen (#op);                                      \
8346       if (*sym == ':')                                          \
8347         ++sym;                                                  \
8348       *symp = sym;                                              \
8349       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8350                         isymbuf, locsymcount, signed_p))        \
8351         return FALSE;                                           \
8352       ++*symp;                                                  \
8353       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
8354                         isymbuf, locsymcount, signed_p))        \
8355         return FALSE;                                           \
8356       if (signed_p)                                             \
8357         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
8358       else                                                      \
8359         *result = a op b;                                       \
8360       return TRUE;                                              \
8361     }
8362
8363     default:
8364       UNARY_OP  (0-);
8365       BINARY_OP (<<);
8366       BINARY_OP (>>);
8367       BINARY_OP (==);
8368       BINARY_OP (!=);
8369       BINARY_OP (<=);
8370       BINARY_OP (>=);
8371       BINARY_OP (&&);
8372       BINARY_OP (||);
8373       UNARY_OP  (~);
8374       UNARY_OP  (!);
8375       BINARY_OP (*);
8376       BINARY_OP (/);
8377       BINARY_OP (%);
8378       BINARY_OP (^);
8379       BINARY_OP (|);
8380       BINARY_OP (&);
8381       BINARY_OP (+);
8382       BINARY_OP (-);
8383       BINARY_OP (<);
8384       BINARY_OP (>);
8385 #undef UNARY_OP
8386 #undef BINARY_OP
8387       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
8388       bfd_set_error (bfd_error_invalid_operation);
8389       return FALSE;
8390     }
8391 }
8392
8393 static void
8394 put_value (bfd_vma size,
8395            unsigned long chunksz,
8396            bfd *input_bfd,
8397            bfd_vma x,
8398            bfd_byte *location)
8399 {
8400   location += (size - chunksz);
8401
8402   for (; size; size -= chunksz, location -= chunksz)
8403     {
8404       switch (chunksz)
8405         {
8406         case 1:
8407           bfd_put_8 (input_bfd, x, location);
8408           x >>= 8;
8409           break;
8410         case 2:
8411           bfd_put_16 (input_bfd, x, location);
8412           x >>= 16;
8413           break;
8414         case 4:
8415           bfd_put_32 (input_bfd, x, location);
8416           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
8417           x >>= 16;
8418           x >>= 16;
8419           break;
8420 #ifdef BFD64
8421         case 8:
8422           bfd_put_64 (input_bfd, x, location);
8423           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
8424           x >>= 32;
8425           x >>= 32;
8426           break;
8427 #endif
8428         default:
8429           abort ();
8430           break;
8431         }
8432     }
8433 }
8434
8435 static bfd_vma
8436 get_value (bfd_vma size,
8437            unsigned long chunksz,
8438            bfd *input_bfd,
8439            bfd_byte *location)
8440 {
8441   int shift;
8442   bfd_vma x = 0;
8443
8444   /* Sanity checks.  */
8445   BFD_ASSERT (chunksz <= sizeof (x)
8446               && size >= chunksz
8447               && chunksz != 0
8448               && (size % chunksz) == 0
8449               && input_bfd != NULL
8450               && location != NULL);
8451
8452   if (chunksz == sizeof (x))
8453     {
8454       BFD_ASSERT (size == chunksz);
8455
8456       /* Make sure that we do not perform an undefined shift operation.
8457          We know that size == chunksz so there will only be one iteration
8458          of the loop below.  */
8459       shift = 0;
8460     }
8461   else
8462     shift = 8 * chunksz;
8463
8464   for (; size; size -= chunksz, location += chunksz)
8465     {
8466       switch (chunksz)
8467         {
8468         case 1:
8469           x = (x << shift) | bfd_get_8 (input_bfd, location);
8470           break;
8471         case 2:
8472           x = (x << shift) | bfd_get_16 (input_bfd, location);
8473           break;
8474         case 4:
8475           x = (x << shift) | bfd_get_32 (input_bfd, location);
8476           break;
8477 #ifdef BFD64
8478         case 8:
8479           x = (x << shift) | bfd_get_64 (input_bfd, location);
8480           break;
8481 #endif
8482         default:
8483           abort ();
8484         }
8485     }
8486   return x;
8487 }
8488
8489 static void
8490 decode_complex_addend (unsigned long *start,   /* in bits */
8491                        unsigned long *oplen,   /* in bits */
8492                        unsigned long *len,     /* in bits */
8493                        unsigned long *wordsz,  /* in bytes */
8494                        unsigned long *chunksz, /* in bytes */
8495                        unsigned long *lsb0_p,
8496                        unsigned long *signed_p,
8497                        unsigned long *trunc_p,
8498                        unsigned long encoded)
8499 {
8500   * start     =  encoded        & 0x3F;
8501   * len       = (encoded >>  6) & 0x3F;
8502   * oplen     = (encoded >> 12) & 0x3F;
8503   * wordsz    = (encoded >> 18) & 0xF;
8504   * chunksz   = (encoded >> 22) & 0xF;
8505   * lsb0_p    = (encoded >> 27) & 1;
8506   * signed_p  = (encoded >> 28) & 1;
8507   * trunc_p   = (encoded >> 29) & 1;
8508 }
8509
8510 bfd_reloc_status_type
8511 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8512                                     asection *input_section ATTRIBUTE_UNUSED,
8513                                     bfd_byte *contents,
8514                                     Elf_Internal_Rela *rel,
8515                                     bfd_vma relocation)
8516 {
8517   bfd_vma shift, x, mask;
8518   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8519   bfd_reloc_status_type r;
8520
8521   /*  Perform this reloc, since it is complex.
8522       (this is not to say that it necessarily refers to a complex
8523       symbol; merely that it is a self-describing CGEN based reloc.
8524       i.e. the addend has the complete reloc information (bit start, end,
8525       word size, etc) encoded within it.).  */
8526
8527   decode_complex_addend (&start, &oplen, &len, &wordsz,
8528                          &chunksz, &lsb0_p, &signed_p,
8529                          &trunc_p, rel->r_addend);
8530
8531   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8532
8533   if (lsb0_p)
8534     shift = (start + 1) - len;
8535   else
8536     shift = (8 * wordsz) - (start + len);
8537
8538   x = get_value (wordsz, chunksz, input_bfd,
8539                  contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8540
8541 #ifdef DEBUG
8542   printf ("Doing complex reloc: "
8543           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8544           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8545           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8546           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8547           oplen, (unsigned long) x, (unsigned long) mask,
8548           (unsigned long) relocation);
8549 #endif
8550
8551   r = bfd_reloc_ok;
8552   if (! trunc_p)
8553     /* Now do an overflow check.  */
8554     r = bfd_check_overflow ((signed_p
8555                              ? complain_overflow_signed
8556                              : complain_overflow_unsigned),
8557                             len, 0, (8 * wordsz),
8558                             relocation);
8559
8560   /* Do the deed.  */
8561   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8562
8563 #ifdef DEBUG
8564   printf ("           relocation: %8.8lx\n"
8565           "         shifted mask: %8.8lx\n"
8566           " shifted/masked reloc: %8.8lx\n"
8567           "               result: %8.8lx\n",
8568           (unsigned long) relocation, (unsigned long) (mask << shift),
8569           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8570 #endif
8571   put_value (wordsz, chunksz, input_bfd, x,
8572              contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8573   return r;
8574 }
8575
8576 /* Functions to read r_offset from external (target order) reloc
8577    entry.  Faster than bfd_getl32 et al, because we let the compiler
8578    know the value is aligned.  */
8579
8580 static bfd_vma
8581 ext32l_r_offset (const void *p)
8582 {
8583   union aligned32
8584   {
8585     uint32_t v;
8586     unsigned char c[4];
8587   };
8588   const union aligned32 *a
8589     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8590
8591   uint32_t aval = (  (uint32_t) a->c[0]
8592                    | (uint32_t) a->c[1] << 8
8593                    | (uint32_t) a->c[2] << 16
8594                    | (uint32_t) a->c[3] << 24);
8595   return aval;
8596 }
8597
8598 static bfd_vma
8599 ext32b_r_offset (const void *p)
8600 {
8601   union aligned32
8602   {
8603     uint32_t v;
8604     unsigned char c[4];
8605   };
8606   const union aligned32 *a
8607     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8608
8609   uint32_t aval = (  (uint32_t) a->c[0] << 24
8610                    | (uint32_t) a->c[1] << 16
8611                    | (uint32_t) a->c[2] << 8
8612                    | (uint32_t) a->c[3]);
8613   return aval;
8614 }
8615
8616 #ifdef BFD_HOST_64_BIT
8617 static bfd_vma
8618 ext64l_r_offset (const void *p)
8619 {
8620   union aligned64
8621   {
8622     uint64_t v;
8623     unsigned char c[8];
8624   };
8625   const union aligned64 *a
8626     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8627
8628   uint64_t aval = (  (uint64_t) a->c[0]
8629                    | (uint64_t) a->c[1] << 8
8630                    | (uint64_t) a->c[2] << 16
8631                    | (uint64_t) a->c[3] << 24
8632                    | (uint64_t) a->c[4] << 32
8633                    | (uint64_t) a->c[5] << 40
8634                    | (uint64_t) a->c[6] << 48
8635                    | (uint64_t) a->c[7] << 56);
8636   return aval;
8637 }
8638
8639 static bfd_vma
8640 ext64b_r_offset (const void *p)
8641 {
8642   union aligned64
8643   {
8644     uint64_t v;
8645     unsigned char c[8];
8646   };
8647   const union aligned64 *a
8648     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8649
8650   uint64_t aval = (  (uint64_t) a->c[0] << 56
8651                    | (uint64_t) a->c[1] << 48
8652                    | (uint64_t) a->c[2] << 40
8653                    | (uint64_t) a->c[3] << 32
8654                    | (uint64_t) a->c[4] << 24
8655                    | (uint64_t) a->c[5] << 16
8656                    | (uint64_t) a->c[6] << 8
8657                    | (uint64_t) a->c[7]);
8658   return aval;
8659 }
8660 #endif
8661
8662 /* When performing a relocatable link, the input relocations are
8663    preserved.  But, if they reference global symbols, the indices
8664    referenced must be updated.  Update all the relocations found in
8665    RELDATA.  */
8666
8667 static bfd_boolean
8668 elf_link_adjust_relocs (bfd *abfd,
8669                         asection *sec,
8670                         struct bfd_elf_section_reloc_data *reldata,
8671                         bfd_boolean sort,
8672                         struct bfd_link_info *info)
8673 {
8674   unsigned int i;
8675   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8676   bfd_byte *erela;
8677   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8678   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8679   bfd_vma r_type_mask;
8680   int r_sym_shift;
8681   unsigned int count = reldata->count;
8682   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8683
8684   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8685     {
8686       swap_in = bed->s->swap_reloc_in;
8687       swap_out = bed->s->swap_reloc_out;
8688     }
8689   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8690     {
8691       swap_in = bed->s->swap_reloca_in;
8692       swap_out = bed->s->swap_reloca_out;
8693     }
8694   else
8695     abort ();
8696
8697   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8698     abort ();
8699
8700   if (bed->s->arch_size == 32)
8701     {
8702       r_type_mask = 0xff;
8703       r_sym_shift = 8;
8704     }
8705   else
8706     {
8707       r_type_mask = 0xffffffff;
8708       r_sym_shift = 32;
8709     }
8710
8711   erela = reldata->hdr->contents;
8712   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8713     {
8714       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8715       unsigned int j;
8716
8717       if (*rel_hash == NULL)
8718         continue;
8719
8720       if ((*rel_hash)->indx == -2
8721           && info->gc_sections
8722           && ! info->gc_keep_exported)
8723         {
8724           /* PR 21524: Let the user know if a symbol was removed by garbage collection.  */
8725           _bfd_error_handler (_("%pB:%pA: error: relocation references symbol %s which was removed by garbage collection"),
8726                               abfd, sec,
8727                               (*rel_hash)->root.root.string);
8728           _bfd_error_handler (_("%pB:%pA: error: try relinking with --gc-keep-exported enabled"),
8729                               abfd, sec);
8730           bfd_set_error (bfd_error_invalid_operation);
8731           return FALSE;
8732         }
8733       BFD_ASSERT ((*rel_hash)->indx >= 0);
8734
8735       (*swap_in) (abfd, erela, irela);
8736       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8737         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8738                            | (irela[j].r_info & r_type_mask));
8739       (*swap_out) (abfd, irela, erela);
8740     }
8741
8742   if (bed->elf_backend_update_relocs)
8743     (*bed->elf_backend_update_relocs) (sec, reldata);
8744
8745   if (sort && count != 0)
8746     {
8747       bfd_vma (*ext_r_off) (const void *);
8748       bfd_vma r_off;
8749       size_t elt_size;
8750       bfd_byte *base, *end, *p, *loc;
8751       bfd_byte *buf = NULL;
8752
8753       if (bed->s->arch_size == 32)
8754         {
8755           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8756             ext_r_off = ext32l_r_offset;
8757           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8758             ext_r_off = ext32b_r_offset;
8759           else
8760             abort ();
8761         }
8762       else
8763         {
8764 #ifdef BFD_HOST_64_BIT
8765           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8766             ext_r_off = ext64l_r_offset;
8767           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8768             ext_r_off = ext64b_r_offset;
8769           else
8770 #endif
8771             abort ();
8772         }
8773
8774       /*  Must use a stable sort here.  A modified insertion sort,
8775           since the relocs are mostly sorted already.  */
8776       elt_size = reldata->hdr->sh_entsize;
8777       base = reldata->hdr->contents;
8778       end = base + count * elt_size;
8779       if (elt_size > sizeof (Elf64_External_Rela))
8780         abort ();
8781
8782       /* Ensure the first element is lowest.  This acts as a sentinel,
8783          speeding the main loop below.  */
8784       r_off = (*ext_r_off) (base);
8785       for (p = loc = base; (p += elt_size) < end; )
8786         {
8787           bfd_vma r_off2 = (*ext_r_off) (p);
8788           if (r_off > r_off2)
8789             {
8790               r_off = r_off2;
8791               loc = p;
8792             }
8793         }
8794       if (loc != base)
8795         {
8796           /* Don't just swap *base and *loc as that changes the order
8797              of the original base[0] and base[1] if they happen to
8798              have the same r_offset.  */
8799           bfd_byte onebuf[sizeof (Elf64_External_Rela)];
8800           memcpy (onebuf, loc, elt_size);
8801           memmove (base + elt_size, base, loc - base);
8802           memcpy (base, onebuf, elt_size);
8803         }
8804
8805       for (p = base + elt_size; (p += elt_size) < end; )
8806         {
8807           /* base to p is sorted, *p is next to insert.  */
8808           r_off = (*ext_r_off) (p);
8809           /* Search the sorted region for location to insert.  */
8810           loc = p - elt_size;
8811           while (r_off < (*ext_r_off) (loc))
8812             loc -= elt_size;
8813           loc += elt_size;
8814           if (loc != p)
8815             {
8816               /* Chances are there is a run of relocs to insert here,
8817                  from one of more input files.  Files are not always
8818                  linked in order due to the way elf_link_input_bfd is
8819                  called.  See pr17666.  */
8820               size_t sortlen = p - loc;
8821               bfd_vma r_off2 = (*ext_r_off) (loc);
8822               size_t runlen = elt_size;
8823               size_t buf_size = 96 * 1024;
8824               while (p + runlen < end
8825                      && (sortlen <= buf_size
8826                          || runlen + elt_size <= buf_size)
8827                      && r_off2 > (*ext_r_off) (p + runlen))
8828                 runlen += elt_size;
8829               if (buf == NULL)
8830                 {
8831                   buf = bfd_malloc (buf_size);
8832                   if (buf == NULL)
8833                     return FALSE;
8834                 }
8835               if (runlen < sortlen)
8836                 {
8837                   memcpy (buf, p, runlen);
8838                   memmove (loc + runlen, loc, sortlen);
8839                   memcpy (loc, buf, runlen);
8840                 }
8841               else
8842                 {
8843                   memcpy (buf, loc, sortlen);
8844                   memmove (loc, p, runlen);
8845                   memcpy (loc + runlen, buf, sortlen);
8846                 }
8847               p += runlen - elt_size;
8848             }
8849         }
8850       /* Hashes are no longer valid.  */
8851       free (reldata->hashes);
8852       reldata->hashes = NULL;
8853       free (buf);
8854     }
8855   return TRUE;
8856 }
8857
8858 struct elf_link_sort_rela
8859 {
8860   union {
8861     bfd_vma offset;
8862     bfd_vma sym_mask;
8863   } u;
8864   enum elf_reloc_type_class type;
8865   /* We use this as an array of size int_rels_per_ext_rel.  */
8866   Elf_Internal_Rela rela[1];
8867 };
8868
8869 static int
8870 elf_link_sort_cmp1 (const void *A, const void *B)
8871 {
8872   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8873   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8874   int relativea, relativeb;
8875
8876   relativea = a->type == reloc_class_relative;
8877   relativeb = b->type == reloc_class_relative;
8878
8879   if (relativea < relativeb)
8880     return 1;
8881   if (relativea > relativeb)
8882     return -1;
8883   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8884     return -1;
8885   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8886     return 1;
8887   if (a->rela->r_offset < b->rela->r_offset)
8888     return -1;
8889   if (a->rela->r_offset > b->rela->r_offset)
8890     return 1;
8891   return 0;
8892 }
8893
8894 static int
8895 elf_link_sort_cmp2 (const void *A, const void *B)
8896 {
8897   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8898   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8899
8900   if (a->type < b->type)
8901     return -1;
8902   if (a->type > b->type)
8903     return 1;
8904   if (a->u.offset < b->u.offset)
8905     return -1;
8906   if (a->u.offset > b->u.offset)
8907     return 1;
8908   if (a->rela->r_offset < b->rela->r_offset)
8909     return -1;
8910   if (a->rela->r_offset > b->rela->r_offset)
8911     return 1;
8912   return 0;
8913 }
8914
8915 static size_t
8916 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8917 {
8918   asection *dynamic_relocs;
8919   asection *rela_dyn;
8920   asection *rel_dyn;
8921   bfd_size_type count, size;
8922   size_t i, ret, sort_elt, ext_size;
8923   bfd_byte *sort, *s_non_relative, *p;
8924   struct elf_link_sort_rela *sq;
8925   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8926   int i2e = bed->s->int_rels_per_ext_rel;
8927   unsigned int opb = bfd_octets_per_byte (abfd);
8928   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8929   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8930   struct bfd_link_order *lo;
8931   bfd_vma r_sym_mask;
8932   bfd_boolean use_rela;
8933
8934   /* Find a dynamic reloc section.  */
8935   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8936   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8937   if (rela_dyn != NULL && rela_dyn->size > 0
8938       && rel_dyn != NULL && rel_dyn->size > 0)
8939     {
8940       bfd_boolean use_rela_initialised = FALSE;
8941
8942       /* This is just here to stop gcc from complaining.
8943          Its initialization checking code is not perfect.  */
8944       use_rela = TRUE;
8945
8946       /* Both sections are present.  Examine the sizes
8947          of the indirect sections to help us choose.  */
8948       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8949         if (lo->type == bfd_indirect_link_order)
8950           {
8951             asection *o = lo->u.indirect.section;
8952
8953             if ((o->size % bed->s->sizeof_rela) == 0)
8954               {
8955                 if ((o->size % bed->s->sizeof_rel) == 0)
8956                   /* Section size is divisible by both rel and rela sizes.
8957                      It is of no help to us.  */
8958                   ;
8959                 else
8960                   {
8961                     /* Section size is only divisible by rela.  */
8962                     if (use_rela_initialised && !use_rela)
8963                       {
8964                         _bfd_error_handler (_("%pB: unable to sort relocs - "
8965                                               "they are in more than one size"),
8966                                             abfd);
8967                         bfd_set_error (bfd_error_invalid_operation);
8968                         return 0;
8969                       }
8970                     else
8971                       {
8972                         use_rela = TRUE;
8973                         use_rela_initialised = TRUE;
8974                       }
8975                   }
8976               }
8977             else if ((o->size % bed->s->sizeof_rel) == 0)
8978               {
8979                 /* Section size is only divisible by rel.  */
8980                 if (use_rela_initialised && use_rela)
8981                   {
8982                     _bfd_error_handler (_("%pB: unable to sort relocs - "
8983                                           "they are in more than one size"),
8984                                         abfd);
8985                     bfd_set_error (bfd_error_invalid_operation);
8986                     return 0;
8987                   }
8988                 else
8989                   {
8990                     use_rela = FALSE;
8991                     use_rela_initialised = TRUE;
8992                   }
8993               }
8994             else
8995               {
8996                 /* The section size is not divisible by either -
8997                    something is wrong.  */
8998                 _bfd_error_handler (_("%pB: unable to sort relocs - "
8999                                       "they are of an unknown size"), abfd);
9000                 bfd_set_error (bfd_error_invalid_operation);
9001                 return 0;
9002               }
9003           }
9004
9005       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
9006         if (lo->type == bfd_indirect_link_order)
9007           {
9008             asection *o = lo->u.indirect.section;
9009
9010             if ((o->size % bed->s->sizeof_rela) == 0)
9011               {
9012                 if ((o->size % bed->s->sizeof_rel) == 0)
9013                   /* Section size is divisible by both rel and rela sizes.
9014                      It is of no help to us.  */
9015                   ;
9016                 else
9017                   {
9018                     /* Section size is only divisible by rela.  */
9019                     if (use_rela_initialised && !use_rela)
9020                       {
9021                         _bfd_error_handler (_("%pB: unable to sort relocs - "
9022                                               "they are in more than one size"),
9023                                             abfd);
9024                         bfd_set_error (bfd_error_invalid_operation);
9025                         return 0;
9026                       }
9027                     else
9028                       {
9029                         use_rela = TRUE;
9030                         use_rela_initialised = TRUE;
9031                       }
9032                   }
9033               }
9034             else if ((o->size % bed->s->sizeof_rel) == 0)
9035               {
9036                 /* Section size is only divisible by rel.  */
9037                 if (use_rela_initialised && use_rela)
9038                   {
9039                     _bfd_error_handler (_("%pB: unable to sort relocs - "
9040                                           "they are in more than one size"),
9041                                         abfd);
9042                     bfd_set_error (bfd_error_invalid_operation);
9043                     return 0;
9044                   }
9045                 else
9046                   {
9047                     use_rela = FALSE;
9048                     use_rela_initialised = TRUE;
9049                   }
9050               }
9051             else
9052               {
9053                 /* The section size is not divisible by either -
9054                    something is wrong.  */
9055                 _bfd_error_handler (_("%pB: unable to sort relocs - "
9056                                       "they are of an unknown size"), abfd);
9057                 bfd_set_error (bfd_error_invalid_operation);
9058                 return 0;
9059               }
9060           }
9061
9062       if (! use_rela_initialised)
9063         /* Make a guess.  */
9064         use_rela = TRUE;
9065     }
9066   else if (rela_dyn != NULL && rela_dyn->size > 0)
9067     use_rela = TRUE;
9068   else if (rel_dyn != NULL && rel_dyn->size > 0)
9069     use_rela = FALSE;
9070   else
9071     return 0;
9072
9073   if (use_rela)
9074     {
9075       dynamic_relocs = rela_dyn;
9076       ext_size = bed->s->sizeof_rela;
9077       swap_in = bed->s->swap_reloca_in;
9078       swap_out = bed->s->swap_reloca_out;
9079     }
9080   else
9081     {
9082       dynamic_relocs = rel_dyn;
9083       ext_size = bed->s->sizeof_rel;
9084       swap_in = bed->s->swap_reloc_in;
9085       swap_out = bed->s->swap_reloc_out;
9086     }
9087
9088   size = 0;
9089   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9090     if (lo->type == bfd_indirect_link_order)
9091       size += lo->u.indirect.section->size;
9092
9093   if (size != dynamic_relocs->size)
9094     return 0;
9095
9096   sort_elt = (sizeof (struct elf_link_sort_rela)
9097               + (i2e - 1) * sizeof (Elf_Internal_Rela));
9098
9099   count = dynamic_relocs->size / ext_size;
9100   if (count == 0)
9101     return 0;
9102   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
9103
9104   if (sort == NULL)
9105     {
9106       (*info->callbacks->warning)
9107         (info, _("not enough memory to sort relocations"), 0, abfd, 0, 0);
9108       return 0;
9109     }
9110
9111   if (bed->s->arch_size == 32)
9112     r_sym_mask = ~(bfd_vma) 0xff;
9113   else
9114     r_sym_mask = ~(bfd_vma) 0xffffffff;
9115
9116   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9117     if (lo->type == bfd_indirect_link_order)
9118       {
9119         bfd_byte *erel, *erelend;
9120         asection *o = lo->u.indirect.section;
9121
9122         if (o->contents == NULL && o->size != 0)
9123           {
9124             /* This is a reloc section that is being handled as a normal
9125                section.  See bfd_section_from_shdr.  We can't combine
9126                relocs in this case.  */
9127             free (sort);
9128             return 0;
9129           }
9130         erel = o->contents;
9131         erelend = o->contents + o->size;
9132         p = sort + o->output_offset * opb / ext_size * sort_elt;
9133
9134         while (erel < erelend)
9135           {
9136             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9137
9138             (*swap_in) (abfd, erel, s->rela);
9139             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
9140             s->u.sym_mask = r_sym_mask;
9141             p += sort_elt;
9142             erel += ext_size;
9143           }
9144       }
9145
9146   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
9147
9148   for (i = 0, p = sort; i < count; i++, p += sort_elt)
9149     {
9150       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9151       if (s->type != reloc_class_relative)
9152         break;
9153     }
9154   ret = i;
9155   s_non_relative = p;
9156
9157   sq = (struct elf_link_sort_rela *) s_non_relative;
9158   for (; i < count; i++, p += sort_elt)
9159     {
9160       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
9161       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
9162         sq = sp;
9163       sp->u.offset = sq->rela->r_offset;
9164     }
9165
9166   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
9167
9168   struct elf_link_hash_table *htab = elf_hash_table (info);
9169   if (htab->srelplt && htab->srelplt->output_section == dynamic_relocs)
9170     {
9171       /* We have plt relocs in .rela.dyn.  */
9172       sq = (struct elf_link_sort_rela *) sort;
9173       for (i = 0; i < count; i++)
9174         if (sq[count - i - 1].type != reloc_class_plt)
9175           break;
9176       if (i != 0 && htab->srelplt->size == i * ext_size)
9177         {
9178           struct bfd_link_order **plo;
9179           /* Put srelplt link_order last.  This is so the output_offset
9180              set in the next loop is correct for DT_JMPREL.  */
9181           for (plo = &dynamic_relocs->map_head.link_order; *plo != NULL; )
9182             if ((*plo)->type == bfd_indirect_link_order
9183                 && (*plo)->u.indirect.section == htab->srelplt)
9184               {
9185                 lo = *plo;
9186                 *plo = lo->next;
9187               }
9188             else
9189               plo = &(*plo)->next;
9190           *plo = lo;
9191           lo->next = NULL;
9192           dynamic_relocs->map_tail.link_order = lo;
9193         }
9194     }
9195
9196   p = sort;
9197   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9198     if (lo->type == bfd_indirect_link_order)
9199       {
9200         bfd_byte *erel, *erelend;
9201         asection *o = lo->u.indirect.section;
9202
9203         erel = o->contents;
9204         erelend = o->contents + o->size;
9205         o->output_offset = (p - sort) / sort_elt * ext_size / opb;
9206         while (erel < erelend)
9207           {
9208             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9209             (*swap_out) (abfd, s->rela, erel);
9210             p += sort_elt;
9211             erel += ext_size;
9212           }
9213       }
9214
9215   free (sort);
9216   *psec = dynamic_relocs;
9217   return ret;
9218 }
9219
9220 /* Add a symbol to the output symbol string table.  */
9221
9222 static int
9223 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
9224                            const char *name,
9225                            Elf_Internal_Sym *elfsym,
9226                            asection *input_sec,
9227                            struct elf_link_hash_entry *h)
9228 {
9229   int (*output_symbol_hook)
9230     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
9231      struct elf_link_hash_entry *);
9232   struct elf_link_hash_table *hash_table;
9233   const struct elf_backend_data *bed;
9234   bfd_size_type strtabsize;
9235
9236   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9237
9238   bed = get_elf_backend_data (flinfo->output_bfd);
9239   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
9240   if (output_symbol_hook != NULL)
9241     {
9242       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
9243       if (ret != 1)
9244         return ret;
9245     }
9246
9247   if (name == NULL
9248       || *name == '\0'
9249       || (input_sec->flags & SEC_EXCLUDE))
9250     elfsym->st_name = (unsigned long) -1;
9251   else
9252     {
9253       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
9254          to get the final offset for st_name.  */
9255       elfsym->st_name
9256         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
9257                                                name, FALSE);
9258       if (elfsym->st_name == (unsigned long) -1)
9259         return 0;
9260     }
9261
9262   hash_table = elf_hash_table (flinfo->info);
9263   strtabsize = hash_table->strtabsize;
9264   if (strtabsize <= hash_table->strtabcount)
9265     {
9266       strtabsize += strtabsize;
9267       hash_table->strtabsize = strtabsize;
9268       strtabsize *= sizeof (*hash_table->strtab);
9269       hash_table->strtab
9270         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
9271                                                  strtabsize);
9272       if (hash_table->strtab == NULL)
9273         return 0;
9274     }
9275   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
9276   hash_table->strtab[hash_table->strtabcount].dest_index
9277     = hash_table->strtabcount;
9278   hash_table->strtab[hash_table->strtabcount].destshndx_index
9279     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
9280
9281   bfd_get_symcount (flinfo->output_bfd) += 1;
9282   hash_table->strtabcount += 1;
9283
9284   return 1;
9285 }
9286
9287 /* Swap symbols out to the symbol table and flush the output symbols to
9288    the file.  */
9289
9290 static bfd_boolean
9291 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
9292 {
9293   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
9294   bfd_size_type amt;
9295   size_t i;
9296   const struct elf_backend_data *bed;
9297   bfd_byte *symbuf;
9298   Elf_Internal_Shdr *hdr;
9299   file_ptr pos;
9300   bfd_boolean ret;
9301
9302   if (!hash_table->strtabcount)
9303     return TRUE;
9304
9305   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9306
9307   bed = get_elf_backend_data (flinfo->output_bfd);
9308
9309   amt = bed->s->sizeof_sym * hash_table->strtabcount;
9310   symbuf = (bfd_byte *) bfd_malloc (amt);
9311   if (symbuf == NULL)
9312     return FALSE;
9313
9314   if (flinfo->symshndxbuf)
9315     {
9316       amt = sizeof (Elf_External_Sym_Shndx);
9317       amt *= bfd_get_symcount (flinfo->output_bfd);
9318       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
9319       if (flinfo->symshndxbuf == NULL)
9320         {
9321           free (symbuf);
9322           return FALSE;
9323         }
9324     }
9325
9326   for (i = 0; i < hash_table->strtabcount; i++)
9327     {
9328       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
9329       if (elfsym->sym.st_name == (unsigned long) -1)
9330         elfsym->sym.st_name = 0;
9331       else
9332         elfsym->sym.st_name
9333           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
9334                                                     elfsym->sym.st_name);
9335       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
9336                                ((bfd_byte *) symbuf
9337                                 + (elfsym->dest_index
9338                                    * bed->s->sizeof_sym)),
9339                                (flinfo->symshndxbuf
9340                                 + elfsym->destshndx_index));
9341     }
9342
9343   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
9344   pos = hdr->sh_offset + hdr->sh_size;
9345   amt = hash_table->strtabcount * bed->s->sizeof_sym;
9346   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
9347       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
9348     {
9349       hdr->sh_size += amt;
9350       ret = TRUE;
9351     }
9352   else
9353     ret = FALSE;
9354
9355   free (symbuf);
9356
9357   free (hash_table->strtab);
9358   hash_table->strtab = NULL;
9359
9360   return ret;
9361 }
9362
9363 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
9364
9365 static bfd_boolean
9366 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
9367 {
9368   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
9369       && sym->st_shndx < SHN_LORESERVE)
9370     {
9371       /* The gABI doesn't support dynamic symbols in output sections
9372          beyond 64k.  */
9373       _bfd_error_handler
9374         /* xgettext:c-format */
9375         (_("%pB: too many sections: %d (>= %d)"),
9376          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
9377       bfd_set_error (bfd_error_nonrepresentable_section);
9378       return FALSE;
9379     }
9380   return TRUE;
9381 }
9382
9383 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
9384    allowing an unsatisfied unversioned symbol in the DSO to match a
9385    versioned symbol that would normally require an explicit version.
9386    We also handle the case that a DSO references a hidden symbol
9387    which may be satisfied by a versioned symbol in another DSO.  */
9388
9389 static bfd_boolean
9390 elf_link_check_versioned_symbol (struct bfd_link_info *info,
9391                                  const struct elf_backend_data *bed,
9392                                  struct elf_link_hash_entry *h)
9393 {
9394   bfd *abfd;
9395   struct elf_link_loaded_list *loaded;
9396
9397   if (!is_elf_hash_table (info->hash))
9398     return FALSE;
9399
9400   /* Check indirect symbol.  */
9401   while (h->root.type == bfd_link_hash_indirect)
9402     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9403
9404   switch (h->root.type)
9405     {
9406     default:
9407       abfd = NULL;
9408       break;
9409
9410     case bfd_link_hash_undefined:
9411     case bfd_link_hash_undefweak:
9412       abfd = h->root.u.undef.abfd;
9413       if (abfd == NULL
9414           || (abfd->flags & DYNAMIC) == 0
9415           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
9416         return FALSE;
9417       break;
9418
9419     case bfd_link_hash_defined:
9420     case bfd_link_hash_defweak:
9421       abfd = h->root.u.def.section->owner;
9422       break;
9423
9424     case bfd_link_hash_common:
9425       abfd = h->root.u.c.p->section->owner;
9426       break;
9427     }
9428   BFD_ASSERT (abfd != NULL);
9429
9430   for (loaded = elf_hash_table (info)->loaded;
9431        loaded != NULL;
9432        loaded = loaded->next)
9433     {
9434       bfd *input;
9435       Elf_Internal_Shdr *hdr;
9436       size_t symcount;
9437       size_t extsymcount;
9438       size_t extsymoff;
9439       Elf_Internal_Shdr *versymhdr;
9440       Elf_Internal_Sym *isym;
9441       Elf_Internal_Sym *isymend;
9442       Elf_Internal_Sym *isymbuf;
9443       Elf_External_Versym *ever;
9444       Elf_External_Versym *extversym;
9445
9446       input = loaded->abfd;
9447
9448       /* We check each DSO for a possible hidden versioned definition.  */
9449       if (input == abfd
9450           || (input->flags & DYNAMIC) == 0
9451           || elf_dynversym (input) == 0)
9452         continue;
9453
9454       hdr = &elf_tdata (input)->dynsymtab_hdr;
9455
9456       symcount = hdr->sh_size / bed->s->sizeof_sym;
9457       if (elf_bad_symtab (input))
9458         {
9459           extsymcount = symcount;
9460           extsymoff = 0;
9461         }
9462       else
9463         {
9464           extsymcount = symcount - hdr->sh_info;
9465           extsymoff = hdr->sh_info;
9466         }
9467
9468       if (extsymcount == 0)
9469         continue;
9470
9471       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
9472                                       NULL, NULL, NULL);
9473       if (isymbuf == NULL)
9474         return FALSE;
9475
9476       /* Read in any version definitions.  */
9477       versymhdr = &elf_tdata (input)->dynversym_hdr;
9478       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
9479       if (extversym == NULL)
9480         goto error_ret;
9481
9482       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
9483           || (bfd_bread (extversym, versymhdr->sh_size, input)
9484               != versymhdr->sh_size))
9485         {
9486           free (extversym);
9487         error_ret:
9488           free (isymbuf);
9489           return FALSE;
9490         }
9491
9492       ever = extversym + extsymoff;
9493       isymend = isymbuf + extsymcount;
9494       for (isym = isymbuf; isym < isymend; isym++, ever++)
9495         {
9496           const char *name;
9497           Elf_Internal_Versym iver;
9498           unsigned short version_index;
9499
9500           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
9501               || isym->st_shndx == SHN_UNDEF)
9502             continue;
9503
9504           name = bfd_elf_string_from_elf_section (input,
9505                                                   hdr->sh_link,
9506                                                   isym->st_name);
9507           if (strcmp (name, h->root.root.string) != 0)
9508             continue;
9509
9510           _bfd_elf_swap_versym_in (input, ever, &iver);
9511
9512           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
9513               && !(h->def_regular
9514                    && h->forced_local))
9515             {
9516               /* If we have a non-hidden versioned sym, then it should
9517                  have provided a definition for the undefined sym unless
9518                  it is defined in a non-shared object and forced local.
9519                */
9520               abort ();
9521             }
9522
9523           version_index = iver.vs_vers & VERSYM_VERSION;
9524           if (version_index == 1 || version_index == 2)
9525             {
9526               /* This is the base or first version.  We can use it.  */
9527               free (extversym);
9528               free (isymbuf);
9529               return TRUE;
9530             }
9531         }
9532
9533       free (extversym);
9534       free (isymbuf);
9535     }
9536
9537   return FALSE;
9538 }
9539
9540 /* Convert ELF common symbol TYPE.  */
9541
9542 static int
9543 elf_link_convert_common_type (struct bfd_link_info *info, int type)
9544 {
9545   /* Commom symbol can only appear in relocatable link.  */
9546   if (!bfd_link_relocatable (info))
9547     abort ();
9548   switch (info->elf_stt_common)
9549     {
9550     case unchanged:
9551       break;
9552     case elf_stt_common:
9553       type = STT_COMMON;
9554       break;
9555     case no_elf_stt_common:
9556       type = STT_OBJECT;
9557       break;
9558     }
9559   return type;
9560 }
9561
9562 /* Add an external symbol to the symbol table.  This is called from
9563    the hash table traversal routine.  When generating a shared object,
9564    we go through the symbol table twice.  The first time we output
9565    anything that might have been forced to local scope in a version
9566    script.  The second time we output the symbols that are still
9567    global symbols.  */
9568
9569 static bfd_boolean
9570 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
9571 {
9572   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
9573   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
9574   struct elf_final_link_info *flinfo = eoinfo->flinfo;
9575   bfd_boolean strip;
9576   Elf_Internal_Sym sym;
9577   asection *input_sec;
9578   const struct elf_backend_data *bed;
9579   long indx;
9580   int ret;
9581   unsigned int type;
9582
9583   if (h->root.type == bfd_link_hash_warning)
9584     {
9585       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9586       if (h->root.type == bfd_link_hash_new)
9587         return TRUE;
9588     }
9589
9590   /* Decide whether to output this symbol in this pass.  */
9591   if (eoinfo->localsyms)
9592     {
9593       if (!h->forced_local)
9594         return TRUE;
9595     }
9596   else
9597     {
9598       if (h->forced_local)
9599         return TRUE;
9600     }
9601
9602   bed = get_elf_backend_data (flinfo->output_bfd);
9603
9604   if (h->root.type == bfd_link_hash_undefined)
9605     {
9606       /* If we have an undefined symbol reference here then it must have
9607          come from a shared library that is being linked in.  (Undefined
9608          references in regular files have already been handled unless
9609          they are in unreferenced sections which are removed by garbage
9610          collection).  */
9611       bfd_boolean ignore_undef = FALSE;
9612
9613       /* Some symbols may be special in that the fact that they're
9614          undefined can be safely ignored - let backend determine that.  */
9615       if (bed->elf_backend_ignore_undef_symbol)
9616         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9617
9618       /* If we are reporting errors for this situation then do so now.  */
9619       if (!ignore_undef
9620           && h->ref_dynamic
9621           && (!h->ref_regular || flinfo->info->gc_sections)
9622           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9623           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9624         (*flinfo->info->callbacks->undefined_symbol)
9625           (flinfo->info, h->root.root.string,
9626            h->ref_regular ? NULL : h->root.u.undef.abfd,
9627            NULL, 0,
9628            flinfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR);
9629
9630       /* Strip a global symbol defined in a discarded section.  */
9631       if (h->indx == -3)
9632         return TRUE;
9633     }
9634
9635   /* We should also warn if a forced local symbol is referenced from
9636      shared libraries.  */
9637   if (bfd_link_executable (flinfo->info)
9638       && h->forced_local
9639       && h->ref_dynamic
9640       && h->def_regular
9641       && !h->dynamic_def
9642       && h->ref_dynamic_nonweak
9643       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9644     {
9645       bfd *def_bfd;
9646       const char *msg;
9647       struct elf_link_hash_entry *hi = h;
9648
9649       /* Check indirect symbol.  */
9650       while (hi->root.type == bfd_link_hash_indirect)
9651         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9652
9653       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9654         /* xgettext:c-format */
9655         msg = _("%pB: internal symbol `%s' in %pB is referenced by DSO");
9656       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9657         /* xgettext:c-format */
9658         msg = _("%pB: hidden symbol `%s' in %pB is referenced by DSO");
9659       else
9660         /* xgettext:c-format */
9661         msg = _("%pB: local symbol `%s' in %pB is referenced by DSO");
9662       def_bfd = flinfo->output_bfd;
9663       if (hi->root.u.def.section != bfd_abs_section_ptr)
9664         def_bfd = hi->root.u.def.section->owner;
9665       _bfd_error_handler (msg, flinfo->output_bfd,
9666                           h->root.root.string, def_bfd);
9667       bfd_set_error (bfd_error_bad_value);
9668       eoinfo->failed = TRUE;
9669       return FALSE;
9670     }
9671
9672   /* We don't want to output symbols that have never been mentioned by
9673      a regular file, or that we have been told to strip.  However, if
9674      h->indx is set to -2, the symbol is used by a reloc and we must
9675      output it.  */
9676   strip = FALSE;
9677   if (h->indx == -2)
9678     ;
9679   else if ((h->def_dynamic
9680             || h->ref_dynamic
9681             || h->root.type == bfd_link_hash_new)
9682            && !h->def_regular
9683            && !h->ref_regular)
9684     strip = TRUE;
9685   else if (flinfo->info->strip == strip_all)
9686     strip = TRUE;
9687   else if (flinfo->info->strip == strip_some
9688            && bfd_hash_lookup (flinfo->info->keep_hash,
9689                                h->root.root.string, FALSE, FALSE) == NULL)
9690     strip = TRUE;
9691   else if ((h->root.type == bfd_link_hash_defined
9692             || h->root.type == bfd_link_hash_defweak)
9693            && ((flinfo->info->strip_discarded
9694                 && discarded_section (h->root.u.def.section))
9695                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9696                    && h->root.u.def.section->owner != NULL
9697                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9698     strip = TRUE;
9699   else if ((h->root.type == bfd_link_hash_undefined
9700             || h->root.type == bfd_link_hash_undefweak)
9701            && h->root.u.undef.abfd != NULL
9702            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9703     strip = TRUE;
9704
9705   type = h->type;
9706
9707   /* If we're stripping it, and it's not a dynamic symbol, there's
9708      nothing else to do.   However, if it is a forced local symbol or
9709      an ifunc symbol we need to give the backend finish_dynamic_symbol
9710      function a chance to make it dynamic.  */
9711   if (strip
9712       && h->dynindx == -1
9713       && type != STT_GNU_IFUNC
9714       && !h->forced_local)
9715     return TRUE;
9716
9717   sym.st_value = 0;
9718   sym.st_size = h->size;
9719   sym.st_other = h->other;
9720   switch (h->root.type)
9721     {
9722     default:
9723     case bfd_link_hash_new:
9724     case bfd_link_hash_warning:
9725       abort ();
9726       return FALSE;
9727
9728     case bfd_link_hash_undefined:
9729     case bfd_link_hash_undefweak:
9730       input_sec = bfd_und_section_ptr;
9731       sym.st_shndx = SHN_UNDEF;
9732       break;
9733
9734     case bfd_link_hash_defined:
9735     case bfd_link_hash_defweak:
9736       {
9737         input_sec = h->root.u.def.section;
9738         if (input_sec->output_section != NULL)
9739           {
9740             sym.st_shndx =
9741               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9742                                                  input_sec->output_section);
9743             if (sym.st_shndx == SHN_BAD)
9744               {
9745                 _bfd_error_handler
9746                   /* xgettext:c-format */
9747                   (_("%pB: could not find output section %pA for input section %pA"),
9748                    flinfo->output_bfd, input_sec->output_section, input_sec);
9749                 bfd_set_error (bfd_error_nonrepresentable_section);
9750                 eoinfo->failed = TRUE;
9751                 return FALSE;
9752               }
9753
9754             /* ELF symbols in relocatable files are section relative,
9755                but in nonrelocatable files they are virtual
9756                addresses.  */
9757             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9758             if (!bfd_link_relocatable (flinfo->info))
9759               {
9760                 sym.st_value += input_sec->output_section->vma;
9761                 if (h->type == STT_TLS)
9762                   {
9763                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9764                     if (tls_sec != NULL)
9765                       sym.st_value -= tls_sec->vma;
9766                   }
9767               }
9768           }
9769         else
9770           {
9771             BFD_ASSERT (input_sec->owner == NULL
9772                         || (input_sec->owner->flags & DYNAMIC) != 0);
9773             sym.st_shndx = SHN_UNDEF;
9774             input_sec = bfd_und_section_ptr;
9775           }
9776       }
9777       break;
9778
9779     case bfd_link_hash_common:
9780       input_sec = h->root.u.c.p->section;
9781       sym.st_shndx = bed->common_section_index (input_sec);
9782       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9783       break;
9784
9785     case bfd_link_hash_indirect:
9786       /* These symbols are created by symbol versioning.  They point
9787          to the decorated version of the name.  For example, if the
9788          symbol foo@@GNU_1.2 is the default, which should be used when
9789          foo is used with no version, then we add an indirect symbol
9790          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9791          since the indirected symbol is already in the hash table.  */
9792       return TRUE;
9793     }
9794
9795   if (type == STT_COMMON || type == STT_OBJECT)
9796     switch (h->root.type)
9797       {
9798       case bfd_link_hash_common:
9799         type = elf_link_convert_common_type (flinfo->info, type);
9800         break;
9801       case bfd_link_hash_defined:
9802       case bfd_link_hash_defweak:
9803         if (bed->common_definition (&sym))
9804           type = elf_link_convert_common_type (flinfo->info, type);
9805         else
9806           type = STT_OBJECT;
9807         break;
9808       case bfd_link_hash_undefined:
9809       case bfd_link_hash_undefweak:
9810         break;
9811       default:
9812         abort ();
9813       }
9814
9815   if (h->forced_local)
9816     {
9817       sym.st_info = ELF_ST_INFO (STB_LOCAL, type);
9818       /* Turn off visibility on local symbol.  */
9819       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9820     }
9821   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9822   else if (h->unique_global && h->def_regular)
9823     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, type);
9824   else if (h->root.type == bfd_link_hash_undefweak
9825            || h->root.type == bfd_link_hash_defweak)
9826     sym.st_info = ELF_ST_INFO (STB_WEAK, type);
9827   else
9828     sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9829   sym.st_target_internal = h->target_internal;
9830
9831   /* Give the processor backend a chance to tweak the symbol value,
9832      and also to finish up anything that needs to be done for this
9833      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9834      forced local syms when non-shared is due to a historical quirk.
9835      STT_GNU_IFUNC symbol must go through PLT.  */
9836   if ((h->type == STT_GNU_IFUNC
9837        && h->def_regular
9838        && !bfd_link_relocatable (flinfo->info))
9839       || ((h->dynindx != -1
9840            || h->forced_local)
9841           && ((bfd_link_pic (flinfo->info)
9842                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9843                    || h->root.type != bfd_link_hash_undefweak))
9844               || !h->forced_local)
9845           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9846     {
9847       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9848              (flinfo->output_bfd, flinfo->info, h, &sym)))
9849         {
9850           eoinfo->failed = TRUE;
9851           return FALSE;
9852         }
9853     }
9854
9855   /* If we are marking the symbol as undefined, and there are no
9856      non-weak references to this symbol from a regular object, then
9857      mark the symbol as weak undefined; if there are non-weak
9858      references, mark the symbol as strong.  We can't do this earlier,
9859      because it might not be marked as undefined until the
9860      finish_dynamic_symbol routine gets through with it.  */
9861   if (sym.st_shndx == SHN_UNDEF
9862       && h->ref_regular
9863       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9864           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9865     {
9866       int bindtype;
9867       type = ELF_ST_TYPE (sym.st_info);
9868
9869       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9870       if (type == STT_GNU_IFUNC)
9871         type = STT_FUNC;
9872
9873       if (h->ref_regular_nonweak)
9874         bindtype = STB_GLOBAL;
9875       else
9876         bindtype = STB_WEAK;
9877       sym.st_info = ELF_ST_INFO (bindtype, type);
9878     }
9879
9880   /* If this is a symbol defined in a dynamic library, don't use the
9881      symbol size from the dynamic library.  Relinking an executable
9882      against a new library may introduce gratuitous changes in the
9883      executable's symbols if we keep the size.  */
9884   if (sym.st_shndx == SHN_UNDEF
9885       && !h->def_regular
9886       && h->def_dynamic)
9887     sym.st_size = 0;
9888
9889   /* If a non-weak symbol with non-default visibility is not defined
9890      locally, it is a fatal error.  */
9891   if (!bfd_link_relocatable (flinfo->info)
9892       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9893       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9894       && h->root.type == bfd_link_hash_undefined
9895       && !h->def_regular)
9896     {
9897       const char *msg;
9898
9899       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9900         /* xgettext:c-format */
9901         msg = _("%pB: protected symbol `%s' isn't defined");
9902       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9903         /* xgettext:c-format */
9904         msg = _("%pB: internal symbol `%s' isn't defined");
9905       else
9906         /* xgettext:c-format */
9907         msg = _("%pB: hidden symbol `%s' isn't defined");
9908       _bfd_error_handler (msg, flinfo->output_bfd, h->root.root.string);
9909       bfd_set_error (bfd_error_bad_value);
9910       eoinfo->failed = TRUE;
9911       return FALSE;
9912     }
9913
9914   /* If this symbol should be put in the .dynsym section, then put it
9915      there now.  We already know the symbol index.  We also fill in
9916      the entry in the .hash section.  */
9917   if (elf_hash_table (flinfo->info)->dynsym != NULL
9918       && h->dynindx != -1
9919       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9920     {
9921       bfd_byte *esym;
9922
9923       /* Since there is no version information in the dynamic string,
9924          if there is no version info in symbol version section, we will
9925          have a run-time problem if not linking executable, referenced
9926          by shared library, or not bound locally.  */
9927       if (h->verinfo.verdef == NULL
9928           && (!bfd_link_executable (flinfo->info)
9929               || h->ref_dynamic
9930               || !h->def_regular))
9931         {
9932           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9933
9934           if (p && p [1] != '\0')
9935             {
9936               _bfd_error_handler
9937                 /* xgettext:c-format */
9938                 (_("%pB: no symbol version section for versioned symbol `%s'"),
9939                  flinfo->output_bfd, h->root.root.string);
9940               eoinfo->failed = TRUE;
9941               return FALSE;
9942             }
9943         }
9944
9945       sym.st_name = h->dynstr_index;
9946       esym = (elf_hash_table (flinfo->info)->dynsym->contents
9947               + h->dynindx * bed->s->sizeof_sym);
9948       if (!check_dynsym (flinfo->output_bfd, &sym))
9949         {
9950           eoinfo->failed = TRUE;
9951           return FALSE;
9952         }
9953       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9954
9955       if (flinfo->hash_sec != NULL)
9956         {
9957           size_t hash_entry_size;
9958           bfd_byte *bucketpos;
9959           bfd_vma chain;
9960           size_t bucketcount;
9961           size_t bucket;
9962
9963           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9964           bucket = h->u.elf_hash_value % bucketcount;
9965
9966           hash_entry_size
9967             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9968           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9969                        + (bucket + 2) * hash_entry_size);
9970           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9971           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9972                    bucketpos);
9973           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9974                    ((bfd_byte *) flinfo->hash_sec->contents
9975                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9976         }
9977
9978       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9979         {
9980           Elf_Internal_Versym iversym;
9981           Elf_External_Versym *eversym;
9982
9983           if (!h->def_regular)
9984             {
9985               if (h->verinfo.verdef == NULL
9986                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9987                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9988                 iversym.vs_vers = 0;
9989               else
9990                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9991             }
9992           else
9993             {
9994               if (h->verinfo.vertree == NULL)
9995                 iversym.vs_vers = 1;
9996               else
9997                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9998               if (flinfo->info->create_default_symver)
9999                 iversym.vs_vers++;
10000             }
10001
10002           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
10003              defined locally.  */
10004           if (h->versioned == versioned_hidden && h->def_regular)
10005             iversym.vs_vers |= VERSYM_HIDDEN;
10006
10007           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
10008           eversym += h->dynindx;
10009           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
10010         }
10011     }
10012
10013   /* If the symbol is undefined, and we didn't output it to .dynsym,
10014      strip it from .symtab too.  Obviously we can't do this for
10015      relocatable output or when needed for --emit-relocs.  */
10016   else if (input_sec == bfd_und_section_ptr
10017            && h->indx != -2
10018            /* PR 22319 Do not strip global undefined symbols marked as being needed.  */
10019            && (h->mark != 1 || ELF_ST_BIND (sym.st_info) != STB_GLOBAL)
10020            && !bfd_link_relocatable (flinfo->info))
10021     return TRUE;
10022
10023   /* Also strip others that we couldn't earlier due to dynamic symbol
10024      processing.  */
10025   if (strip)
10026     return TRUE;
10027   if ((input_sec->flags & SEC_EXCLUDE) != 0)
10028     return TRUE;
10029
10030   /* Output a FILE symbol so that following locals are not associated
10031      with the wrong input file.  We need one for forced local symbols
10032      if we've seen more than one FILE symbol or when we have exactly
10033      one FILE symbol but global symbols are present in a file other
10034      than the one with the FILE symbol.  We also need one if linker
10035      defined symbols are present.  In practice these conditions are
10036      always met, so just emit the FILE symbol unconditionally.  */
10037   if (eoinfo->localsyms
10038       && !eoinfo->file_sym_done
10039       && eoinfo->flinfo->filesym_count != 0)
10040     {
10041       Elf_Internal_Sym fsym;
10042
10043       memset (&fsym, 0, sizeof (fsym));
10044       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10045       fsym.st_shndx = SHN_ABS;
10046       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
10047                                       bfd_und_section_ptr, NULL))
10048         return FALSE;
10049
10050       eoinfo->file_sym_done = TRUE;
10051     }
10052
10053   indx = bfd_get_symcount (flinfo->output_bfd);
10054   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
10055                                    input_sec, h);
10056   if (ret == 0)
10057     {
10058       eoinfo->failed = TRUE;
10059       return FALSE;
10060     }
10061   else if (ret == 1)
10062     h->indx = indx;
10063   else if (h->indx == -2)
10064     abort();
10065
10066   return TRUE;
10067 }
10068
10069 /* Return TRUE if special handling is done for relocs in SEC against
10070    symbols defined in discarded sections.  */
10071
10072 static bfd_boolean
10073 elf_section_ignore_discarded_relocs (asection *sec)
10074 {
10075   const struct elf_backend_data *bed;
10076
10077   switch (sec->sec_info_type)
10078     {
10079     case SEC_INFO_TYPE_STABS:
10080     case SEC_INFO_TYPE_EH_FRAME:
10081     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10082       return TRUE;
10083     default:
10084       break;
10085     }
10086
10087   bed = get_elf_backend_data (sec->owner);
10088   if (bed->elf_backend_ignore_discarded_relocs != NULL
10089       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
10090     return TRUE;
10091
10092   return FALSE;
10093 }
10094
10095 /* Return a mask saying how ld should treat relocations in SEC against
10096    symbols defined in discarded sections.  If this function returns
10097    COMPLAIN set, ld will issue a warning message.  If this function
10098    returns PRETEND set, and the discarded section was link-once and the
10099    same size as the kept link-once section, ld will pretend that the
10100    symbol was actually defined in the kept section.  Otherwise ld will
10101    zero the reloc (at least that is the intent, but some cooperation by
10102    the target dependent code is needed, particularly for REL targets).  */
10103
10104 unsigned int
10105 _bfd_elf_default_action_discarded (asection *sec)
10106 {
10107   if (sec->flags & SEC_DEBUGGING)
10108     return PRETEND;
10109
10110   if (strcmp (".eh_frame", sec->name) == 0)
10111     return 0;
10112
10113   if (strcmp (".gcc_except_table", sec->name) == 0)
10114     return 0;
10115
10116   return COMPLAIN | PRETEND;
10117 }
10118
10119 /* Find a match between a section and a member of a section group.  */
10120
10121 static asection *
10122 match_group_member (asection *sec, asection *group,
10123                     struct bfd_link_info *info)
10124 {
10125   asection *first = elf_next_in_group (group);
10126   asection *s = first;
10127
10128   while (s != NULL)
10129     {
10130       if (bfd_elf_match_symbols_in_sections (s, sec, info))
10131         return s;
10132
10133       s = elf_next_in_group (s);
10134       if (s == first)
10135         break;
10136     }
10137
10138   return NULL;
10139 }
10140
10141 /* Check if the kept section of a discarded section SEC can be used
10142    to replace it.  Return the replacement if it is OK.  Otherwise return
10143    NULL.  */
10144
10145 asection *
10146 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
10147 {
10148   asection *kept;
10149
10150   kept = sec->kept_section;
10151   if (kept != NULL)
10152     {
10153       if ((kept->flags & SEC_GROUP) != 0)
10154         kept = match_group_member (sec, kept, info);
10155       if (kept != NULL
10156           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
10157               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
10158         kept = NULL;
10159       sec->kept_section = kept;
10160     }
10161   return kept;
10162 }
10163
10164 /* Link an input file into the linker output file.  This function
10165    handles all the sections and relocations of the input file at once.
10166    This is so that we only have to read the local symbols once, and
10167    don't have to keep them in memory.  */
10168
10169 static bfd_boolean
10170 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
10171 {
10172   int (*relocate_section)
10173     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
10174      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
10175   bfd *output_bfd;
10176   Elf_Internal_Shdr *symtab_hdr;
10177   size_t locsymcount;
10178   size_t extsymoff;
10179   Elf_Internal_Sym *isymbuf;
10180   Elf_Internal_Sym *isym;
10181   Elf_Internal_Sym *isymend;
10182   long *pindex;
10183   asection **ppsection;
10184   asection *o;
10185   const struct elf_backend_data *bed;
10186   struct elf_link_hash_entry **sym_hashes;
10187   bfd_size_type address_size;
10188   bfd_vma r_type_mask;
10189   int r_sym_shift;
10190   bfd_boolean have_file_sym = FALSE;
10191
10192   output_bfd = flinfo->output_bfd;
10193   bed = get_elf_backend_data (output_bfd);
10194   relocate_section = bed->elf_backend_relocate_section;
10195
10196   /* If this is a dynamic object, we don't want to do anything here:
10197      we don't want the local symbols, and we don't want the section
10198      contents.  */
10199   if ((input_bfd->flags & DYNAMIC) != 0)
10200     return TRUE;
10201
10202   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
10203   if (elf_bad_symtab (input_bfd))
10204     {
10205       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
10206       extsymoff = 0;
10207     }
10208   else
10209     {
10210       locsymcount = symtab_hdr->sh_info;
10211       extsymoff = symtab_hdr->sh_info;
10212     }
10213
10214   /* Read the local symbols.  */
10215   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
10216   if (isymbuf == NULL && locsymcount != 0)
10217     {
10218       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
10219                                       flinfo->internal_syms,
10220                                       flinfo->external_syms,
10221                                       flinfo->locsym_shndx);
10222       if (isymbuf == NULL)
10223         return FALSE;
10224     }
10225
10226   /* Find local symbol sections and adjust values of symbols in
10227      SEC_MERGE sections.  Write out those local symbols we know are
10228      going into the output file.  */
10229   isymend = isymbuf + locsymcount;
10230   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
10231        isym < isymend;
10232        isym++, pindex++, ppsection++)
10233     {
10234       asection *isec;
10235       const char *name;
10236       Elf_Internal_Sym osym;
10237       long indx;
10238       int ret;
10239
10240       *pindex = -1;
10241
10242       if (elf_bad_symtab (input_bfd))
10243         {
10244           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
10245             {
10246               *ppsection = NULL;
10247               continue;
10248             }
10249         }
10250
10251       if (isym->st_shndx == SHN_UNDEF)
10252         isec = bfd_und_section_ptr;
10253       else if (isym->st_shndx == SHN_ABS)
10254         isec = bfd_abs_section_ptr;
10255       else if (isym->st_shndx == SHN_COMMON)
10256         isec = bfd_com_section_ptr;
10257       else
10258         {
10259           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
10260           if (isec == NULL)
10261             {
10262               /* Don't attempt to output symbols with st_shnx in the
10263                  reserved range other than SHN_ABS and SHN_COMMON.  */
10264               *ppsection = NULL;
10265               continue;
10266             }
10267           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
10268                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
10269             isym->st_value =
10270               _bfd_merged_section_offset (output_bfd, &isec,
10271                                           elf_section_data (isec)->sec_info,
10272                                           isym->st_value);
10273         }
10274
10275       *ppsection = isec;
10276
10277       /* Don't output the first, undefined, symbol.  In fact, don't
10278          output any undefined local symbol.  */
10279       if (isec == bfd_und_section_ptr)
10280         continue;
10281
10282       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
10283         {
10284           /* We never output section symbols.  Instead, we use the
10285              section symbol of the corresponding section in the output
10286              file.  */
10287           continue;
10288         }
10289
10290       /* If we are stripping all symbols, we don't want to output this
10291          one.  */
10292       if (flinfo->info->strip == strip_all)
10293         continue;
10294
10295       /* If we are discarding all local symbols, we don't want to
10296          output this one.  If we are generating a relocatable output
10297          file, then some of the local symbols may be required by
10298          relocs; we output them below as we discover that they are
10299          needed.  */
10300       if (flinfo->info->discard == discard_all)
10301         continue;
10302
10303       /* If this symbol is defined in a section which we are
10304          discarding, we don't need to keep it.  */
10305       if (isym->st_shndx != SHN_UNDEF
10306           && isym->st_shndx < SHN_LORESERVE
10307           && bfd_section_removed_from_list (output_bfd,
10308                                             isec->output_section))
10309         continue;
10310
10311       /* Get the name of the symbol.  */
10312       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
10313                                               isym->st_name);
10314       if (name == NULL)
10315         return FALSE;
10316
10317       /* See if we are discarding symbols with this name.  */
10318       if ((flinfo->info->strip == strip_some
10319            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
10320                == NULL))
10321           || (((flinfo->info->discard == discard_sec_merge
10322                 && (isec->flags & SEC_MERGE)
10323                 && !bfd_link_relocatable (flinfo->info))
10324                || flinfo->info->discard == discard_l)
10325               && bfd_is_local_label_name (input_bfd, name)))
10326         continue;
10327
10328       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
10329         {
10330           if (input_bfd->lto_output)
10331             /* -flto puts a temp file name here.  This means builds
10332                are not reproducible.  Discard the symbol.  */
10333             continue;
10334           have_file_sym = TRUE;
10335           flinfo->filesym_count += 1;
10336         }
10337       if (!have_file_sym)
10338         {
10339           /* In the absence of debug info, bfd_find_nearest_line uses
10340              FILE symbols to determine the source file for local
10341              function symbols.  Provide a FILE symbol here if input
10342              files lack such, so that their symbols won't be
10343              associated with a previous input file.  It's not the
10344              source file, but the best we can do.  */
10345           have_file_sym = TRUE;
10346           flinfo->filesym_count += 1;
10347           memset (&osym, 0, sizeof (osym));
10348           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10349           osym.st_shndx = SHN_ABS;
10350           if (!elf_link_output_symstrtab (flinfo,
10351                                           (input_bfd->lto_output ? NULL
10352                                            : input_bfd->filename),
10353                                           &osym, bfd_abs_section_ptr,
10354                                           NULL))
10355             return FALSE;
10356         }
10357
10358       osym = *isym;
10359
10360       /* Adjust the section index for the output file.  */
10361       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10362                                                          isec->output_section);
10363       if (osym.st_shndx == SHN_BAD)
10364         return FALSE;
10365
10366       /* ELF symbols in relocatable files are section relative, but
10367          in executable files they are virtual addresses.  Note that
10368          this code assumes that all ELF sections have an associated
10369          BFD section with a reasonable value for output_offset; below
10370          we assume that they also have a reasonable value for
10371          output_section.  Any special sections must be set up to meet
10372          these requirements.  */
10373       osym.st_value += isec->output_offset;
10374       if (!bfd_link_relocatable (flinfo->info))
10375         {
10376           osym.st_value += isec->output_section->vma;
10377           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
10378             {
10379               /* STT_TLS symbols are relative to PT_TLS segment base.  */
10380               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
10381               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
10382             }
10383         }
10384
10385       indx = bfd_get_symcount (output_bfd);
10386       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
10387       if (ret == 0)
10388         return FALSE;
10389       else if (ret == 1)
10390         *pindex = indx;
10391     }
10392
10393   if (bed->s->arch_size == 32)
10394     {
10395       r_type_mask = 0xff;
10396       r_sym_shift = 8;
10397       address_size = 4;
10398     }
10399   else
10400     {
10401       r_type_mask = 0xffffffff;
10402       r_sym_shift = 32;
10403       address_size = 8;
10404     }
10405
10406   /* Relocate the contents of each section.  */
10407   sym_hashes = elf_sym_hashes (input_bfd);
10408   for (o = input_bfd->sections; o != NULL; o = o->next)
10409     {
10410       bfd_byte *contents;
10411
10412       if (! o->linker_mark)
10413         {
10414           /* This section was omitted from the link.  */
10415           continue;
10416         }
10417
10418       if (!flinfo->info->resolve_section_groups
10419           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
10420         {
10421           /* Deal with the group signature symbol.  */
10422           struct bfd_elf_section_data *sec_data = elf_section_data (o);
10423           unsigned long symndx = sec_data->this_hdr.sh_info;
10424           asection *osec = o->output_section;
10425
10426           BFD_ASSERT (bfd_link_relocatable (flinfo->info));
10427           if (symndx >= locsymcount
10428               || (elf_bad_symtab (input_bfd)
10429                   && flinfo->sections[symndx] == NULL))
10430             {
10431               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
10432               while (h->root.type == bfd_link_hash_indirect
10433                      || h->root.type == bfd_link_hash_warning)
10434                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
10435               /* Arrange for symbol to be output.  */
10436               h->indx = -2;
10437               elf_section_data (osec)->this_hdr.sh_info = -2;
10438             }
10439           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
10440             {
10441               /* We'll use the output section target_index.  */
10442               asection *sec = flinfo->sections[symndx]->output_section;
10443               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
10444             }
10445           else
10446             {
10447               if (flinfo->indices[symndx] == -1)
10448                 {
10449                   /* Otherwise output the local symbol now.  */
10450                   Elf_Internal_Sym sym = isymbuf[symndx];
10451                   asection *sec = flinfo->sections[symndx]->output_section;
10452                   const char *name;
10453                   long indx;
10454                   int ret;
10455
10456                   name = bfd_elf_string_from_elf_section (input_bfd,
10457                                                           symtab_hdr->sh_link,
10458                                                           sym.st_name);
10459                   if (name == NULL)
10460                     return FALSE;
10461
10462                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10463                                                                     sec);
10464                   if (sym.st_shndx == SHN_BAD)
10465                     return FALSE;
10466
10467                   sym.st_value += o->output_offset;
10468
10469                   indx = bfd_get_symcount (output_bfd);
10470                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
10471                                                    NULL);
10472                   if (ret == 0)
10473                     return FALSE;
10474                   else if (ret == 1)
10475                     flinfo->indices[symndx] = indx;
10476                   else
10477                     abort ();
10478                 }
10479               elf_section_data (osec)->this_hdr.sh_info
10480                 = flinfo->indices[symndx];
10481             }
10482         }
10483
10484       if ((o->flags & SEC_HAS_CONTENTS) == 0
10485           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
10486         continue;
10487
10488       if ((o->flags & SEC_LINKER_CREATED) != 0)
10489         {
10490           /* Section was created by _bfd_elf_link_create_dynamic_sections
10491              or somesuch.  */
10492           continue;
10493         }
10494
10495       /* Get the contents of the section.  They have been cached by a
10496          relaxation routine.  Note that o is a section in an input
10497          file, so the contents field will not have been set by any of
10498          the routines which work on output files.  */
10499       if (elf_section_data (o)->this_hdr.contents != NULL)
10500         {
10501           contents = elf_section_data (o)->this_hdr.contents;
10502           if (bed->caches_rawsize
10503               && o->rawsize != 0
10504               && o->rawsize < o->size)
10505             {
10506               memcpy (flinfo->contents, contents, o->rawsize);
10507               contents = flinfo->contents;
10508             }
10509         }
10510       else
10511         {
10512           contents = flinfo->contents;
10513           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
10514             return FALSE;
10515         }
10516
10517       if ((o->flags & SEC_RELOC) != 0)
10518         {
10519           Elf_Internal_Rela *internal_relocs;
10520           Elf_Internal_Rela *rel, *relend;
10521           int action_discarded;
10522           int ret;
10523
10524           /* Get the swapped relocs.  */
10525           internal_relocs
10526             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
10527                                          flinfo->internal_relocs, FALSE);
10528           if (internal_relocs == NULL
10529               && o->reloc_count > 0)
10530             return FALSE;
10531
10532           /* We need to reverse-copy input .ctors/.dtors sections if
10533              they are placed in .init_array/.finit_array for output.  */
10534           if (o->size > address_size
10535               && ((strncmp (o->name, ".ctors", 6) == 0
10536                    && strcmp (o->output_section->name,
10537                               ".init_array") == 0)
10538                   || (strncmp (o->name, ".dtors", 6) == 0
10539                       && strcmp (o->output_section->name,
10540                                  ".fini_array") == 0))
10541               && (o->name[6] == 0 || o->name[6] == '.'))
10542             {
10543               if (o->size * bed->s->int_rels_per_ext_rel
10544                   != o->reloc_count * address_size)
10545                 {
10546                   _bfd_error_handler
10547                     /* xgettext:c-format */
10548                     (_("error: %pB: size of section %pA is not "
10549                        "multiple of address size"),
10550                      input_bfd, o);
10551                   bfd_set_error (bfd_error_bad_value);
10552                   return FALSE;
10553                 }
10554               o->flags |= SEC_ELF_REVERSE_COPY;
10555             }
10556
10557           action_discarded = -1;
10558           if (!elf_section_ignore_discarded_relocs (o))
10559             action_discarded = (*bed->action_discarded) (o);
10560
10561           /* Run through the relocs evaluating complex reloc symbols and
10562              looking for relocs against symbols from discarded sections
10563              or section symbols from removed link-once sections.
10564              Complain about relocs against discarded sections.  Zero
10565              relocs against removed link-once sections.  */
10566
10567           rel = internal_relocs;
10568           relend = rel + o->reloc_count;
10569           for ( ; rel < relend; rel++)
10570             {
10571               unsigned long r_symndx = rel->r_info >> r_sym_shift;
10572               unsigned int s_type;
10573               asection **ps, *sec;
10574               struct elf_link_hash_entry *h = NULL;
10575               const char *sym_name;
10576
10577               if (r_symndx == STN_UNDEF)
10578                 continue;
10579
10580               if (r_symndx >= locsymcount
10581                   || (elf_bad_symtab (input_bfd)
10582                       && flinfo->sections[r_symndx] == NULL))
10583                 {
10584                   h = sym_hashes[r_symndx - extsymoff];
10585
10586                   /* Badly formatted input files can contain relocs that
10587                      reference non-existant symbols.  Check here so that
10588                      we do not seg fault.  */
10589                   if (h == NULL)
10590                     {
10591                       _bfd_error_handler
10592                         /* xgettext:c-format */
10593                         (_("error: %pB contains a reloc (%#" PRIx64 ") for section %pA "
10594                            "that references a non-existent global symbol"),
10595                          input_bfd, (uint64_t) rel->r_info, o);
10596                       bfd_set_error (bfd_error_bad_value);
10597                       return FALSE;
10598                     }
10599
10600                   while (h->root.type == bfd_link_hash_indirect
10601                          || h->root.type == bfd_link_hash_warning)
10602                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10603
10604                   s_type = h->type;
10605
10606                   /* If a plugin symbol is referenced from a non-IR file,
10607                      mark the symbol as undefined.  Note that the
10608                      linker may attach linker created dynamic sections
10609                      to the plugin bfd.  Symbols defined in linker
10610                      created sections are not plugin symbols.  */
10611                   if ((h->root.non_ir_ref_regular
10612                        || h->root.non_ir_ref_dynamic)
10613                       && (h->root.type == bfd_link_hash_defined
10614                           || h->root.type == bfd_link_hash_defweak)
10615                       && (h->root.u.def.section->flags
10616                           & SEC_LINKER_CREATED) == 0
10617                       && h->root.u.def.section->owner != NULL
10618                       && (h->root.u.def.section->owner->flags
10619                           & BFD_PLUGIN) != 0)
10620                     {
10621                       h->root.type = bfd_link_hash_undefined;
10622                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10623                     }
10624
10625                   ps = NULL;
10626                   if (h->root.type == bfd_link_hash_defined
10627                       || h->root.type == bfd_link_hash_defweak)
10628                     ps = &h->root.u.def.section;
10629
10630                   sym_name = h->root.root.string;
10631                 }
10632               else
10633                 {
10634                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10635
10636                   s_type = ELF_ST_TYPE (sym->st_info);
10637                   ps = &flinfo->sections[r_symndx];
10638                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10639                                                sym, *ps);
10640                 }
10641
10642               if ((s_type == STT_RELC || s_type == STT_SRELC)
10643                   && !bfd_link_relocatable (flinfo->info))
10644                 {
10645                   bfd_vma val;
10646                   bfd_vma dot = (rel->r_offset
10647                                  + o->output_offset + o->output_section->vma);
10648 #ifdef DEBUG
10649                   printf ("Encountered a complex symbol!");
10650                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10651                           input_bfd->filename, o->name,
10652                           (long) (rel - internal_relocs));
10653                   printf (" symbol: idx  %8.8lx, name %s\n",
10654                           r_symndx, sym_name);
10655                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10656                           (unsigned long) rel->r_info,
10657                           (unsigned long) rel->r_offset);
10658 #endif
10659                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10660                                     isymbuf, locsymcount, s_type == STT_SRELC))
10661                     return FALSE;
10662
10663                   /* Symbol evaluated OK.  Update to absolute value.  */
10664                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10665                                     r_symndx, val);
10666                   continue;
10667                 }
10668
10669               if (action_discarded != -1 && ps != NULL)
10670                 {
10671                   /* Complain if the definition comes from a
10672                      discarded section.  */
10673                   if ((sec = *ps) != NULL && discarded_section (sec))
10674                     {
10675                       BFD_ASSERT (r_symndx != STN_UNDEF);
10676                       if (action_discarded & COMPLAIN)
10677                         (*flinfo->info->callbacks->einfo)
10678                           /* xgettext:c-format */
10679                           (_("%X`%s' referenced in section `%pA' of %pB: "
10680                              "defined in discarded section `%pA' of %pB\n"),
10681                            sym_name, o, input_bfd, sec, sec->owner);
10682
10683                       /* Try to do the best we can to support buggy old
10684                          versions of gcc.  Pretend that the symbol is
10685                          really defined in the kept linkonce section.
10686                          FIXME: This is quite broken.  Modifying the
10687                          symbol here means we will be changing all later
10688                          uses of the symbol, not just in this section.  */
10689                       if (action_discarded & PRETEND)
10690                         {
10691                           asection *kept;
10692
10693                           kept = _bfd_elf_check_kept_section (sec,
10694                                                               flinfo->info);
10695                           if (kept != NULL)
10696                             {
10697                               *ps = kept;
10698                               continue;
10699                             }
10700                         }
10701                     }
10702                 }
10703             }
10704
10705           /* Relocate the section by invoking a back end routine.
10706
10707              The back end routine is responsible for adjusting the
10708              section contents as necessary, and (if using Rela relocs
10709              and generating a relocatable output file) adjusting the
10710              reloc addend as necessary.
10711
10712              The back end routine does not have to worry about setting
10713              the reloc address or the reloc symbol index.
10714
10715              The back end routine is given a pointer to the swapped in
10716              internal symbols, and can access the hash table entries
10717              for the external symbols via elf_sym_hashes (input_bfd).
10718
10719              When generating relocatable output, the back end routine
10720              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10721              output symbol is going to be a section symbol
10722              corresponding to the output section, which will require
10723              the addend to be adjusted.  */
10724
10725           ret = (*relocate_section) (output_bfd, flinfo->info,
10726                                      input_bfd, o, contents,
10727                                      internal_relocs,
10728                                      isymbuf,
10729                                      flinfo->sections);
10730           if (!ret)
10731             return FALSE;
10732
10733           if (ret == 2
10734               || bfd_link_relocatable (flinfo->info)
10735               || flinfo->info->emitrelocations)
10736             {
10737               Elf_Internal_Rela *irela;
10738               Elf_Internal_Rela *irelaend, *irelamid;
10739               bfd_vma last_offset;
10740               struct elf_link_hash_entry **rel_hash;
10741               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10742               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10743               unsigned int next_erel;
10744               bfd_boolean rela_normal;
10745               struct bfd_elf_section_data *esdi, *esdo;
10746
10747               esdi = elf_section_data (o);
10748               esdo = elf_section_data (o->output_section);
10749               rela_normal = FALSE;
10750
10751               /* Adjust the reloc addresses and symbol indices.  */
10752
10753               irela = internal_relocs;
10754               irelaend = irela + o->reloc_count;
10755               rel_hash = esdo->rel.hashes + esdo->rel.count;
10756               /* We start processing the REL relocs, if any.  When we reach
10757                  IRELAMID in the loop, we switch to the RELA relocs.  */
10758               irelamid = irela;
10759               if (esdi->rel.hdr != NULL)
10760                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10761                              * bed->s->int_rels_per_ext_rel);
10762               rel_hash_list = rel_hash;
10763               rela_hash_list = NULL;
10764               last_offset = o->output_offset;
10765               if (!bfd_link_relocatable (flinfo->info))
10766                 last_offset += o->output_section->vma;
10767               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10768                 {
10769                   unsigned long r_symndx;
10770                   asection *sec;
10771                   Elf_Internal_Sym sym;
10772
10773                   if (next_erel == bed->s->int_rels_per_ext_rel)
10774                     {
10775                       rel_hash++;
10776                       next_erel = 0;
10777                     }
10778
10779                   if (irela == irelamid)
10780                     {
10781                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10782                       rela_hash_list = rel_hash;
10783                       rela_normal = bed->rela_normal;
10784                     }
10785
10786                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10787                                                              flinfo->info, o,
10788                                                              irela->r_offset);
10789                   if (irela->r_offset >= (bfd_vma) -2)
10790                     {
10791                       /* This is a reloc for a deleted entry or somesuch.
10792                          Turn it into an R_*_NONE reloc, at the same
10793                          offset as the last reloc.  elf_eh_frame.c and
10794                          bfd_elf_discard_info rely on reloc offsets
10795                          being ordered.  */
10796                       irela->r_offset = last_offset;
10797                       irela->r_info = 0;
10798                       irela->r_addend = 0;
10799                       continue;
10800                     }
10801
10802                   irela->r_offset += o->output_offset;
10803
10804                   /* Relocs in an executable have to be virtual addresses.  */
10805                   if (!bfd_link_relocatable (flinfo->info))
10806                     irela->r_offset += o->output_section->vma;
10807
10808                   last_offset = irela->r_offset;
10809
10810                   r_symndx = irela->r_info >> r_sym_shift;
10811                   if (r_symndx == STN_UNDEF)
10812                     continue;
10813
10814                   if (r_symndx >= locsymcount
10815                       || (elf_bad_symtab (input_bfd)
10816                           && flinfo->sections[r_symndx] == NULL))
10817                     {
10818                       struct elf_link_hash_entry *rh;
10819                       unsigned long indx;
10820
10821                       /* This is a reloc against a global symbol.  We
10822                          have not yet output all the local symbols, so
10823                          we do not know the symbol index of any global
10824                          symbol.  We set the rel_hash entry for this
10825                          reloc to point to the global hash table entry
10826                          for this symbol.  The symbol index is then
10827                          set at the end of bfd_elf_final_link.  */
10828                       indx = r_symndx - extsymoff;
10829                       rh = elf_sym_hashes (input_bfd)[indx];
10830                       while (rh->root.type == bfd_link_hash_indirect
10831                              || rh->root.type == bfd_link_hash_warning)
10832                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10833
10834                       /* Setting the index to -2 tells
10835                          elf_link_output_extsym that this symbol is
10836                          used by a reloc.  */
10837                       BFD_ASSERT (rh->indx < 0);
10838                       rh->indx = -2;
10839                       *rel_hash = rh;
10840
10841                       continue;
10842                     }
10843
10844                   /* This is a reloc against a local symbol.  */
10845
10846                   *rel_hash = NULL;
10847                   sym = isymbuf[r_symndx];
10848                   sec = flinfo->sections[r_symndx];
10849                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10850                     {
10851                       /* I suppose the backend ought to fill in the
10852                          section of any STT_SECTION symbol against a
10853                          processor specific section.  */
10854                       r_symndx = STN_UNDEF;
10855                       if (bfd_is_abs_section (sec))
10856                         ;
10857                       else if (sec == NULL || sec->owner == NULL)
10858                         {
10859                           bfd_set_error (bfd_error_bad_value);
10860                           return FALSE;
10861                         }
10862                       else
10863                         {
10864                           asection *osec = sec->output_section;
10865
10866                           /* If we have discarded a section, the output
10867                              section will be the absolute section.  In
10868                              case of discarded SEC_MERGE sections, use
10869                              the kept section.  relocate_section should
10870                              have already handled discarded linkonce
10871                              sections.  */
10872                           if (bfd_is_abs_section (osec)
10873                               && sec->kept_section != NULL
10874                               && sec->kept_section->output_section != NULL)
10875                             {
10876                               osec = sec->kept_section->output_section;
10877                               irela->r_addend -= osec->vma;
10878                             }
10879
10880                           if (!bfd_is_abs_section (osec))
10881                             {
10882                               r_symndx = osec->target_index;
10883                               if (r_symndx == STN_UNDEF)
10884                                 {
10885                                   irela->r_addend += osec->vma;
10886                                   osec = _bfd_nearby_section (output_bfd, osec,
10887                                                               osec->vma);
10888                                   irela->r_addend -= osec->vma;
10889                                   r_symndx = osec->target_index;
10890                                 }
10891                             }
10892                         }
10893
10894                       /* Adjust the addend according to where the
10895                          section winds up in the output section.  */
10896                       if (rela_normal)
10897                         irela->r_addend += sec->output_offset;
10898                     }
10899                   else
10900                     {
10901                       if (flinfo->indices[r_symndx] == -1)
10902                         {
10903                           unsigned long shlink;
10904                           const char *name;
10905                           asection *osec;
10906                           long indx;
10907
10908                           if (flinfo->info->strip == strip_all)
10909                             {
10910                               /* You can't do ld -r -s.  */
10911                               bfd_set_error (bfd_error_invalid_operation);
10912                               return FALSE;
10913                             }
10914
10915                           /* This symbol was skipped earlier, but
10916                              since it is needed by a reloc, we
10917                              must output it now.  */
10918                           shlink = symtab_hdr->sh_link;
10919                           name = (bfd_elf_string_from_elf_section
10920                                   (input_bfd, shlink, sym.st_name));
10921                           if (name == NULL)
10922                             return FALSE;
10923
10924                           osec = sec->output_section;
10925                           sym.st_shndx =
10926                             _bfd_elf_section_from_bfd_section (output_bfd,
10927                                                                osec);
10928                           if (sym.st_shndx == SHN_BAD)
10929                             return FALSE;
10930
10931                           sym.st_value += sec->output_offset;
10932                           if (!bfd_link_relocatable (flinfo->info))
10933                             {
10934                               sym.st_value += osec->vma;
10935                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10936                                 {
10937                                   /* STT_TLS symbols are relative to PT_TLS
10938                                      segment base.  */
10939                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10940                                               ->tls_sec != NULL);
10941                                   sym.st_value -= (elf_hash_table (flinfo->info)
10942                                                    ->tls_sec->vma);
10943                                 }
10944                             }
10945
10946                           indx = bfd_get_symcount (output_bfd);
10947                           ret = elf_link_output_symstrtab (flinfo, name,
10948                                                            &sym, sec,
10949                                                            NULL);
10950                           if (ret == 0)
10951                             return FALSE;
10952                           else if (ret == 1)
10953                             flinfo->indices[r_symndx] = indx;
10954                           else
10955                             abort ();
10956                         }
10957
10958                       r_symndx = flinfo->indices[r_symndx];
10959                     }
10960
10961                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10962                                    | (irela->r_info & r_type_mask));
10963                 }
10964
10965               /* Swap out the relocs.  */
10966               input_rel_hdr = esdi->rel.hdr;
10967               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10968                 {
10969                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10970                                                      input_rel_hdr,
10971                                                      internal_relocs,
10972                                                      rel_hash_list))
10973                     return FALSE;
10974                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10975                                       * bed->s->int_rels_per_ext_rel);
10976                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10977                 }
10978
10979               input_rela_hdr = esdi->rela.hdr;
10980               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10981                 {
10982                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10983                                                      input_rela_hdr,
10984                                                      internal_relocs,
10985                                                      rela_hash_list))
10986                     return FALSE;
10987                 }
10988             }
10989         }
10990
10991       /* Write out the modified section contents.  */
10992       if (bed->elf_backend_write_section
10993           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10994                                                 contents))
10995         {
10996           /* Section written out.  */
10997         }
10998       else switch (o->sec_info_type)
10999         {
11000         case SEC_INFO_TYPE_STABS:
11001           if (! (_bfd_write_section_stabs
11002                  (output_bfd,
11003                   &elf_hash_table (flinfo->info)->stab_info,
11004                   o, &elf_section_data (o)->sec_info, contents)))
11005             return FALSE;
11006           break;
11007         case SEC_INFO_TYPE_MERGE:
11008           if (! _bfd_write_merged_section (output_bfd, o,
11009                                            elf_section_data (o)->sec_info))
11010             return FALSE;
11011           break;
11012         case SEC_INFO_TYPE_EH_FRAME:
11013           {
11014             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
11015                                                    o, contents))
11016               return FALSE;
11017           }
11018           break;
11019         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
11020           {
11021             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
11022                                                          flinfo->info,
11023                                                          o, contents))
11024               return FALSE;
11025           }
11026           break;
11027         default:
11028           {
11029             if (! (o->flags & SEC_EXCLUDE))
11030               {
11031                 file_ptr offset = (file_ptr) o->output_offset;
11032                 bfd_size_type todo = o->size;
11033
11034                 offset *= bfd_octets_per_byte (output_bfd);
11035
11036                 if ((o->flags & SEC_ELF_REVERSE_COPY))
11037                   {
11038                     /* Reverse-copy input section to output.  */
11039                     do
11040                       {
11041                         todo -= address_size;
11042                         if (! bfd_set_section_contents (output_bfd,
11043                                                         o->output_section,
11044                                                         contents + todo,
11045                                                         offset,
11046                                                         address_size))
11047                           return FALSE;
11048                         if (todo == 0)
11049                           break;
11050                         offset += address_size;
11051                       }
11052                     while (1);
11053                   }
11054                 else if (! bfd_set_section_contents (output_bfd,
11055                                                      o->output_section,
11056                                                      contents,
11057                                                      offset, todo))
11058                   return FALSE;
11059               }
11060           }
11061           break;
11062         }
11063     }
11064
11065   return TRUE;
11066 }
11067
11068 /* Generate a reloc when linking an ELF file.  This is a reloc
11069    requested by the linker, and does not come from any input file.  This
11070    is used to build constructor and destructor tables when linking
11071    with -Ur.  */
11072
11073 static bfd_boolean
11074 elf_reloc_link_order (bfd *output_bfd,
11075                       struct bfd_link_info *info,
11076                       asection *output_section,
11077                       struct bfd_link_order *link_order)
11078 {
11079   reloc_howto_type *howto;
11080   long indx;
11081   bfd_vma offset;
11082   bfd_vma addend;
11083   struct bfd_elf_section_reloc_data *reldata;
11084   struct elf_link_hash_entry **rel_hash_ptr;
11085   Elf_Internal_Shdr *rel_hdr;
11086   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
11087   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
11088   bfd_byte *erel;
11089   unsigned int i;
11090   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
11091
11092   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
11093   if (howto == NULL)
11094     {
11095       bfd_set_error (bfd_error_bad_value);
11096       return FALSE;
11097     }
11098
11099   addend = link_order->u.reloc.p->addend;
11100
11101   if (esdo->rel.hdr)
11102     reldata = &esdo->rel;
11103   else if (esdo->rela.hdr)
11104     reldata = &esdo->rela;
11105   else
11106     {
11107       reldata = NULL;
11108       BFD_ASSERT (0);
11109     }
11110
11111   /* Figure out the symbol index.  */
11112   rel_hash_ptr = reldata->hashes + reldata->count;
11113   if (link_order->type == bfd_section_reloc_link_order)
11114     {
11115       indx = link_order->u.reloc.p->u.section->target_index;
11116       BFD_ASSERT (indx != 0);
11117       *rel_hash_ptr = NULL;
11118     }
11119   else
11120     {
11121       struct elf_link_hash_entry *h;
11122
11123       /* Treat a reloc against a defined symbol as though it were
11124          actually against the section.  */
11125       h = ((struct elf_link_hash_entry *)
11126            bfd_wrapped_link_hash_lookup (output_bfd, info,
11127                                          link_order->u.reloc.p->u.name,
11128                                          FALSE, FALSE, TRUE));
11129       if (h != NULL
11130           && (h->root.type == bfd_link_hash_defined
11131               || h->root.type == bfd_link_hash_defweak))
11132         {
11133           asection *section;
11134
11135           section = h->root.u.def.section;
11136           indx = section->output_section->target_index;
11137           *rel_hash_ptr = NULL;
11138           /* It seems that we ought to add the symbol value to the
11139              addend here, but in practice it has already been added
11140              because it was passed to constructor_callback.  */
11141           addend += section->output_section->vma + section->output_offset;
11142         }
11143       else if (h != NULL)
11144         {
11145           /* Setting the index to -2 tells elf_link_output_extsym that
11146              this symbol is used by a reloc.  */
11147           h->indx = -2;
11148           *rel_hash_ptr = h;
11149           indx = 0;
11150         }
11151       else
11152         {
11153           (*info->callbacks->unattached_reloc)
11154             (info, link_order->u.reloc.p->u.name, NULL, NULL, 0);
11155           indx = 0;
11156         }
11157     }
11158
11159   /* If this is an inplace reloc, we must write the addend into the
11160      object file.  */
11161   if (howto->partial_inplace && addend != 0)
11162     {
11163       bfd_size_type size;
11164       bfd_reloc_status_type rstat;
11165       bfd_byte *buf;
11166       bfd_boolean ok;
11167       const char *sym_name;
11168
11169       size = (bfd_size_type) bfd_get_reloc_size (howto);
11170       buf = (bfd_byte *) bfd_zmalloc (size);
11171       if (buf == NULL && size != 0)
11172         return FALSE;
11173       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
11174       switch (rstat)
11175         {
11176         case bfd_reloc_ok:
11177           break;
11178
11179         default:
11180         case bfd_reloc_outofrange:
11181           abort ();
11182
11183         case bfd_reloc_overflow:
11184           if (link_order->type == bfd_section_reloc_link_order)
11185             sym_name = bfd_section_name (output_bfd,
11186                                          link_order->u.reloc.p->u.section);
11187           else
11188             sym_name = link_order->u.reloc.p->u.name;
11189           (*info->callbacks->reloc_overflow) (info, NULL, sym_name,
11190                                               howto->name, addend, NULL, NULL,
11191                                               (bfd_vma) 0);
11192           break;
11193         }
11194
11195       ok = bfd_set_section_contents (output_bfd, output_section, buf,
11196                                      link_order->offset
11197                                      * bfd_octets_per_byte (output_bfd),
11198                                      size);
11199       free (buf);
11200       if (! ok)
11201         return FALSE;
11202     }
11203
11204   /* The address of a reloc is relative to the section in a
11205      relocatable file, and is a virtual address in an executable
11206      file.  */
11207   offset = link_order->offset;
11208   if (! bfd_link_relocatable (info))
11209     offset += output_section->vma;
11210
11211   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
11212     {
11213       irel[i].r_offset = offset;
11214       irel[i].r_info = 0;
11215       irel[i].r_addend = 0;
11216     }
11217   if (bed->s->arch_size == 32)
11218     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
11219   else
11220     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
11221
11222   rel_hdr = reldata->hdr;
11223   erel = rel_hdr->contents;
11224   if (rel_hdr->sh_type == SHT_REL)
11225     {
11226       erel += reldata->count * bed->s->sizeof_rel;
11227       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
11228     }
11229   else
11230     {
11231       irel[0].r_addend = addend;
11232       erel += reldata->count * bed->s->sizeof_rela;
11233       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
11234     }
11235
11236   ++reldata->count;
11237
11238   return TRUE;
11239 }
11240
11241
11242 /* Get the output vma of the section pointed to by the sh_link field.  */
11243
11244 static bfd_vma
11245 elf_get_linked_section_vma (struct bfd_link_order *p)
11246 {
11247   Elf_Internal_Shdr **elf_shdrp;
11248   asection *s;
11249   int elfsec;
11250
11251   s = p->u.indirect.section;
11252   elf_shdrp = elf_elfsections (s->owner);
11253   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
11254   elfsec = elf_shdrp[elfsec]->sh_link;
11255   /* PR 290:
11256      The Intel C compiler generates SHT_IA_64_UNWIND with
11257      SHF_LINK_ORDER.  But it doesn't set the sh_link or
11258      sh_info fields.  Hence we could get the situation
11259      where elfsec is 0.  */
11260   if (elfsec == 0)
11261     {
11262       const struct elf_backend_data *bed
11263         = get_elf_backend_data (s->owner);
11264       if (bed->link_order_error_handler)
11265         bed->link_order_error_handler
11266           /* xgettext:c-format */
11267           (_("%pB: warning: sh_link not set for section `%pA'"), s->owner, s);
11268       return 0;
11269     }
11270   else
11271     {
11272       s = elf_shdrp[elfsec]->bfd_section;
11273       return s->output_section->vma + s->output_offset;
11274     }
11275 }
11276
11277
11278 /* Compare two sections based on the locations of the sections they are
11279    linked to.  Used by elf_fixup_link_order.  */
11280
11281 static int
11282 compare_link_order (const void * a, const void * b)
11283 {
11284   bfd_vma apos;
11285   bfd_vma bpos;
11286
11287   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
11288   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
11289   if (apos < bpos)
11290     return -1;
11291   return apos > bpos;
11292 }
11293
11294
11295 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
11296    order as their linked sections.  Returns false if this could not be done
11297    because an output section includes both ordered and unordered
11298    sections.  Ideally we'd do this in the linker proper.  */
11299
11300 static bfd_boolean
11301 elf_fixup_link_order (bfd *abfd, asection *o)
11302 {
11303   int seen_linkorder;
11304   int seen_other;
11305   int n;
11306   struct bfd_link_order *p;
11307   bfd *sub;
11308   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11309   unsigned elfsec;
11310   struct bfd_link_order **sections;
11311   asection *s, *other_sec, *linkorder_sec;
11312   bfd_vma offset;
11313
11314   other_sec = NULL;
11315   linkorder_sec = NULL;
11316   seen_other = 0;
11317   seen_linkorder = 0;
11318   for (p = o->map_head.link_order; p != NULL; p = p->next)
11319     {
11320       if (p->type == bfd_indirect_link_order)
11321         {
11322           s = p->u.indirect.section;
11323           sub = s->owner;
11324           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11325               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
11326               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
11327               && elfsec < elf_numsections (sub)
11328               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
11329               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
11330             {
11331               seen_linkorder++;
11332               linkorder_sec = s;
11333             }
11334           else
11335             {
11336               seen_other++;
11337               other_sec = s;
11338             }
11339         }
11340       else
11341         seen_other++;
11342
11343       if (seen_other && seen_linkorder)
11344         {
11345           if (other_sec && linkorder_sec)
11346             _bfd_error_handler
11347               /* xgettext:c-format */
11348               (_("%pA has both ordered [`%pA' in %pB] "
11349                  "and unordered [`%pA' in %pB] sections"),
11350                o, linkorder_sec, linkorder_sec->owner,
11351                other_sec, other_sec->owner);
11352           else
11353             _bfd_error_handler
11354               (_("%pA has both ordered and unordered sections"), o);
11355           bfd_set_error (bfd_error_bad_value);
11356           return FALSE;
11357         }
11358     }
11359
11360   if (!seen_linkorder)
11361     return TRUE;
11362
11363   sections = (struct bfd_link_order **)
11364     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
11365   if (sections == NULL)
11366     return FALSE;
11367   seen_linkorder = 0;
11368
11369   for (p = o->map_head.link_order; p != NULL; p = p->next)
11370     {
11371       sections[seen_linkorder++] = p;
11372     }
11373   /* Sort the input sections in the order of their linked section.  */
11374   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
11375          compare_link_order);
11376
11377   /* Change the offsets of the sections.  */
11378   offset = 0;
11379   for (n = 0; n < seen_linkorder; n++)
11380     {
11381       s = sections[n]->u.indirect.section;
11382       offset &= ~(bfd_vma) 0 << s->alignment_power;
11383       s->output_offset = offset / bfd_octets_per_byte (abfd);
11384       sections[n]->offset = offset;
11385       offset += sections[n]->size;
11386     }
11387
11388   free (sections);
11389   return TRUE;
11390 }
11391
11392 /* Generate an import library in INFO->implib_bfd from symbols in ABFD.
11393    Returns TRUE upon success, FALSE otherwise.  */
11394
11395 static bfd_boolean
11396 elf_output_implib (bfd *abfd, struct bfd_link_info *info)
11397 {
11398   bfd_boolean ret = FALSE;
11399   bfd *implib_bfd;
11400   const struct elf_backend_data *bed;
11401   flagword flags;
11402   enum bfd_architecture arch;
11403   unsigned int mach;
11404   asymbol **sympp = NULL;
11405   long symsize;
11406   long symcount;
11407   long src_count;
11408   elf_symbol_type *osymbuf;
11409
11410   implib_bfd = info->out_implib_bfd;
11411   bed = get_elf_backend_data (abfd);
11412
11413   if (!bfd_set_format (implib_bfd, bfd_object))
11414     return FALSE;
11415
11416   /* Use flag from executable but make it a relocatable object.  */
11417   flags = bfd_get_file_flags (abfd);
11418   flags &= ~HAS_RELOC;
11419   if (!bfd_set_start_address (implib_bfd, 0)
11420       || !bfd_set_file_flags (implib_bfd, flags & ~EXEC_P))
11421     return FALSE;
11422
11423   /* Copy architecture of output file to import library file.  */
11424   arch = bfd_get_arch (abfd);
11425   mach = bfd_get_mach (abfd);
11426   if (!bfd_set_arch_mach (implib_bfd, arch, mach)
11427       && (abfd->target_defaulted
11428           || bfd_get_arch (abfd) != bfd_get_arch (implib_bfd)))
11429     return FALSE;
11430
11431   /* Get symbol table size.  */
11432   symsize = bfd_get_symtab_upper_bound (abfd);
11433   if (symsize < 0)
11434     return FALSE;
11435
11436   /* Read in the symbol table.  */
11437   sympp = (asymbol **) xmalloc (symsize);
11438   symcount = bfd_canonicalize_symtab (abfd, sympp);
11439   if (symcount < 0)
11440     goto free_sym_buf;
11441
11442   /* Allow the BFD backend to copy any private header data it
11443      understands from the output BFD to the import library BFD.  */
11444   if (! bfd_copy_private_header_data (abfd, implib_bfd))
11445     goto free_sym_buf;
11446
11447   /* Filter symbols to appear in the import library.  */
11448   if (bed->elf_backend_filter_implib_symbols)
11449     symcount = bed->elf_backend_filter_implib_symbols (abfd, info, sympp,
11450                                                        symcount);
11451   else
11452     symcount = _bfd_elf_filter_global_symbols (abfd, info, sympp, symcount);
11453   if (symcount == 0)
11454     {
11455       bfd_set_error (bfd_error_no_symbols);
11456       _bfd_error_handler (_("%pB: no symbol found for import library"),
11457                           implib_bfd);
11458       goto free_sym_buf;
11459     }
11460
11461
11462   /* Make symbols absolute.  */
11463   osymbuf = (elf_symbol_type *) bfd_alloc2 (implib_bfd, symcount,
11464                                             sizeof (*osymbuf));
11465   for (src_count = 0; src_count < symcount; src_count++)
11466     {
11467       memcpy (&osymbuf[src_count], (elf_symbol_type *) sympp[src_count],
11468               sizeof (*osymbuf));
11469       osymbuf[src_count].symbol.section = bfd_abs_section_ptr;
11470       osymbuf[src_count].internal_elf_sym.st_shndx = SHN_ABS;
11471       osymbuf[src_count].symbol.value += sympp[src_count]->section->vma;
11472       osymbuf[src_count].internal_elf_sym.st_value =
11473         osymbuf[src_count].symbol.value;
11474       sympp[src_count] = &osymbuf[src_count].symbol;
11475     }
11476
11477   bfd_set_symtab (implib_bfd, sympp, symcount);
11478
11479   /* Allow the BFD backend to copy any private data it understands
11480      from the output BFD to the import library BFD.  This is done last
11481      to permit the routine to look at the filtered symbol table.  */
11482   if (! bfd_copy_private_bfd_data (abfd, implib_bfd))
11483     goto free_sym_buf;
11484
11485   if (!bfd_close (implib_bfd))
11486     goto free_sym_buf;
11487
11488   ret = TRUE;
11489
11490 free_sym_buf:
11491   free (sympp);
11492   return ret;
11493 }
11494
11495 static void
11496 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
11497 {
11498   asection *o;
11499
11500   if (flinfo->symstrtab != NULL)
11501     _bfd_elf_strtab_free (flinfo->symstrtab);
11502   if (flinfo->contents != NULL)
11503     free (flinfo->contents);
11504   if (flinfo->external_relocs != NULL)
11505     free (flinfo->external_relocs);
11506   if (flinfo->internal_relocs != NULL)
11507     free (flinfo->internal_relocs);
11508   if (flinfo->external_syms != NULL)
11509     free (flinfo->external_syms);
11510   if (flinfo->locsym_shndx != NULL)
11511     free (flinfo->locsym_shndx);
11512   if (flinfo->internal_syms != NULL)
11513     free (flinfo->internal_syms);
11514   if (flinfo->indices != NULL)
11515     free (flinfo->indices);
11516   if (flinfo->sections != NULL)
11517     free (flinfo->sections);
11518   if (flinfo->symshndxbuf != NULL)
11519     free (flinfo->symshndxbuf);
11520   for (o = obfd->sections; o != NULL; o = o->next)
11521     {
11522       struct bfd_elf_section_data *esdo = elf_section_data (o);
11523       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11524         free (esdo->rel.hashes);
11525       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11526         free (esdo->rela.hashes);
11527     }
11528 }
11529
11530 /* Do the final step of an ELF link.  */
11531
11532 bfd_boolean
11533 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
11534 {
11535   bfd_boolean dynamic;
11536   bfd_boolean emit_relocs;
11537   bfd *dynobj;
11538   struct elf_final_link_info flinfo;
11539   asection *o;
11540   struct bfd_link_order *p;
11541   bfd *sub;
11542   bfd_size_type max_contents_size;
11543   bfd_size_type max_external_reloc_size;
11544   bfd_size_type max_internal_reloc_count;
11545   bfd_size_type max_sym_count;
11546   bfd_size_type max_sym_shndx_count;
11547   Elf_Internal_Sym elfsym;
11548   unsigned int i;
11549   Elf_Internal_Shdr *symtab_hdr;
11550   Elf_Internal_Shdr *symtab_shndx_hdr;
11551   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11552   struct elf_outext_info eoinfo;
11553   bfd_boolean merged;
11554   size_t relativecount = 0;
11555   asection *reldyn = 0;
11556   bfd_size_type amt;
11557   asection *attr_section = NULL;
11558   bfd_vma attr_size = 0;
11559   const char *std_attrs_section;
11560   struct elf_link_hash_table *htab = elf_hash_table (info);
11561
11562   if (!is_elf_hash_table (htab))
11563     return FALSE;
11564
11565   if (bfd_link_pic (info))
11566     abfd->flags |= DYNAMIC;
11567
11568   dynamic = htab->dynamic_sections_created;
11569   dynobj = htab->dynobj;
11570
11571   emit_relocs = (bfd_link_relocatable (info)
11572                  || info->emitrelocations);
11573
11574   flinfo.info = info;
11575   flinfo.output_bfd = abfd;
11576   flinfo.symstrtab = _bfd_elf_strtab_init ();
11577   if (flinfo.symstrtab == NULL)
11578     return FALSE;
11579
11580   if (! dynamic)
11581     {
11582       flinfo.hash_sec = NULL;
11583       flinfo.symver_sec = NULL;
11584     }
11585   else
11586     {
11587       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
11588       /* Note that dynsym_sec can be NULL (on VMS).  */
11589       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
11590       /* Note that it is OK if symver_sec is NULL.  */
11591     }
11592
11593   flinfo.contents = NULL;
11594   flinfo.external_relocs = NULL;
11595   flinfo.internal_relocs = NULL;
11596   flinfo.external_syms = NULL;
11597   flinfo.locsym_shndx = NULL;
11598   flinfo.internal_syms = NULL;
11599   flinfo.indices = NULL;
11600   flinfo.sections = NULL;
11601   flinfo.symshndxbuf = NULL;
11602   flinfo.filesym_count = 0;
11603
11604   /* The object attributes have been merged.  Remove the input
11605      sections from the link, and set the contents of the output
11606      secton.  */
11607   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
11608   for (o = abfd->sections; o != NULL; o = o->next)
11609     {
11610       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
11611           || strcmp (o->name, ".gnu.attributes") == 0)
11612         {
11613           for (p = o->map_head.link_order; p != NULL; p = p->next)
11614             {
11615               asection *input_section;
11616
11617               if (p->type != bfd_indirect_link_order)
11618                 continue;
11619               input_section = p->u.indirect.section;
11620               /* Hack: reset the SEC_HAS_CONTENTS flag so that
11621                  elf_link_input_bfd ignores this section.  */
11622               input_section->flags &= ~SEC_HAS_CONTENTS;
11623             }
11624
11625           attr_size = bfd_elf_obj_attr_size (abfd);
11626           if (attr_size)
11627             {
11628               bfd_set_section_size (abfd, o, attr_size);
11629               attr_section = o;
11630               /* Skip this section later on.  */
11631               o->map_head.link_order = NULL;
11632             }
11633           else
11634             o->flags |= SEC_EXCLUDE;
11635         }
11636       else if ((o->flags & SEC_GROUP) != 0 && o->size == 0)
11637         {
11638           /* Remove empty group section from linker output.  */
11639           o->flags |= SEC_EXCLUDE;
11640           bfd_section_list_remove (abfd, o);
11641           abfd->section_count--;
11642         }
11643     }
11644
11645   /* Count up the number of relocations we will output for each output
11646      section, so that we know the sizes of the reloc sections.  We
11647      also figure out some maximum sizes.  */
11648   max_contents_size = 0;
11649   max_external_reloc_size = 0;
11650   max_internal_reloc_count = 0;
11651   max_sym_count = 0;
11652   max_sym_shndx_count = 0;
11653   merged = FALSE;
11654   for (o = abfd->sections; o != NULL; o = o->next)
11655     {
11656       struct bfd_elf_section_data *esdo = elf_section_data (o);
11657       o->reloc_count = 0;
11658
11659       for (p = o->map_head.link_order; p != NULL; p = p->next)
11660         {
11661           unsigned int reloc_count = 0;
11662           unsigned int additional_reloc_count = 0;
11663           struct bfd_elf_section_data *esdi = NULL;
11664
11665           if (p->type == bfd_section_reloc_link_order
11666               || p->type == bfd_symbol_reloc_link_order)
11667             reloc_count = 1;
11668           else if (p->type == bfd_indirect_link_order)
11669             {
11670               asection *sec;
11671
11672               sec = p->u.indirect.section;
11673
11674               /* Mark all sections which are to be included in the
11675                  link.  This will normally be every section.  We need
11676                  to do this so that we can identify any sections which
11677                  the linker has decided to not include.  */
11678               sec->linker_mark = TRUE;
11679
11680               if (sec->flags & SEC_MERGE)
11681                 merged = TRUE;
11682
11683               if (sec->rawsize > max_contents_size)
11684                 max_contents_size = sec->rawsize;
11685               if (sec->size > max_contents_size)
11686                 max_contents_size = sec->size;
11687
11688               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
11689                   && (sec->owner->flags & DYNAMIC) == 0)
11690                 {
11691                   size_t sym_count;
11692
11693                   /* We are interested in just local symbols, not all
11694                      symbols.  */
11695                   if (elf_bad_symtab (sec->owner))
11696                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
11697                                  / bed->s->sizeof_sym);
11698                   else
11699                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
11700
11701                   if (sym_count > max_sym_count)
11702                     max_sym_count = sym_count;
11703
11704                   if (sym_count > max_sym_shndx_count
11705                       && elf_symtab_shndx_list (sec->owner) != NULL)
11706                     max_sym_shndx_count = sym_count;
11707
11708                   if (esdo->this_hdr.sh_type == SHT_REL
11709                       || esdo->this_hdr.sh_type == SHT_RELA)
11710                     /* Some backends use reloc_count in relocation sections
11711                        to count particular types of relocs.  Of course,
11712                        reloc sections themselves can't have relocations.  */
11713                     ;
11714                   else if (emit_relocs)
11715                     {
11716                       reloc_count = sec->reloc_count;
11717                       if (bed->elf_backend_count_additional_relocs)
11718                         {
11719                           int c;
11720                           c = (*bed->elf_backend_count_additional_relocs) (sec);
11721                           additional_reloc_count += c;
11722                         }
11723                     }
11724                   else if (bed->elf_backend_count_relocs)
11725                     reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
11726
11727                   esdi = elf_section_data (sec);
11728
11729                   if ((sec->flags & SEC_RELOC) != 0)
11730                     {
11731                       size_t ext_size = 0;
11732
11733                       if (esdi->rel.hdr != NULL)
11734                         ext_size = esdi->rel.hdr->sh_size;
11735                       if (esdi->rela.hdr != NULL)
11736                         ext_size += esdi->rela.hdr->sh_size;
11737
11738                       if (ext_size > max_external_reloc_size)
11739                         max_external_reloc_size = ext_size;
11740                       if (sec->reloc_count > max_internal_reloc_count)
11741                         max_internal_reloc_count = sec->reloc_count;
11742                     }
11743                 }
11744             }
11745
11746           if (reloc_count == 0)
11747             continue;
11748
11749           reloc_count += additional_reloc_count;
11750           o->reloc_count += reloc_count;
11751
11752           if (p->type == bfd_indirect_link_order && emit_relocs)
11753             {
11754               if (esdi->rel.hdr)
11755                 {
11756                   esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11757                   esdo->rel.count += additional_reloc_count;
11758                 }
11759               if (esdi->rela.hdr)
11760                 {
11761                   esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11762                   esdo->rela.count += additional_reloc_count;
11763                 }
11764             }
11765           else
11766             {
11767               if (o->use_rela_p)
11768                 esdo->rela.count += reloc_count;
11769               else
11770                 esdo->rel.count += reloc_count;
11771             }
11772         }
11773
11774       if (o->reloc_count > 0)
11775         o->flags |= SEC_RELOC;
11776       else
11777         {
11778           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11779              set it (this is probably a bug) and if it is set
11780              assign_section_numbers will create a reloc section.  */
11781           o->flags &=~ SEC_RELOC;
11782         }
11783
11784       /* If the SEC_ALLOC flag is not set, force the section VMA to
11785          zero.  This is done in elf_fake_sections as well, but forcing
11786          the VMA to 0 here will ensure that relocs against these
11787          sections are handled correctly.  */
11788       if ((o->flags & SEC_ALLOC) == 0
11789           && ! o->user_set_vma)
11790         o->vma = 0;
11791     }
11792
11793   if (! bfd_link_relocatable (info) && merged)
11794     elf_link_hash_traverse (htab, _bfd_elf_link_sec_merge_syms, abfd);
11795
11796   /* Figure out the file positions for everything but the symbol table
11797      and the relocs.  We set symcount to force assign_section_numbers
11798      to create a symbol table.  */
11799   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11800   BFD_ASSERT (! abfd->output_has_begun);
11801   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11802     goto error_return;
11803
11804   /* Set sizes, and assign file positions for reloc sections.  */
11805   for (o = abfd->sections; o != NULL; o = o->next)
11806     {
11807       struct bfd_elf_section_data *esdo = elf_section_data (o);
11808       if ((o->flags & SEC_RELOC) != 0)
11809         {
11810           if (esdo->rel.hdr
11811               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11812             goto error_return;
11813
11814           if (esdo->rela.hdr
11815               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11816             goto error_return;
11817         }
11818
11819       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
11820          to count upwards while actually outputting the relocations.  */
11821       esdo->rel.count = 0;
11822       esdo->rela.count = 0;
11823
11824       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
11825         {
11826           /* Cache the section contents so that they can be compressed
11827              later.  Use bfd_malloc since it will be freed by
11828              bfd_compress_section_contents.  */
11829           unsigned char *contents = esdo->this_hdr.contents;
11830           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
11831             abort ();
11832           contents
11833             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
11834           if (contents == NULL)
11835             goto error_return;
11836           esdo->this_hdr.contents = contents;
11837         }
11838     }
11839
11840   /* We have now assigned file positions for all the sections except
11841      .symtab, .strtab, and non-loaded reloc sections.  We start the
11842      .symtab section at the current file position, and write directly
11843      to it.  We build the .strtab section in memory.  */
11844   bfd_get_symcount (abfd) = 0;
11845   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11846   /* sh_name is set in prep_headers.  */
11847   symtab_hdr->sh_type = SHT_SYMTAB;
11848   /* sh_flags, sh_addr and sh_size all start off zero.  */
11849   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
11850   /* sh_link is set in assign_section_numbers.  */
11851   /* sh_info is set below.  */
11852   /* sh_offset is set just below.  */
11853   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
11854
11855   if (max_sym_count < 20)
11856     max_sym_count = 20;
11857   htab->strtabsize = max_sym_count;
11858   amt = max_sym_count * sizeof (struct elf_sym_strtab);
11859   htab->strtab = (struct elf_sym_strtab *) bfd_malloc (amt);
11860   if (htab->strtab == NULL)
11861     goto error_return;
11862   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
11863   flinfo.symshndxbuf
11864     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
11865        ? (Elf_External_Sym_Shndx *) -1 : NULL);
11866
11867   if (info->strip != strip_all || emit_relocs)
11868     {
11869       file_ptr off = elf_next_file_pos (abfd);
11870
11871       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
11872
11873       /* Note that at this point elf_next_file_pos (abfd) is
11874          incorrect.  We do not yet know the size of the .symtab section.
11875          We correct next_file_pos below, after we do know the size.  */
11876
11877       /* Start writing out the symbol table.  The first symbol is always a
11878          dummy symbol.  */
11879       elfsym.st_value = 0;
11880       elfsym.st_size = 0;
11881       elfsym.st_info = 0;
11882       elfsym.st_other = 0;
11883       elfsym.st_shndx = SHN_UNDEF;
11884       elfsym.st_target_internal = 0;
11885       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
11886                                      bfd_und_section_ptr, NULL) != 1)
11887         goto error_return;
11888
11889       /* Output a symbol for each section.  We output these even if we are
11890          discarding local symbols, since they are used for relocs.  These
11891          symbols have no names.  We store the index of each one in the
11892          index field of the section, so that we can find it again when
11893          outputting relocs.  */
11894
11895       elfsym.st_size = 0;
11896       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11897       elfsym.st_other = 0;
11898       elfsym.st_value = 0;
11899       elfsym.st_target_internal = 0;
11900       for (i = 1; i < elf_numsections (abfd); i++)
11901         {
11902           o = bfd_section_from_elf_index (abfd, i);
11903           if (o != NULL)
11904             {
11905               o->target_index = bfd_get_symcount (abfd);
11906               elfsym.st_shndx = i;
11907               if (!bfd_link_relocatable (info))
11908                 elfsym.st_value = o->vma;
11909               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
11910                                              NULL) != 1)
11911                 goto error_return;
11912             }
11913         }
11914     }
11915
11916   /* Allocate some memory to hold information read in from the input
11917      files.  */
11918   if (max_contents_size != 0)
11919     {
11920       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
11921       if (flinfo.contents == NULL)
11922         goto error_return;
11923     }
11924
11925   if (max_external_reloc_size != 0)
11926     {
11927       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
11928       if (flinfo.external_relocs == NULL)
11929         goto error_return;
11930     }
11931
11932   if (max_internal_reloc_count != 0)
11933     {
11934       amt = max_internal_reloc_count * sizeof (Elf_Internal_Rela);
11935       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
11936       if (flinfo.internal_relocs == NULL)
11937         goto error_return;
11938     }
11939
11940   if (max_sym_count != 0)
11941     {
11942       amt = max_sym_count * bed->s->sizeof_sym;
11943       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
11944       if (flinfo.external_syms == NULL)
11945         goto error_return;
11946
11947       amt = max_sym_count * sizeof (Elf_Internal_Sym);
11948       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
11949       if (flinfo.internal_syms == NULL)
11950         goto error_return;
11951
11952       amt = max_sym_count * sizeof (long);
11953       flinfo.indices = (long int *) bfd_malloc (amt);
11954       if (flinfo.indices == NULL)
11955         goto error_return;
11956
11957       amt = max_sym_count * sizeof (asection *);
11958       flinfo.sections = (asection **) bfd_malloc (amt);
11959       if (flinfo.sections == NULL)
11960         goto error_return;
11961     }
11962
11963   if (max_sym_shndx_count != 0)
11964     {
11965       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
11966       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
11967       if (flinfo.locsym_shndx == NULL)
11968         goto error_return;
11969     }
11970
11971   if (htab->tls_sec)
11972     {
11973       bfd_vma base, end = 0;
11974       asection *sec;
11975
11976       for (sec = htab->tls_sec;
11977            sec && (sec->flags & SEC_THREAD_LOCAL);
11978            sec = sec->next)
11979         {
11980           bfd_size_type size = sec->size;
11981
11982           if (size == 0
11983               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11984             {
11985               struct bfd_link_order *ord = sec->map_tail.link_order;
11986
11987               if (ord != NULL)
11988                 size = ord->offset + ord->size;
11989             }
11990           end = sec->vma + size;
11991         }
11992       base = htab->tls_sec->vma;
11993       /* Only align end of TLS section if static TLS doesn't have special
11994          alignment requirements.  */
11995       if (bed->static_tls_alignment == 1)
11996         end = align_power (end, htab->tls_sec->alignment_power);
11997       htab->tls_size = end - base;
11998     }
11999
12000   /* Reorder SHF_LINK_ORDER sections.  */
12001   for (o = abfd->sections; o != NULL; o = o->next)
12002     {
12003       if (!elf_fixup_link_order (abfd, o))
12004         return FALSE;
12005     }
12006
12007   if (!_bfd_elf_fixup_eh_frame_hdr (info))
12008     return FALSE;
12009
12010   /* Since ELF permits relocations to be against local symbols, we
12011      must have the local symbols available when we do the relocations.
12012      Since we would rather only read the local symbols once, and we
12013      would rather not keep them in memory, we handle all the
12014      relocations for a single input file at the same time.
12015
12016      Unfortunately, there is no way to know the total number of local
12017      symbols until we have seen all of them, and the local symbol
12018      indices precede the global symbol indices.  This means that when
12019      we are generating relocatable output, and we see a reloc against
12020      a global symbol, we can not know the symbol index until we have
12021      finished examining all the local symbols to see which ones we are
12022      going to output.  To deal with this, we keep the relocations in
12023      memory, and don't output them until the end of the link.  This is
12024      an unfortunate waste of memory, but I don't see a good way around
12025      it.  Fortunately, it only happens when performing a relocatable
12026      link, which is not the common case.  FIXME: If keep_memory is set
12027      we could write the relocs out and then read them again; I don't
12028      know how bad the memory loss will be.  */
12029
12030   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12031     sub->output_has_begun = FALSE;
12032   for (o = abfd->sections; o != NULL; o = o->next)
12033     {
12034       for (p = o->map_head.link_order; p != NULL; p = p->next)
12035         {
12036           if (p->type == bfd_indirect_link_order
12037               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
12038                   == bfd_target_elf_flavour)
12039               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
12040             {
12041               if (! sub->output_has_begun)
12042                 {
12043                   if (! elf_link_input_bfd (&flinfo, sub))
12044                     goto error_return;
12045                   sub->output_has_begun = TRUE;
12046                 }
12047             }
12048           else if (p->type == bfd_section_reloc_link_order
12049                    || p->type == bfd_symbol_reloc_link_order)
12050             {
12051               if (! elf_reloc_link_order (abfd, info, o, p))
12052                 goto error_return;
12053             }
12054           else
12055             {
12056               if (! _bfd_default_link_order (abfd, info, o, p))
12057                 {
12058                   if (p->type == bfd_indirect_link_order
12059                       && (bfd_get_flavour (sub)
12060                           == bfd_target_elf_flavour)
12061                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
12062                           != bed->s->elfclass))
12063                     {
12064                       const char *iclass, *oclass;
12065
12066                       switch (bed->s->elfclass)
12067                         {
12068                         case ELFCLASS64: oclass = "ELFCLASS64"; break;
12069                         case ELFCLASS32: oclass = "ELFCLASS32"; break;
12070                         case ELFCLASSNONE: oclass = "ELFCLASSNONE"; break;
12071                         default: abort ();
12072                         }
12073
12074                       switch (elf_elfheader (sub)->e_ident[EI_CLASS])
12075                         {
12076                         case ELFCLASS64: iclass = "ELFCLASS64"; break;
12077                         case ELFCLASS32: iclass = "ELFCLASS32"; break;
12078                         case ELFCLASSNONE: iclass = "ELFCLASSNONE"; break;
12079                         default: abort ();
12080                         }
12081
12082                       bfd_set_error (bfd_error_wrong_format);
12083                       _bfd_error_handler
12084                         /* xgettext:c-format */
12085                         (_("%pB: file class %s incompatible with %s"),
12086                          sub, iclass, oclass);
12087                     }
12088
12089                   goto error_return;
12090                 }
12091             }
12092         }
12093     }
12094
12095   /* Free symbol buffer if needed.  */
12096   if (!info->reduce_memory_overheads)
12097     {
12098       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12099         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
12100             && elf_tdata (sub)->symbuf)
12101           {
12102             free (elf_tdata (sub)->symbuf);
12103             elf_tdata (sub)->symbuf = NULL;
12104           }
12105     }
12106
12107   /* Output any global symbols that got converted to local in a
12108      version script or due to symbol visibility.  We do this in a
12109      separate step since ELF requires all local symbols to appear
12110      prior to any global symbols.  FIXME: We should only do this if
12111      some global symbols were, in fact, converted to become local.
12112      FIXME: Will this work correctly with the Irix 5 linker?  */
12113   eoinfo.failed = FALSE;
12114   eoinfo.flinfo = &flinfo;
12115   eoinfo.localsyms = TRUE;
12116   eoinfo.file_sym_done = FALSE;
12117   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12118   if (eoinfo.failed)
12119     return FALSE;
12120
12121   /* If backend needs to output some local symbols not present in the hash
12122      table, do it now.  */
12123   if (bed->elf_backend_output_arch_local_syms
12124       && (info->strip != strip_all || emit_relocs))
12125     {
12126       typedef int (*out_sym_func)
12127         (void *, const char *, Elf_Internal_Sym *, asection *,
12128          struct elf_link_hash_entry *);
12129
12130       if (! ((*bed->elf_backend_output_arch_local_syms)
12131              (abfd, info, &flinfo,
12132               (out_sym_func) elf_link_output_symstrtab)))
12133         return FALSE;
12134     }
12135
12136   /* That wrote out all the local symbols.  Finish up the symbol table
12137      with the global symbols. Even if we want to strip everything we
12138      can, we still need to deal with those global symbols that got
12139      converted to local in a version script.  */
12140
12141   /* The sh_info field records the index of the first non local symbol.  */
12142   symtab_hdr->sh_info = bfd_get_symcount (abfd);
12143
12144   if (dynamic
12145       && htab->dynsym != NULL
12146       && htab->dynsym->output_section != bfd_abs_section_ptr)
12147     {
12148       Elf_Internal_Sym sym;
12149       bfd_byte *dynsym = htab->dynsym->contents;
12150
12151       o = htab->dynsym->output_section;
12152       elf_section_data (o)->this_hdr.sh_info = htab->local_dynsymcount + 1;
12153
12154       /* Write out the section symbols for the output sections.  */
12155       if (bfd_link_pic (info)
12156           || htab->is_relocatable_executable)
12157         {
12158           asection *s;
12159
12160           sym.st_size = 0;
12161           sym.st_name = 0;
12162           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
12163           sym.st_other = 0;
12164           sym.st_target_internal = 0;
12165
12166           for (s = abfd->sections; s != NULL; s = s->next)
12167             {
12168               int indx;
12169               bfd_byte *dest;
12170               long dynindx;
12171
12172               dynindx = elf_section_data (s)->dynindx;
12173               if (dynindx <= 0)
12174                 continue;
12175               indx = elf_section_data (s)->this_idx;
12176               BFD_ASSERT (indx > 0);
12177               sym.st_shndx = indx;
12178               if (! check_dynsym (abfd, &sym))
12179                 return FALSE;
12180               sym.st_value = s->vma;
12181               dest = dynsym + dynindx * bed->s->sizeof_sym;
12182               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12183             }
12184         }
12185
12186       /* Write out the local dynsyms.  */
12187       if (htab->dynlocal)
12188         {
12189           struct elf_link_local_dynamic_entry *e;
12190           for (e = htab->dynlocal; e ; e = e->next)
12191             {
12192               asection *s;
12193               bfd_byte *dest;
12194
12195               /* Copy the internal symbol and turn off visibility.
12196                  Note that we saved a word of storage and overwrote
12197                  the original st_name with the dynstr_index.  */
12198               sym = e->isym;
12199               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
12200
12201               s = bfd_section_from_elf_index (e->input_bfd,
12202                                               e->isym.st_shndx);
12203               if (s != NULL)
12204                 {
12205                   sym.st_shndx =
12206                     elf_section_data (s->output_section)->this_idx;
12207                   if (! check_dynsym (abfd, &sym))
12208                     return FALSE;
12209                   sym.st_value = (s->output_section->vma
12210                                   + s->output_offset
12211                                   + e->isym.st_value);
12212                 }
12213
12214               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
12215               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12216             }
12217         }
12218     }
12219
12220   /* We get the global symbols from the hash table.  */
12221   eoinfo.failed = FALSE;
12222   eoinfo.localsyms = FALSE;
12223   eoinfo.flinfo = &flinfo;
12224   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12225   if (eoinfo.failed)
12226     return FALSE;
12227
12228   /* If backend needs to output some symbols not present in the hash
12229      table, do it now.  */
12230   if (bed->elf_backend_output_arch_syms
12231       && (info->strip != strip_all || emit_relocs))
12232     {
12233       typedef int (*out_sym_func)
12234         (void *, const char *, Elf_Internal_Sym *, asection *,
12235          struct elf_link_hash_entry *);
12236
12237       if (! ((*bed->elf_backend_output_arch_syms)
12238              (abfd, info, &flinfo,
12239               (out_sym_func) elf_link_output_symstrtab)))
12240         return FALSE;
12241     }
12242
12243   /* Finalize the .strtab section.  */
12244   _bfd_elf_strtab_finalize (flinfo.symstrtab);
12245
12246   /* Swap out the .strtab section. */
12247   if (!elf_link_swap_symbols_out (&flinfo))
12248     return FALSE;
12249
12250   /* Now we know the size of the symtab section.  */
12251   if (bfd_get_symcount (abfd) > 0)
12252     {
12253       /* Finish up and write out the symbol string table (.strtab)
12254          section.  */
12255       Elf_Internal_Shdr *symstrtab_hdr = NULL;
12256       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
12257
12258       if (elf_symtab_shndx_list (abfd))
12259         {
12260           symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
12261
12262           if (symtab_shndx_hdr != NULL && symtab_shndx_hdr->sh_name != 0)
12263             {
12264               symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
12265               symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
12266               symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
12267               amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
12268               symtab_shndx_hdr->sh_size = amt;
12269
12270               off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
12271                                                                off, TRUE);
12272
12273               if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
12274                   || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
12275                 return FALSE;
12276             }
12277         }
12278
12279       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
12280       /* sh_name was set in prep_headers.  */
12281       symstrtab_hdr->sh_type = SHT_STRTAB;
12282       symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
12283       symstrtab_hdr->sh_addr = 0;
12284       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
12285       symstrtab_hdr->sh_entsize = 0;
12286       symstrtab_hdr->sh_link = 0;
12287       symstrtab_hdr->sh_info = 0;
12288       /* sh_offset is set just below.  */
12289       symstrtab_hdr->sh_addralign = 1;
12290
12291       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
12292                                                        off, TRUE);
12293       elf_next_file_pos (abfd) = off;
12294
12295       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
12296           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
12297         return FALSE;
12298     }
12299
12300   if (info->out_implib_bfd && !elf_output_implib (abfd, info))
12301     {
12302       _bfd_error_handler (_("%pB: failed to generate import library"),
12303                           info->out_implib_bfd);
12304       return FALSE;
12305     }
12306
12307   /* Adjust the relocs to have the correct symbol indices.  */
12308   for (o = abfd->sections; o != NULL; o = o->next)
12309     {
12310       struct bfd_elf_section_data *esdo = elf_section_data (o);
12311       bfd_boolean sort;
12312
12313       if ((o->flags & SEC_RELOC) == 0)
12314         continue;
12315
12316       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
12317       if (esdo->rel.hdr != NULL
12318           && !elf_link_adjust_relocs (abfd, o, &esdo->rel, sort, info))
12319         return FALSE;
12320       if (esdo->rela.hdr != NULL
12321           && !elf_link_adjust_relocs (abfd, o, &esdo->rela, sort, info))
12322         return FALSE;
12323
12324       /* Set the reloc_count field to 0 to prevent write_relocs from
12325          trying to swap the relocs out itself.  */
12326       o->reloc_count = 0;
12327     }
12328
12329   if (dynamic && info->combreloc && dynobj != NULL)
12330     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
12331
12332   /* If we are linking against a dynamic object, or generating a
12333      shared library, finish up the dynamic linking information.  */
12334   if (dynamic)
12335     {
12336       bfd_byte *dyncon, *dynconend;
12337
12338       /* Fix up .dynamic entries.  */
12339       o = bfd_get_linker_section (dynobj, ".dynamic");
12340       BFD_ASSERT (o != NULL);
12341
12342       dyncon = o->contents;
12343       dynconend = o->contents + o->size;
12344       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12345         {
12346           Elf_Internal_Dyn dyn;
12347           const char *name;
12348           unsigned int type;
12349           bfd_size_type sh_size;
12350           bfd_vma sh_addr;
12351
12352           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12353
12354           switch (dyn.d_tag)
12355             {
12356             default:
12357               continue;
12358             case DT_NULL:
12359               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
12360                 {
12361                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
12362                     {
12363                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
12364                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
12365                     default: continue;
12366                     }
12367                   dyn.d_un.d_val = relativecount;
12368                   relativecount = 0;
12369                   break;
12370                 }
12371               continue;
12372
12373             case DT_INIT:
12374               name = info->init_function;
12375               goto get_sym;
12376             case DT_FINI:
12377               name = info->fini_function;
12378             get_sym:
12379               {
12380                 struct elf_link_hash_entry *h;
12381
12382                 h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
12383                 if (h != NULL
12384                     && (h->root.type == bfd_link_hash_defined
12385                         || h->root.type == bfd_link_hash_defweak))
12386                   {
12387                     dyn.d_un.d_ptr = h->root.u.def.value;
12388                     o = h->root.u.def.section;
12389                     if (o->output_section != NULL)
12390                       dyn.d_un.d_ptr += (o->output_section->vma
12391                                          + o->output_offset);
12392                     else
12393                       {
12394                         /* The symbol is imported from another shared
12395                            library and does not apply to this one.  */
12396                         dyn.d_un.d_ptr = 0;
12397                       }
12398                     break;
12399                   }
12400               }
12401               continue;
12402
12403             case DT_PREINIT_ARRAYSZ:
12404               name = ".preinit_array";
12405               goto get_out_size;
12406             case DT_INIT_ARRAYSZ:
12407               name = ".init_array";
12408               goto get_out_size;
12409             case DT_FINI_ARRAYSZ:
12410               name = ".fini_array";
12411             get_out_size:
12412               o = bfd_get_section_by_name (abfd, name);
12413               if (o == NULL)
12414                 {
12415                   _bfd_error_handler
12416                     (_("could not find section %s"), name);
12417                   goto error_return;
12418                 }
12419               if (o->size == 0)
12420                 _bfd_error_handler
12421                   (_("warning: %s section has zero size"), name);
12422               dyn.d_un.d_val = o->size;
12423               break;
12424
12425             case DT_PREINIT_ARRAY:
12426               name = ".preinit_array";
12427               goto get_out_vma;
12428             case DT_INIT_ARRAY:
12429               name = ".init_array";
12430               goto get_out_vma;
12431             case DT_FINI_ARRAY:
12432               name = ".fini_array";
12433             get_out_vma:
12434               o = bfd_get_section_by_name (abfd, name);
12435               goto do_vma;
12436
12437             case DT_HASH:
12438               name = ".hash";
12439               goto get_vma;
12440             case DT_GNU_HASH:
12441               name = ".gnu.hash";
12442               goto get_vma;
12443             case DT_STRTAB:
12444               name = ".dynstr";
12445               goto get_vma;
12446             case DT_SYMTAB:
12447               name = ".dynsym";
12448               goto get_vma;
12449             case DT_VERDEF:
12450               name = ".gnu.version_d";
12451               goto get_vma;
12452             case DT_VERNEED:
12453               name = ".gnu.version_r";
12454               goto get_vma;
12455             case DT_VERSYM:
12456               name = ".gnu.version";
12457             get_vma:
12458               o = bfd_get_linker_section (dynobj, name);
12459             do_vma:
12460               if (o == NULL || bfd_is_abs_section (o->output_section))
12461                 {
12462                   _bfd_error_handler
12463                     (_("could not find section %s"), name);
12464                   goto error_return;
12465                 }
12466               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
12467                 {
12468                   _bfd_error_handler
12469                     (_("warning: section '%s' is being made into a note"), name);
12470                   bfd_set_error (bfd_error_nonrepresentable_section);
12471                   goto error_return;
12472                 }
12473               dyn.d_un.d_ptr = o->output_section->vma + o->output_offset;
12474               break;
12475
12476             case DT_REL:
12477             case DT_RELA:
12478             case DT_RELSZ:
12479             case DT_RELASZ:
12480               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
12481                 type = SHT_REL;
12482               else
12483                 type = SHT_RELA;
12484               sh_size = 0;
12485               sh_addr = 0;
12486               for (i = 1; i < elf_numsections (abfd); i++)
12487                 {
12488                   Elf_Internal_Shdr *hdr;
12489
12490                   hdr = elf_elfsections (abfd)[i];
12491                   if (hdr->sh_type == type
12492                       && (hdr->sh_flags & SHF_ALLOC) != 0)
12493                     {
12494                       sh_size += hdr->sh_size;
12495                       if (sh_addr == 0
12496                           || sh_addr > hdr->sh_addr)
12497                         sh_addr = hdr->sh_addr;
12498                     }
12499                 }
12500
12501               if (bed->dtrel_excludes_plt && htab->srelplt != NULL)
12502                 {
12503                   /* Don't count procedure linkage table relocs in the
12504                      overall reloc count.  */
12505                   sh_size -= htab->srelplt->size;
12506                   if (sh_size == 0)
12507                     /* If the size is zero, make the address zero too.
12508                        This is to avoid a glibc bug.  If the backend
12509                        emits DT_RELA/DT_RELASZ even when DT_RELASZ is
12510                        zero, then we'll put DT_RELA at the end of
12511                        DT_JMPREL.  glibc will interpret the end of
12512                        DT_RELA matching the end of DT_JMPREL as the
12513                        case where DT_RELA includes DT_JMPREL, and for
12514                        LD_BIND_NOW will decide that processing DT_RELA
12515                        will process the PLT relocs too.  Net result:
12516                        No PLT relocs applied.  */
12517                     sh_addr = 0;
12518
12519                   /* If .rela.plt is the first .rela section, exclude
12520                      it from DT_RELA.  */
12521                   else if (sh_addr == (htab->srelplt->output_section->vma
12522                                        + htab->srelplt->output_offset))
12523                     sh_addr += htab->srelplt->size;
12524                 }
12525
12526               if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
12527                 dyn.d_un.d_val = sh_size;
12528               else
12529                 dyn.d_un.d_ptr = sh_addr;
12530               break;
12531             }
12532           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
12533         }
12534     }
12535
12536   /* If we have created any dynamic sections, then output them.  */
12537   if (dynobj != NULL)
12538     {
12539       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
12540         goto error_return;
12541
12542       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
12543       if (((info->warn_shared_textrel && bfd_link_pic (info))
12544            || info->error_textrel)
12545           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
12546         {
12547           bfd_byte *dyncon, *dynconend;
12548
12549           dyncon = o->contents;
12550           dynconend = o->contents + o->size;
12551           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12552             {
12553               Elf_Internal_Dyn dyn;
12554
12555               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12556
12557               if (dyn.d_tag == DT_TEXTREL)
12558                 {
12559                   if (info->error_textrel)
12560                     info->callbacks->einfo
12561                       (_("%P%X: read-only segment has dynamic relocations\n"));
12562                   else
12563                     info->callbacks->einfo
12564                       (_("%P: warning: creating a DT_TEXTREL in a shared object\n"));
12565                   break;
12566                 }
12567             }
12568         }
12569
12570       for (o = dynobj->sections; o != NULL; o = o->next)
12571         {
12572           if ((o->flags & SEC_HAS_CONTENTS) == 0
12573               || o->size == 0
12574               || o->output_section == bfd_abs_section_ptr)
12575             continue;
12576           if ((o->flags & SEC_LINKER_CREATED) == 0)
12577             {
12578               /* At this point, we are only interested in sections
12579                  created by _bfd_elf_link_create_dynamic_sections.  */
12580               continue;
12581             }
12582           if (htab->stab_info.stabstr == o)
12583             continue;
12584           if (htab->eh_info.hdr_sec == o)
12585             continue;
12586           if (strcmp (o->name, ".dynstr") != 0)
12587             {
12588               if (! bfd_set_section_contents (abfd, o->output_section,
12589                                               o->contents,
12590                                               (file_ptr) o->output_offset
12591                                               * bfd_octets_per_byte (abfd),
12592                                               o->size))
12593                 goto error_return;
12594             }
12595           else
12596             {
12597               /* The contents of the .dynstr section are actually in a
12598                  stringtab.  */
12599               file_ptr off;
12600
12601               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
12602               if (bfd_seek (abfd, off, SEEK_SET) != 0
12603                   || !_bfd_elf_strtab_emit (abfd, htab->dynstr))
12604                 goto error_return;
12605             }
12606         }
12607     }
12608
12609   if (!info->resolve_section_groups)
12610     {
12611       bfd_boolean failed = FALSE;
12612
12613       BFD_ASSERT (bfd_link_relocatable (info));
12614       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
12615       if (failed)
12616         goto error_return;
12617     }
12618
12619   /* If we have optimized stabs strings, output them.  */
12620   if (htab->stab_info.stabstr != NULL)
12621     {
12622       if (!_bfd_write_stab_strings (abfd, &htab->stab_info))
12623         goto error_return;
12624     }
12625
12626   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
12627     goto error_return;
12628
12629   elf_final_link_free (abfd, &flinfo);
12630
12631   elf_linker (abfd) = TRUE;
12632
12633   if (attr_section)
12634     {
12635       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
12636       if (contents == NULL)
12637         return FALSE;   /* Bail out and fail.  */
12638       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
12639       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
12640       free (contents);
12641     }
12642
12643   return TRUE;
12644
12645  error_return:
12646   elf_final_link_free (abfd, &flinfo);
12647   return FALSE;
12648 }
12649 \f
12650 /* Initialize COOKIE for input bfd ABFD.  */
12651
12652 static bfd_boolean
12653 init_reloc_cookie (struct elf_reloc_cookie *cookie,
12654                    struct bfd_link_info *info, bfd *abfd)
12655 {
12656   Elf_Internal_Shdr *symtab_hdr;
12657   const struct elf_backend_data *bed;
12658
12659   bed = get_elf_backend_data (abfd);
12660   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12661
12662   cookie->abfd = abfd;
12663   cookie->sym_hashes = elf_sym_hashes (abfd);
12664   cookie->bad_symtab = elf_bad_symtab (abfd);
12665   if (cookie->bad_symtab)
12666     {
12667       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12668       cookie->extsymoff = 0;
12669     }
12670   else
12671     {
12672       cookie->locsymcount = symtab_hdr->sh_info;
12673       cookie->extsymoff = symtab_hdr->sh_info;
12674     }
12675
12676   if (bed->s->arch_size == 32)
12677     cookie->r_sym_shift = 8;
12678   else
12679     cookie->r_sym_shift = 32;
12680
12681   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
12682   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
12683     {
12684       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12685                                               cookie->locsymcount, 0,
12686                                               NULL, NULL, NULL);
12687       if (cookie->locsyms == NULL)
12688         {
12689           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
12690           return FALSE;
12691         }
12692       if (info->keep_memory)
12693         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
12694     }
12695   return TRUE;
12696 }
12697
12698 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
12699
12700 static void
12701 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
12702 {
12703   Elf_Internal_Shdr *symtab_hdr;
12704
12705   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12706   if (cookie->locsyms != NULL
12707       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
12708     free (cookie->locsyms);
12709 }
12710
12711 /* Initialize the relocation information in COOKIE for input section SEC
12712    of input bfd ABFD.  */
12713
12714 static bfd_boolean
12715 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12716                         struct bfd_link_info *info, bfd *abfd,
12717                         asection *sec)
12718 {
12719   if (sec->reloc_count == 0)
12720     {
12721       cookie->rels = NULL;
12722       cookie->relend = NULL;
12723     }
12724   else
12725     {
12726       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
12727                                                 info->keep_memory);
12728       if (cookie->rels == NULL)
12729         return FALSE;
12730       cookie->rel = cookie->rels;
12731       cookie->relend = cookie->rels + sec->reloc_count;
12732     }
12733   cookie->rel = cookie->rels;
12734   return TRUE;
12735 }
12736
12737 /* Free the memory allocated by init_reloc_cookie_rels,
12738    if appropriate.  */
12739
12740 static void
12741 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12742                         asection *sec)
12743 {
12744   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
12745     free (cookie->rels);
12746 }
12747
12748 /* Initialize the whole of COOKIE for input section SEC.  */
12749
12750 static bfd_boolean
12751 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12752                                struct bfd_link_info *info,
12753                                asection *sec)
12754 {
12755   if (!init_reloc_cookie (cookie, info, sec->owner))
12756     goto error1;
12757   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
12758     goto error2;
12759   return TRUE;
12760
12761  error2:
12762   fini_reloc_cookie (cookie, sec->owner);
12763  error1:
12764   return FALSE;
12765 }
12766
12767 /* Free the memory allocated by init_reloc_cookie_for_section,
12768    if appropriate.  */
12769
12770 static void
12771 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12772                                asection *sec)
12773 {
12774   fini_reloc_cookie_rels (cookie, sec);
12775   fini_reloc_cookie (cookie, sec->owner);
12776 }
12777 \f
12778 /* Garbage collect unused sections.  */
12779
12780 /* Default gc_mark_hook.  */
12781
12782 asection *
12783 _bfd_elf_gc_mark_hook (asection *sec,
12784                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12785                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12786                        struct elf_link_hash_entry *h,
12787                        Elf_Internal_Sym *sym)
12788 {
12789   if (h != NULL)
12790     {
12791       switch (h->root.type)
12792         {
12793         case bfd_link_hash_defined:
12794         case bfd_link_hash_defweak:
12795           return h->root.u.def.section;
12796
12797         case bfd_link_hash_common:
12798           return h->root.u.c.p->section;
12799
12800         default:
12801           break;
12802         }
12803     }
12804   else
12805     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12806
12807   return NULL;
12808 }
12809
12810 /* Return the debug definition section.  */
12811
12812 static asection *
12813 elf_gc_mark_debug_section (asection *sec ATTRIBUTE_UNUSED,
12814                            struct bfd_link_info *info ATTRIBUTE_UNUSED,
12815                            Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12816                            struct elf_link_hash_entry *h,
12817                            Elf_Internal_Sym *sym)
12818 {
12819   if (h != NULL)
12820     {
12821       /* Return the global debug definition section.  */
12822       if ((h->root.type == bfd_link_hash_defined
12823            || h->root.type == bfd_link_hash_defweak)
12824           && (h->root.u.def.section->flags & SEC_DEBUGGING) != 0)
12825         return h->root.u.def.section;
12826     }
12827   else
12828     {
12829       /* Return the local debug definition section.  */
12830       asection *isec = bfd_section_from_elf_index (sec->owner,
12831                                                    sym->st_shndx);
12832       if ((isec->flags & SEC_DEBUGGING) != 0)
12833         return isec;
12834     }
12835
12836   return NULL;
12837 }
12838
12839 /* COOKIE->rel describes a relocation against section SEC, which is
12840    a section we've decided to keep.  Return the section that contains
12841    the relocation symbol, or NULL if no section contains it.  */
12842
12843 asection *
12844 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
12845                        elf_gc_mark_hook_fn gc_mark_hook,
12846                        struct elf_reloc_cookie *cookie,
12847                        bfd_boolean *start_stop)
12848 {
12849   unsigned long r_symndx;
12850   struct elf_link_hash_entry *h;
12851
12852   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
12853   if (r_symndx == STN_UNDEF)
12854     return NULL;
12855
12856   if (r_symndx >= cookie->locsymcount
12857       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12858     {
12859       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
12860       if (h == NULL)
12861         {
12862           info->callbacks->einfo (_("%F%P: corrupt input: %pB\n"),
12863                                   sec->owner);
12864           return NULL;
12865         }
12866       while (h->root.type == bfd_link_hash_indirect
12867              || h->root.type == bfd_link_hash_warning)
12868         h = (struct elf_link_hash_entry *) h->root.u.i.link;
12869       h->mark = 1;
12870       /* If this symbol is weak and there is a non-weak definition, we
12871          keep the non-weak definition because many backends put
12872          dynamic reloc info on the non-weak definition for code
12873          handling copy relocs.  */
12874       if (h->is_weakalias)
12875         weakdef (h)->mark = 1;
12876
12877       if (start_stop != NULL)
12878         {
12879           /* To work around a glibc bug, mark XXX input sections
12880              when there is a reference to __start_XXX or __stop_XXX
12881              symbols.  */
12882           if (h->start_stop)
12883             {
12884               asection *s = h->u2.start_stop_section;
12885               *start_stop = !s->gc_mark;
12886               return s;
12887             }
12888         }
12889
12890       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
12891     }
12892
12893   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
12894                           &cookie->locsyms[r_symndx]);
12895 }
12896
12897 /* COOKIE->rel describes a relocation against section SEC, which is
12898    a section we've decided to keep.  Mark the section that contains
12899    the relocation symbol.  */
12900
12901 bfd_boolean
12902 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
12903                         asection *sec,
12904                         elf_gc_mark_hook_fn gc_mark_hook,
12905                         struct elf_reloc_cookie *cookie)
12906 {
12907   asection *rsec;
12908   bfd_boolean start_stop = FALSE;
12909
12910   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie, &start_stop);
12911   while (rsec != NULL)
12912     {
12913       if (!rsec->gc_mark)
12914         {
12915           if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
12916               || (rsec->owner->flags & DYNAMIC) != 0)
12917             rsec->gc_mark = 1;
12918           else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
12919             return FALSE;
12920         }
12921       if (!start_stop)
12922         break;
12923       rsec = bfd_get_next_section_by_name (rsec->owner, rsec);
12924     }
12925   return TRUE;
12926 }
12927
12928 /* The mark phase of garbage collection.  For a given section, mark
12929    it and any sections in this section's group, and all the sections
12930    which define symbols to which it refers.  */
12931
12932 bfd_boolean
12933 _bfd_elf_gc_mark (struct bfd_link_info *info,
12934                   asection *sec,
12935                   elf_gc_mark_hook_fn gc_mark_hook)
12936 {
12937   bfd_boolean ret;
12938   asection *group_sec, *eh_frame;
12939
12940   sec->gc_mark = 1;
12941
12942   /* Mark all the sections in the group.  */
12943   group_sec = elf_section_data (sec)->next_in_group;
12944   if (group_sec && !group_sec->gc_mark)
12945     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
12946       return FALSE;
12947
12948   /* Look through the section relocs.  */
12949   ret = TRUE;
12950   eh_frame = elf_eh_frame_section (sec->owner);
12951   if ((sec->flags & SEC_RELOC) != 0
12952       && sec->reloc_count > 0
12953       && sec != eh_frame)
12954     {
12955       struct elf_reloc_cookie cookie;
12956
12957       if (!init_reloc_cookie_for_section (&cookie, info, sec))
12958         ret = FALSE;
12959       else
12960         {
12961           for (; cookie.rel < cookie.relend; cookie.rel++)
12962             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
12963               {
12964                 ret = FALSE;
12965                 break;
12966               }
12967           fini_reloc_cookie_for_section (&cookie, sec);
12968         }
12969     }
12970
12971   if (ret && eh_frame && elf_fde_list (sec))
12972     {
12973       struct elf_reloc_cookie cookie;
12974
12975       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
12976         ret = FALSE;
12977       else
12978         {
12979           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
12980                                       gc_mark_hook, &cookie))
12981             ret = FALSE;
12982           fini_reloc_cookie_for_section (&cookie, eh_frame);
12983         }
12984     }
12985
12986   eh_frame = elf_section_eh_frame_entry (sec);
12987   if (ret && eh_frame && !eh_frame->gc_mark)
12988     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
12989       ret = FALSE;
12990
12991   return ret;
12992 }
12993
12994 /* Scan and mark sections in a special or debug section group.  */
12995
12996 static void
12997 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
12998 {
12999   /* Point to first section of section group.  */
13000   asection *ssec;
13001   /* Used to iterate the section group.  */
13002   asection *msec;
13003
13004   bfd_boolean is_special_grp = TRUE;
13005   bfd_boolean is_debug_grp = TRUE;
13006
13007   /* First scan to see if group contains any section other than debug
13008      and special section.  */
13009   ssec = msec = elf_next_in_group (grp);
13010   do
13011     {
13012       if ((msec->flags & SEC_DEBUGGING) == 0)
13013         is_debug_grp = FALSE;
13014
13015       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
13016         is_special_grp = FALSE;
13017
13018       msec = elf_next_in_group (msec);
13019     }
13020   while (msec != ssec);
13021
13022   /* If this is a pure debug section group or pure special section group,
13023      keep all sections in this group.  */
13024   if (is_debug_grp || is_special_grp)
13025     {
13026       do
13027         {
13028           msec->gc_mark = 1;
13029           msec = elf_next_in_group (msec);
13030         }
13031       while (msec != ssec);
13032     }
13033 }
13034
13035 /* Keep debug and special sections.  */
13036
13037 bfd_boolean
13038 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
13039                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
13040 {
13041   bfd *ibfd;
13042
13043   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13044     {
13045       asection *isec;
13046       bfd_boolean some_kept;
13047       bfd_boolean debug_frag_seen;
13048       bfd_boolean has_kept_debug_info;
13049
13050       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13051         continue;
13052       isec = ibfd->sections;
13053       if (isec == NULL || isec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13054         continue;
13055
13056       /* Ensure all linker created sections are kept,
13057          see if any other section is already marked,
13058          and note if we have any fragmented debug sections.  */
13059       debug_frag_seen = some_kept = has_kept_debug_info = FALSE;
13060       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13061         {
13062           if ((isec->flags & SEC_LINKER_CREATED) != 0)
13063             isec->gc_mark = 1;
13064           else if (isec->gc_mark
13065                    && (isec->flags & SEC_ALLOC) != 0
13066                    && elf_section_type (isec) != SHT_NOTE)
13067             some_kept = TRUE;
13068
13069           if (!debug_frag_seen
13070               && (isec->flags & SEC_DEBUGGING)
13071               && CONST_STRNEQ (isec->name, ".debug_line."))
13072             debug_frag_seen = TRUE;
13073         }
13074
13075       /* If no non-note alloc section in this file will be kept, then
13076          we can toss out the debug and special sections.  */
13077       if (!some_kept)
13078         continue;
13079
13080       /* Keep debug and special sections like .comment when they are
13081          not part of a group.  Also keep section groups that contain
13082          just debug sections or special sections.  */
13083       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13084         {
13085           if ((isec->flags & SEC_GROUP) != 0)
13086             _bfd_elf_gc_mark_debug_special_section_group (isec);
13087           else if (((isec->flags & SEC_DEBUGGING) != 0
13088                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
13089                    && elf_next_in_group (isec) == NULL)
13090             isec->gc_mark = 1;
13091           if (isec->gc_mark && (isec->flags & SEC_DEBUGGING) != 0)
13092             has_kept_debug_info = TRUE;
13093         }
13094
13095       /* Look for CODE sections which are going to be discarded,
13096          and find and discard any fragmented debug sections which
13097          are associated with that code section.  */
13098       if (debug_frag_seen)
13099         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13100           if ((isec->flags & SEC_CODE) != 0
13101               && isec->gc_mark == 0)
13102             {
13103               unsigned int ilen;
13104               asection *dsec;
13105
13106               ilen = strlen (isec->name);
13107
13108               /* Association is determined by the name of the debug
13109                  section containing the name of the code section as
13110                  a suffix.  For example .debug_line.text.foo is a
13111                  debug section associated with .text.foo.  */
13112               for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
13113                 {
13114                   unsigned int dlen;
13115
13116                   if (dsec->gc_mark == 0
13117                       || (dsec->flags & SEC_DEBUGGING) == 0)
13118                     continue;
13119
13120                   dlen = strlen (dsec->name);
13121
13122                   if (dlen > ilen
13123                       && strncmp (dsec->name + (dlen - ilen),
13124                                   isec->name, ilen) == 0)
13125                     dsec->gc_mark = 0;
13126                 }
13127           }
13128
13129       /* Mark debug sections referenced by kept debug sections.  */
13130       if (has_kept_debug_info)
13131         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13132           if (isec->gc_mark
13133               && (isec->flags & SEC_DEBUGGING) != 0)
13134             if (!_bfd_elf_gc_mark (info, isec,
13135                                    elf_gc_mark_debug_section))
13136               return FALSE;
13137     }
13138   return TRUE;
13139 }
13140
13141 static bfd_boolean
13142 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
13143 {
13144   bfd *sub;
13145   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13146
13147   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13148     {
13149       asection *o;
13150
13151       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13152           || elf_object_id (sub) != elf_hash_table_id (elf_hash_table (info))
13153           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13154         continue;
13155       o = sub->sections;
13156       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13157         continue;
13158
13159       for (o = sub->sections; o != NULL; o = o->next)
13160         {
13161           /* When any section in a section group is kept, we keep all
13162              sections in the section group.  If the first member of
13163              the section group is excluded, we will also exclude the
13164              group section.  */
13165           if (o->flags & SEC_GROUP)
13166             {
13167               asection *first = elf_next_in_group (o);
13168               o->gc_mark = first->gc_mark;
13169             }
13170
13171           if (o->gc_mark)
13172             continue;
13173
13174           /* Skip sweeping sections already excluded.  */
13175           if (o->flags & SEC_EXCLUDE)
13176             continue;
13177
13178           /* Since this is early in the link process, it is simple
13179              to remove a section from the output.  */
13180           o->flags |= SEC_EXCLUDE;
13181
13182           if (info->print_gc_sections && o->size != 0)
13183             /* xgettext:c-format */
13184             _bfd_error_handler (_("removing unused section '%pA' in file '%pB'"),
13185                                 o, sub);
13186         }
13187     }
13188
13189   return TRUE;
13190 }
13191
13192 /* Propagate collected vtable information.  This is called through
13193    elf_link_hash_traverse.  */
13194
13195 static bfd_boolean
13196 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
13197 {
13198   /* Those that are not vtables.  */
13199   if (h->start_stop
13200       || h->u2.vtable == NULL
13201       || h->u2.vtable->parent == NULL)
13202     return TRUE;
13203
13204   /* Those vtables that do not have parents, we cannot merge.  */
13205   if (h->u2.vtable->parent == (struct elf_link_hash_entry *) -1)
13206     return TRUE;
13207
13208   /* If we've already been done, exit.  */
13209   if (h->u2.vtable->used && h->u2.vtable->used[-1])
13210     return TRUE;
13211
13212   /* Make sure the parent's table is up to date.  */
13213   elf_gc_propagate_vtable_entries_used (h->u2.vtable->parent, okp);
13214
13215   if (h->u2.vtable->used == NULL)
13216     {
13217       /* None of this table's entries were referenced.  Re-use the
13218          parent's table.  */
13219       h->u2.vtable->used = h->u2.vtable->parent->u2.vtable->used;
13220       h->u2.vtable->size = h->u2.vtable->parent->u2.vtable->size;
13221     }
13222   else
13223     {
13224       size_t n;
13225       bfd_boolean *cu, *pu;
13226
13227       /* Or the parent's entries into ours.  */
13228       cu = h->u2.vtable->used;
13229       cu[-1] = TRUE;
13230       pu = h->u2.vtable->parent->u2.vtable->used;
13231       if (pu != NULL)
13232         {
13233           const struct elf_backend_data *bed;
13234           unsigned int log_file_align;
13235
13236           bed = get_elf_backend_data (h->root.u.def.section->owner);
13237           log_file_align = bed->s->log_file_align;
13238           n = h->u2.vtable->parent->u2.vtable->size >> log_file_align;
13239           while (n--)
13240             {
13241               if (*pu)
13242                 *cu = TRUE;
13243               pu++;
13244               cu++;
13245             }
13246         }
13247     }
13248
13249   return TRUE;
13250 }
13251
13252 static bfd_boolean
13253 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
13254 {
13255   asection *sec;
13256   bfd_vma hstart, hend;
13257   Elf_Internal_Rela *relstart, *relend, *rel;
13258   const struct elf_backend_data *bed;
13259   unsigned int log_file_align;
13260
13261   /* Take care of both those symbols that do not describe vtables as
13262      well as those that are not loaded.  */
13263   if (h->start_stop
13264       || h->u2.vtable == NULL
13265       || h->u2.vtable->parent == NULL)
13266     return TRUE;
13267
13268   BFD_ASSERT (h->root.type == bfd_link_hash_defined
13269               || h->root.type == bfd_link_hash_defweak);
13270
13271   sec = h->root.u.def.section;
13272   hstart = h->root.u.def.value;
13273   hend = hstart + h->size;
13274
13275   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
13276   if (!relstart)
13277     return *(bfd_boolean *) okp = FALSE;
13278   bed = get_elf_backend_data (sec->owner);
13279   log_file_align = bed->s->log_file_align;
13280
13281   relend = relstart + sec->reloc_count;
13282
13283   for (rel = relstart; rel < relend; ++rel)
13284     if (rel->r_offset >= hstart && rel->r_offset < hend)
13285       {
13286         /* If the entry is in use, do nothing.  */
13287         if (h->u2.vtable->used
13288             && (rel->r_offset - hstart) < h->u2.vtable->size)
13289           {
13290             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
13291             if (h->u2.vtable->used[entry])
13292               continue;
13293           }
13294         /* Otherwise, kill it.  */
13295         rel->r_offset = rel->r_info = rel->r_addend = 0;
13296       }
13297
13298   return TRUE;
13299 }
13300
13301 /* Mark sections containing dynamically referenced symbols.  When
13302    building shared libraries, we must assume that any visible symbol is
13303    referenced.  */
13304
13305 bfd_boolean
13306 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
13307 {
13308   struct bfd_link_info *info = (struct bfd_link_info *) inf;
13309   struct bfd_elf_dynamic_list *d = info->dynamic_list;
13310
13311   if ((h->root.type == bfd_link_hash_defined
13312        || h->root.type == bfd_link_hash_defweak)
13313       && ((h->ref_dynamic && !h->forced_local)
13314           || ((h->def_regular || ELF_COMMON_DEF_P (h))
13315               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
13316               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
13317               && (!bfd_link_executable (info)
13318                   || info->gc_keep_exported
13319                   || info->export_dynamic
13320                   || (h->dynamic
13321                       && d != NULL
13322                       && (*d->match) (&d->head, NULL, h->root.root.string)))
13323               && (h->versioned >= versioned
13324                   || !bfd_hide_sym_by_version (info->version_info,
13325                                                h->root.root.string)))))
13326     h->root.u.def.section->flags |= SEC_KEEP;
13327
13328   return TRUE;
13329 }
13330
13331 /* Keep all sections containing symbols undefined on the command-line,
13332    and the section containing the entry symbol.  */
13333
13334 void
13335 _bfd_elf_gc_keep (struct bfd_link_info *info)
13336 {
13337   struct bfd_sym_chain *sym;
13338
13339   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
13340     {
13341       struct elf_link_hash_entry *h;
13342
13343       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
13344                                 FALSE, FALSE, FALSE);
13345
13346       if (h != NULL
13347           && (h->root.type == bfd_link_hash_defined
13348               || h->root.type == bfd_link_hash_defweak)
13349           && !bfd_is_abs_section (h->root.u.def.section)
13350           && !bfd_is_und_section (h->root.u.def.section))
13351         h->root.u.def.section->flags |= SEC_KEEP;
13352     }
13353 }
13354
13355 bfd_boolean
13356 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
13357                                 struct bfd_link_info *info)
13358 {
13359   bfd *ibfd = info->input_bfds;
13360
13361   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13362     {
13363       asection *sec;
13364       struct elf_reloc_cookie cookie;
13365
13366       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13367         continue;
13368       sec = ibfd->sections;
13369       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13370         continue;
13371
13372       if (!init_reloc_cookie (&cookie, info, ibfd))
13373         return FALSE;
13374
13375       for (sec = ibfd->sections; sec; sec = sec->next)
13376         {
13377           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
13378               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
13379             {
13380               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
13381               fini_reloc_cookie_rels (&cookie, sec);
13382             }
13383         }
13384     }
13385   return TRUE;
13386 }
13387
13388 /* Do mark and sweep of unused sections.  */
13389
13390 bfd_boolean
13391 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
13392 {
13393   bfd_boolean ok = TRUE;
13394   bfd *sub;
13395   elf_gc_mark_hook_fn gc_mark_hook;
13396   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13397   struct elf_link_hash_table *htab;
13398
13399   if (!bed->can_gc_sections
13400       || !is_elf_hash_table (info->hash))
13401     {
13402       _bfd_error_handler(_("warning: gc-sections option ignored"));
13403       return TRUE;
13404     }
13405
13406   bed->gc_keep (info);
13407   htab = elf_hash_table (info);
13408
13409   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
13410      at the .eh_frame section if we can mark the FDEs individually.  */
13411   for (sub = info->input_bfds;
13412        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
13413        sub = sub->link.next)
13414     {
13415       asection *sec;
13416       struct elf_reloc_cookie cookie;
13417
13418       sec = sub->sections;
13419       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13420         continue;
13421       sec = bfd_get_section_by_name (sub, ".eh_frame");
13422       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
13423         {
13424           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
13425           if (elf_section_data (sec)->sec_info
13426               && (sec->flags & SEC_LINKER_CREATED) == 0)
13427             elf_eh_frame_section (sub) = sec;
13428           fini_reloc_cookie_for_section (&cookie, sec);
13429           sec = bfd_get_next_section_by_name (NULL, sec);
13430         }
13431     }
13432
13433   /* Apply transitive closure to the vtable entry usage info.  */
13434   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
13435   if (!ok)
13436     return FALSE;
13437
13438   /* Kill the vtable relocations that were not used.  */
13439   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
13440   if (!ok)
13441     return FALSE;
13442
13443   /* Mark dynamically referenced symbols.  */
13444   if (htab->dynamic_sections_created || info->gc_keep_exported)
13445     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
13446
13447   /* Grovel through relocs to find out who stays ...  */
13448   gc_mark_hook = bed->gc_mark_hook;
13449   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13450     {
13451       asection *o;
13452
13453       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13454           || elf_object_id (sub) != elf_hash_table_id (htab)
13455           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13456         continue;
13457
13458       o = sub->sections;
13459       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13460         continue;
13461
13462       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
13463          Also treat note sections as a root, if the section is not part
13464          of a group.  We must keep all PREINIT_ARRAY, INIT_ARRAY as
13465          well as FINI_ARRAY sections for ld -r.  */
13466       for (o = sub->sections; o != NULL; o = o->next)
13467         if (!o->gc_mark
13468             && (o->flags & SEC_EXCLUDE) == 0
13469             && ((o->flags & SEC_KEEP) != 0
13470                 || (bfd_link_relocatable (info)
13471                     && ((elf_section_data (o)->this_hdr.sh_type
13472                          == SHT_PREINIT_ARRAY)
13473                         || (elf_section_data (o)->this_hdr.sh_type
13474                             == SHT_INIT_ARRAY)
13475                         || (elf_section_data (o)->this_hdr.sh_type
13476                             == SHT_FINI_ARRAY)))
13477                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
13478                     && elf_next_in_group (o) == NULL )))
13479           {
13480             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
13481               return FALSE;
13482           }
13483     }
13484
13485   /* Allow the backend to mark additional target specific sections.  */
13486   bed->gc_mark_extra_sections (info, gc_mark_hook);
13487
13488   /* ... and mark SEC_EXCLUDE for those that go.  */
13489   return elf_gc_sweep (abfd, info);
13490 }
13491 \f
13492 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
13493
13494 bfd_boolean
13495 bfd_elf_gc_record_vtinherit (bfd *abfd,
13496                              asection *sec,
13497                              struct elf_link_hash_entry *h,
13498                              bfd_vma offset)
13499 {
13500   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
13501   struct elf_link_hash_entry **search, *child;
13502   size_t extsymcount;
13503   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13504
13505   /* The sh_info field of the symtab header tells us where the
13506      external symbols start.  We don't care about the local symbols at
13507      this point.  */
13508   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
13509   if (!elf_bad_symtab (abfd))
13510     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
13511
13512   sym_hashes = elf_sym_hashes (abfd);
13513   sym_hashes_end = sym_hashes + extsymcount;
13514
13515   /* Hunt down the child symbol, which is in this section at the same
13516      offset as the relocation.  */
13517   for (search = sym_hashes; search != sym_hashes_end; ++search)
13518     {
13519       if ((child = *search) != NULL
13520           && (child->root.type == bfd_link_hash_defined
13521               || child->root.type == bfd_link_hash_defweak)
13522           && child->root.u.def.section == sec
13523           && child->root.u.def.value == offset)
13524         goto win;
13525     }
13526
13527   /* xgettext:c-format */
13528   _bfd_error_handler (_("%pB: %pA+%#" PRIx64 ": no symbol found for INHERIT"),
13529                       abfd, sec, (uint64_t) offset);
13530   bfd_set_error (bfd_error_invalid_operation);
13531   return FALSE;
13532
13533  win:
13534   if (!child->u2.vtable)
13535     {
13536       child->u2.vtable = ((struct elf_link_virtual_table_entry *)
13537                           bfd_zalloc (abfd, sizeof (*child->u2.vtable)));
13538       if (!child->u2.vtable)
13539         return FALSE;
13540     }
13541   if (!h)
13542     {
13543       /* This *should* only be the absolute section.  It could potentially
13544          be that someone has defined a non-global vtable though, which
13545          would be bad.  It isn't worth paging in the local symbols to be
13546          sure though; that case should simply be handled by the assembler.  */
13547
13548       child->u2.vtable->parent = (struct elf_link_hash_entry *) -1;
13549     }
13550   else
13551     child->u2.vtable->parent = h;
13552
13553   return TRUE;
13554 }
13555
13556 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
13557
13558 bfd_boolean
13559 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
13560                            asection *sec ATTRIBUTE_UNUSED,
13561                            struct elf_link_hash_entry *h,
13562                            bfd_vma addend)
13563 {
13564   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13565   unsigned int log_file_align = bed->s->log_file_align;
13566
13567   if (!h->u2.vtable)
13568     {
13569       h->u2.vtable = ((struct elf_link_virtual_table_entry *)
13570                       bfd_zalloc (abfd, sizeof (*h->u2.vtable)));
13571       if (!h->u2.vtable)
13572         return FALSE;
13573     }
13574
13575   if (addend >= h->u2.vtable->size)
13576     {
13577       size_t size, bytes, file_align;
13578       bfd_boolean *ptr = h->u2.vtable->used;
13579
13580       /* While the symbol is undefined, we have to be prepared to handle
13581          a zero size.  */
13582       file_align = 1 << log_file_align;
13583       if (h->root.type == bfd_link_hash_undefined)
13584         size = addend + file_align;
13585       else
13586         {
13587           size = h->size;
13588           if (addend >= size)
13589             {
13590               /* Oops!  We've got a reference past the defined end of
13591                  the table.  This is probably a bug -- shall we warn?  */
13592               size = addend + file_align;
13593             }
13594         }
13595       size = (size + file_align - 1) & -file_align;
13596
13597       /* Allocate one extra entry for use as a "done" flag for the
13598          consolidation pass.  */
13599       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
13600
13601       if (ptr)
13602         {
13603           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
13604
13605           if (ptr != NULL)
13606             {
13607               size_t oldbytes;
13608
13609               oldbytes = (((h->u2.vtable->size >> log_file_align) + 1)
13610                           * sizeof (bfd_boolean));
13611               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
13612             }
13613         }
13614       else
13615         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
13616
13617       if (ptr == NULL)
13618         return FALSE;
13619
13620       /* And arrange for that done flag to be at index -1.  */
13621       h->u2.vtable->used = ptr + 1;
13622       h->u2.vtable->size = size;
13623     }
13624
13625   h->u2.vtable->used[addend >> log_file_align] = TRUE;
13626
13627   return TRUE;
13628 }
13629
13630 /* Map an ELF section header flag to its corresponding string.  */
13631 typedef struct
13632 {
13633   char *flag_name;
13634   flagword flag_value;
13635 } elf_flags_to_name_table;
13636
13637 static elf_flags_to_name_table elf_flags_to_names [] =
13638 {
13639   { "SHF_WRITE", SHF_WRITE },
13640   { "SHF_ALLOC", SHF_ALLOC },
13641   { "SHF_EXECINSTR", SHF_EXECINSTR },
13642   { "SHF_MERGE", SHF_MERGE },
13643   { "SHF_STRINGS", SHF_STRINGS },
13644   { "SHF_INFO_LINK", SHF_INFO_LINK},
13645   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
13646   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
13647   { "SHF_GROUP", SHF_GROUP },
13648   { "SHF_TLS", SHF_TLS },
13649   { "SHF_MASKOS", SHF_MASKOS },
13650   { "SHF_EXCLUDE", SHF_EXCLUDE },
13651 };
13652
13653 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
13654 bfd_boolean
13655 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
13656                               struct flag_info *flaginfo,
13657                               asection *section)
13658 {
13659   const bfd_vma sh_flags = elf_section_flags (section);
13660
13661   if (!flaginfo->flags_initialized)
13662     {
13663       bfd *obfd = info->output_bfd;
13664       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13665       struct flag_info_list *tf = flaginfo->flag_list;
13666       int with_hex = 0;
13667       int without_hex = 0;
13668
13669       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
13670         {
13671           unsigned i;
13672           flagword (*lookup) (char *);
13673
13674           lookup = bed->elf_backend_lookup_section_flags_hook;
13675           if (lookup != NULL)
13676             {
13677               flagword hexval = (*lookup) ((char *) tf->name);
13678
13679               if (hexval != 0)
13680                 {
13681                   if (tf->with == with_flags)
13682                     with_hex |= hexval;
13683                   else if (tf->with == without_flags)
13684                     without_hex |= hexval;
13685                   tf->valid = TRUE;
13686                   continue;
13687                 }
13688             }
13689           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
13690             {
13691               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
13692                 {
13693                   if (tf->with == with_flags)
13694                     with_hex |= elf_flags_to_names[i].flag_value;
13695                   else if (tf->with == without_flags)
13696                     without_hex |= elf_flags_to_names[i].flag_value;
13697                   tf->valid = TRUE;
13698                   break;
13699                 }
13700             }
13701           if (!tf->valid)
13702             {
13703               info->callbacks->einfo
13704                 (_("unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
13705               return FALSE;
13706             }
13707         }
13708       flaginfo->flags_initialized = TRUE;
13709       flaginfo->only_with_flags |= with_hex;
13710       flaginfo->not_with_flags |= without_hex;
13711     }
13712
13713   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
13714     return FALSE;
13715
13716   if ((flaginfo->not_with_flags & sh_flags) != 0)
13717     return FALSE;
13718
13719   return TRUE;
13720 }
13721
13722 struct alloc_got_off_arg {
13723   bfd_vma gotoff;
13724   struct bfd_link_info *info;
13725 };
13726
13727 /* We need a special top-level link routine to convert got reference counts
13728    to real got offsets.  */
13729
13730 static bfd_boolean
13731 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
13732 {
13733   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
13734   bfd *obfd = gofarg->info->output_bfd;
13735   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13736
13737   if (h->got.refcount > 0)
13738     {
13739       h->got.offset = gofarg->gotoff;
13740       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
13741     }
13742   else
13743     h->got.offset = (bfd_vma) -1;
13744
13745   return TRUE;
13746 }
13747
13748 /* And an accompanying bit to work out final got entry offsets once
13749    we're done.  Should be called from final_link.  */
13750
13751 bfd_boolean
13752 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
13753                                         struct bfd_link_info *info)
13754 {
13755   bfd *i;
13756   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13757   bfd_vma gotoff;
13758   struct alloc_got_off_arg gofarg;
13759
13760   BFD_ASSERT (abfd == info->output_bfd);
13761
13762   if (! is_elf_hash_table (info->hash))
13763     return FALSE;
13764
13765   /* The GOT offset is relative to the .got section, but the GOT header is
13766      put into the .got.plt section, if the backend uses it.  */
13767   if (bed->want_got_plt)
13768     gotoff = 0;
13769   else
13770     gotoff = bed->got_header_size;
13771
13772   /* Do the local .got entries first.  */
13773   for (i = info->input_bfds; i; i = i->link.next)
13774     {
13775       bfd_signed_vma *local_got;
13776       size_t j, locsymcount;
13777       Elf_Internal_Shdr *symtab_hdr;
13778
13779       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13780         continue;
13781
13782       local_got = elf_local_got_refcounts (i);
13783       if (!local_got)
13784         continue;
13785
13786       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13787       if (elf_bad_symtab (i))
13788         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13789       else
13790         locsymcount = symtab_hdr->sh_info;
13791
13792       for (j = 0; j < locsymcount; ++j)
13793         {
13794           if (local_got[j] > 0)
13795             {
13796               local_got[j] = gotoff;
13797               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13798             }
13799           else
13800             local_got[j] = (bfd_vma) -1;
13801         }
13802     }
13803
13804   /* Then the global .got entries.  .plt refcounts are handled by
13805      adjust_dynamic_symbol  */
13806   gofarg.gotoff = gotoff;
13807   gofarg.info = info;
13808   elf_link_hash_traverse (elf_hash_table (info),
13809                           elf_gc_allocate_got_offsets,
13810                           &gofarg);
13811   return TRUE;
13812 }
13813
13814 /* Many folk need no more in the way of final link than this, once
13815    got entry reference counting is enabled.  */
13816
13817 bfd_boolean
13818 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
13819 {
13820   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
13821     return FALSE;
13822
13823   /* Invoke the regular ELF backend linker to do all the work.  */
13824   return bfd_elf_final_link (abfd, info);
13825 }
13826
13827 bfd_boolean
13828 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
13829 {
13830   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
13831
13832   if (rcookie->bad_symtab)
13833     rcookie->rel = rcookie->rels;
13834
13835   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
13836     {
13837       unsigned long r_symndx;
13838
13839       if (! rcookie->bad_symtab)
13840         if (rcookie->rel->r_offset > offset)
13841           return FALSE;
13842       if (rcookie->rel->r_offset != offset)
13843         continue;
13844
13845       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
13846       if (r_symndx == STN_UNDEF)
13847         return TRUE;
13848
13849       if (r_symndx >= rcookie->locsymcount
13850           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13851         {
13852           struct elf_link_hash_entry *h;
13853
13854           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
13855
13856           while (h->root.type == bfd_link_hash_indirect
13857                  || h->root.type == bfd_link_hash_warning)
13858             h = (struct elf_link_hash_entry *) h->root.u.i.link;
13859
13860           if ((h->root.type == bfd_link_hash_defined
13861                || h->root.type == bfd_link_hash_defweak)
13862               && (h->root.u.def.section->owner != rcookie->abfd
13863                   || h->root.u.def.section->kept_section != NULL
13864                   || discarded_section (h->root.u.def.section)))
13865             return TRUE;
13866         }
13867       else
13868         {
13869           /* It's not a relocation against a global symbol,
13870              but it could be a relocation against a local
13871              symbol for a discarded section.  */
13872           asection *isec;
13873           Elf_Internal_Sym *isym;
13874
13875           /* Need to: get the symbol; get the section.  */
13876           isym = &rcookie->locsyms[r_symndx];
13877           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
13878           if (isec != NULL
13879               && (isec->kept_section != NULL
13880                   || discarded_section (isec)))
13881             return TRUE;
13882         }
13883       return FALSE;
13884     }
13885   return FALSE;
13886 }
13887
13888 /* Discard unneeded references to discarded sections.
13889    Returns -1 on error, 1 if any section's size was changed, 0 if
13890    nothing changed.  This function assumes that the relocations are in
13891    sorted order, which is true for all known assemblers.  */
13892
13893 int
13894 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
13895 {
13896   struct elf_reloc_cookie cookie;
13897   asection *o;
13898   bfd *abfd;
13899   int changed = 0;
13900
13901   if (info->traditional_format
13902       || !is_elf_hash_table (info->hash))
13903     return 0;
13904
13905   o = bfd_get_section_by_name (output_bfd, ".stab");
13906   if (o != NULL)
13907     {
13908       asection *i;
13909
13910       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13911         {
13912           if (i->size == 0
13913               || i->reloc_count == 0
13914               || i->sec_info_type != SEC_INFO_TYPE_STABS)
13915             continue;
13916
13917           abfd = i->owner;
13918           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13919             continue;
13920
13921           if (!init_reloc_cookie_for_section (&cookie, info, i))
13922             return -1;
13923
13924           if (_bfd_discard_section_stabs (abfd, i,
13925                                           elf_section_data (i)->sec_info,
13926                                           bfd_elf_reloc_symbol_deleted_p,
13927                                           &cookie))
13928             changed = 1;
13929
13930           fini_reloc_cookie_for_section (&cookie, i);
13931         }
13932     }
13933
13934   o = NULL;
13935   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
13936     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
13937   if (o != NULL)
13938     {
13939       asection *i;
13940       int eh_changed = 0;
13941       unsigned int eh_alignment;
13942
13943       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13944         {
13945           if (i->size == 0)
13946             continue;
13947
13948           abfd = i->owner;
13949           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13950             continue;
13951
13952           if (!init_reloc_cookie_for_section (&cookie, info, i))
13953             return -1;
13954
13955           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
13956           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
13957                                                  bfd_elf_reloc_symbol_deleted_p,
13958                                                  &cookie))
13959             {
13960               eh_changed = 1;
13961               if (i->size != i->rawsize)
13962                 changed = 1;
13963             }
13964
13965           fini_reloc_cookie_for_section (&cookie, i);
13966         }
13967
13968       eh_alignment = 1 << o->alignment_power;
13969       /* Skip over zero terminator, and prevent empty sections from
13970          adding alignment padding at the end.  */
13971       for (i = o->map_tail.s; i != NULL; i = i->map_tail.s)
13972         if (i->size == 0)
13973           i->flags |= SEC_EXCLUDE;
13974         else if (i->size > 4)
13975           break;
13976       /* The last non-empty eh_frame section doesn't need padding.  */
13977       if (i != NULL)
13978         i = i->map_tail.s;
13979       /* Any prior sections must pad the last FDE out to the output
13980          section alignment.  Otherwise we might have zero padding
13981          between sections, which would be seen as a terminator.  */
13982       for (; i != NULL; i = i->map_tail.s)
13983         if (i->size == 4)
13984           /* All but the last zero terminator should have been removed.  */
13985           BFD_FAIL ();
13986         else
13987           {
13988             bfd_size_type size
13989               = (i->size + eh_alignment - 1) & -eh_alignment;
13990             if (i->size != size)
13991               {
13992                 i->size = size;
13993                 changed = 1;
13994                 eh_changed = 1;
13995               }
13996           }
13997       if (eh_changed)
13998         elf_link_hash_traverse (elf_hash_table (info),
13999                                 _bfd_elf_adjust_eh_frame_global_symbol, NULL);
14000     }
14001
14002   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
14003     {
14004       const struct elf_backend_data *bed;
14005       asection *s;
14006
14007       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
14008         continue;
14009       s = abfd->sections;
14010       if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
14011         continue;
14012
14013       bed = get_elf_backend_data (abfd);
14014
14015       if (bed->elf_backend_discard_info != NULL)
14016         {
14017           if (!init_reloc_cookie (&cookie, info, abfd))
14018             return -1;
14019
14020           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
14021             changed = 1;
14022
14023           fini_reloc_cookie (&cookie, abfd);
14024         }
14025     }
14026
14027   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
14028     _bfd_elf_end_eh_frame_parsing (info);
14029
14030   if (info->eh_frame_hdr_type
14031       && !bfd_link_relocatable (info)
14032       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
14033     changed = 1;
14034
14035   return changed;
14036 }
14037
14038 bfd_boolean
14039 _bfd_elf_section_already_linked (bfd *abfd,
14040                                  asection *sec,
14041                                  struct bfd_link_info *info)
14042 {
14043   flagword flags;
14044   const char *name, *key;
14045   struct bfd_section_already_linked *l;
14046   struct bfd_section_already_linked_hash_entry *already_linked_list;
14047
14048   if (sec->output_section == bfd_abs_section_ptr)
14049     return FALSE;
14050
14051   flags = sec->flags;
14052
14053   /* Return if it isn't a linkonce section.  A comdat group section
14054      also has SEC_LINK_ONCE set.  */
14055   if ((flags & SEC_LINK_ONCE) == 0)
14056     return FALSE;
14057
14058   /* Don't put group member sections on our list of already linked
14059      sections.  They are handled as a group via their group section.  */
14060   if (elf_sec_group (sec) != NULL)
14061     return FALSE;
14062
14063   /* For a SHT_GROUP section, use the group signature as the key.  */
14064   name = sec->name;
14065   if ((flags & SEC_GROUP) != 0
14066       && elf_next_in_group (sec) != NULL
14067       && elf_group_name (elf_next_in_group (sec)) != NULL)
14068     key = elf_group_name (elf_next_in_group (sec));
14069   else
14070     {
14071       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
14072       if (CONST_STRNEQ (name, ".gnu.linkonce.")
14073           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
14074         key++;
14075       else
14076         /* Must be a user linkonce section that doesn't follow gcc's
14077            naming convention.  In this case we won't be matching
14078            single member groups.  */
14079         key = name;
14080     }
14081
14082   already_linked_list = bfd_section_already_linked_table_lookup (key);
14083
14084   for (l = already_linked_list->entry; l != NULL; l = l->next)
14085     {
14086       /* We may have 2 different types of sections on the list: group
14087          sections with a signature of <key> (<key> is some string),
14088          and linkonce sections named .gnu.linkonce.<type>.<key>.
14089          Match like sections.  LTO plugin sections are an exception.
14090          They are always named .gnu.linkonce.t.<key> and match either
14091          type of section.  */
14092       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
14093            && ((flags & SEC_GROUP) != 0
14094                || strcmp (name, l->sec->name) == 0))
14095           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
14096         {
14097           /* The section has already been linked.  See if we should
14098              issue a warning.  */
14099           if (!_bfd_handle_already_linked (sec, l, info))
14100             return FALSE;
14101
14102           if (flags & SEC_GROUP)
14103             {
14104               asection *first = elf_next_in_group (sec);
14105               asection *s = first;
14106
14107               while (s != NULL)
14108                 {
14109                   s->output_section = bfd_abs_section_ptr;
14110                   /* Record which group discards it.  */
14111                   s->kept_section = l->sec;
14112                   s = elf_next_in_group (s);
14113                   /* These lists are circular.  */
14114                   if (s == first)
14115                     break;
14116                 }
14117             }
14118
14119           return TRUE;
14120         }
14121     }
14122
14123   /* A single member comdat group section may be discarded by a
14124      linkonce section and vice versa.  */
14125   if ((flags & SEC_GROUP) != 0)
14126     {
14127       asection *first = elf_next_in_group (sec);
14128
14129       if (first != NULL && elf_next_in_group (first) == first)
14130         /* Check this single member group against linkonce sections.  */
14131         for (l = already_linked_list->entry; l != NULL; l = l->next)
14132           if ((l->sec->flags & SEC_GROUP) == 0
14133               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
14134             {
14135               first->output_section = bfd_abs_section_ptr;
14136               first->kept_section = l->sec;
14137               sec->output_section = bfd_abs_section_ptr;
14138               break;
14139             }
14140     }
14141   else
14142     /* Check this linkonce section against single member groups.  */
14143     for (l = already_linked_list->entry; l != NULL; l = l->next)
14144       if (l->sec->flags & SEC_GROUP)
14145         {
14146           asection *first = elf_next_in_group (l->sec);
14147
14148           if (first != NULL
14149               && elf_next_in_group (first) == first
14150               && bfd_elf_match_symbols_in_sections (first, sec, info))
14151             {
14152               sec->output_section = bfd_abs_section_ptr;
14153               sec->kept_section = first;
14154               break;
14155             }
14156         }
14157
14158   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
14159      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
14160      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
14161      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
14162      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
14163      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
14164      `.gnu.linkonce.t.F' section from a different bfd not requiring any
14165      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
14166      The reverse order cannot happen as there is never a bfd with only the
14167      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
14168      matter as here were are looking only for cross-bfd sections.  */
14169
14170   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
14171     for (l = already_linked_list->entry; l != NULL; l = l->next)
14172       if ((l->sec->flags & SEC_GROUP) == 0
14173           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
14174         {
14175           if (abfd != l->sec->owner)
14176             sec->output_section = bfd_abs_section_ptr;
14177           break;
14178         }
14179
14180   /* This is the first section with this name.  Record it.  */
14181   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
14182     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
14183   return sec->output_section == bfd_abs_section_ptr;
14184 }
14185
14186 bfd_boolean
14187 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
14188 {
14189   return sym->st_shndx == SHN_COMMON;
14190 }
14191
14192 unsigned int
14193 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
14194 {
14195   return SHN_COMMON;
14196 }
14197
14198 asection *
14199 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
14200 {
14201   return bfd_com_section_ptr;
14202 }
14203
14204 bfd_vma
14205 _bfd_elf_default_got_elt_size (bfd *abfd,
14206                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
14207                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
14208                                bfd *ibfd ATTRIBUTE_UNUSED,
14209                                unsigned long symndx ATTRIBUTE_UNUSED)
14210 {
14211   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14212   return bed->s->arch_size / 8;
14213 }
14214
14215 /* Routines to support the creation of dynamic relocs.  */
14216
14217 /* Returns the name of the dynamic reloc section associated with SEC.  */
14218
14219 static const char *
14220 get_dynamic_reloc_section_name (bfd *       abfd,
14221                                 asection *  sec,
14222                                 bfd_boolean is_rela)
14223 {
14224   char *name;
14225   const char *old_name = bfd_get_section_name (NULL, sec);
14226   const char *prefix = is_rela ? ".rela" : ".rel";
14227
14228   if (old_name == NULL)
14229     return NULL;
14230
14231   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
14232   sprintf (name, "%s%s", prefix, old_name);
14233
14234   return name;
14235 }
14236
14237 /* Returns the dynamic reloc section associated with SEC.
14238    If necessary compute the name of the dynamic reloc section based
14239    on SEC's name (looked up in ABFD's string table) and the setting
14240    of IS_RELA.  */
14241
14242 asection *
14243 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
14244                                     asection *  sec,
14245                                     bfd_boolean is_rela)
14246 {
14247   asection * reloc_sec = elf_section_data (sec)->sreloc;
14248
14249   if (reloc_sec == NULL)
14250     {
14251       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14252
14253       if (name != NULL)
14254         {
14255           reloc_sec = bfd_get_linker_section (abfd, name);
14256
14257           if (reloc_sec != NULL)
14258             elf_section_data (sec)->sreloc = reloc_sec;
14259         }
14260     }
14261
14262   return reloc_sec;
14263 }
14264
14265 /* Returns the dynamic reloc section associated with SEC.  If the
14266    section does not exist it is created and attached to the DYNOBJ
14267    bfd and stored in the SRELOC field of SEC's elf_section_data
14268    structure.
14269
14270    ALIGNMENT is the alignment for the newly created section and
14271    IS_RELA defines whether the name should be .rela.<SEC's name>
14272    or .rel.<SEC's name>.  The section name is looked up in the
14273    string table associated with ABFD.  */
14274
14275 asection *
14276 _bfd_elf_make_dynamic_reloc_section (asection *sec,
14277                                      bfd *dynobj,
14278                                      unsigned int alignment,
14279                                      bfd *abfd,
14280                                      bfd_boolean is_rela)
14281 {
14282   asection * reloc_sec = elf_section_data (sec)->sreloc;
14283
14284   if (reloc_sec == NULL)
14285     {
14286       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14287
14288       if (name == NULL)
14289         return NULL;
14290
14291       reloc_sec = bfd_get_linker_section (dynobj, name);
14292
14293       if (reloc_sec == NULL)
14294         {
14295           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
14296                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
14297           if ((sec->flags & SEC_ALLOC) != 0)
14298             flags |= SEC_ALLOC | SEC_LOAD;
14299
14300           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
14301           if (reloc_sec != NULL)
14302             {
14303               /* _bfd_elf_get_sec_type_attr chooses a section type by
14304                  name.  Override as it may be wrong, eg. for a user
14305                  section named "auto" we'll get ".relauto" which is
14306                  seen to be a .rela section.  */
14307               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
14308               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
14309                 reloc_sec = NULL;
14310             }
14311         }
14312
14313       elf_section_data (sec)->sreloc = reloc_sec;
14314     }
14315
14316   return reloc_sec;
14317 }
14318
14319 /* Copy the ELF symbol type and other attributes for a linker script
14320    assignment from HSRC to HDEST.  Generally this should be treated as
14321    if we found a strong non-dynamic definition for HDEST (except that
14322    ld ignores multiple definition errors).  */
14323 void
14324 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
14325                                      struct bfd_link_hash_entry *hdest,
14326                                      struct bfd_link_hash_entry *hsrc)
14327 {
14328   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
14329   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
14330   Elf_Internal_Sym isym;
14331
14332   ehdest->type = ehsrc->type;
14333   ehdest->target_internal = ehsrc->target_internal;
14334
14335   isym.st_other = ehsrc->other;
14336   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
14337 }
14338
14339 /* Append a RELA relocation REL to section S in BFD.  */
14340
14341 void
14342 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14343 {
14344   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14345   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
14346   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
14347   bed->s->swap_reloca_out (abfd, rel, loc);
14348 }
14349
14350 /* Append a REL relocation REL to section S in BFD.  */
14351
14352 void
14353 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14354 {
14355   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14356   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
14357   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
14358   bed->s->swap_reloc_out (abfd, rel, loc);
14359 }
14360
14361 /* Define __start, __stop, .startof. or .sizeof. symbol.  */
14362
14363 struct bfd_link_hash_entry *
14364 bfd_elf_define_start_stop (struct bfd_link_info *info,
14365                            const char *symbol, asection *sec)
14366 {
14367   struct elf_link_hash_entry *h;
14368
14369   h = elf_link_hash_lookup (elf_hash_table (info), symbol,
14370                             FALSE, FALSE, TRUE);
14371   if (h != NULL
14372       && (h->root.type == bfd_link_hash_undefined
14373           || h->root.type == bfd_link_hash_undefweak
14374           || ((h->ref_regular || h->def_dynamic) && !h->def_regular)))
14375     {
14376       bfd_boolean was_dynamic = h->ref_dynamic || h->def_dynamic;
14377       h->root.type = bfd_link_hash_defined;
14378       h->root.u.def.section = sec;
14379       h->root.u.def.value = 0;
14380       h->def_regular = 1;
14381       h->def_dynamic = 0;
14382       h->start_stop = 1;
14383       h->u2.start_stop_section = sec;
14384       if (symbol[0] == '.')
14385         {
14386           /* .startof. and .sizeof. symbols are local.  */
14387           const struct elf_backend_data *bed;
14388           bed = get_elf_backend_data (info->output_bfd);
14389           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
14390         }
14391       else
14392         {
14393           if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
14394             h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_PROTECTED;
14395           if (was_dynamic)
14396             bfd_elf_link_record_dynamic_symbol (info, h);
14397         }
14398       return &h->root;
14399     }
14400   return NULL;
14401 }