Automatic date update in version.in
[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                 && elf_object_id (ibfd) == elf_hash_table_id (hash_table)
227                 && !((s = ibfd->sections) != NULL
228                      && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS))
229               {
230                 abfd = ibfd;
231                 break;
232               }
233         }
234       hash_table->dynobj = abfd;
235     }
236
237   if (hash_table->dynstr == NULL)
238     {
239       hash_table->dynstr = _bfd_elf_strtab_init ();
240       if (hash_table->dynstr == NULL)
241         return FALSE;
242     }
243   return TRUE;
244 }
245
246 /* Create some sections which will be filled in with dynamic linking
247    information.  ABFD is an input file which requires dynamic sections
248    to be created.  The dynamic sections take up virtual memory space
249    when the final executable is run, so we need to create them before
250    addresses are assigned to the output sections.  We work out the
251    actual contents and size of these sections later.  */
252
253 bfd_boolean
254 _bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
255 {
256   flagword flags;
257   asection *s;
258   const struct elf_backend_data *bed;
259   struct elf_link_hash_entry *h;
260
261   if (! is_elf_hash_table (info->hash))
262     return FALSE;
263
264   if (elf_hash_table (info)->dynamic_sections_created)
265     return TRUE;
266
267   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
268     return FALSE;
269
270   abfd = elf_hash_table (info)->dynobj;
271   bed = get_elf_backend_data (abfd);
272
273   flags = bed->dynamic_sec_flags;
274
275   /* A dynamically linked executable has a .interp section, but a
276      shared library does not.  */
277   if (bfd_link_executable (info) && !info->nointerp)
278     {
279       s = bfd_make_section_anyway_with_flags (abfd, ".interp",
280                                               flags | SEC_READONLY);
281       if (s == NULL)
282         return FALSE;
283     }
284
285   /* Create sections to hold version informations.  These are removed
286      if they are not needed.  */
287   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_d",
288                                           flags | SEC_READONLY);
289   if (s == NULL
290       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
291     return FALSE;
292
293   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version",
294                                           flags | SEC_READONLY);
295   if (s == NULL
296       || ! bfd_set_section_alignment (abfd, s, 1))
297     return FALSE;
298
299   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_r",
300                                           flags | SEC_READONLY);
301   if (s == NULL
302       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
303     return FALSE;
304
305   s = bfd_make_section_anyway_with_flags (abfd, ".dynsym",
306                                           flags | SEC_READONLY);
307   if (s == NULL
308       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
309     return FALSE;
310   elf_hash_table (info)->dynsym = s;
311
312   s = bfd_make_section_anyway_with_flags (abfd, ".dynstr",
313                                           flags | SEC_READONLY);
314   if (s == NULL)
315     return FALSE;
316
317   s = bfd_make_section_anyway_with_flags (abfd, ".dynamic", flags);
318   if (s == NULL
319       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
320     return FALSE;
321
322   /* The special symbol _DYNAMIC is always set to the start of the
323      .dynamic section.  We could set _DYNAMIC in a linker script, but we
324      only want to define it if we are, in fact, creating a .dynamic
325      section.  We don't want to define it if there is no .dynamic
326      section, since on some ELF platforms the start up code examines it
327      to decide how to initialize the process.  */
328   h = _bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC");
329   elf_hash_table (info)->hdynamic = h;
330   if (h == NULL)
331     return FALSE;
332
333   if (info->emit_hash)
334     {
335       s = bfd_make_section_anyway_with_flags (abfd, ".hash",
336                                               flags | SEC_READONLY);
337       if (s == NULL
338           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
339         return FALSE;
340       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
341     }
342
343   if (info->emit_gnu_hash)
344     {
345       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
346                                               flags | SEC_READONLY);
347       if (s == NULL
348           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
349         return FALSE;
350       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
351          4 32-bit words followed by variable count of 64-bit words, then
352          variable count of 32-bit words.  */
353       if (bed->s->arch_size == 64)
354         elf_section_data (s)->this_hdr.sh_entsize = 0;
355       else
356         elf_section_data (s)->this_hdr.sh_entsize = 4;
357     }
358
359   /* Let the backend create the rest of the sections.  This lets the
360      backend set the right flags.  The backend will normally create
361      the .got and .plt sections.  */
362   if (bed->elf_backend_create_dynamic_sections == NULL
363       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
364     return FALSE;
365
366   elf_hash_table (info)->dynamic_sections_created = TRUE;
367
368   return TRUE;
369 }
370
371 /* Create dynamic sections when linking against a dynamic object.  */
372
373 bfd_boolean
374 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
375 {
376   flagword flags, pltflags;
377   struct elf_link_hash_entry *h;
378   asection *s;
379   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
380   struct elf_link_hash_table *htab = elf_hash_table (info);
381
382   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
383      .rel[a].bss sections.  */
384   flags = bed->dynamic_sec_flags;
385
386   pltflags = flags;
387   if (bed->plt_not_loaded)
388     /* We do not clear SEC_ALLOC here because we still want the OS to
389        allocate space for the section; it's just that there's nothing
390        to read in from the object file.  */
391     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
392   else
393     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
394   if (bed->plt_readonly)
395     pltflags |= SEC_READONLY;
396
397   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
398   if (s == NULL
399       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
400     return FALSE;
401   htab->splt = s;
402
403   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
404      .plt section.  */
405   if (bed->want_plt_sym)
406     {
407       h = _bfd_elf_define_linkage_sym (abfd, info, s,
408                                        "_PROCEDURE_LINKAGE_TABLE_");
409       elf_hash_table (info)->hplt = h;
410       if (h == NULL)
411         return FALSE;
412     }
413
414   s = bfd_make_section_anyway_with_flags (abfd,
415                                           (bed->rela_plts_and_copies_p
416                                            ? ".rela.plt" : ".rel.plt"),
417                                           flags | SEC_READONLY);
418   if (s == NULL
419       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
420     return FALSE;
421   htab->srelplt = s;
422
423   if (! _bfd_elf_create_got_section (abfd, info))
424     return FALSE;
425
426   if (bed->want_dynbss)
427     {
428       /* The .dynbss section is a place to put symbols which are defined
429          by dynamic objects, are referenced by regular objects, and are
430          not functions.  We must allocate space for them in the process
431          image and use a R_*_COPY reloc to tell the dynamic linker to
432          initialize them at run time.  The linker script puts the .dynbss
433          section into the .bss section of the final image.  */
434       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
435                                               SEC_ALLOC | SEC_LINKER_CREATED);
436       if (s == NULL)
437         return FALSE;
438       htab->sdynbss = s;
439
440       if (bed->want_dynrelro)
441         {
442           /* Similarly, but for symbols that were originally in read-only
443              sections.  This section doesn't really need to have contents,
444              but make it like other .data.rel.ro sections.  */
445           s = bfd_make_section_anyway_with_flags (abfd, ".data.rel.ro",
446                                                   flags);
447           if (s == NULL)
448             return FALSE;
449           htab->sdynrelro = s;
450         }
451
452       /* The .rel[a].bss section holds copy relocs.  This section is not
453          normally needed.  We need to create it here, though, so that the
454          linker will map it to an output section.  We can't just create it
455          only if we need it, because we will not know whether we need it
456          until we have seen all the input files, and the first time the
457          main linker code calls BFD after examining all the input files
458          (size_dynamic_sections) the input sections have already been
459          mapped to the output sections.  If the section turns out not to
460          be needed, we can discard it later.  We will never need this
461          section when generating a shared object, since they do not use
462          copy relocs.  */
463       if (bfd_link_executable (info))
464         {
465           s = bfd_make_section_anyway_with_flags (abfd,
466                                                   (bed->rela_plts_and_copies_p
467                                                    ? ".rela.bss" : ".rel.bss"),
468                                                   flags | SEC_READONLY);
469           if (s == NULL
470               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
471             return FALSE;
472           htab->srelbss = s;
473
474           if (bed->want_dynrelro)
475             {
476               s = (bfd_make_section_anyway_with_flags
477                    (abfd, (bed->rela_plts_and_copies_p
478                            ? ".rela.data.rel.ro" : ".rel.data.rel.ro"),
479                     flags | SEC_READONLY));
480               if (s == NULL
481                   || ! bfd_set_section_alignment (abfd, s,
482                                                   bed->s->log_file_align))
483                 return FALSE;
484               htab->sreldynrelro = s;
485             }
486         }
487     }
488
489   return TRUE;
490 }
491 \f
492 /* Record a new dynamic symbol.  We record the dynamic symbols as we
493    read the input files, since we need to have a list of all of them
494    before we can determine the final sizes of the output sections.
495    Note that we may actually call this function even though we are not
496    going to output any dynamic symbols; in some cases we know that a
497    symbol should be in the dynamic symbol table, but only if there is
498    one.  */
499
500 bfd_boolean
501 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
502                                     struct elf_link_hash_entry *h)
503 {
504   if (h->dynindx == -1)
505     {
506       struct elf_strtab_hash *dynstr;
507       char *p;
508       const char *name;
509       size_t indx;
510
511       /* XXX: The ABI draft says the linker must turn hidden and
512          internal symbols into STB_LOCAL symbols when producing the
513          DSO. However, if ld.so honors st_other in the dynamic table,
514          this would not be necessary.  */
515       switch (ELF_ST_VISIBILITY (h->other))
516         {
517         case STV_INTERNAL:
518         case STV_HIDDEN:
519           if (h->root.type != bfd_link_hash_undefined
520               && h->root.type != bfd_link_hash_undefweak)
521             {
522               h->forced_local = 1;
523               if (!elf_hash_table (info)->is_relocatable_executable)
524                 return TRUE;
525             }
526
527         default:
528           break;
529         }
530
531       h->dynindx = elf_hash_table (info)->dynsymcount;
532       ++elf_hash_table (info)->dynsymcount;
533
534       dynstr = elf_hash_table (info)->dynstr;
535       if (dynstr == NULL)
536         {
537           /* Create a strtab to hold the dynamic symbol names.  */
538           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
539           if (dynstr == NULL)
540             return FALSE;
541         }
542
543       /* We don't put any version information in the dynamic string
544          table.  */
545       name = h->root.root.string;
546       p = strchr (name, ELF_VER_CHR);
547       if (p != NULL)
548         /* We know that the p points into writable memory.  In fact,
549            there are only a few symbols that have read-only names, being
550            those like _GLOBAL_OFFSET_TABLE_ that are created specially
551            by the backends.  Most symbols will have names pointing into
552            an ELF string table read from a file, or to objalloc memory.  */
553         *p = 0;
554
555       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
556
557       if (p != NULL)
558         *p = ELF_VER_CHR;
559
560       if (indx == (size_t) -1)
561         return FALSE;
562       h->dynstr_index = indx;
563     }
564
565   return TRUE;
566 }
567 \f
568 /* Mark a symbol dynamic.  */
569
570 static void
571 bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
572                                   struct elf_link_hash_entry *h,
573                                   Elf_Internal_Sym *sym)
574 {
575   struct bfd_elf_dynamic_list *d = info->dynamic_list;
576
577   /* It may be called more than once on the same H.  */
578   if(h->dynamic || bfd_link_relocatable (info))
579     return;
580
581   if ((info->dynamic_data
582        && (h->type == STT_OBJECT
583            || h->type == STT_COMMON
584            || (sym != NULL
585                && (ELF_ST_TYPE (sym->st_info) == STT_OBJECT
586                    || ELF_ST_TYPE (sym->st_info) == STT_COMMON))))
587       || (d != NULL
588           && h->non_elf
589           && (*d->match) (&d->head, NULL, h->root.root.string)))
590     {
591       h->dynamic = 1;
592       /* NB: If a symbol is made dynamic by --dynamic-list, it has
593          non-IR reference.  */
594       h->root.non_ir_ref_dynamic = 1;
595     }
596 }
597
598 /* Record an assignment to a symbol made by a linker script.  We need
599    this in case some dynamic object refers to this symbol.  */
600
601 bfd_boolean
602 bfd_elf_record_link_assignment (bfd *output_bfd,
603                                 struct bfd_link_info *info,
604                                 const char *name,
605                                 bfd_boolean provide,
606                                 bfd_boolean hidden)
607 {
608   struct elf_link_hash_entry *h, *hv;
609   struct elf_link_hash_table *htab;
610   const struct elf_backend_data *bed;
611
612   if (!is_elf_hash_table (info->hash))
613     return TRUE;
614
615   htab = elf_hash_table (info);
616   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
617   if (h == NULL)
618     return provide;
619
620   if (h->root.type == bfd_link_hash_warning)
621     h = (struct elf_link_hash_entry *) h->root.u.i.link;
622
623   if (h->versioned == unknown)
624     {
625       /* Set versioned if symbol version is unknown.  */
626       char *version = strrchr (name, ELF_VER_CHR);
627       if (version)
628         {
629           if (version > name && version[-1] != ELF_VER_CHR)
630             h->versioned = versioned_hidden;
631           else
632             h->versioned = versioned;
633         }
634     }
635
636   /* Symbols defined in a linker script but not referenced anywhere
637      else will have non_elf set.  */
638   if (h->non_elf)
639     {
640       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
641       h->non_elf = 0;
642     }
643
644   switch (h->root.type)
645     {
646     case bfd_link_hash_defined:
647     case bfd_link_hash_defweak:
648     case bfd_link_hash_common:
649       break;
650     case bfd_link_hash_undefweak:
651     case bfd_link_hash_undefined:
652       /* Since we're defining the symbol, don't let it seem to have not
653          been defined.  record_dynamic_symbol and size_dynamic_sections
654          may depend on this.  */
655       h->root.type = bfd_link_hash_new;
656       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
657         bfd_link_repair_undef_list (&htab->root);
658       break;
659     case bfd_link_hash_new:
660       break;
661     case bfd_link_hash_indirect:
662       /* We had a versioned symbol in a dynamic library.  We make the
663          the versioned symbol point to this one.  */
664       bed = get_elf_backend_data (output_bfd);
665       hv = h;
666       while (hv->root.type == bfd_link_hash_indirect
667              || hv->root.type == bfd_link_hash_warning)
668         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
669       /* We don't need to update h->root.u since linker will set them
670          later.  */
671       h->root.type = bfd_link_hash_undefined;
672       hv->root.type = bfd_link_hash_indirect;
673       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
674       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
675       break;
676     default:
677       BFD_FAIL ();
678       return FALSE;
679     }
680
681   /* If this symbol is being provided by the linker script, and it is
682      currently defined by a dynamic object, but not by a regular
683      object, then mark it as undefined so that the generic linker will
684      force the correct value.  */
685   if (provide
686       && h->def_dynamic
687       && !h->def_regular)
688     h->root.type = bfd_link_hash_undefined;
689
690   /* If this symbol is currently defined by a dynamic object, but not
691      by a regular object, then clear out any version information because
692      the symbol will not be associated with the dynamic object any
693      more.  */
694   if (h->def_dynamic && !h->def_regular)
695     h->verinfo.verdef = NULL;
696
697   /* Make sure this symbol is not garbage collected.  */
698   h->mark = 1;
699
700   h->def_regular = 1;
701
702   if (hidden)
703     {
704       bed = get_elf_backend_data (output_bfd);
705       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
706         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
707       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
708     }
709
710   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
711      and executables.  */
712   if (!bfd_link_relocatable (info)
713       && h->dynindx != -1
714       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
715           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
716     h->forced_local = 1;
717
718   if ((h->def_dynamic
719        || h->ref_dynamic
720        || bfd_link_dll (info)
721        || elf_hash_table (info)->is_relocatable_executable)
722       && !h->forced_local
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             && elf_hash_table (info)->dynamic_relocs
956             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
957           {
958             ++dynsymcount;
959             if (do_sec)
960               elf_section_data (p)->dynindx = dynsymcount;
961           }
962         else if (do_sec)
963           elf_section_data (p)->dynindx = 0;
964     }
965   if (do_sec)
966     *section_sym_count = dynsymcount;
967
968   elf_link_hash_traverse (elf_hash_table (info),
969                           elf_link_renumber_local_hash_table_dynsyms,
970                           &dynsymcount);
971
972   if (elf_hash_table (info)->dynlocal)
973     {
974       struct elf_link_local_dynamic_entry *p;
975       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
976         p->dynindx = ++dynsymcount;
977     }
978   elf_hash_table (info)->local_dynsymcount = dynsymcount;
979
980   elf_link_hash_traverse (elf_hash_table (info),
981                           elf_link_renumber_hash_table_dynsyms,
982                           &dynsymcount);
983
984   /* There is an unused NULL entry at the head of the table which we
985      must account for in our count even if the table is empty since it
986      is intended for the mandatory DT_SYMTAB tag (.dynsym section) in
987      .dynamic section.  */
988   dynsymcount++;
989
990   elf_hash_table (info)->dynsymcount = dynsymcount;
991   return dynsymcount;
992 }
993
994 /* Merge st_other field.  */
995
996 static void
997 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
998                     const Elf_Internal_Sym *isym, asection *sec,
999                     bfd_boolean definition, bfd_boolean dynamic)
1000 {
1001   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
1002
1003   /* If st_other has a processor-specific meaning, specific
1004      code might be needed here.  */
1005   if (bed->elf_backend_merge_symbol_attribute)
1006     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
1007                                                 dynamic);
1008
1009   if (!dynamic)
1010     {
1011       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
1012       unsigned hvis = ELF_ST_VISIBILITY (h->other);
1013
1014       /* Keep the most constraining visibility.  Leave the remainder
1015          of the st_other field to elf_backend_merge_symbol_attribute.  */
1016       if (symvis - 1 < hvis - 1)
1017         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
1018     }
1019   else if (definition
1020            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
1021            && (sec->flags & SEC_READONLY) == 0)
1022     h->protected_def = 1;
1023 }
1024
1025 /* This function is called when we want to merge a new symbol with an
1026    existing symbol.  It handles the various cases which arise when we
1027    find a definition in a dynamic object, or when there is already a
1028    definition in a dynamic object.  The new symbol is described by
1029    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
1030    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
1031    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
1032    of an old common symbol.  We set OVERRIDE if the old symbol is
1033    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
1034    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
1035    to change.  By OK to change, we mean that we shouldn't warn if the
1036    type or size does change.  */
1037
1038 static bfd_boolean
1039 _bfd_elf_merge_symbol (bfd *abfd,
1040                        struct bfd_link_info *info,
1041                        const char *name,
1042                        Elf_Internal_Sym *sym,
1043                        asection **psec,
1044                        bfd_vma *pvalue,
1045                        struct elf_link_hash_entry **sym_hash,
1046                        bfd **poldbfd,
1047                        bfd_boolean *pold_weak,
1048                        unsigned int *pold_alignment,
1049                        bfd_boolean *skip,
1050                        bfd_boolean *override,
1051                        bfd_boolean *type_change_ok,
1052                        bfd_boolean *size_change_ok,
1053                        bfd_boolean *matched)
1054 {
1055   asection *sec, *oldsec;
1056   struct elf_link_hash_entry *h;
1057   struct elf_link_hash_entry *hi;
1058   struct elf_link_hash_entry *flip;
1059   int bind;
1060   bfd *oldbfd;
1061   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
1062   bfd_boolean newweak, oldweak, newfunc, oldfunc;
1063   const struct elf_backend_data *bed;
1064   char *new_version;
1065   bfd_boolean default_sym = *matched;
1066
1067   *skip = FALSE;
1068   *override = FALSE;
1069
1070   sec = *psec;
1071   bind = ELF_ST_BIND (sym->st_info);
1072
1073   if (! bfd_is_und_section (sec))
1074     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
1075   else
1076     h = ((struct elf_link_hash_entry *)
1077          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
1078   if (h == NULL)
1079     return FALSE;
1080   *sym_hash = h;
1081
1082   bed = get_elf_backend_data (abfd);
1083
1084   /* NEW_VERSION is the symbol version of the new symbol.  */
1085   if (h->versioned != unversioned)
1086     {
1087       /* Symbol version is unknown or versioned.  */
1088       new_version = strrchr (name, ELF_VER_CHR);
1089       if (new_version)
1090         {
1091           if (h->versioned == unknown)
1092             {
1093               if (new_version > name && new_version[-1] != ELF_VER_CHR)
1094                 h->versioned = versioned_hidden;
1095               else
1096                 h->versioned = versioned;
1097             }
1098           new_version += 1;
1099           if (new_version[0] == '\0')
1100             new_version = NULL;
1101         }
1102       else
1103         h->versioned = unversioned;
1104     }
1105   else
1106     new_version = NULL;
1107
1108   /* For merging, we only care about real symbols.  But we need to make
1109      sure that indirect symbol dynamic flags are updated.  */
1110   hi = h;
1111   while (h->root.type == bfd_link_hash_indirect
1112          || h->root.type == bfd_link_hash_warning)
1113     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1114
1115   if (!*matched)
1116     {
1117       if (hi == h || h->root.type == bfd_link_hash_new)
1118         *matched = TRUE;
1119       else
1120         {
1121           /* OLD_HIDDEN is true if the existing symbol is only visible
1122              to the symbol with the same symbol version.  NEW_HIDDEN is
1123              true if the new symbol is only visible to the symbol with
1124              the same symbol version.  */
1125           bfd_boolean old_hidden = h->versioned == versioned_hidden;
1126           bfd_boolean new_hidden = hi->versioned == versioned_hidden;
1127           if (!old_hidden && !new_hidden)
1128             /* The new symbol matches the existing symbol if both
1129                aren't hidden.  */
1130             *matched = TRUE;
1131           else
1132             {
1133               /* OLD_VERSION is the symbol version of the existing
1134                  symbol. */
1135               char *old_version;
1136
1137               if (h->versioned >= versioned)
1138                 old_version = strrchr (h->root.root.string,
1139                                        ELF_VER_CHR) + 1;
1140               else
1141                  old_version = NULL;
1142
1143               /* The new symbol matches the existing symbol if they
1144                  have the same symbol version.  */
1145               *matched = (old_version == new_version
1146                           || (old_version != NULL
1147                               && new_version != NULL
1148                               && strcmp (old_version, new_version) == 0));
1149             }
1150         }
1151     }
1152
1153   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
1154      existing symbol.  */
1155
1156   oldbfd = NULL;
1157   oldsec = NULL;
1158   switch (h->root.type)
1159     {
1160     default:
1161       break;
1162
1163     case bfd_link_hash_undefined:
1164     case bfd_link_hash_undefweak:
1165       oldbfd = h->root.u.undef.abfd;
1166       break;
1167
1168     case bfd_link_hash_defined:
1169     case bfd_link_hash_defweak:
1170       oldbfd = h->root.u.def.section->owner;
1171       oldsec = h->root.u.def.section;
1172       break;
1173
1174     case bfd_link_hash_common:
1175       oldbfd = h->root.u.c.p->section->owner;
1176       oldsec = h->root.u.c.p->section;
1177       if (pold_alignment)
1178         *pold_alignment = h->root.u.c.p->alignment_power;
1179       break;
1180     }
1181   if (poldbfd && *poldbfd == NULL)
1182     *poldbfd = oldbfd;
1183
1184   /* Differentiate strong and weak symbols.  */
1185   newweak = bind == STB_WEAK;
1186   oldweak = (h->root.type == bfd_link_hash_defweak
1187              || h->root.type == bfd_link_hash_undefweak);
1188   if (pold_weak)
1189     *pold_weak = oldweak;
1190
1191   /* We have to check it for every instance since the first few may be
1192      references and not all compilers emit symbol type for undefined
1193      symbols.  */
1194   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
1195
1196   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1197      respectively, is from a dynamic object.  */
1198
1199   newdyn = (abfd->flags & DYNAMIC) != 0;
1200
1201   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
1202      syms and defined syms in dynamic libraries respectively.
1203      ref_dynamic on the other hand can be set for a symbol defined in
1204      a dynamic library, and def_dynamic may not be set;  When the
1205      definition in a dynamic lib is overridden by a definition in the
1206      executable use of the symbol in the dynamic lib becomes a
1207      reference to the executable symbol.  */
1208   if (newdyn)
1209     {
1210       if (bfd_is_und_section (sec))
1211         {
1212           if (bind != STB_WEAK)
1213             {
1214               h->ref_dynamic_nonweak = 1;
1215               hi->ref_dynamic_nonweak = 1;
1216             }
1217         }
1218       else
1219         {
1220           /* Update the existing symbol only if they match. */
1221           if (*matched)
1222             h->dynamic_def = 1;
1223           hi->dynamic_def = 1;
1224         }
1225     }
1226
1227   /* If we just created the symbol, mark it as being an ELF symbol.
1228      Other than that, there is nothing to do--there is no merge issue
1229      with a newly defined symbol--so we just return.  */
1230
1231   if (h->root.type == bfd_link_hash_new)
1232     {
1233       h->non_elf = 0;
1234       return TRUE;
1235     }
1236
1237   /* In cases involving weak versioned symbols, we may wind up trying
1238      to merge a symbol with itself.  Catch that here, to avoid the
1239      confusion that results if we try to override a symbol with
1240      itself.  The additional tests catch cases like
1241      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1242      dynamic object, which we do want to handle here.  */
1243   if (abfd == oldbfd
1244       && (newweak || oldweak)
1245       && ((abfd->flags & DYNAMIC) == 0
1246           || !h->def_regular))
1247     return TRUE;
1248
1249   olddyn = FALSE;
1250   if (oldbfd != NULL)
1251     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1252   else if (oldsec != NULL)
1253     {
1254       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1255          indices used by MIPS ELF.  */
1256       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1257     }
1258
1259   /* Handle a case where plugin_notice won't be called and thus won't
1260      set the non_ir_ref flags on the first pass over symbols.  */
1261   if (oldbfd != NULL
1262       && (oldbfd->flags & BFD_PLUGIN) != (abfd->flags & BFD_PLUGIN)
1263       && newdyn != olddyn)
1264     {
1265       h->root.non_ir_ref_dynamic = TRUE;
1266       hi->root.non_ir_ref_dynamic = TRUE;
1267     }
1268
1269   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1270      respectively, appear to be a definition rather than reference.  */
1271
1272   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1273
1274   olddef = (h->root.type != bfd_link_hash_undefined
1275             && h->root.type != bfd_link_hash_undefweak
1276             && h->root.type != bfd_link_hash_common);
1277
1278   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1279      respectively, appear to be a function.  */
1280
1281   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1282              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1283
1284   oldfunc = (h->type != STT_NOTYPE
1285              && bed->is_function_type (h->type));
1286
1287   if (!(newfunc && oldfunc)
1288       && ELF_ST_TYPE (sym->st_info) != h->type
1289       && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1290       && h->type != STT_NOTYPE
1291       && (newdef || bfd_is_com_section (sec))
1292       && (olddef || h->root.type == bfd_link_hash_common))
1293     {
1294       /* If creating a default indirect symbol ("foo" or "foo@") from
1295          a dynamic versioned definition ("foo@@") skip doing so if
1296          there is an existing regular definition with a different
1297          type.  We don't want, for example, a "time" variable in the
1298          executable overriding a "time" function in a shared library.  */
1299       if (newdyn
1300           && !olddyn)
1301         {
1302           *skip = TRUE;
1303           return TRUE;
1304         }
1305
1306       /* When adding a symbol from a regular object file after we have
1307          created indirect symbols, undo the indirection and any
1308          dynamic state.  */
1309       if (hi != h
1310           && !newdyn
1311           && olddyn)
1312         {
1313           h = hi;
1314           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1315           h->forced_local = 0;
1316           h->ref_dynamic = 0;
1317           h->def_dynamic = 0;
1318           h->dynamic_def = 0;
1319           if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1320             {
1321               h->root.type = bfd_link_hash_undefined;
1322               h->root.u.undef.abfd = abfd;
1323             }
1324           else
1325             {
1326               h->root.type = bfd_link_hash_new;
1327               h->root.u.undef.abfd = NULL;
1328             }
1329           return TRUE;
1330         }
1331     }
1332
1333   /* Check TLS symbols.  We don't check undefined symbols introduced
1334      by "ld -u" which have no type (and oldbfd NULL), and we don't
1335      check symbols from plugins because they also have no type.  */
1336   if (oldbfd != NULL
1337       && (oldbfd->flags & BFD_PLUGIN) == 0
1338       && (abfd->flags & BFD_PLUGIN) == 0
1339       && ELF_ST_TYPE (sym->st_info) != h->type
1340       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1341     {
1342       bfd *ntbfd, *tbfd;
1343       bfd_boolean ntdef, tdef;
1344       asection *ntsec, *tsec;
1345
1346       if (h->type == STT_TLS)
1347         {
1348           ntbfd = abfd;
1349           ntsec = sec;
1350           ntdef = newdef;
1351           tbfd = oldbfd;
1352           tsec = oldsec;
1353           tdef = olddef;
1354         }
1355       else
1356         {
1357           ntbfd = oldbfd;
1358           ntsec = oldsec;
1359           ntdef = olddef;
1360           tbfd = abfd;
1361           tsec = sec;
1362           tdef = newdef;
1363         }
1364
1365       if (tdef && ntdef)
1366         _bfd_error_handler
1367           /* xgettext:c-format */
1368           (_("%s: TLS definition in %pB section %pA "
1369              "mismatches non-TLS definition in %pB section %pA"),
1370            h->root.root.string, tbfd, tsec, ntbfd, ntsec);
1371       else if (!tdef && !ntdef)
1372         _bfd_error_handler
1373           /* xgettext:c-format */
1374           (_("%s: TLS reference in %pB "
1375              "mismatches non-TLS reference in %pB"),
1376            h->root.root.string, tbfd, ntbfd);
1377       else if (tdef)
1378         _bfd_error_handler
1379           /* xgettext:c-format */
1380           (_("%s: TLS definition in %pB section %pA "
1381              "mismatches non-TLS reference in %pB"),
1382            h->root.root.string, tbfd, tsec, ntbfd);
1383       else
1384         _bfd_error_handler
1385           /* xgettext:c-format */
1386           (_("%s: TLS reference in %pB "
1387              "mismatches non-TLS definition in %pB section %pA"),
1388            h->root.root.string, tbfd, ntbfd, ntsec);
1389
1390       bfd_set_error (bfd_error_bad_value);
1391       return FALSE;
1392     }
1393
1394   /* If the old symbol has non-default visibility, we ignore the new
1395      definition from a dynamic object.  */
1396   if (newdyn
1397       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1398       && !bfd_is_und_section (sec))
1399     {
1400       *skip = TRUE;
1401       /* Make sure this symbol is dynamic.  */
1402       h->ref_dynamic = 1;
1403       hi->ref_dynamic = 1;
1404       /* A protected symbol has external availability. Make sure it is
1405          recorded as dynamic.
1406
1407          FIXME: Should we check type and size for protected symbol?  */
1408       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1409         return bfd_elf_link_record_dynamic_symbol (info, h);
1410       else
1411         return TRUE;
1412     }
1413   else if (!newdyn
1414            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1415            && h->def_dynamic)
1416     {
1417       /* If the new symbol with non-default visibility comes from a
1418          relocatable file and the old definition comes from a dynamic
1419          object, we remove the old definition.  */
1420       if (hi->root.type == bfd_link_hash_indirect)
1421         {
1422           /* Handle the case where the old dynamic definition is
1423              default versioned.  We need to copy the symbol info from
1424              the symbol with default version to the normal one if it
1425              was referenced before.  */
1426           if (h->ref_regular)
1427             {
1428               hi->root.type = h->root.type;
1429               h->root.type = bfd_link_hash_indirect;
1430               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1431
1432               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1433               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1434                 {
1435                   /* If the new symbol is hidden or internal, completely undo
1436                      any dynamic link state.  */
1437                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1438                   h->forced_local = 0;
1439                   h->ref_dynamic = 0;
1440                 }
1441               else
1442                 h->ref_dynamic = 1;
1443
1444               h->def_dynamic = 0;
1445               /* FIXME: Should we check type and size for protected symbol?  */
1446               h->size = 0;
1447               h->type = 0;
1448
1449               h = hi;
1450             }
1451           else
1452             h = hi;
1453         }
1454
1455       /* If the old symbol was undefined before, then it will still be
1456          on the undefs list.  If the new symbol is undefined or
1457          common, we can't make it bfd_link_hash_new here, because new
1458          undefined or common symbols will be added to the undefs list
1459          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1460          added twice to the undefs list.  Also, if the new symbol is
1461          undefweak then we don't want to lose the strong undef.  */
1462       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1463         {
1464           h->root.type = bfd_link_hash_undefined;
1465           h->root.u.undef.abfd = abfd;
1466         }
1467       else
1468         {
1469           h->root.type = bfd_link_hash_new;
1470           h->root.u.undef.abfd = NULL;
1471         }
1472
1473       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1474         {
1475           /* If the new symbol is hidden or internal, completely undo
1476              any dynamic link state.  */
1477           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1478           h->forced_local = 0;
1479           h->ref_dynamic = 0;
1480         }
1481       else
1482         h->ref_dynamic = 1;
1483       h->def_dynamic = 0;
1484       /* FIXME: Should we check type and size for protected symbol?  */
1485       h->size = 0;
1486       h->type = 0;
1487       return TRUE;
1488     }
1489
1490   /* If a new weak symbol definition comes from a regular file and the
1491      old symbol comes from a dynamic library, we treat the new one as
1492      strong.  Similarly, an old weak symbol definition from a regular
1493      file is treated as strong when the new symbol comes from a dynamic
1494      library.  Further, an old weak symbol from a dynamic library is
1495      treated as strong if the new symbol is from a dynamic library.
1496      This reflects the way glibc's ld.so works.
1497
1498      Also allow a weak symbol to override a linker script symbol
1499      defined by an early pass over the script.  This is done so the
1500      linker knows the symbol is defined in an object file, for the
1501      DEFINED script function.
1502
1503      Do this before setting *type_change_ok or *size_change_ok so that
1504      we warn properly when dynamic library symbols are overridden.  */
1505
1506   if (newdef && !newdyn && (olddyn || h->root.ldscript_def))
1507     newweak = FALSE;
1508   if (olddef && newdyn)
1509     oldweak = FALSE;
1510
1511   /* Allow changes between different types of function symbol.  */
1512   if (newfunc && oldfunc)
1513     *type_change_ok = TRUE;
1514
1515   /* It's OK to change the type if either the existing symbol or the
1516      new symbol is weak.  A type change is also OK if the old symbol
1517      is undefined and the new symbol is defined.  */
1518
1519   if (oldweak
1520       || newweak
1521       || (newdef
1522           && h->root.type == bfd_link_hash_undefined))
1523     *type_change_ok = TRUE;
1524
1525   /* It's OK to change the size if either the existing symbol or the
1526      new symbol is weak, or if the old symbol is undefined.  */
1527
1528   if (*type_change_ok
1529       || h->root.type == bfd_link_hash_undefined)
1530     *size_change_ok = TRUE;
1531
1532   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1533      symbol, respectively, appears to be a common symbol in a dynamic
1534      object.  If a symbol appears in an uninitialized section, and is
1535      not weak, and is not a function, then it may be a common symbol
1536      which was resolved when the dynamic object was created.  We want
1537      to treat such symbols specially, because they raise special
1538      considerations when setting the symbol size: if the symbol
1539      appears as a common symbol in a regular object, and the size in
1540      the regular object is larger, we must make sure that we use the
1541      larger size.  This problematic case can always be avoided in C,
1542      but it must be handled correctly when using Fortran shared
1543      libraries.
1544
1545      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1546      likewise for OLDDYNCOMMON and OLDDEF.
1547
1548      Note that this test is just a heuristic, and that it is quite
1549      possible to have an uninitialized symbol in a shared object which
1550      is really a definition, rather than a common symbol.  This could
1551      lead to some minor confusion when the symbol really is a common
1552      symbol in some regular object.  However, I think it will be
1553      harmless.  */
1554
1555   if (newdyn
1556       && newdef
1557       && !newweak
1558       && (sec->flags & SEC_ALLOC) != 0
1559       && (sec->flags & SEC_LOAD) == 0
1560       && sym->st_size > 0
1561       && !newfunc)
1562     newdyncommon = TRUE;
1563   else
1564     newdyncommon = FALSE;
1565
1566   if (olddyn
1567       && olddef
1568       && h->root.type == bfd_link_hash_defined
1569       && h->def_dynamic
1570       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1571       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1572       && h->size > 0
1573       && !oldfunc)
1574     olddyncommon = TRUE;
1575   else
1576     olddyncommon = FALSE;
1577
1578   /* We now know everything about the old and new symbols.  We ask the
1579      backend to check if we can merge them.  */
1580   if (bed->merge_symbol != NULL)
1581     {
1582       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1583         return FALSE;
1584       sec = *psec;
1585     }
1586
1587   /* There are multiple definitions of a normal symbol.  Skip the
1588      default symbol as well as definition from an IR object.  */
1589   if (olddef && !olddyn && !oldweak && newdef && !newdyn && !newweak
1590       && !default_sym && h->def_regular
1591       && !(oldbfd != NULL
1592            && (oldbfd->flags & BFD_PLUGIN) != 0
1593            && (abfd->flags & BFD_PLUGIN) == 0))
1594     {
1595       /* Handle a multiple definition.  */
1596       (*info->callbacks->multiple_definition) (info, &h->root,
1597                                                abfd, sec, *pvalue);
1598       *skip = TRUE;
1599       return TRUE;
1600     }
1601
1602   /* If both the old and the new symbols look like common symbols in a
1603      dynamic object, set the size of the symbol to the larger of the
1604      two.  */
1605
1606   if (olddyncommon
1607       && newdyncommon
1608       && sym->st_size != h->size)
1609     {
1610       /* Since we think we have two common symbols, issue a multiple
1611          common warning if desired.  Note that we only warn if the
1612          size is different.  If the size is the same, we simply let
1613          the old symbol override the new one as normally happens with
1614          symbols defined in dynamic objects.  */
1615
1616       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1617                                            bfd_link_hash_common, sym->st_size);
1618       if (sym->st_size > h->size)
1619         h->size = sym->st_size;
1620
1621       *size_change_ok = TRUE;
1622     }
1623
1624   /* If we are looking at a dynamic object, and we have found a
1625      definition, we need to see if the symbol was already defined by
1626      some other object.  If so, we want to use the existing
1627      definition, and we do not want to report a multiple symbol
1628      definition error; we do this by clobbering *PSEC to be
1629      bfd_und_section_ptr.
1630
1631      We treat a common symbol as a definition if the symbol in the
1632      shared library is a function, since common symbols always
1633      represent variables; this can cause confusion in principle, but
1634      any such confusion would seem to indicate an erroneous program or
1635      shared library.  We also permit a common symbol in a regular
1636      object to override a weak symbol in a shared object.  */
1637
1638   if (newdyn
1639       && newdef
1640       && (olddef
1641           || (h->root.type == bfd_link_hash_common
1642               && (newweak || newfunc))))
1643     {
1644       *override = TRUE;
1645       newdef = FALSE;
1646       newdyncommon = FALSE;
1647
1648       *psec = sec = bfd_und_section_ptr;
1649       *size_change_ok = TRUE;
1650
1651       /* If we get here when the old symbol is a common symbol, then
1652          we are explicitly letting it override a weak symbol or
1653          function in a dynamic object, and we don't want to warn about
1654          a type change.  If the old symbol is a defined symbol, a type
1655          change warning may still be appropriate.  */
1656
1657       if (h->root.type == bfd_link_hash_common)
1658         *type_change_ok = TRUE;
1659     }
1660
1661   /* Handle the special case of an old common symbol merging with a
1662      new symbol which looks like a common symbol in a shared object.
1663      We change *PSEC and *PVALUE to make the new symbol look like a
1664      common symbol, and let _bfd_generic_link_add_one_symbol do the
1665      right thing.  */
1666
1667   if (newdyncommon
1668       && h->root.type == bfd_link_hash_common)
1669     {
1670       *override = TRUE;
1671       newdef = FALSE;
1672       newdyncommon = FALSE;
1673       *pvalue = sym->st_size;
1674       *psec = sec = bed->common_section (oldsec);
1675       *size_change_ok = TRUE;
1676     }
1677
1678   /* Skip weak definitions of symbols that are already defined.  */
1679   if (newdef && olddef && newweak)
1680     {
1681       /* Don't skip new non-IR weak syms.  */
1682       if (!(oldbfd != NULL
1683             && (oldbfd->flags & BFD_PLUGIN) != 0
1684             && (abfd->flags & BFD_PLUGIN) == 0))
1685         {
1686           newdef = FALSE;
1687           *skip = TRUE;
1688         }
1689
1690       /* Merge st_other.  If the symbol already has a dynamic index,
1691          but visibility says it should not be visible, turn it into a
1692          local symbol.  */
1693       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1694       if (h->dynindx != -1)
1695         switch (ELF_ST_VISIBILITY (h->other))
1696           {
1697           case STV_INTERNAL:
1698           case STV_HIDDEN:
1699             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1700             break;
1701           }
1702     }
1703
1704   /* If the old symbol is from a dynamic object, and the new symbol is
1705      a definition which is not from a dynamic object, then the new
1706      symbol overrides the old symbol.  Symbols from regular files
1707      always take precedence over symbols from dynamic objects, even if
1708      they are defined after the dynamic object in the link.
1709
1710      As above, we again permit a common symbol in a regular object to
1711      override a definition in a shared object if the shared object
1712      symbol is a function or is weak.  */
1713
1714   flip = NULL;
1715   if (!newdyn
1716       && (newdef
1717           || (bfd_is_com_section (sec)
1718               && (oldweak || oldfunc)))
1719       && olddyn
1720       && olddef
1721       && h->def_dynamic)
1722     {
1723       /* Change the hash table entry to undefined, and let
1724          _bfd_generic_link_add_one_symbol do the right thing with the
1725          new definition.  */
1726
1727       h->root.type = bfd_link_hash_undefined;
1728       h->root.u.undef.abfd = h->root.u.def.section->owner;
1729       *size_change_ok = TRUE;
1730
1731       olddef = FALSE;
1732       olddyncommon = FALSE;
1733
1734       /* We again permit a type change when a common symbol may be
1735          overriding a function.  */
1736
1737       if (bfd_is_com_section (sec))
1738         {
1739           if (oldfunc)
1740             {
1741               /* If a common symbol overrides a function, make sure
1742                  that it isn't defined dynamically nor has type
1743                  function.  */
1744               h->def_dynamic = 0;
1745               h->type = STT_NOTYPE;
1746             }
1747           *type_change_ok = TRUE;
1748         }
1749
1750       if (hi->root.type == bfd_link_hash_indirect)
1751         flip = hi;
1752       else
1753         /* This union may have been set to be non-NULL when this symbol
1754            was seen in a dynamic object.  We must force the union to be
1755            NULL, so that it is correct for a regular symbol.  */
1756         h->verinfo.vertree = NULL;
1757     }
1758
1759   /* Handle the special case of a new common symbol merging with an
1760      old symbol that looks like it might be a common symbol defined in
1761      a shared object.  Note that we have already handled the case in
1762      which a new common symbol should simply override the definition
1763      in the shared library.  */
1764
1765   if (! newdyn
1766       && bfd_is_com_section (sec)
1767       && olddyncommon)
1768     {
1769       /* It would be best if we could set the hash table entry to a
1770          common symbol, but we don't know what to use for the section
1771          or the alignment.  */
1772       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1773                                            bfd_link_hash_common, sym->st_size);
1774
1775       /* If the presumed common symbol in the dynamic object is
1776          larger, pretend that the new symbol has its size.  */
1777
1778       if (h->size > *pvalue)
1779         *pvalue = h->size;
1780
1781       /* We need to remember the alignment required by the symbol
1782          in the dynamic object.  */
1783       BFD_ASSERT (pold_alignment);
1784       *pold_alignment = h->root.u.def.section->alignment_power;
1785
1786       olddef = FALSE;
1787       olddyncommon = FALSE;
1788
1789       h->root.type = bfd_link_hash_undefined;
1790       h->root.u.undef.abfd = h->root.u.def.section->owner;
1791
1792       *size_change_ok = TRUE;
1793       *type_change_ok = TRUE;
1794
1795       if (hi->root.type == bfd_link_hash_indirect)
1796         flip = hi;
1797       else
1798         h->verinfo.vertree = NULL;
1799     }
1800
1801   if (flip != NULL)
1802     {
1803       /* Handle the case where we had a versioned symbol in a dynamic
1804          library and now find a definition in a normal object.  In this
1805          case, we make the versioned symbol point to the normal one.  */
1806       flip->root.type = h->root.type;
1807       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1808       h->root.type = bfd_link_hash_indirect;
1809       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1810       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1811       if (h->def_dynamic)
1812         {
1813           h->def_dynamic = 0;
1814           flip->ref_dynamic = 1;
1815         }
1816     }
1817
1818   return TRUE;
1819 }
1820
1821 /* This function is called to create an indirect symbol from the
1822    default for the symbol with the default version if needed. The
1823    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1824    set DYNSYM if the new indirect symbol is dynamic.  */
1825
1826 static bfd_boolean
1827 _bfd_elf_add_default_symbol (bfd *abfd,
1828                              struct bfd_link_info *info,
1829                              struct elf_link_hash_entry *h,
1830                              const char *name,
1831                              Elf_Internal_Sym *sym,
1832                              asection *sec,
1833                              bfd_vma value,
1834                              bfd **poldbfd,
1835                              bfd_boolean *dynsym)
1836 {
1837   bfd_boolean type_change_ok;
1838   bfd_boolean size_change_ok;
1839   bfd_boolean skip;
1840   char *shortname;
1841   struct elf_link_hash_entry *hi;
1842   struct bfd_link_hash_entry *bh;
1843   const struct elf_backend_data *bed;
1844   bfd_boolean collect;
1845   bfd_boolean dynamic;
1846   bfd_boolean override;
1847   char *p;
1848   size_t len, shortlen;
1849   asection *tmp_sec;
1850   bfd_boolean matched;
1851
1852   if (h->versioned == unversioned || h->versioned == versioned_hidden)
1853     return TRUE;
1854
1855   /* If this symbol has a version, and it is the default version, we
1856      create an indirect symbol from the default name to the fully
1857      decorated name.  This will cause external references which do not
1858      specify a version to be bound to this version of the symbol.  */
1859   p = strchr (name, ELF_VER_CHR);
1860   if (h->versioned == unknown)
1861     {
1862       if (p == NULL)
1863         {
1864           h->versioned = unversioned;
1865           return TRUE;
1866         }
1867       else
1868         {
1869           if (p[1] != ELF_VER_CHR)
1870             {
1871               h->versioned = versioned_hidden;
1872               return TRUE;
1873             }
1874           else
1875             h->versioned = versioned;
1876         }
1877     }
1878   else
1879     {
1880       /* PR ld/19073: We may see an unversioned definition after the
1881          default version.  */
1882       if (p == NULL)
1883         return TRUE;
1884     }
1885
1886   bed = get_elf_backend_data (abfd);
1887   collect = bed->collect;
1888   dynamic = (abfd->flags & DYNAMIC) != 0;
1889
1890   shortlen = p - name;
1891   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1892   if (shortname == NULL)
1893     return FALSE;
1894   memcpy (shortname, name, shortlen);
1895   shortname[shortlen] = '\0';
1896
1897   /* We are going to create a new symbol.  Merge it with any existing
1898      symbol with this name.  For the purposes of the merge, act as
1899      though we were defining the symbol we just defined, although we
1900      actually going to define an indirect symbol.  */
1901   type_change_ok = FALSE;
1902   size_change_ok = FALSE;
1903   matched = TRUE;
1904   tmp_sec = sec;
1905   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1906                               &hi, poldbfd, NULL, NULL, &skip, &override,
1907                               &type_change_ok, &size_change_ok, &matched))
1908     return FALSE;
1909
1910   if (skip)
1911     goto nondefault;
1912
1913   if (hi->def_regular)
1914     {
1915       /* If the undecorated symbol will have a version added by a
1916          script different to H, then don't indirect to/from the
1917          undecorated symbol.  This isn't ideal because we may not yet
1918          have seen symbol versions, if given by a script on the
1919          command line rather than via --version-script.  */
1920       if (hi->verinfo.vertree == NULL && info->version_info != NULL)
1921         {
1922           bfd_boolean hide;
1923
1924           hi->verinfo.vertree
1925             = bfd_find_version_for_sym (info->version_info,
1926                                         hi->root.root.string, &hide);
1927           if (hi->verinfo.vertree != NULL && hide)
1928             {
1929               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
1930               goto nondefault;
1931             }
1932         }
1933       if (hi->verinfo.vertree != NULL
1934           && strcmp (p + 1 + (p[1] == '@'), hi->verinfo.vertree->name) != 0)
1935         goto nondefault;
1936     }
1937
1938   if (! override)
1939     {
1940       /* Add the default symbol if not performing a relocatable link.  */
1941       if (! bfd_link_relocatable (info))
1942         {
1943           bh = &hi->root;
1944           if (! (_bfd_generic_link_add_one_symbol
1945                  (info, abfd, shortname, BSF_INDIRECT,
1946                   bfd_ind_section_ptr,
1947                   0, name, FALSE, collect, &bh)))
1948             return FALSE;
1949           hi = (struct elf_link_hash_entry *) bh;
1950         }
1951     }
1952   else
1953     {
1954       /* In this case the symbol named SHORTNAME is overriding the
1955          indirect symbol we want to add.  We were planning on making
1956          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1957          is the name without a version.  NAME is the fully versioned
1958          name, and it is the default version.
1959
1960          Overriding means that we already saw a definition for the
1961          symbol SHORTNAME in a regular object, and it is overriding
1962          the symbol defined in the dynamic object.
1963
1964          When this happens, we actually want to change NAME, the
1965          symbol we just added, to refer to SHORTNAME.  This will cause
1966          references to NAME in the shared object to become references
1967          to SHORTNAME in the regular object.  This is what we expect
1968          when we override a function in a shared object: that the
1969          references in the shared object will be mapped to the
1970          definition in the regular object.  */
1971
1972       while (hi->root.type == bfd_link_hash_indirect
1973              || hi->root.type == bfd_link_hash_warning)
1974         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1975
1976       h->root.type = bfd_link_hash_indirect;
1977       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1978       if (h->def_dynamic)
1979         {
1980           h->def_dynamic = 0;
1981           hi->ref_dynamic = 1;
1982           if (hi->ref_regular
1983               || hi->def_regular)
1984             {
1985               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1986                 return FALSE;
1987             }
1988         }
1989
1990       /* Now set HI to H, so that the following code will set the
1991          other fields correctly.  */
1992       hi = h;
1993     }
1994
1995   /* Check if HI is a warning symbol.  */
1996   if (hi->root.type == bfd_link_hash_warning)
1997     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1998
1999   /* If there is a duplicate definition somewhere, then HI may not
2000      point to an indirect symbol.  We will have reported an error to
2001      the user in that case.  */
2002
2003   if (hi->root.type == bfd_link_hash_indirect)
2004     {
2005       struct elf_link_hash_entry *ht;
2006
2007       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
2008       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
2009
2010       /* A reference to the SHORTNAME symbol from a dynamic library
2011          will be satisfied by the versioned symbol at runtime.  In
2012          effect, we have a reference to the versioned symbol.  */
2013       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
2014       hi->dynamic_def |= ht->dynamic_def;
2015
2016       /* See if the new flags lead us to realize that the symbol must
2017          be dynamic.  */
2018       if (! *dynsym)
2019         {
2020           if (! dynamic)
2021             {
2022               if (! bfd_link_executable (info)
2023                   || hi->def_dynamic
2024                   || hi->ref_dynamic)
2025                 *dynsym = TRUE;
2026             }
2027           else
2028             {
2029               if (hi->ref_regular)
2030                 *dynsym = TRUE;
2031             }
2032         }
2033     }
2034
2035   /* We also need to define an indirection from the nondefault version
2036      of the symbol.  */
2037
2038 nondefault:
2039   len = strlen (name);
2040   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
2041   if (shortname == NULL)
2042     return FALSE;
2043   memcpy (shortname, name, shortlen);
2044   memcpy (shortname + shortlen, p + 1, len - shortlen);
2045
2046   /* Once again, merge with any existing symbol.  */
2047   type_change_ok = FALSE;
2048   size_change_ok = FALSE;
2049   tmp_sec = sec;
2050   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
2051                               &hi, poldbfd, NULL, NULL, &skip, &override,
2052                               &type_change_ok, &size_change_ok, &matched))
2053     return FALSE;
2054
2055   if (skip)
2056     return TRUE;
2057
2058   if (override)
2059     {
2060       /* Here SHORTNAME is a versioned name, so we don't expect to see
2061          the type of override we do in the case above unless it is
2062          overridden by a versioned definition.  */
2063       if (hi->root.type != bfd_link_hash_defined
2064           && hi->root.type != bfd_link_hash_defweak)
2065         _bfd_error_handler
2066           /* xgettext:c-format */
2067           (_("%pB: unexpected redefinition of indirect versioned symbol `%s'"),
2068            abfd, shortname);
2069     }
2070   else
2071     {
2072       bh = &hi->root;
2073       if (! (_bfd_generic_link_add_one_symbol
2074              (info, abfd, shortname, BSF_INDIRECT,
2075               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
2076         return FALSE;
2077       hi = (struct elf_link_hash_entry *) bh;
2078
2079       /* If there is a duplicate definition somewhere, then HI may not
2080          point to an indirect symbol.  We will have reported an error
2081          to the user in that case.  */
2082
2083       if (hi->root.type == bfd_link_hash_indirect)
2084         {
2085           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
2086           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
2087           hi->dynamic_def |= h->dynamic_def;
2088
2089           /* See if the new flags lead us to realize that the symbol
2090              must be dynamic.  */
2091           if (! *dynsym)
2092             {
2093               if (! dynamic)
2094                 {
2095                   if (! bfd_link_executable (info)
2096                       || hi->ref_dynamic)
2097                     *dynsym = TRUE;
2098                 }
2099               else
2100                 {
2101                   if (hi->ref_regular)
2102                     *dynsym = TRUE;
2103                 }
2104             }
2105         }
2106     }
2107
2108   return TRUE;
2109 }
2110 \f
2111 /* This routine is used to export all defined symbols into the dynamic
2112    symbol table.  It is called via elf_link_hash_traverse.  */
2113
2114 static bfd_boolean
2115 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
2116 {
2117   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2118
2119   /* Ignore indirect symbols.  These are added by the versioning code.  */
2120   if (h->root.type == bfd_link_hash_indirect)
2121     return TRUE;
2122
2123   /* Ignore this if we won't export it.  */
2124   if (!eif->info->export_dynamic && !h->dynamic)
2125     return TRUE;
2126
2127   if (h->dynindx == -1
2128       && (h->def_regular || h->ref_regular)
2129       && ! bfd_hide_sym_by_version (eif->info->version_info,
2130                                     h->root.root.string))
2131     {
2132       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2133         {
2134           eif->failed = TRUE;
2135           return FALSE;
2136         }
2137     }
2138
2139   return TRUE;
2140 }
2141 \f
2142 /* Look through the symbols which are defined in other shared
2143    libraries and referenced here.  Update the list of version
2144    dependencies.  This will be put into the .gnu.version_r section.
2145    This function is called via elf_link_hash_traverse.  */
2146
2147 static bfd_boolean
2148 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
2149                                          void *data)
2150 {
2151   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
2152   Elf_Internal_Verneed *t;
2153   Elf_Internal_Vernaux *a;
2154   bfd_size_type amt;
2155
2156   /* We only care about symbols defined in shared objects with version
2157      information.  */
2158   if (!h->def_dynamic
2159       || h->def_regular
2160       || h->dynindx == -1
2161       || h->verinfo.verdef == NULL
2162       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
2163           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
2164     return TRUE;
2165
2166   /* See if we already know about this version.  */
2167   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
2168        t != NULL;
2169        t = t->vn_nextref)
2170     {
2171       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
2172         continue;
2173
2174       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
2175         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
2176           return TRUE;
2177
2178       break;
2179     }
2180
2181   /* This is a new version.  Add it to tree we are building.  */
2182
2183   if (t == NULL)
2184     {
2185       amt = sizeof *t;
2186       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
2187       if (t == NULL)
2188         {
2189           rinfo->failed = TRUE;
2190           return FALSE;
2191         }
2192
2193       t->vn_bfd = h->verinfo.verdef->vd_bfd;
2194       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
2195       elf_tdata (rinfo->info->output_bfd)->verref = t;
2196     }
2197
2198   amt = sizeof *a;
2199   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
2200   if (a == NULL)
2201     {
2202       rinfo->failed = TRUE;
2203       return FALSE;
2204     }
2205
2206   /* Note that we are copying a string pointer here, and testing it
2207      above.  If bfd_elf_string_from_elf_section is ever changed to
2208      discard the string data when low in memory, this will have to be
2209      fixed.  */
2210   a->vna_nodename = h->verinfo.verdef->vd_nodename;
2211
2212   a->vna_flags = h->verinfo.verdef->vd_flags;
2213   a->vna_nextptr = t->vn_auxptr;
2214
2215   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
2216   ++rinfo->vers;
2217
2218   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
2219
2220   t->vn_auxptr = a;
2221
2222   return TRUE;
2223 }
2224
2225 /* Return TRUE and set *HIDE to TRUE if the versioned symbol is
2226    hidden.  Set *T_P to NULL if there is no match.  */
2227
2228 static bfd_boolean
2229 _bfd_elf_link_hide_versioned_symbol (struct bfd_link_info *info,
2230                                      struct elf_link_hash_entry *h,
2231                                      const char *version_p,
2232                                      struct bfd_elf_version_tree **t_p,
2233                                      bfd_boolean *hide)
2234 {
2235   struct bfd_elf_version_tree *t;
2236
2237   /* Look for the version.  If we find it, it is no longer weak.  */
2238   for (t = info->version_info; t != NULL; t = t->next)
2239     {
2240       if (strcmp (t->name, version_p) == 0)
2241         {
2242           size_t len;
2243           char *alc;
2244           struct bfd_elf_version_expr *d;
2245
2246           len = version_p - h->root.root.string;
2247           alc = (char *) bfd_malloc (len);
2248           if (alc == NULL)
2249             return FALSE;
2250           memcpy (alc, h->root.root.string, len - 1);
2251           alc[len - 1] = '\0';
2252           if (alc[len - 2] == ELF_VER_CHR)
2253             alc[len - 2] = '\0';
2254
2255           h->verinfo.vertree = t;
2256           t->used = TRUE;
2257           d = NULL;
2258
2259           if (t->globals.list != NULL)
2260             d = (*t->match) (&t->globals, NULL, alc);
2261
2262           /* See if there is anything to force this symbol to
2263              local scope.  */
2264           if (d == NULL && t->locals.list != NULL)
2265             {
2266               d = (*t->match) (&t->locals, NULL, alc);
2267               if (d != NULL
2268                   && h->dynindx != -1
2269                   && ! info->export_dynamic)
2270                 *hide = TRUE;
2271             }
2272
2273           free (alc);
2274           break;
2275         }
2276     }
2277
2278   *t_p = t;
2279
2280   return TRUE;
2281 }
2282
2283 /* Return TRUE if the symbol H is hidden by version script.  */
2284
2285 bfd_boolean
2286 _bfd_elf_link_hide_sym_by_version (struct bfd_link_info *info,
2287                                    struct elf_link_hash_entry *h)
2288 {
2289   const char *p;
2290   bfd_boolean hide = FALSE;
2291   const struct elf_backend_data *bed
2292     = get_elf_backend_data (info->output_bfd);
2293
2294   /* Version script only hides symbols defined in regular objects.  */
2295   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
2296     return TRUE;
2297
2298   p = strchr (h->root.root.string, ELF_VER_CHR);
2299   if (p != NULL && h->verinfo.vertree == NULL)
2300     {
2301       struct bfd_elf_version_tree *t;
2302
2303       ++p;
2304       if (*p == ELF_VER_CHR)
2305         ++p;
2306
2307       if (*p != '\0'
2308           && _bfd_elf_link_hide_versioned_symbol (info, h, p, &t, &hide)
2309           && hide)
2310         {
2311           if (hide)
2312             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2313           return TRUE;
2314         }
2315     }
2316
2317   /* If we don't have a version for this symbol, see if we can find
2318      something.  */
2319   if (h->verinfo.vertree == NULL && info->version_info != NULL)
2320     {
2321       h->verinfo.vertree
2322         = bfd_find_version_for_sym (info->version_info,
2323                                     h->root.root.string, &hide);
2324       if (h->verinfo.vertree != NULL && hide)
2325         {
2326           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2327           return TRUE;
2328         }
2329     }
2330
2331   return FALSE;
2332 }
2333
2334 /* Figure out appropriate versions for all the symbols.  We may not
2335    have the version number script until we have read all of the input
2336    files, so until that point we don't know which symbols should be
2337    local.  This function is called via elf_link_hash_traverse.  */
2338
2339 static bfd_boolean
2340 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2341 {
2342   struct elf_info_failed *sinfo;
2343   struct bfd_link_info *info;
2344   const struct elf_backend_data *bed;
2345   struct elf_info_failed eif;
2346   char *p;
2347   bfd_boolean hide;
2348
2349   sinfo = (struct elf_info_failed *) data;
2350   info = sinfo->info;
2351
2352   /* Fix the symbol flags.  */
2353   eif.failed = FALSE;
2354   eif.info = info;
2355   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2356     {
2357       if (eif.failed)
2358         sinfo->failed = TRUE;
2359       return FALSE;
2360     }
2361
2362   /* We only need version numbers for symbols defined in regular
2363      objects.  */
2364   if (!h->def_regular)
2365     return TRUE;
2366
2367   hide = FALSE;
2368   bed = get_elf_backend_data (info->output_bfd);
2369   p = strchr (h->root.root.string, ELF_VER_CHR);
2370   if (p != NULL && h->verinfo.vertree == NULL)
2371     {
2372       struct bfd_elf_version_tree *t;
2373
2374       ++p;
2375       if (*p == ELF_VER_CHR)
2376         ++p;
2377
2378       /* If there is no version string, we can just return out.  */
2379       if (*p == '\0')
2380         return TRUE;
2381
2382       if (!_bfd_elf_link_hide_versioned_symbol (info, h, p, &t, &hide))
2383         {
2384           sinfo->failed = TRUE;
2385           return FALSE;
2386         }
2387
2388       if (hide)
2389         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2390
2391       /* If we are building an application, we need to create a
2392          version node for this version.  */
2393       if (t == NULL && bfd_link_executable (info))
2394         {
2395           struct bfd_elf_version_tree **pp;
2396           int version_index;
2397
2398           /* If we aren't going to export this symbol, we don't need
2399              to worry about it.  */
2400           if (h->dynindx == -1)
2401             return TRUE;
2402
2403           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd,
2404                                                           sizeof *t);
2405           if (t == NULL)
2406             {
2407               sinfo->failed = TRUE;
2408               return FALSE;
2409             }
2410
2411           t->name = p;
2412           t->name_indx = (unsigned int) -1;
2413           t->used = TRUE;
2414
2415           version_index = 1;
2416           /* Don't count anonymous version tag.  */
2417           if (sinfo->info->version_info != NULL
2418               && sinfo->info->version_info->vernum == 0)
2419             version_index = 0;
2420           for (pp = &sinfo->info->version_info;
2421                *pp != NULL;
2422                pp = &(*pp)->next)
2423             ++version_index;
2424           t->vernum = version_index;
2425
2426           *pp = t;
2427
2428           h->verinfo.vertree = t;
2429         }
2430       else if (t == NULL)
2431         {
2432           /* We could not find the version for a symbol when
2433              generating a shared archive.  Return an error.  */
2434           _bfd_error_handler
2435             /* xgettext:c-format */
2436             (_("%pB: version node not found for symbol %s"),
2437              info->output_bfd, h->root.root.string);
2438           bfd_set_error (bfd_error_bad_value);
2439           sinfo->failed = TRUE;
2440           return FALSE;
2441         }
2442     }
2443
2444   /* If we don't have a version for this symbol, see if we can find
2445      something.  */
2446   if (!hide
2447       && h->verinfo.vertree == NULL
2448       && sinfo->info->version_info != NULL)
2449     {
2450       h->verinfo.vertree
2451         = bfd_find_version_for_sym (sinfo->info->version_info,
2452                                     h->root.root.string, &hide);
2453       if (h->verinfo.vertree != NULL && hide)
2454         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2455     }
2456
2457   return TRUE;
2458 }
2459 \f
2460 /* Read and swap the relocs from the section indicated by SHDR.  This
2461    may be either a REL or a RELA section.  The relocations are
2462    translated into RELA relocations and stored in INTERNAL_RELOCS,
2463    which should have already been allocated to contain enough space.
2464    The EXTERNAL_RELOCS are a buffer where the external form of the
2465    relocations should be stored.
2466
2467    Returns FALSE if something goes wrong.  */
2468
2469 static bfd_boolean
2470 elf_link_read_relocs_from_section (bfd *abfd,
2471                                    asection *sec,
2472                                    Elf_Internal_Shdr *shdr,
2473                                    void *external_relocs,
2474                                    Elf_Internal_Rela *internal_relocs)
2475 {
2476   const struct elf_backend_data *bed;
2477   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2478   const bfd_byte *erela;
2479   const bfd_byte *erelaend;
2480   Elf_Internal_Rela *irela;
2481   Elf_Internal_Shdr *symtab_hdr;
2482   size_t nsyms;
2483
2484   /* Position ourselves at the start of the section.  */
2485   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2486     return FALSE;
2487
2488   /* Read the relocations.  */
2489   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2490     return FALSE;
2491
2492   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2493   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2494
2495   bed = get_elf_backend_data (abfd);
2496
2497   /* Convert the external relocations to the internal format.  */
2498   if (shdr->sh_entsize == bed->s->sizeof_rel)
2499     swap_in = bed->s->swap_reloc_in;
2500   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2501     swap_in = bed->s->swap_reloca_in;
2502   else
2503     {
2504       bfd_set_error (bfd_error_wrong_format);
2505       return FALSE;
2506     }
2507
2508   erela = (const bfd_byte *) external_relocs;
2509   erelaend = erela + shdr->sh_size;
2510   irela = internal_relocs;
2511   while (erela < erelaend)
2512     {
2513       bfd_vma r_symndx;
2514
2515       (*swap_in) (abfd, erela, irela);
2516       r_symndx = ELF32_R_SYM (irela->r_info);
2517       if (bed->s->arch_size == 64)
2518         r_symndx >>= 24;
2519       if (nsyms > 0)
2520         {
2521           if ((size_t) r_symndx >= nsyms)
2522             {
2523               _bfd_error_handler
2524                 /* xgettext:c-format */
2525                 (_("%pB: bad reloc symbol index (%#" PRIx64 " >= %#lx)"
2526                    " for offset %#" PRIx64 " in section `%pA'"),
2527                  abfd, (uint64_t) r_symndx, (unsigned long) nsyms,
2528                  (uint64_t) irela->r_offset, sec);
2529               bfd_set_error (bfd_error_bad_value);
2530               return FALSE;
2531             }
2532         }
2533       else if (r_symndx != STN_UNDEF)
2534         {
2535           _bfd_error_handler
2536             /* xgettext:c-format */
2537             (_("%pB: non-zero symbol index (%#" PRIx64 ")"
2538                " for offset %#" PRIx64 " in section `%pA'"
2539                " when the object file has no symbol table"),
2540              abfd, (uint64_t) r_symndx,
2541              (uint64_t) irela->r_offset, sec);
2542           bfd_set_error (bfd_error_bad_value);
2543           return FALSE;
2544         }
2545       irela += bed->s->int_rels_per_ext_rel;
2546       erela += shdr->sh_entsize;
2547     }
2548
2549   return TRUE;
2550 }
2551
2552 /* Read and swap the relocs for a section O.  They may have been
2553    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2554    not NULL, they are used as buffers to read into.  They are known to
2555    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2556    the return value is allocated using either malloc or bfd_alloc,
2557    according to the KEEP_MEMORY argument.  If O has two relocation
2558    sections (both REL and RELA relocations), then the REL_HDR
2559    relocations will appear first in INTERNAL_RELOCS, followed by the
2560    RELA_HDR relocations.  */
2561
2562 Elf_Internal_Rela *
2563 _bfd_elf_link_read_relocs (bfd *abfd,
2564                            asection *o,
2565                            void *external_relocs,
2566                            Elf_Internal_Rela *internal_relocs,
2567                            bfd_boolean keep_memory)
2568 {
2569   void *alloc1 = NULL;
2570   Elf_Internal_Rela *alloc2 = NULL;
2571   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2572   struct bfd_elf_section_data *esdo = elf_section_data (o);
2573   Elf_Internal_Rela *internal_rela_relocs;
2574
2575   if (esdo->relocs != NULL)
2576     return esdo->relocs;
2577
2578   if (o->reloc_count == 0)
2579     return NULL;
2580
2581   if (internal_relocs == NULL)
2582     {
2583       bfd_size_type size;
2584
2585       size = (bfd_size_type) o->reloc_count * sizeof (Elf_Internal_Rela);
2586       if (keep_memory)
2587         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2588       else
2589         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2590       if (internal_relocs == NULL)
2591         goto error_return;
2592     }
2593
2594   if (external_relocs == NULL)
2595     {
2596       bfd_size_type size = 0;
2597
2598       if (esdo->rel.hdr)
2599         size += esdo->rel.hdr->sh_size;
2600       if (esdo->rela.hdr)
2601         size += esdo->rela.hdr->sh_size;
2602
2603       alloc1 = bfd_malloc (size);
2604       if (alloc1 == NULL)
2605         goto error_return;
2606       external_relocs = alloc1;
2607     }
2608
2609   internal_rela_relocs = internal_relocs;
2610   if (esdo->rel.hdr)
2611     {
2612       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2613                                               external_relocs,
2614                                               internal_relocs))
2615         goto error_return;
2616       external_relocs = (((bfd_byte *) external_relocs)
2617                          + esdo->rel.hdr->sh_size);
2618       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2619                                * bed->s->int_rels_per_ext_rel);
2620     }
2621
2622   if (esdo->rela.hdr
2623       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2624                                               external_relocs,
2625                                               internal_rela_relocs)))
2626     goto error_return;
2627
2628   /* Cache the results for next time, if we can.  */
2629   if (keep_memory)
2630     esdo->relocs = internal_relocs;
2631
2632   if (alloc1 != NULL)
2633     free (alloc1);
2634
2635   /* Don't free alloc2, since if it was allocated we are passing it
2636      back (under the name of internal_relocs).  */
2637
2638   return internal_relocs;
2639
2640  error_return:
2641   if (alloc1 != NULL)
2642     free (alloc1);
2643   if (alloc2 != NULL)
2644     {
2645       if (keep_memory)
2646         bfd_release (abfd, alloc2);
2647       else
2648         free (alloc2);
2649     }
2650   return NULL;
2651 }
2652
2653 /* Compute the size of, and allocate space for, REL_HDR which is the
2654    section header for a section containing relocations for O.  */
2655
2656 static bfd_boolean
2657 _bfd_elf_link_size_reloc_section (bfd *abfd,
2658                                   struct bfd_elf_section_reloc_data *reldata)
2659 {
2660   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2661
2662   /* That allows us to calculate the size of the section.  */
2663   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2664
2665   /* The contents field must last into write_object_contents, so we
2666      allocate it with bfd_alloc rather than malloc.  Also since we
2667      cannot be sure that the contents will actually be filled in,
2668      we zero the allocated space.  */
2669   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2670   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2671     return FALSE;
2672
2673   if (reldata->hashes == NULL && reldata->count)
2674     {
2675       struct elf_link_hash_entry **p;
2676
2677       p = ((struct elf_link_hash_entry **)
2678            bfd_zmalloc (reldata->count * sizeof (*p)));
2679       if (p == NULL)
2680         return FALSE;
2681
2682       reldata->hashes = p;
2683     }
2684
2685   return TRUE;
2686 }
2687
2688 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2689    originated from the section given by INPUT_REL_HDR) to the
2690    OUTPUT_BFD.  */
2691
2692 bfd_boolean
2693 _bfd_elf_link_output_relocs (bfd *output_bfd,
2694                              asection *input_section,
2695                              Elf_Internal_Shdr *input_rel_hdr,
2696                              Elf_Internal_Rela *internal_relocs,
2697                              struct elf_link_hash_entry **rel_hash
2698                                ATTRIBUTE_UNUSED)
2699 {
2700   Elf_Internal_Rela *irela;
2701   Elf_Internal_Rela *irelaend;
2702   bfd_byte *erel;
2703   struct bfd_elf_section_reloc_data *output_reldata;
2704   asection *output_section;
2705   const struct elf_backend_data *bed;
2706   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2707   struct bfd_elf_section_data *esdo;
2708
2709   output_section = input_section->output_section;
2710
2711   bed = get_elf_backend_data (output_bfd);
2712   esdo = elf_section_data (output_section);
2713   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2714     {
2715       output_reldata = &esdo->rel;
2716       swap_out = bed->s->swap_reloc_out;
2717     }
2718   else if (esdo->rela.hdr
2719            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2720     {
2721       output_reldata = &esdo->rela;
2722       swap_out = bed->s->swap_reloca_out;
2723     }
2724   else
2725     {
2726       _bfd_error_handler
2727         /* xgettext:c-format */
2728         (_("%pB: relocation size mismatch in %pB section %pA"),
2729          output_bfd, input_section->owner, input_section);
2730       bfd_set_error (bfd_error_wrong_format);
2731       return FALSE;
2732     }
2733
2734   erel = output_reldata->hdr->contents;
2735   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2736   irela = internal_relocs;
2737   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2738                       * bed->s->int_rels_per_ext_rel);
2739   while (irela < irelaend)
2740     {
2741       (*swap_out) (output_bfd, irela, erel);
2742       irela += bed->s->int_rels_per_ext_rel;
2743       erel += input_rel_hdr->sh_entsize;
2744     }
2745
2746   /* Bump the counter, so that we know where to add the next set of
2747      relocations.  */
2748   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2749
2750   return TRUE;
2751 }
2752 \f
2753 /* Make weak undefined symbols in PIE dynamic.  */
2754
2755 bfd_boolean
2756 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2757                                  struct elf_link_hash_entry *h)
2758 {
2759   if (bfd_link_pie (info)
2760       && h->dynindx == -1
2761       && h->root.type == bfd_link_hash_undefweak)
2762     return bfd_elf_link_record_dynamic_symbol (info, h);
2763
2764   return TRUE;
2765 }
2766
2767 /* Fix up the flags for a symbol.  This handles various cases which
2768    can only be fixed after all the input files are seen.  This is
2769    currently called by both adjust_dynamic_symbol and
2770    assign_sym_version, which is unnecessary but perhaps more robust in
2771    the face of future changes.  */
2772
2773 static bfd_boolean
2774 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2775                            struct elf_info_failed *eif)
2776 {
2777   const struct elf_backend_data *bed;
2778
2779   /* If this symbol was mentioned in a non-ELF file, try to set
2780      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2781      permit a non-ELF file to correctly refer to a symbol defined in
2782      an ELF dynamic object.  */
2783   if (h->non_elf)
2784     {
2785       while (h->root.type == bfd_link_hash_indirect)
2786         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2787
2788       if (h->root.type != bfd_link_hash_defined
2789           && h->root.type != bfd_link_hash_defweak)
2790         {
2791           h->ref_regular = 1;
2792           h->ref_regular_nonweak = 1;
2793         }
2794       else
2795         {
2796           if (h->root.u.def.section->owner != NULL
2797               && (bfd_get_flavour (h->root.u.def.section->owner)
2798                   == bfd_target_elf_flavour))
2799             {
2800               h->ref_regular = 1;
2801               h->ref_regular_nonweak = 1;
2802             }
2803           else
2804             h->def_regular = 1;
2805         }
2806
2807       if (h->dynindx == -1
2808           && (h->def_dynamic
2809               || h->ref_dynamic))
2810         {
2811           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2812             {
2813               eif->failed = TRUE;
2814               return FALSE;
2815             }
2816         }
2817     }
2818   else
2819     {
2820       /* Unfortunately, NON_ELF is only correct if the symbol
2821          was first seen in a non-ELF file.  Fortunately, if the symbol
2822          was first seen in an ELF file, we're probably OK unless the
2823          symbol was defined in a non-ELF file.  Catch that case here.
2824          FIXME: We're still in trouble if the symbol was first seen in
2825          a dynamic object, and then later in a non-ELF regular object.  */
2826       if ((h->root.type == bfd_link_hash_defined
2827            || h->root.type == bfd_link_hash_defweak)
2828           && !h->def_regular
2829           && (h->root.u.def.section->owner != NULL
2830               ? (bfd_get_flavour (h->root.u.def.section->owner)
2831                  != bfd_target_elf_flavour)
2832               : (bfd_is_abs_section (h->root.u.def.section)
2833                  && !h->def_dynamic)))
2834         h->def_regular = 1;
2835     }
2836
2837   /* Backend specific symbol fixup.  */
2838   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2839   if (bed->elf_backend_fixup_symbol
2840       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2841     return FALSE;
2842
2843   /* If this is a final link, and the symbol was defined as a common
2844      symbol in a regular object file, and there was no definition in
2845      any dynamic object, then the linker will have allocated space for
2846      the symbol in a common section but the DEF_REGULAR
2847      flag will not have been set.  */
2848   if (h->root.type == bfd_link_hash_defined
2849       && !h->def_regular
2850       && h->ref_regular
2851       && !h->def_dynamic
2852       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2853     h->def_regular = 1;
2854
2855   /* Symbols defined in discarded sections shouldn't be dynamic.  */
2856   if (h->root.type == bfd_link_hash_undefined && h->indx == -3)
2857     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2858
2859   /* If a weak undefined symbol has non-default visibility, we also
2860      hide it from the dynamic linker.  */
2861   else if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2862            && h->root.type == bfd_link_hash_undefweak)
2863     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2864
2865   /* A hidden versioned symbol in executable should be forced local if
2866      it is is locally defined, not referenced by shared library and not
2867      exported.  */
2868   else if (bfd_link_executable (eif->info)
2869            && h->versioned == versioned_hidden
2870            && !eif->info->export_dynamic
2871            && !h->dynamic
2872            && !h->ref_dynamic
2873            && h->def_regular)
2874     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2875
2876   /* If -Bsymbolic was used (which means to bind references to global
2877      symbols to the definition within the shared object), and this
2878      symbol was defined in a regular object, then it actually doesn't
2879      need a PLT entry.  Likewise, if the symbol has non-default
2880      visibility.  If the symbol has hidden or internal visibility, we
2881      will force it local.  */
2882   else if (h->needs_plt
2883            && bfd_link_pic (eif->info)
2884            && is_elf_hash_table (eif->info->hash)
2885            && (SYMBOLIC_BIND (eif->info, h)
2886                || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2887            && h->def_regular)
2888     {
2889       bfd_boolean force_local;
2890
2891       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2892                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2893       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2894     }
2895
2896   /* If this is a weak defined symbol in a dynamic object, and we know
2897      the real definition in the dynamic object, copy interesting flags
2898      over to the real definition.  */
2899   if (h->is_weakalias)
2900     {
2901       struct elf_link_hash_entry *def = weakdef (h);
2902
2903       /* If the real definition is defined by a regular object file,
2904          don't do anything special.  See the longer description in
2905          _bfd_elf_adjust_dynamic_symbol, below.  */
2906       if (def->def_regular)
2907         {
2908           h = def;
2909           while ((h = h->u.alias) != def)
2910             h->is_weakalias = 0;
2911         }
2912       else
2913         {
2914           while (h->root.type == bfd_link_hash_indirect)
2915             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2916           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2917                       || h->root.type == bfd_link_hash_defweak);
2918           BFD_ASSERT (def->def_dynamic);
2919           BFD_ASSERT (def->root.type == bfd_link_hash_defined);
2920           (*bed->elf_backend_copy_indirect_symbol) (eif->info, def, h);
2921         }
2922     }
2923
2924   return TRUE;
2925 }
2926
2927 /* Make the backend pick a good value for a dynamic symbol.  This is
2928    called via elf_link_hash_traverse, and also calls itself
2929    recursively.  */
2930
2931 static bfd_boolean
2932 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2933 {
2934   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2935   struct elf_link_hash_table *htab;
2936   const struct elf_backend_data *bed;
2937
2938   if (! is_elf_hash_table (eif->info->hash))
2939     return FALSE;
2940
2941   /* Ignore indirect symbols.  These are added by the versioning code.  */
2942   if (h->root.type == bfd_link_hash_indirect)
2943     return TRUE;
2944
2945   /* Fix the symbol flags.  */
2946   if (! _bfd_elf_fix_symbol_flags (h, eif))
2947     return FALSE;
2948
2949   htab = elf_hash_table (eif->info);
2950   bed = get_elf_backend_data (htab->dynobj);
2951
2952   if (h->root.type == bfd_link_hash_undefweak)
2953     {
2954       if (eif->info->dynamic_undefined_weak == 0)
2955         (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2956       else if (eif->info->dynamic_undefined_weak > 0
2957                && h->ref_regular
2958                && ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2959                && !bfd_hide_sym_by_version (eif->info->version_info,
2960                                             h->root.root.string))
2961         {
2962           if (!bfd_elf_link_record_dynamic_symbol (eif->info, h))
2963             {
2964               eif->failed = TRUE;
2965               return FALSE;
2966             }
2967         }
2968     }
2969
2970   /* If this symbol does not require a PLT entry, and it is not
2971      defined by a dynamic object, or is not referenced by a regular
2972      object, ignore it.  We do have to handle a weak defined symbol,
2973      even if no regular object refers to it, if we decided to add it
2974      to the dynamic symbol table.  FIXME: Do we normally need to worry
2975      about symbols which are defined by one dynamic object and
2976      referenced by another one?  */
2977   if (!h->needs_plt
2978       && h->type != STT_GNU_IFUNC
2979       && (h->def_regular
2980           || !h->def_dynamic
2981           || (!h->ref_regular
2982               && (!h->is_weakalias || weakdef (h)->dynindx == -1))))
2983     {
2984       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2985       return TRUE;
2986     }
2987
2988   /* If we've already adjusted this symbol, don't do it again.  This
2989      can happen via a recursive call.  */
2990   if (h->dynamic_adjusted)
2991     return TRUE;
2992
2993   /* Don't look at this symbol again.  Note that we must set this
2994      after checking the above conditions, because we may look at a
2995      symbol once, decide not to do anything, and then get called
2996      recursively later after REF_REGULAR is set below.  */
2997   h->dynamic_adjusted = 1;
2998
2999   /* If this is a weak definition, and we know a real definition, and
3000      the real symbol is not itself defined by a regular object file,
3001      then get a good value for the real definition.  We handle the
3002      real symbol first, for the convenience of the backend routine.
3003
3004      Note that there is a confusing case here.  If the real definition
3005      is defined by a regular object file, we don't get the real symbol
3006      from the dynamic object, but we do get the weak symbol.  If the
3007      processor backend uses a COPY reloc, then if some routine in the
3008      dynamic object changes the real symbol, we will not see that
3009      change in the corresponding weak symbol.  This is the way other
3010      ELF linkers work as well, and seems to be a result of the shared
3011      library model.
3012
3013      I will clarify this issue.  Most SVR4 shared libraries define the
3014      variable _timezone and define timezone as a weak synonym.  The
3015      tzset call changes _timezone.  If you write
3016        extern int timezone;
3017        int _timezone = 5;
3018        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
3019      you might expect that, since timezone is a synonym for _timezone,
3020      the same number will print both times.  However, if the processor
3021      backend uses a COPY reloc, then actually timezone will be copied
3022      into your process image, and, since you define _timezone
3023      yourself, _timezone will not.  Thus timezone and _timezone will
3024      wind up at different memory locations.  The tzset call will set
3025      _timezone, leaving timezone unchanged.  */
3026
3027   if (h->is_weakalias)
3028     {
3029       struct elf_link_hash_entry *def = weakdef (h);
3030
3031       /* If we get to this point, there is an implicit reference to
3032          the alias by a regular object file via the weak symbol H.  */
3033       def->ref_regular = 1;
3034
3035       /* Ensure that the backend adjust_dynamic_symbol function sees
3036          the strong alias before H by recursively calling ourselves.  */
3037       if (!_bfd_elf_adjust_dynamic_symbol (def, eif))
3038         return FALSE;
3039     }
3040
3041   /* If a symbol has no type and no size and does not require a PLT
3042      entry, then we are probably about to do the wrong thing here: we
3043      are probably going to create a COPY reloc for an empty object.
3044      This case can arise when a shared object is built with assembly
3045      code, and the assembly code fails to set the symbol type.  */
3046   if (h->size == 0
3047       && h->type == STT_NOTYPE
3048       && !h->needs_plt)
3049     _bfd_error_handler
3050       (_("warning: type and size of dynamic symbol `%s' are not defined"),
3051        h->root.root.string);
3052
3053   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
3054     {
3055       eif->failed = TRUE;
3056       return FALSE;
3057     }
3058
3059   return TRUE;
3060 }
3061
3062 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
3063    DYNBSS.  */
3064
3065 bfd_boolean
3066 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
3067                               struct elf_link_hash_entry *h,
3068                               asection *dynbss)
3069 {
3070   unsigned int power_of_two;
3071   bfd_vma mask;
3072   asection *sec = h->root.u.def.section;
3073
3074   /* The section alignment of the definition is the maximum alignment
3075      requirement of symbols defined in the section.  Since we don't
3076      know the symbol alignment requirement, we start with the
3077      maximum alignment and check low bits of the symbol address
3078      for the minimum alignment.  */
3079   power_of_two = bfd_get_section_alignment (sec->owner, sec);
3080   mask = ((bfd_vma) 1 << power_of_two) - 1;
3081   while ((h->root.u.def.value & mask) != 0)
3082     {
3083        mask >>= 1;
3084        --power_of_two;
3085     }
3086
3087   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
3088                                                 dynbss))
3089     {
3090       /* Adjust the section alignment if needed.  */
3091       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
3092                                        power_of_two))
3093         return FALSE;
3094     }
3095
3096   /* We make sure that the symbol will be aligned properly.  */
3097   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
3098
3099   /* Define the symbol as being at this point in DYNBSS.  */
3100   h->root.u.def.section = dynbss;
3101   h->root.u.def.value = dynbss->size;
3102
3103   /* Increment the size of DYNBSS to make room for the symbol.  */
3104   dynbss->size += h->size;
3105
3106   /* No error if extern_protected_data is true.  */
3107   if (h->protected_def
3108       && (!info->extern_protected_data
3109           || (info->extern_protected_data < 0
3110               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
3111     info->callbacks->einfo
3112       (_("%P: copy reloc against protected `%pT' is dangerous\n"),
3113        h->root.root.string);
3114
3115   return TRUE;
3116 }
3117
3118 /* Adjust all external symbols pointing into SEC_MERGE sections
3119    to reflect the object merging within the sections.  */
3120
3121 static bfd_boolean
3122 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
3123 {
3124   asection *sec;
3125
3126   if ((h->root.type == bfd_link_hash_defined
3127        || h->root.type == bfd_link_hash_defweak)
3128       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
3129       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
3130     {
3131       bfd *output_bfd = (bfd *) data;
3132
3133       h->root.u.def.value =
3134         _bfd_merged_section_offset (output_bfd,
3135                                     &h->root.u.def.section,
3136                                     elf_section_data (sec)->sec_info,
3137                                     h->root.u.def.value);
3138     }
3139
3140   return TRUE;
3141 }
3142
3143 /* Returns false if the symbol referred to by H should be considered
3144    to resolve local to the current module, and true if it should be
3145    considered to bind dynamically.  */
3146
3147 bfd_boolean
3148 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
3149                            struct bfd_link_info *info,
3150                            bfd_boolean not_local_protected)
3151 {
3152   bfd_boolean binding_stays_local_p;
3153   const struct elf_backend_data *bed;
3154   struct elf_link_hash_table *hash_table;
3155
3156   if (h == NULL)
3157     return FALSE;
3158
3159   while (h->root.type == bfd_link_hash_indirect
3160          || h->root.type == bfd_link_hash_warning)
3161     h = (struct elf_link_hash_entry *) h->root.u.i.link;
3162
3163   /* If it was forced local, then clearly it's not dynamic.  */
3164   if (h->dynindx == -1)
3165     return FALSE;
3166   if (h->forced_local)
3167     return FALSE;
3168
3169   /* Identify the cases where name binding rules say that a
3170      visible symbol resolves locally.  */
3171   binding_stays_local_p = (bfd_link_executable (info)
3172                            || SYMBOLIC_BIND (info, h));
3173
3174   switch (ELF_ST_VISIBILITY (h->other))
3175     {
3176     case STV_INTERNAL:
3177     case STV_HIDDEN:
3178       return FALSE;
3179
3180     case STV_PROTECTED:
3181       hash_table = elf_hash_table (info);
3182       if (!is_elf_hash_table (hash_table))
3183         return FALSE;
3184
3185       bed = get_elf_backend_data (hash_table->dynobj);
3186
3187       /* Proper resolution for function pointer equality may require
3188          that these symbols perhaps be resolved dynamically, even though
3189          we should be resolving them to the current module.  */
3190       if (!not_local_protected || !bed->is_function_type (h->type))
3191         binding_stays_local_p = TRUE;
3192       break;
3193
3194     default:
3195       break;
3196     }
3197
3198   /* If it isn't defined locally, then clearly it's dynamic.  */
3199   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
3200     return TRUE;
3201
3202   /* Otherwise, the symbol is dynamic if binding rules don't tell
3203      us that it remains local.  */
3204   return !binding_stays_local_p;
3205 }
3206
3207 /* Return true if the symbol referred to by H should be considered
3208    to resolve local to the current module, and false otherwise.  Differs
3209    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
3210    undefined symbols.  The two functions are virtually identical except
3211    for the place where dynindx == -1 is tested.  If that test is true,
3212    _bfd_elf_dynamic_symbol_p will say the symbol is local, while
3213    _bfd_elf_symbol_refs_local_p will say the symbol is local only for
3214    defined symbols.
3215    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
3216    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
3217    treatment of undefined weak symbols.  For those that do not make
3218    undefined weak symbols dynamic, both functions may return false.  */
3219
3220 bfd_boolean
3221 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
3222                               struct bfd_link_info *info,
3223                               bfd_boolean local_protected)
3224 {
3225   const struct elf_backend_data *bed;
3226   struct elf_link_hash_table *hash_table;
3227
3228   /* If it's a local sym, of course we resolve locally.  */
3229   if (h == NULL)
3230     return TRUE;
3231
3232   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
3233   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
3234       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
3235     return TRUE;
3236
3237   /* Forced local symbols resolve locally.  */
3238   if (h->forced_local)
3239     return TRUE;
3240
3241   /* Common symbols that become definitions don't get the DEF_REGULAR
3242      flag set, so test it first, and don't bail out.  */
3243   if (ELF_COMMON_DEF_P (h))
3244     /* Do nothing.  */;
3245   /* If we don't have a definition in a regular file, then we can't
3246      resolve locally.  The sym is either undefined or dynamic.  */
3247   else if (!h->def_regular)
3248     return FALSE;
3249
3250   /* Non-dynamic symbols resolve locally.  */
3251   if (h->dynindx == -1)
3252     return TRUE;
3253
3254   /* At this point, we know the symbol is defined and dynamic.  In an
3255      executable it must resolve locally, likewise when building symbolic
3256      shared libraries.  */
3257   if (bfd_link_executable (info) || SYMBOLIC_BIND (info, h))
3258     return TRUE;
3259
3260   /* Now deal with defined dynamic symbols in shared libraries.  Ones
3261      with default visibility might not resolve locally.  */
3262   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
3263     return FALSE;
3264
3265   hash_table = elf_hash_table (info);
3266   if (!is_elf_hash_table (hash_table))
3267     return TRUE;
3268
3269   bed = get_elf_backend_data (hash_table->dynobj);
3270
3271   /* If extern_protected_data is false, STV_PROTECTED non-function
3272      symbols are local.  */
3273   if ((!info->extern_protected_data
3274        || (info->extern_protected_data < 0
3275            && !bed->extern_protected_data))
3276       && !bed->is_function_type (h->type))
3277     return TRUE;
3278
3279   /* Function pointer equality tests may require that STV_PROTECTED
3280      symbols be treated as dynamic symbols.  If the address of a
3281      function not defined in an executable is set to that function's
3282      plt entry in the executable, then the address of the function in
3283      a shared library must also be the plt entry in the executable.  */
3284   return local_protected;
3285 }
3286
3287 /* Caches some TLS segment info, and ensures that the TLS segment vma is
3288    aligned.  Returns the first TLS output section.  */
3289
3290 struct bfd_section *
3291 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
3292 {
3293   struct bfd_section *sec, *tls;
3294   unsigned int align = 0;
3295
3296   for (sec = obfd->sections; sec != NULL; sec = sec->next)
3297     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
3298       break;
3299   tls = sec;
3300
3301   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
3302     if (sec->alignment_power > align)
3303       align = sec->alignment_power;
3304
3305   elf_hash_table (info)->tls_sec = tls;
3306
3307   /* Ensure the alignment of the first section is the largest alignment,
3308      so that the tls segment starts aligned.  */
3309   if (tls != NULL)
3310     tls->alignment_power = align;
3311
3312   return tls;
3313 }
3314
3315 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
3316 static bfd_boolean
3317 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
3318                                   Elf_Internal_Sym *sym)
3319 {
3320   const struct elf_backend_data *bed;
3321
3322   /* Local symbols do not count, but target specific ones might.  */
3323   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
3324       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
3325     return FALSE;
3326
3327   bed = get_elf_backend_data (abfd);
3328   /* Function symbols do not count.  */
3329   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
3330     return FALSE;
3331
3332   /* If the section is undefined, then so is the symbol.  */
3333   if (sym->st_shndx == SHN_UNDEF)
3334     return FALSE;
3335
3336   /* If the symbol is defined in the common section, then
3337      it is a common definition and so does not count.  */
3338   if (bed->common_definition (sym))
3339     return FALSE;
3340
3341   /* If the symbol is in a target specific section then we
3342      must rely upon the backend to tell us what it is.  */
3343   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3344     /* FIXME - this function is not coded yet:
3345
3346        return _bfd_is_global_symbol_definition (abfd, sym);
3347
3348        Instead for now assume that the definition is not global,
3349        Even if this is wrong, at least the linker will behave
3350        in the same way that it used to do.  */
3351     return FALSE;
3352
3353   return TRUE;
3354 }
3355
3356 /* Search the symbol table of the archive element of the archive ABFD
3357    whose archive map contains a mention of SYMDEF, and determine if
3358    the symbol is defined in this element.  */
3359 static bfd_boolean
3360 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3361 {
3362   Elf_Internal_Shdr * hdr;
3363   size_t symcount;
3364   size_t extsymcount;
3365   size_t extsymoff;
3366   Elf_Internal_Sym *isymbuf;
3367   Elf_Internal_Sym *isym;
3368   Elf_Internal_Sym *isymend;
3369   bfd_boolean result;
3370
3371   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3372   if (abfd == NULL)
3373     return FALSE;
3374
3375   if (! bfd_check_format (abfd, bfd_object))
3376     return FALSE;
3377
3378   /* Select the appropriate symbol table.  If we don't know if the
3379      object file is an IR object, give linker LTO plugin a chance to
3380      get the correct symbol table.  */
3381   if (abfd->plugin_format == bfd_plugin_yes
3382 #if BFD_SUPPORTS_PLUGINS
3383       || (abfd->plugin_format == bfd_plugin_unknown
3384           && bfd_link_plugin_object_p (abfd))
3385 #endif
3386       )
3387     {
3388       /* Use the IR symbol table if the object has been claimed by
3389          plugin.  */
3390       abfd = abfd->plugin_dummy_bfd;
3391       hdr = &elf_tdata (abfd)->symtab_hdr;
3392     }
3393   else if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3394     hdr = &elf_tdata (abfd)->symtab_hdr;
3395   else
3396     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3397
3398   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3399
3400   /* The sh_info field of the symtab header tells us where the
3401      external symbols start.  We don't care about the local symbols.  */
3402   if (elf_bad_symtab (abfd))
3403     {
3404       extsymcount = symcount;
3405       extsymoff = 0;
3406     }
3407   else
3408     {
3409       extsymcount = symcount - hdr->sh_info;
3410       extsymoff = hdr->sh_info;
3411     }
3412
3413   if (extsymcount == 0)
3414     return FALSE;
3415
3416   /* Read in the symbol table.  */
3417   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3418                                   NULL, NULL, NULL);
3419   if (isymbuf == NULL)
3420     return FALSE;
3421
3422   /* Scan the symbol table looking for SYMDEF.  */
3423   result = FALSE;
3424   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3425     {
3426       const char *name;
3427
3428       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3429                                               isym->st_name);
3430       if (name == NULL)
3431         break;
3432
3433       if (strcmp (name, symdef->name) == 0)
3434         {
3435           result = is_global_data_symbol_definition (abfd, isym);
3436           break;
3437         }
3438     }
3439
3440   free (isymbuf);
3441
3442   return result;
3443 }
3444 \f
3445 /* Add an entry to the .dynamic table.  */
3446
3447 bfd_boolean
3448 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3449                             bfd_vma tag,
3450                             bfd_vma val)
3451 {
3452   struct elf_link_hash_table *hash_table;
3453   const struct elf_backend_data *bed;
3454   asection *s;
3455   bfd_size_type newsize;
3456   bfd_byte *newcontents;
3457   Elf_Internal_Dyn dyn;
3458
3459   hash_table = elf_hash_table (info);
3460   if (! is_elf_hash_table (hash_table))
3461     return FALSE;
3462
3463   if (tag == DT_RELA || tag == DT_REL)
3464     hash_table->dynamic_relocs = TRUE;
3465
3466   bed = get_elf_backend_data (hash_table->dynobj);
3467   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3468   BFD_ASSERT (s != NULL);
3469
3470   newsize = s->size + bed->s->sizeof_dyn;
3471   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3472   if (newcontents == NULL)
3473     return FALSE;
3474
3475   dyn.d_tag = tag;
3476   dyn.d_un.d_val = val;
3477   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3478
3479   s->size = newsize;
3480   s->contents = newcontents;
3481
3482   return TRUE;
3483 }
3484
3485 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3486    otherwise just check whether one already exists.  Returns -1 on error,
3487    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3488
3489 static int
3490 elf_add_dt_needed_tag (bfd *abfd,
3491                        struct bfd_link_info *info,
3492                        const char *soname,
3493                        bfd_boolean do_it)
3494 {
3495   struct elf_link_hash_table *hash_table;
3496   size_t strindex;
3497
3498   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3499     return -1;
3500
3501   hash_table = elf_hash_table (info);
3502   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3503   if (strindex == (size_t) -1)
3504     return -1;
3505
3506   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3507     {
3508       asection *sdyn;
3509       const struct elf_backend_data *bed;
3510       bfd_byte *extdyn;
3511
3512       bed = get_elf_backend_data (hash_table->dynobj);
3513       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3514       if (sdyn != NULL)
3515         for (extdyn = sdyn->contents;
3516              extdyn < sdyn->contents + sdyn->size;
3517              extdyn += bed->s->sizeof_dyn)
3518           {
3519             Elf_Internal_Dyn dyn;
3520
3521             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3522             if (dyn.d_tag == DT_NEEDED
3523                 && dyn.d_un.d_val == strindex)
3524               {
3525                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3526                 return 1;
3527               }
3528           }
3529     }
3530
3531   if (do_it)
3532     {
3533       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3534         return -1;
3535
3536       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3537         return -1;
3538     }
3539   else
3540     /* We were just checking for existence of the tag.  */
3541     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3542
3543   return 0;
3544 }
3545
3546 /* Return true if SONAME is on the needed list between NEEDED and STOP
3547    (or the end of list if STOP is NULL), and needed by a library that
3548    will be loaded.  */
3549
3550 static bfd_boolean
3551 on_needed_list (const char *soname,
3552                 struct bfd_link_needed_list *needed,
3553                 struct bfd_link_needed_list *stop)
3554 {
3555   struct bfd_link_needed_list *look;
3556   for (look = needed; look != stop; look = look->next)
3557     if (strcmp (soname, look->name) == 0
3558         && ((elf_dyn_lib_class (look->by) & DYN_AS_NEEDED) == 0
3559             /* If needed by a library that itself is not directly
3560                needed, recursively check whether that library is
3561                indirectly needed.  Since we add DT_NEEDED entries to
3562                the end of the list, library dependencies appear after
3563                the library.  Therefore search prior to the current
3564                LOOK, preventing possible infinite recursion.  */
3565             || on_needed_list (elf_dt_name (look->by), needed, look)))
3566       return TRUE;
3567
3568   return FALSE;
3569 }
3570
3571 /* Sort symbol by value, section, and size.  */
3572 static int
3573 elf_sort_symbol (const void *arg1, const void *arg2)
3574 {
3575   const struct elf_link_hash_entry *h1;
3576   const struct elf_link_hash_entry *h2;
3577   bfd_signed_vma vdiff;
3578
3579   h1 = *(const struct elf_link_hash_entry **) arg1;
3580   h2 = *(const struct elf_link_hash_entry **) arg2;
3581   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3582   if (vdiff != 0)
3583     return vdiff > 0 ? 1 : -1;
3584   else
3585     {
3586       int sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3587       if (sdiff != 0)
3588         return sdiff > 0 ? 1 : -1;
3589     }
3590   vdiff = h1->size - h2->size;
3591   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3592 }
3593
3594 /* This function is used to adjust offsets into .dynstr for
3595    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3596
3597 static bfd_boolean
3598 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3599 {
3600   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3601
3602   if (h->dynindx != -1)
3603     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3604   return TRUE;
3605 }
3606
3607 /* Assign string offsets in .dynstr, update all structures referencing
3608    them.  */
3609
3610 static bfd_boolean
3611 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3612 {
3613   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3614   struct elf_link_local_dynamic_entry *entry;
3615   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3616   bfd *dynobj = hash_table->dynobj;
3617   asection *sdyn;
3618   bfd_size_type size;
3619   const struct elf_backend_data *bed;
3620   bfd_byte *extdyn;
3621
3622   _bfd_elf_strtab_finalize (dynstr);
3623   size = _bfd_elf_strtab_size (dynstr);
3624
3625   bed = get_elf_backend_data (dynobj);
3626   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3627   BFD_ASSERT (sdyn != NULL);
3628
3629   /* Update all .dynamic entries referencing .dynstr strings.  */
3630   for (extdyn = sdyn->contents;
3631        extdyn < sdyn->contents + sdyn->size;
3632        extdyn += bed->s->sizeof_dyn)
3633     {
3634       Elf_Internal_Dyn dyn;
3635
3636       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3637       switch (dyn.d_tag)
3638         {
3639         case DT_STRSZ:
3640           dyn.d_un.d_val = size;
3641           break;
3642         case DT_NEEDED:
3643         case DT_SONAME:
3644         case DT_RPATH:
3645         case DT_RUNPATH:
3646         case DT_FILTER:
3647         case DT_AUXILIARY:
3648         case DT_AUDIT:
3649         case DT_DEPAUDIT:
3650           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3651           break;
3652         default:
3653           continue;
3654         }
3655       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3656     }
3657
3658   /* Now update local dynamic symbols.  */
3659   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3660     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3661                                                   entry->isym.st_name);
3662
3663   /* And the rest of dynamic symbols.  */
3664   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3665
3666   /* Adjust version definitions.  */
3667   if (elf_tdata (output_bfd)->cverdefs)
3668     {
3669       asection *s;
3670       bfd_byte *p;
3671       size_t i;
3672       Elf_Internal_Verdef def;
3673       Elf_Internal_Verdaux defaux;
3674
3675       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3676       p = s->contents;
3677       do
3678         {
3679           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3680                                    &def);
3681           p += sizeof (Elf_External_Verdef);
3682           if (def.vd_aux != sizeof (Elf_External_Verdef))
3683             continue;
3684           for (i = 0; i < def.vd_cnt; ++i)
3685             {
3686               _bfd_elf_swap_verdaux_in (output_bfd,
3687                                         (Elf_External_Verdaux *) p, &defaux);
3688               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3689                                                         defaux.vda_name);
3690               _bfd_elf_swap_verdaux_out (output_bfd,
3691                                          &defaux, (Elf_External_Verdaux *) p);
3692               p += sizeof (Elf_External_Verdaux);
3693             }
3694         }
3695       while (def.vd_next);
3696     }
3697
3698   /* Adjust version references.  */
3699   if (elf_tdata (output_bfd)->verref)
3700     {
3701       asection *s;
3702       bfd_byte *p;
3703       size_t i;
3704       Elf_Internal_Verneed need;
3705       Elf_Internal_Vernaux needaux;
3706
3707       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3708       p = s->contents;
3709       do
3710         {
3711           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3712                                     &need);
3713           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3714           _bfd_elf_swap_verneed_out (output_bfd, &need,
3715                                      (Elf_External_Verneed *) p);
3716           p += sizeof (Elf_External_Verneed);
3717           for (i = 0; i < need.vn_cnt; ++i)
3718             {
3719               _bfd_elf_swap_vernaux_in (output_bfd,
3720                                         (Elf_External_Vernaux *) p, &needaux);
3721               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3722                                                          needaux.vna_name);
3723               _bfd_elf_swap_vernaux_out (output_bfd,
3724                                          &needaux,
3725                                          (Elf_External_Vernaux *) p);
3726               p += sizeof (Elf_External_Vernaux);
3727             }
3728         }
3729       while (need.vn_next);
3730     }
3731
3732   return TRUE;
3733 }
3734 \f
3735 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3736    The default is to only match when the INPUT and OUTPUT are exactly
3737    the same target.  */
3738
3739 bfd_boolean
3740 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3741                                     const bfd_target *output)
3742 {
3743   return input == output;
3744 }
3745
3746 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3747    This version is used when different targets for the same architecture
3748    are virtually identical.  */
3749
3750 bfd_boolean
3751 _bfd_elf_relocs_compatible (const bfd_target *input,
3752                             const bfd_target *output)
3753 {
3754   const struct elf_backend_data *obed, *ibed;
3755
3756   if (input == output)
3757     return TRUE;
3758
3759   ibed = xvec_get_elf_backend_data (input);
3760   obed = xvec_get_elf_backend_data (output);
3761
3762   if (ibed->arch != obed->arch)
3763     return FALSE;
3764
3765   /* If both backends are using this function, deem them compatible.  */
3766   return ibed->relocs_compatible == obed->relocs_compatible;
3767 }
3768
3769 /* Make a special call to the linker "notice" function to tell it that
3770    we are about to handle an as-needed lib, or have finished
3771    processing the lib.  */
3772
3773 bfd_boolean
3774 _bfd_elf_notice_as_needed (bfd *ibfd,
3775                            struct bfd_link_info *info,
3776                            enum notice_asneeded_action act)
3777 {
3778   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3779 }
3780
3781 /* Check relocations an ELF object file.  */
3782
3783 bfd_boolean
3784 _bfd_elf_link_check_relocs (bfd *abfd, struct bfd_link_info *info)
3785 {
3786   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3787   struct elf_link_hash_table *htab = elf_hash_table (info);
3788
3789   /* If this object is the same format as the output object, and it is
3790      not a shared library, then let the backend look through the
3791      relocs.
3792
3793      This is required to build global offset table entries and to
3794      arrange for dynamic relocs.  It is not required for the
3795      particular common case of linking non PIC code, even when linking
3796      against shared libraries, but unfortunately there is no way of
3797      knowing whether an object file has been compiled PIC or not.
3798      Looking through the relocs is not particularly time consuming.
3799      The problem is that we must either (1) keep the relocs in memory,
3800      which causes the linker to require additional runtime memory or
3801      (2) read the relocs twice from the input file, which wastes time.
3802      This would be a good case for using mmap.
3803
3804      I have no idea how to handle linking PIC code into a file of a
3805      different format.  It probably can't be done.  */
3806   if ((abfd->flags & DYNAMIC) == 0
3807       && is_elf_hash_table (htab)
3808       && bed->check_relocs != NULL
3809       && elf_object_id (abfd) == elf_hash_table_id (htab)
3810       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
3811     {
3812       asection *o;
3813
3814       for (o = abfd->sections; o != NULL; o = o->next)
3815         {
3816           Elf_Internal_Rela *internal_relocs;
3817           bfd_boolean ok;
3818
3819           /* Don't check relocations in excluded sections.  */
3820           if ((o->flags & SEC_RELOC) == 0
3821               || (o->flags & SEC_EXCLUDE) != 0
3822               || o->reloc_count == 0
3823               || ((info->strip == strip_all || info->strip == strip_debugger)
3824                   && (o->flags & SEC_DEBUGGING) != 0)
3825               || bfd_is_abs_section (o->output_section))
3826             continue;
3827
3828           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
3829                                                        info->keep_memory);
3830           if (internal_relocs == NULL)
3831             return FALSE;
3832
3833           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
3834
3835           if (elf_section_data (o)->relocs != internal_relocs)
3836             free (internal_relocs);
3837
3838           if (! ok)
3839             return FALSE;
3840         }
3841     }
3842
3843   return TRUE;
3844 }
3845
3846 /* Add symbols from an ELF object file to the linker hash table.  */
3847
3848 static bfd_boolean
3849 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3850 {
3851   Elf_Internal_Ehdr *ehdr;
3852   Elf_Internal_Shdr *hdr;
3853   size_t symcount;
3854   size_t extsymcount;
3855   size_t extsymoff;
3856   struct elf_link_hash_entry **sym_hash;
3857   bfd_boolean dynamic;
3858   Elf_External_Versym *extversym = NULL;
3859   Elf_External_Versym *ever;
3860   struct elf_link_hash_entry *weaks;
3861   struct elf_link_hash_entry **nondeflt_vers = NULL;
3862   size_t nondeflt_vers_cnt = 0;
3863   Elf_Internal_Sym *isymbuf = NULL;
3864   Elf_Internal_Sym *isym;
3865   Elf_Internal_Sym *isymend;
3866   const struct elf_backend_data *bed;
3867   bfd_boolean add_needed;
3868   struct elf_link_hash_table *htab;
3869   bfd_size_type amt;
3870   void *alloc_mark = NULL;
3871   struct bfd_hash_entry **old_table = NULL;
3872   unsigned int old_size = 0;
3873   unsigned int old_count = 0;
3874   void *old_tab = NULL;
3875   void *old_ent;
3876   struct bfd_link_hash_entry *old_undefs = NULL;
3877   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3878   void *old_strtab = NULL;
3879   size_t tabsize = 0;
3880   asection *s;
3881   bfd_boolean just_syms;
3882
3883   htab = elf_hash_table (info);
3884   bed = get_elf_backend_data (abfd);
3885
3886   if ((abfd->flags & DYNAMIC) == 0)
3887     dynamic = FALSE;
3888   else
3889     {
3890       dynamic = TRUE;
3891
3892       /* You can't use -r against a dynamic object.  Also, there's no
3893          hope of using a dynamic object which does not exactly match
3894          the format of the output file.  */
3895       if (bfd_link_relocatable (info)
3896           || !is_elf_hash_table (htab)
3897           || info->output_bfd->xvec != abfd->xvec)
3898         {
3899           if (bfd_link_relocatable (info))
3900             bfd_set_error (bfd_error_invalid_operation);
3901           else
3902             bfd_set_error (bfd_error_wrong_format);
3903           goto error_return;
3904         }
3905     }
3906
3907   ehdr = elf_elfheader (abfd);
3908   if (info->warn_alternate_em
3909       && bed->elf_machine_code != ehdr->e_machine
3910       && ((bed->elf_machine_alt1 != 0
3911            && ehdr->e_machine == bed->elf_machine_alt1)
3912           || (bed->elf_machine_alt2 != 0
3913               && ehdr->e_machine == bed->elf_machine_alt2)))
3914     _bfd_error_handler
3915       /* xgettext:c-format */
3916       (_("alternate ELF machine code found (%d) in %pB, expecting %d"),
3917        ehdr->e_machine, abfd, bed->elf_machine_code);
3918
3919   /* As a GNU extension, any input sections which are named
3920      .gnu.warning.SYMBOL are treated as warning symbols for the given
3921      symbol.  This differs from .gnu.warning sections, which generate
3922      warnings when they are included in an output file.  */
3923   /* PR 12761: Also generate this warning when building shared libraries.  */
3924   for (s = abfd->sections; s != NULL; s = s->next)
3925     {
3926       const char *name;
3927
3928       name = bfd_get_section_name (abfd, s);
3929       if (CONST_STRNEQ (name, ".gnu.warning."))
3930         {
3931           char *msg;
3932           bfd_size_type sz;
3933
3934           name += sizeof ".gnu.warning." - 1;
3935
3936           /* If this is a shared object, then look up the symbol
3937              in the hash table.  If it is there, and it is already
3938              been defined, then we will not be using the entry
3939              from this shared object, so we don't need to warn.
3940              FIXME: If we see the definition in a regular object
3941              later on, we will warn, but we shouldn't.  The only
3942              fix is to keep track of what warnings we are supposed
3943              to emit, and then handle them all at the end of the
3944              link.  */
3945           if (dynamic)
3946             {
3947               struct elf_link_hash_entry *h;
3948
3949               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3950
3951               /* FIXME: What about bfd_link_hash_common?  */
3952               if (h != NULL
3953                   && (h->root.type == bfd_link_hash_defined
3954                       || h->root.type == bfd_link_hash_defweak))
3955                 continue;
3956             }
3957
3958           sz = s->size;
3959           msg = (char *) bfd_alloc (abfd, sz + 1);
3960           if (msg == NULL)
3961             goto error_return;
3962
3963           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3964             goto error_return;
3965
3966           msg[sz] = '\0';
3967
3968           if (! (_bfd_generic_link_add_one_symbol
3969                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3970                   FALSE, bed->collect, NULL)))
3971             goto error_return;
3972
3973           if (bfd_link_executable (info))
3974             {
3975               /* Clobber the section size so that the warning does
3976                  not get copied into the output file.  */
3977               s->size = 0;
3978
3979               /* Also set SEC_EXCLUDE, so that symbols defined in
3980                  the warning section don't get copied to the output.  */
3981               s->flags |= SEC_EXCLUDE;
3982             }
3983         }
3984     }
3985
3986   just_syms = ((s = abfd->sections) != NULL
3987                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3988
3989   add_needed = TRUE;
3990   if (! dynamic)
3991     {
3992       /* If we are creating a shared library, create all the dynamic
3993          sections immediately.  We need to attach them to something,
3994          so we attach them to this BFD, provided it is the right
3995          format and is not from ld --just-symbols.  Always create the
3996          dynamic sections for -E/--dynamic-list.  FIXME: If there
3997          are no input BFD's of the same format as the output, we can't
3998          make a shared library.  */
3999       if (!just_syms
4000           && (bfd_link_pic (info)
4001               || (!bfd_link_relocatable (info)
4002                   && info->nointerp
4003                   && (info->export_dynamic || info->dynamic)))
4004           && is_elf_hash_table (htab)
4005           && info->output_bfd->xvec == abfd->xvec
4006           && !htab->dynamic_sections_created)
4007         {
4008           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
4009             goto error_return;
4010         }
4011     }
4012   else if (!is_elf_hash_table (htab))
4013     goto error_return;
4014   else
4015     {
4016       const char *soname = NULL;
4017       char *audit = NULL;
4018       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
4019       const Elf_Internal_Phdr *phdr;
4020       int ret;
4021
4022       /* ld --just-symbols and dynamic objects don't mix very well.
4023          ld shouldn't allow it.  */
4024       if (just_syms)
4025         abort ();
4026
4027       /* If this dynamic lib was specified on the command line with
4028          --as-needed in effect, then we don't want to add a DT_NEEDED
4029          tag unless the lib is actually used.  Similary for libs brought
4030          in by another lib's DT_NEEDED.  When --no-add-needed is used
4031          on a dynamic lib, we don't want to add a DT_NEEDED entry for
4032          any dynamic library in DT_NEEDED tags in the dynamic lib at
4033          all.  */
4034       add_needed = (elf_dyn_lib_class (abfd)
4035                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
4036                        | DYN_NO_NEEDED)) == 0;
4037
4038       s = bfd_get_section_by_name (abfd, ".dynamic");
4039       if (s != NULL)
4040         {
4041           bfd_byte *dynbuf;
4042           bfd_byte *extdyn;
4043           unsigned int elfsec;
4044           unsigned long shlink;
4045
4046           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
4047             {
4048 error_free_dyn:
4049               free (dynbuf);
4050               goto error_return;
4051             }
4052
4053           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
4054           if (elfsec == SHN_BAD)
4055             goto error_free_dyn;
4056           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
4057
4058           for (extdyn = dynbuf;
4059                extdyn < dynbuf + s->size;
4060                extdyn += bed->s->sizeof_dyn)
4061             {
4062               Elf_Internal_Dyn dyn;
4063
4064               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
4065               if (dyn.d_tag == DT_SONAME)
4066                 {
4067                   unsigned int tagv = dyn.d_un.d_val;
4068                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4069                   if (soname == NULL)
4070                     goto error_free_dyn;
4071                 }
4072               if (dyn.d_tag == DT_NEEDED)
4073                 {
4074                   struct bfd_link_needed_list *n, **pn;
4075                   char *fnm, *anm;
4076                   unsigned int tagv = dyn.d_un.d_val;
4077
4078                   amt = sizeof (struct bfd_link_needed_list);
4079                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
4080                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4081                   if (n == NULL || fnm == NULL)
4082                     goto error_free_dyn;
4083                   amt = strlen (fnm) + 1;
4084                   anm = (char *) bfd_alloc (abfd, amt);
4085                   if (anm == NULL)
4086                     goto error_free_dyn;
4087                   memcpy (anm, fnm, amt);
4088                   n->name = anm;
4089                   n->by = abfd;
4090                   n->next = NULL;
4091                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
4092                     ;
4093                   *pn = n;
4094                 }
4095               if (dyn.d_tag == DT_RUNPATH)
4096                 {
4097                   struct bfd_link_needed_list *n, **pn;
4098                   char *fnm, *anm;
4099                   unsigned int tagv = dyn.d_un.d_val;
4100
4101                   amt = sizeof (struct bfd_link_needed_list);
4102                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
4103                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4104                   if (n == NULL || fnm == NULL)
4105                     goto error_free_dyn;
4106                   amt = strlen (fnm) + 1;
4107                   anm = (char *) bfd_alloc (abfd, amt);
4108                   if (anm == NULL)
4109                     goto error_free_dyn;
4110                   memcpy (anm, fnm, amt);
4111                   n->name = anm;
4112                   n->by = abfd;
4113                   n->next = NULL;
4114                   for (pn = & runpath;
4115                        *pn != NULL;
4116                        pn = &(*pn)->next)
4117                     ;
4118                   *pn = n;
4119                 }
4120               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
4121               if (!runpath && dyn.d_tag == DT_RPATH)
4122                 {
4123                   struct bfd_link_needed_list *n, **pn;
4124                   char *fnm, *anm;
4125                   unsigned int tagv = dyn.d_un.d_val;
4126
4127                   amt = sizeof (struct bfd_link_needed_list);
4128                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
4129                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4130                   if (n == NULL || fnm == NULL)
4131                     goto error_free_dyn;
4132                   amt = strlen (fnm) + 1;
4133                   anm = (char *) bfd_alloc (abfd, amt);
4134                   if (anm == NULL)
4135                     goto error_free_dyn;
4136                   memcpy (anm, fnm, amt);
4137                   n->name = anm;
4138                   n->by = abfd;
4139                   n->next = NULL;
4140                   for (pn = & rpath;
4141                        *pn != NULL;
4142                        pn = &(*pn)->next)
4143                     ;
4144                   *pn = n;
4145                 }
4146               if (dyn.d_tag == DT_AUDIT)
4147                 {
4148                   unsigned int tagv = dyn.d_un.d_val;
4149                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4150                 }
4151             }
4152
4153           free (dynbuf);
4154         }
4155
4156       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
4157          frees all more recently bfd_alloc'd blocks as well.  */
4158       if (runpath)
4159         rpath = runpath;
4160
4161       if (rpath)
4162         {
4163           struct bfd_link_needed_list **pn;
4164           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
4165             ;
4166           *pn = rpath;
4167         }
4168
4169       /* If we have a PT_GNU_RELRO program header, mark as read-only
4170          all sections contained fully therein.  This makes relro
4171          shared library sections appear as they will at run-time.  */
4172       phdr = elf_tdata (abfd)->phdr + elf_elfheader (abfd)->e_phnum;
4173       while (--phdr >= elf_tdata (abfd)->phdr)
4174         if (phdr->p_type == PT_GNU_RELRO)
4175           {
4176             for (s = abfd->sections; s != NULL; s = s->next)
4177               if ((s->flags & SEC_ALLOC) != 0
4178                   && s->vma >= phdr->p_vaddr
4179                   && s->vma + s->size <= phdr->p_vaddr + phdr->p_memsz)
4180                 s->flags |= SEC_READONLY;
4181             break;
4182           }
4183
4184       /* We do not want to include any of the sections in a dynamic
4185          object in the output file.  We hack by simply clobbering the
4186          list of sections in the BFD.  This could be handled more
4187          cleanly by, say, a new section flag; the existing
4188          SEC_NEVER_LOAD flag is not the one we want, because that one
4189          still implies that the section takes up space in the output
4190          file.  */
4191       bfd_section_list_clear (abfd);
4192
4193       /* Find the name to use in a DT_NEEDED entry that refers to this
4194          object.  If the object has a DT_SONAME entry, we use it.
4195          Otherwise, if the generic linker stuck something in
4196          elf_dt_name, we use that.  Otherwise, we just use the file
4197          name.  */
4198       if (soname == NULL || *soname == '\0')
4199         {
4200           soname = elf_dt_name (abfd);
4201           if (soname == NULL || *soname == '\0')
4202             soname = bfd_get_filename (abfd);
4203         }
4204
4205       /* Save the SONAME because sometimes the linker emulation code
4206          will need to know it.  */
4207       elf_dt_name (abfd) = soname;
4208
4209       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4210       if (ret < 0)
4211         goto error_return;
4212
4213       /* If we have already included this dynamic object in the
4214          link, just ignore it.  There is no reason to include a
4215          particular dynamic object more than once.  */
4216       if (ret > 0)
4217         return TRUE;
4218
4219       /* Save the DT_AUDIT entry for the linker emulation code. */
4220       elf_dt_audit (abfd) = audit;
4221     }
4222
4223   /* If this is a dynamic object, we always link against the .dynsym
4224      symbol table, not the .symtab symbol table.  The dynamic linker
4225      will only see the .dynsym symbol table, so there is no reason to
4226      look at .symtab for a dynamic object.  */
4227
4228   if (! dynamic || elf_dynsymtab (abfd) == 0)
4229     hdr = &elf_tdata (abfd)->symtab_hdr;
4230   else
4231     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
4232
4233   symcount = hdr->sh_size / bed->s->sizeof_sym;
4234
4235   /* The sh_info field of the symtab header tells us where the
4236      external symbols start.  We don't care about the local symbols at
4237      this point.  */
4238   if (elf_bad_symtab (abfd))
4239     {
4240       extsymcount = symcount;
4241       extsymoff = 0;
4242     }
4243   else
4244     {
4245       extsymcount = symcount - hdr->sh_info;
4246       extsymoff = hdr->sh_info;
4247     }
4248
4249   sym_hash = elf_sym_hashes (abfd);
4250   if (extsymcount != 0)
4251     {
4252       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
4253                                       NULL, NULL, NULL);
4254       if (isymbuf == NULL)
4255         goto error_return;
4256
4257       if (sym_hash == NULL)
4258         {
4259           /* We store a pointer to the hash table entry for each
4260              external symbol.  */
4261           amt = extsymcount;
4262           amt *= sizeof (struct elf_link_hash_entry *);
4263           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
4264           if (sym_hash == NULL)
4265             goto error_free_sym;
4266           elf_sym_hashes (abfd) = sym_hash;
4267         }
4268     }
4269
4270   if (dynamic)
4271     {
4272       /* Read in any version definitions.  */
4273       if (!_bfd_elf_slurp_version_tables (abfd,
4274                                           info->default_imported_symver))
4275         goto error_free_sym;
4276
4277       /* Read in the symbol versions, but don't bother to convert them
4278          to internal format.  */
4279       if (elf_dynversym (abfd) != 0)
4280         {
4281           Elf_Internal_Shdr *versymhdr;
4282
4283           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
4284           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
4285           if (extversym == NULL)
4286             goto error_free_sym;
4287           amt = versymhdr->sh_size;
4288           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
4289               || bfd_bread (extversym, amt, abfd) != amt)
4290             goto error_free_vers;
4291         }
4292     }
4293
4294   /* If we are loading an as-needed shared lib, save the symbol table
4295      state before we start adding symbols.  If the lib turns out
4296      to be unneeded, restore the state.  */
4297   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4298     {
4299       unsigned int i;
4300       size_t entsize;
4301
4302       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
4303         {
4304           struct bfd_hash_entry *p;
4305           struct elf_link_hash_entry *h;
4306
4307           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4308             {
4309               h = (struct elf_link_hash_entry *) p;
4310               entsize += htab->root.table.entsize;
4311               if (h->root.type == bfd_link_hash_warning)
4312                 entsize += htab->root.table.entsize;
4313             }
4314         }
4315
4316       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
4317       old_tab = bfd_malloc (tabsize + entsize);
4318       if (old_tab == NULL)
4319         goto error_free_vers;
4320
4321       /* Remember the current objalloc pointer, so that all mem for
4322          symbols added can later be reclaimed.  */
4323       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
4324       if (alloc_mark == NULL)
4325         goto error_free_vers;
4326
4327       /* Make a special call to the linker "notice" function to
4328          tell it that we are about to handle an as-needed lib.  */
4329       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
4330         goto error_free_vers;
4331
4332       /* Clone the symbol table.  Remember some pointers into the
4333          symbol table, and dynamic symbol count.  */
4334       old_ent = (char *) old_tab + tabsize;
4335       memcpy (old_tab, htab->root.table.table, tabsize);
4336       old_undefs = htab->root.undefs;
4337       old_undefs_tail = htab->root.undefs_tail;
4338       old_table = htab->root.table.table;
4339       old_size = htab->root.table.size;
4340       old_count = htab->root.table.count;
4341       old_strtab = _bfd_elf_strtab_save (htab->dynstr);
4342       if (old_strtab == NULL)
4343         goto error_free_vers;
4344
4345       for (i = 0; i < htab->root.table.size; i++)
4346         {
4347           struct bfd_hash_entry *p;
4348           struct elf_link_hash_entry *h;
4349
4350           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4351             {
4352               memcpy (old_ent, p, htab->root.table.entsize);
4353               old_ent = (char *) old_ent + htab->root.table.entsize;
4354               h = (struct elf_link_hash_entry *) p;
4355               if (h->root.type == bfd_link_hash_warning)
4356                 {
4357                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
4358                   old_ent = (char *) old_ent + htab->root.table.entsize;
4359                 }
4360             }
4361         }
4362     }
4363
4364   weaks = NULL;
4365   ever = extversym != NULL ? extversym + extsymoff : NULL;
4366   for (isym = isymbuf, isymend = isymbuf + extsymcount;
4367        isym < isymend;
4368        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
4369     {
4370       int bind;
4371       bfd_vma value;
4372       asection *sec, *new_sec;
4373       flagword flags;
4374       const char *name;
4375       struct elf_link_hash_entry *h;
4376       struct elf_link_hash_entry *hi;
4377       bfd_boolean definition;
4378       bfd_boolean size_change_ok;
4379       bfd_boolean type_change_ok;
4380       bfd_boolean new_weak;
4381       bfd_boolean old_weak;
4382       bfd_boolean override;
4383       bfd_boolean common;
4384       bfd_boolean discarded;
4385       unsigned int old_alignment;
4386       bfd *old_bfd;
4387       bfd_boolean matched;
4388
4389       override = FALSE;
4390
4391       flags = BSF_NO_FLAGS;
4392       sec = NULL;
4393       value = isym->st_value;
4394       common = bed->common_definition (isym);
4395       if (common && info->inhibit_common_definition)
4396         {
4397           /* Treat common symbol as undefined for --no-define-common.  */
4398           isym->st_shndx = SHN_UNDEF;
4399           common = FALSE;
4400         }
4401       discarded = FALSE;
4402
4403       bind = ELF_ST_BIND (isym->st_info);
4404       switch (bind)
4405         {
4406         case STB_LOCAL:
4407           /* This should be impossible, since ELF requires that all
4408              global symbols follow all local symbols, and that sh_info
4409              point to the first global symbol.  Unfortunately, Irix 5
4410              screws this up.  */
4411           continue;
4412
4413         case STB_GLOBAL:
4414           if (isym->st_shndx != SHN_UNDEF && !common)
4415             flags = BSF_GLOBAL;
4416           break;
4417
4418         case STB_WEAK:
4419           flags = BSF_WEAK;
4420           break;
4421
4422         case STB_GNU_UNIQUE:
4423           flags = BSF_GNU_UNIQUE;
4424           break;
4425
4426         default:
4427           /* Leave it up to the processor backend.  */
4428           break;
4429         }
4430
4431       if (isym->st_shndx == SHN_UNDEF)
4432         sec = bfd_und_section_ptr;
4433       else if (isym->st_shndx == SHN_ABS)
4434         sec = bfd_abs_section_ptr;
4435       else if (isym->st_shndx == SHN_COMMON)
4436         {
4437           sec = bfd_com_section_ptr;
4438           /* What ELF calls the size we call the value.  What ELF
4439              calls the value we call the alignment.  */
4440           value = isym->st_size;
4441         }
4442       else
4443         {
4444           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
4445           if (sec == NULL)
4446             sec = bfd_abs_section_ptr;
4447           else if (discarded_section (sec))
4448             {
4449               /* Symbols from discarded section are undefined.  We keep
4450                  its visibility.  */
4451               sec = bfd_und_section_ptr;
4452               discarded = TRUE;
4453               isym->st_shndx = SHN_UNDEF;
4454             }
4455           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
4456             value -= sec->vma;
4457         }
4458
4459       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4460                                               isym->st_name);
4461       if (name == NULL)
4462         goto error_free_vers;
4463
4464       if (isym->st_shndx == SHN_COMMON
4465           && (abfd->flags & BFD_PLUGIN) != 0)
4466         {
4467           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4468
4469           if (xc == NULL)
4470             {
4471               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4472                                  | SEC_EXCLUDE);
4473               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4474               if (xc == NULL)
4475                 goto error_free_vers;
4476             }
4477           sec = xc;
4478         }
4479       else if (isym->st_shndx == SHN_COMMON
4480                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4481                && !bfd_link_relocatable (info))
4482         {
4483           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4484
4485           if (tcomm == NULL)
4486             {
4487               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4488                                  | SEC_LINKER_CREATED);
4489               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4490               if (tcomm == NULL)
4491                 goto error_free_vers;
4492             }
4493           sec = tcomm;
4494         }
4495       else if (bed->elf_add_symbol_hook)
4496         {
4497           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4498                                              &sec, &value))
4499             goto error_free_vers;
4500
4501           /* The hook function sets the name to NULL if this symbol
4502              should be skipped for some reason.  */
4503           if (name == NULL)
4504             continue;
4505         }
4506
4507       /* Sanity check that all possibilities were handled.  */
4508       if (sec == NULL)
4509         {
4510           bfd_set_error (bfd_error_bad_value);
4511           goto error_free_vers;
4512         }
4513
4514       /* Silently discard TLS symbols from --just-syms.  There's
4515          no way to combine a static TLS block with a new TLS block
4516          for this executable.  */
4517       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4518           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4519         continue;
4520
4521       if (bfd_is_und_section (sec)
4522           || bfd_is_com_section (sec))
4523         definition = FALSE;
4524       else
4525         definition = TRUE;
4526
4527       size_change_ok = FALSE;
4528       type_change_ok = bed->type_change_ok;
4529       old_weak = FALSE;
4530       matched = FALSE;
4531       old_alignment = 0;
4532       old_bfd = NULL;
4533       new_sec = sec;
4534
4535       if (is_elf_hash_table (htab))
4536         {
4537           Elf_Internal_Versym iver;
4538           unsigned int vernum = 0;
4539           bfd_boolean skip;
4540
4541           if (ever == NULL)
4542             {
4543               if (info->default_imported_symver)
4544                 /* Use the default symbol version created earlier.  */
4545                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4546               else
4547                 iver.vs_vers = 0;
4548             }
4549           else
4550             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4551
4552           vernum = iver.vs_vers & VERSYM_VERSION;
4553
4554           /* If this is a hidden symbol, or if it is not version
4555              1, we append the version name to the symbol name.
4556              However, we do not modify a non-hidden absolute symbol
4557              if it is not a function, because it might be the version
4558              symbol itself.  FIXME: What if it isn't?  */
4559           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4560               || (vernum > 1
4561                   && (!bfd_is_abs_section (sec)
4562                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4563             {
4564               const char *verstr;
4565               size_t namelen, verlen, newlen;
4566               char *newname, *p;
4567
4568               if (isym->st_shndx != SHN_UNDEF)
4569                 {
4570                   if (vernum > elf_tdata (abfd)->cverdefs)
4571                     verstr = NULL;
4572                   else if (vernum > 1)
4573                     verstr =
4574                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4575                   else
4576                     verstr = "";
4577
4578                   if (verstr == NULL)
4579                     {
4580                       _bfd_error_handler
4581                         /* xgettext:c-format */
4582                         (_("%pB: %s: invalid version %u (max %d)"),
4583                          abfd, name, vernum,
4584                          elf_tdata (abfd)->cverdefs);
4585                       bfd_set_error (bfd_error_bad_value);
4586                       goto error_free_vers;
4587                     }
4588                 }
4589               else
4590                 {
4591                   /* We cannot simply test for the number of
4592                      entries in the VERNEED section since the
4593                      numbers for the needed versions do not start
4594                      at 0.  */
4595                   Elf_Internal_Verneed *t;
4596
4597                   verstr = NULL;
4598                   for (t = elf_tdata (abfd)->verref;
4599                        t != NULL;
4600                        t = t->vn_nextref)
4601                     {
4602                       Elf_Internal_Vernaux *a;
4603
4604                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4605                         {
4606                           if (a->vna_other == vernum)
4607                             {
4608                               verstr = a->vna_nodename;
4609                               break;
4610                             }
4611                         }
4612                       if (a != NULL)
4613                         break;
4614                     }
4615                   if (verstr == NULL)
4616                     {
4617                       _bfd_error_handler
4618                         /* xgettext:c-format */
4619                         (_("%pB: %s: invalid needed version %d"),
4620                          abfd, name, vernum);
4621                       bfd_set_error (bfd_error_bad_value);
4622                       goto error_free_vers;
4623                     }
4624                 }
4625
4626               namelen = strlen (name);
4627               verlen = strlen (verstr);
4628               newlen = namelen + verlen + 2;
4629               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4630                   && isym->st_shndx != SHN_UNDEF)
4631                 ++newlen;
4632
4633               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4634               if (newname == NULL)
4635                 goto error_free_vers;
4636               memcpy (newname, name, namelen);
4637               p = newname + namelen;
4638               *p++ = ELF_VER_CHR;
4639               /* If this is a defined non-hidden version symbol,
4640                  we add another @ to the name.  This indicates the
4641                  default version of the symbol.  */
4642               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4643                   && isym->st_shndx != SHN_UNDEF)
4644                 *p++ = ELF_VER_CHR;
4645               memcpy (p, verstr, verlen + 1);
4646
4647               name = newname;
4648             }
4649
4650           /* If this symbol has default visibility and the user has
4651              requested we not re-export it, then mark it as hidden.  */
4652           if (!bfd_is_und_section (sec)
4653               && !dynamic
4654               && abfd->no_export
4655               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4656             isym->st_other = (STV_HIDDEN
4657                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4658
4659           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4660                                       sym_hash, &old_bfd, &old_weak,
4661                                       &old_alignment, &skip, &override,
4662                                       &type_change_ok, &size_change_ok,
4663                                       &matched))
4664             goto error_free_vers;
4665
4666           if (skip)
4667             continue;
4668
4669           /* Override a definition only if the new symbol matches the
4670              existing one.  */
4671           if (override && matched)
4672             definition = FALSE;
4673
4674           h = *sym_hash;
4675           while (h->root.type == bfd_link_hash_indirect
4676                  || h->root.type == bfd_link_hash_warning)
4677             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4678
4679           if (elf_tdata (abfd)->verdef != NULL
4680               && vernum > 1
4681               && definition)
4682             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4683         }
4684
4685       if (! (_bfd_generic_link_add_one_symbol
4686              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4687               (struct bfd_link_hash_entry **) sym_hash)))
4688         goto error_free_vers;
4689
4690       if ((abfd->flags & DYNAMIC) == 0
4691           && (bfd_get_flavour (info->output_bfd)
4692               == bfd_target_elf_flavour))
4693         {
4694           if (ELF_ST_TYPE (isym->st_info) == STT_GNU_IFUNC)
4695             elf_tdata (info->output_bfd)->has_gnu_symbols
4696               |= elf_gnu_symbol_ifunc;
4697           if ((flags & BSF_GNU_UNIQUE))
4698             elf_tdata (info->output_bfd)->has_gnu_symbols
4699               |= elf_gnu_symbol_unique;
4700         }
4701
4702       h = *sym_hash;
4703       /* We need to make sure that indirect symbol dynamic flags are
4704          updated.  */
4705       hi = h;
4706       while (h->root.type == bfd_link_hash_indirect
4707              || h->root.type == bfd_link_hash_warning)
4708         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4709
4710       /* Setting the index to -3 tells elf_link_output_extsym that
4711          this symbol is defined in a discarded section.  */
4712       if (discarded)
4713         h->indx = -3;
4714
4715       *sym_hash = h;
4716
4717       new_weak = (flags & BSF_WEAK) != 0;
4718       if (dynamic
4719           && definition
4720           && new_weak
4721           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4722           && is_elf_hash_table (htab)
4723           && h->u.alias == NULL)
4724         {
4725           /* Keep a list of all weak defined non function symbols from
4726              a dynamic object, using the alias field.  Later in this
4727              function we will set the alias field to the correct
4728              value.  We only put non-function symbols from dynamic
4729              objects on this list, because that happens to be the only
4730              time we need to know the normal symbol corresponding to a
4731              weak symbol, and the information is time consuming to
4732              figure out.  If the alias field is not already NULL,
4733              then this symbol was already defined by some previous
4734              dynamic object, and we will be using that previous
4735              definition anyhow.  */
4736
4737           h->u.alias = weaks;
4738           weaks = h;
4739         }
4740
4741       /* Set the alignment of a common symbol.  */
4742       if ((common || bfd_is_com_section (sec))
4743           && h->root.type == bfd_link_hash_common)
4744         {
4745           unsigned int align;
4746
4747           if (common)
4748             align = bfd_log2 (isym->st_value);
4749           else
4750             {
4751               /* The new symbol is a common symbol in a shared object.
4752                  We need to get the alignment from the section.  */
4753               align = new_sec->alignment_power;
4754             }
4755           if (align > old_alignment)
4756             h->root.u.c.p->alignment_power = align;
4757           else
4758             h->root.u.c.p->alignment_power = old_alignment;
4759         }
4760
4761       if (is_elf_hash_table (htab))
4762         {
4763           /* Set a flag in the hash table entry indicating the type of
4764              reference or definition we just found.  A dynamic symbol
4765              is one which is referenced or defined by both a regular
4766              object and a shared object.  */
4767           bfd_boolean dynsym = FALSE;
4768
4769           /* Plugin symbols aren't normal.  Don't set def_regular or
4770              ref_regular for them, or make them dynamic.  */
4771           if ((abfd->flags & BFD_PLUGIN) != 0)
4772             ;
4773           else if (! dynamic)
4774             {
4775               if (! definition)
4776                 {
4777                   h->ref_regular = 1;
4778                   if (bind != STB_WEAK)
4779                     h->ref_regular_nonweak = 1;
4780                 }
4781               else
4782                 {
4783                   h->def_regular = 1;
4784                   if (h->def_dynamic)
4785                     {
4786                       h->def_dynamic = 0;
4787                       h->ref_dynamic = 1;
4788                     }
4789                 }
4790
4791               /* If the indirect symbol has been forced local, don't
4792                  make the real symbol dynamic.  */
4793               if ((h == hi || !hi->forced_local)
4794                   && (bfd_link_dll (info)
4795                       || h->def_dynamic
4796                       || h->ref_dynamic))
4797                 dynsym = TRUE;
4798             }
4799           else
4800             {
4801               if (! definition)
4802                 {
4803                   h->ref_dynamic = 1;
4804                   hi->ref_dynamic = 1;
4805                 }
4806               else
4807                 {
4808                   h->def_dynamic = 1;
4809                   hi->def_dynamic = 1;
4810                 }
4811
4812               /* If the indirect symbol has been forced local, don't
4813                  make the real symbol dynamic.  */
4814               if ((h == hi || !hi->forced_local)
4815                   && (h->def_regular
4816                       || h->ref_regular
4817                       || (h->is_weakalias
4818                           && weakdef (h)->dynindx != -1)))
4819                 dynsym = TRUE;
4820             }
4821
4822           /* Check to see if we need to add an indirect symbol for
4823              the default name.  */
4824           if (definition
4825               || (!override && h->root.type == bfd_link_hash_common))
4826             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4827                                               sec, value, &old_bfd, &dynsym))
4828               goto error_free_vers;
4829
4830           /* Check the alignment when a common symbol is involved. This
4831              can change when a common symbol is overridden by a normal
4832              definition or a common symbol is ignored due to the old
4833              normal definition. We need to make sure the maximum
4834              alignment is maintained.  */
4835           if ((old_alignment || common)
4836               && h->root.type != bfd_link_hash_common)
4837             {
4838               unsigned int common_align;
4839               unsigned int normal_align;
4840               unsigned int symbol_align;
4841               bfd *normal_bfd;
4842               bfd *common_bfd;
4843
4844               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4845                           || h->root.type == bfd_link_hash_defweak);
4846
4847               symbol_align = ffs (h->root.u.def.value) - 1;
4848               if (h->root.u.def.section->owner != NULL
4849                   && (h->root.u.def.section->owner->flags
4850                        & (DYNAMIC | BFD_PLUGIN)) == 0)
4851                 {
4852                   normal_align = h->root.u.def.section->alignment_power;
4853                   if (normal_align > symbol_align)
4854                     normal_align = symbol_align;
4855                 }
4856               else
4857                 normal_align = symbol_align;
4858
4859               if (old_alignment)
4860                 {
4861                   common_align = old_alignment;
4862                   common_bfd = old_bfd;
4863                   normal_bfd = abfd;
4864                 }
4865               else
4866                 {
4867                   common_align = bfd_log2 (isym->st_value);
4868                   common_bfd = abfd;
4869                   normal_bfd = old_bfd;
4870                 }
4871
4872               if (normal_align < common_align)
4873                 {
4874                   /* PR binutils/2735 */
4875                   if (normal_bfd == NULL)
4876                     _bfd_error_handler
4877                       /* xgettext:c-format */
4878                       (_("warning: alignment %u of common symbol `%s' in %pB is"
4879                          " greater than the alignment (%u) of its section %pA"),
4880                        1 << common_align, name, common_bfd,
4881                        1 << normal_align, h->root.u.def.section);
4882                   else
4883                     _bfd_error_handler
4884                       /* xgettext:c-format */
4885                       (_("warning: alignment %u of symbol `%s' in %pB"
4886                          " is smaller than %u in %pB"),
4887                        1 << normal_align, name, normal_bfd,
4888                        1 << common_align, common_bfd);
4889                 }
4890             }
4891
4892           /* Remember the symbol size if it isn't undefined.  */
4893           if (isym->st_size != 0
4894               && isym->st_shndx != SHN_UNDEF
4895               && (definition || h->size == 0))
4896             {
4897               if (h->size != 0
4898                   && h->size != isym->st_size
4899                   && ! size_change_ok)
4900                 _bfd_error_handler
4901                   /* xgettext:c-format */
4902                   (_("warning: size of symbol `%s' changed"
4903                      " from %" PRIu64 " in %pB to %" PRIu64 " in %pB"),
4904                    name, (uint64_t) h->size, old_bfd,
4905                    (uint64_t) isym->st_size, abfd);
4906
4907               h->size = isym->st_size;
4908             }
4909
4910           /* If this is a common symbol, then we always want H->SIZE
4911              to be the size of the common symbol.  The code just above
4912              won't fix the size if a common symbol becomes larger.  We
4913              don't warn about a size change here, because that is
4914              covered by --warn-common.  Allow changes between different
4915              function types.  */
4916           if (h->root.type == bfd_link_hash_common)
4917             h->size = h->root.u.c.size;
4918
4919           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4920               && ((definition && !new_weak)
4921                   || (old_weak && h->root.type == bfd_link_hash_common)
4922                   || h->type == STT_NOTYPE))
4923             {
4924               unsigned int type = ELF_ST_TYPE (isym->st_info);
4925
4926               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4927                  symbol.  */
4928               if (type == STT_GNU_IFUNC
4929                   && (abfd->flags & DYNAMIC) != 0)
4930                 type = STT_FUNC;
4931
4932               if (h->type != type)
4933                 {
4934                   if (h->type != STT_NOTYPE && ! type_change_ok)
4935                     /* xgettext:c-format */
4936                     _bfd_error_handler
4937                       (_("warning: type of symbol `%s' changed"
4938                          " from %d to %d in %pB"),
4939                        name, h->type, type, abfd);
4940
4941                   h->type = type;
4942                 }
4943             }
4944
4945           /* Merge st_other field.  */
4946           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4947
4948           /* We don't want to make debug symbol dynamic.  */
4949           if (definition
4950               && (sec->flags & SEC_DEBUGGING)
4951               && !bfd_link_relocatable (info))
4952             dynsym = FALSE;
4953
4954           /* Nor should we make plugin symbols dynamic.  */
4955           if ((abfd->flags & BFD_PLUGIN) != 0)
4956             dynsym = FALSE;
4957
4958           if (definition)
4959             {
4960               h->target_internal = isym->st_target_internal;
4961               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4962             }
4963
4964           if (definition && !dynamic)
4965             {
4966               char *p = strchr (name, ELF_VER_CHR);
4967               if (p != NULL && p[1] != ELF_VER_CHR)
4968                 {
4969                   /* Queue non-default versions so that .symver x, x@FOO
4970                      aliases can be checked.  */
4971                   if (!nondeflt_vers)
4972                     {
4973                       amt = ((isymend - isym + 1)
4974                              * sizeof (struct elf_link_hash_entry *));
4975                       nondeflt_vers
4976                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
4977                       if (!nondeflt_vers)
4978                         goto error_free_vers;
4979                     }
4980                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4981                 }
4982             }
4983
4984           if (dynsym && h->dynindx == -1)
4985             {
4986               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4987                 goto error_free_vers;
4988               if (h->is_weakalias
4989                   && weakdef (h)->dynindx == -1)
4990                 {
4991                   if (!bfd_elf_link_record_dynamic_symbol (info, weakdef (h)))
4992                     goto error_free_vers;
4993                 }
4994             }
4995           else if (h->dynindx != -1)
4996             /* If the symbol already has a dynamic index, but
4997                visibility says it should not be visible, turn it into
4998                a local symbol.  */
4999             switch (ELF_ST_VISIBILITY (h->other))
5000               {
5001               case STV_INTERNAL:
5002               case STV_HIDDEN:
5003                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
5004                 dynsym = FALSE;
5005                 break;
5006               }
5007
5008           /* Don't add DT_NEEDED for references from the dummy bfd nor
5009              for unmatched symbol.  */
5010           if (!add_needed
5011               && matched
5012               && definition
5013               && ((dynsym
5014                    && h->ref_regular_nonweak
5015                    && (old_bfd == NULL
5016                        || (old_bfd->flags & BFD_PLUGIN) == 0))
5017                   || (h->ref_dynamic_nonweak
5018                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
5019                       && !on_needed_list (elf_dt_name (abfd),
5020                                           htab->needed, NULL))))
5021             {
5022               int ret;
5023               const char *soname = elf_dt_name (abfd);
5024
5025               info->callbacks->minfo ("%!", soname, old_bfd,
5026                                       h->root.root.string);
5027
5028               /* A symbol from a library loaded via DT_NEEDED of some
5029                  other library is referenced by a regular object.
5030                  Add a DT_NEEDED entry for it.  Issue an error if
5031                  --no-add-needed is used and the reference was not
5032                  a weak one.  */
5033               if (old_bfd != NULL
5034                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
5035                 {
5036                   _bfd_error_handler
5037                     /* xgettext:c-format */
5038                     (_("%pB: undefined reference to symbol '%s'"),
5039                      old_bfd, name);
5040                   bfd_set_error (bfd_error_missing_dso);
5041                   goto error_free_vers;
5042                 }
5043
5044               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
5045                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
5046
5047               add_needed = TRUE;
5048               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
5049               if (ret < 0)
5050                 goto error_free_vers;
5051
5052               BFD_ASSERT (ret == 0);
5053             }
5054         }
5055     }
5056
5057   if (info->lto_plugin_active
5058       && !bfd_link_relocatable (info)
5059       && (abfd->flags & BFD_PLUGIN) == 0
5060       && !just_syms
5061       && extsymcount)
5062     {
5063       int r_sym_shift;
5064
5065       if (bed->s->arch_size == 32)
5066         r_sym_shift = 8;
5067       else
5068         r_sym_shift = 32;
5069
5070       /* If linker plugin is enabled, set non_ir_ref_regular on symbols
5071          referenced in regular objects so that linker plugin will get
5072          the correct symbol resolution.  */
5073
5074       sym_hash = elf_sym_hashes (abfd);
5075       for (s = abfd->sections; s != NULL; s = s->next)
5076         {
5077           Elf_Internal_Rela *internal_relocs;
5078           Elf_Internal_Rela *rel, *relend;
5079
5080           /* Don't check relocations in excluded sections.  */
5081           if ((s->flags & SEC_RELOC) == 0
5082               || s->reloc_count == 0
5083               || (s->flags & SEC_EXCLUDE) != 0
5084               || ((info->strip == strip_all
5085                    || info->strip == strip_debugger)
5086                   && (s->flags & SEC_DEBUGGING) != 0))
5087             continue;
5088
5089           internal_relocs = _bfd_elf_link_read_relocs (abfd, s, NULL,
5090                                                        NULL,
5091                                                        info->keep_memory);
5092           if (internal_relocs == NULL)
5093             goto error_free_vers;
5094
5095           rel = internal_relocs;
5096           relend = rel + s->reloc_count;
5097           for ( ; rel < relend; rel++)
5098             {
5099               unsigned long r_symndx = rel->r_info >> r_sym_shift;
5100               struct elf_link_hash_entry *h;
5101
5102               /* Skip local symbols.  */
5103               if (r_symndx < extsymoff)
5104                 continue;
5105
5106               h = sym_hash[r_symndx - extsymoff];
5107               if (h != NULL)
5108                 h->root.non_ir_ref_regular = 1;
5109             }
5110
5111           if (elf_section_data (s)->relocs != internal_relocs)
5112             free (internal_relocs);
5113         }
5114     }
5115
5116   if (extversym != NULL)
5117     {
5118       free (extversym);
5119       extversym = NULL;
5120     }
5121
5122   if (isymbuf != NULL)
5123     {
5124       free (isymbuf);
5125       isymbuf = NULL;
5126     }
5127
5128   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
5129     {
5130       unsigned int i;
5131
5132       /* Restore the symbol table.  */
5133       old_ent = (char *) old_tab + tabsize;
5134       memset (elf_sym_hashes (abfd), 0,
5135               extsymcount * sizeof (struct elf_link_hash_entry *));
5136       htab->root.table.table = old_table;
5137       htab->root.table.size = old_size;
5138       htab->root.table.count = old_count;
5139       memcpy (htab->root.table.table, old_tab, tabsize);
5140       htab->root.undefs = old_undefs;
5141       htab->root.undefs_tail = old_undefs_tail;
5142       _bfd_elf_strtab_restore (htab->dynstr, old_strtab);
5143       free (old_strtab);
5144       old_strtab = NULL;
5145       for (i = 0; i < htab->root.table.size; i++)
5146         {
5147           struct bfd_hash_entry *p;
5148           struct elf_link_hash_entry *h;
5149           bfd_size_type size;
5150           unsigned int alignment_power;
5151           unsigned int non_ir_ref_dynamic;
5152
5153           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
5154             {
5155               h = (struct elf_link_hash_entry *) p;
5156               if (h->root.type == bfd_link_hash_warning)
5157                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
5158
5159               /* Preserve the maximum alignment and size for common
5160                  symbols even if this dynamic lib isn't on DT_NEEDED
5161                  since it can still be loaded at run time by another
5162                  dynamic lib.  */
5163               if (h->root.type == bfd_link_hash_common)
5164                 {
5165                   size = h->root.u.c.size;
5166                   alignment_power = h->root.u.c.p->alignment_power;
5167                 }
5168               else
5169                 {
5170                   size = 0;
5171                   alignment_power = 0;
5172                 }
5173               /* Preserve non_ir_ref_dynamic so that this symbol
5174                  will be exported when the dynamic lib becomes needed
5175                  in the second pass.  */
5176               non_ir_ref_dynamic = h->root.non_ir_ref_dynamic;
5177               memcpy (p, old_ent, htab->root.table.entsize);
5178               old_ent = (char *) old_ent + htab->root.table.entsize;
5179               h = (struct elf_link_hash_entry *) p;
5180               if (h->root.type == bfd_link_hash_warning)
5181                 {
5182                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
5183                   old_ent = (char *) old_ent + htab->root.table.entsize;
5184                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
5185                 }
5186               if (h->root.type == bfd_link_hash_common)
5187                 {
5188                   if (size > h->root.u.c.size)
5189                     h->root.u.c.size = size;
5190                   if (alignment_power > h->root.u.c.p->alignment_power)
5191                     h->root.u.c.p->alignment_power = alignment_power;
5192                 }
5193               h->root.non_ir_ref_dynamic = non_ir_ref_dynamic;
5194             }
5195         }
5196
5197       /* Make a special call to the linker "notice" function to
5198          tell it that symbols added for crefs may need to be removed.  */
5199       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
5200         goto error_free_vers;
5201
5202       free (old_tab);
5203       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
5204                            alloc_mark);
5205       if (nondeflt_vers != NULL)
5206         free (nondeflt_vers);
5207       return TRUE;
5208     }
5209
5210   if (old_tab != NULL)
5211     {
5212       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
5213         goto error_free_vers;
5214       free (old_tab);
5215       old_tab = NULL;
5216     }
5217
5218   /* Now that all the symbols from this input file are created, if
5219      not performing a relocatable link, handle .symver foo, foo@BAR
5220      such that any relocs against foo become foo@BAR.  */
5221   if (!bfd_link_relocatable (info) && nondeflt_vers != NULL)
5222     {
5223       size_t cnt, symidx;
5224
5225       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
5226         {
5227           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
5228           char *shortname, *p;
5229
5230           p = strchr (h->root.root.string, ELF_VER_CHR);
5231           if (p == NULL
5232               || (h->root.type != bfd_link_hash_defined
5233                   && h->root.type != bfd_link_hash_defweak))
5234             continue;
5235
5236           amt = p - h->root.root.string;
5237           shortname = (char *) bfd_malloc (amt + 1);
5238           if (!shortname)
5239             goto error_free_vers;
5240           memcpy (shortname, h->root.root.string, amt);
5241           shortname[amt] = '\0';
5242
5243           hi = (struct elf_link_hash_entry *)
5244                bfd_link_hash_lookup (&htab->root, shortname,
5245                                      FALSE, FALSE, FALSE);
5246           if (hi != NULL
5247               && hi->root.type == h->root.type
5248               && hi->root.u.def.value == h->root.u.def.value
5249               && hi->root.u.def.section == h->root.u.def.section)
5250             {
5251               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
5252               hi->root.type = bfd_link_hash_indirect;
5253               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
5254               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
5255               sym_hash = elf_sym_hashes (abfd);
5256               if (sym_hash)
5257                 for (symidx = 0; symidx < extsymcount; ++symidx)
5258                   if (sym_hash[symidx] == hi)
5259                     {
5260                       sym_hash[symidx] = h;
5261                       break;
5262                     }
5263             }
5264           free (shortname);
5265         }
5266       free (nondeflt_vers);
5267       nondeflt_vers = NULL;
5268     }
5269
5270   /* Now set the alias field correctly for all the weak defined
5271      symbols we found.  The only way to do this is to search all the
5272      symbols.  Since we only need the information for non functions in
5273      dynamic objects, that's the only time we actually put anything on
5274      the list WEAKS.  We need this information so that if a regular
5275      object refers to a symbol defined weakly in a dynamic object, the
5276      real symbol in the dynamic object is also put in the dynamic
5277      symbols; we also must arrange for both symbols to point to the
5278      same memory location.  We could handle the general case of symbol
5279      aliasing, but a general symbol alias can only be generated in
5280      assembler code, handling it correctly would be very time
5281      consuming, and other ELF linkers don't handle general aliasing
5282      either.  */
5283   if (weaks != NULL)
5284     {
5285       struct elf_link_hash_entry **hpp;
5286       struct elf_link_hash_entry **hppend;
5287       struct elf_link_hash_entry **sorted_sym_hash;
5288       struct elf_link_hash_entry *h;
5289       size_t sym_count;
5290
5291       /* Since we have to search the whole symbol list for each weak
5292          defined symbol, search time for N weak defined symbols will be
5293          O(N^2). Binary search will cut it down to O(NlogN).  */
5294       amt = extsymcount;
5295       amt *= sizeof (struct elf_link_hash_entry *);
5296       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
5297       if (sorted_sym_hash == NULL)
5298         goto error_return;
5299       sym_hash = sorted_sym_hash;
5300       hpp = elf_sym_hashes (abfd);
5301       hppend = hpp + extsymcount;
5302       sym_count = 0;
5303       for (; hpp < hppend; hpp++)
5304         {
5305           h = *hpp;
5306           if (h != NULL
5307               && h->root.type == bfd_link_hash_defined
5308               && !bed->is_function_type (h->type))
5309             {
5310               *sym_hash = h;
5311               sym_hash++;
5312               sym_count++;
5313             }
5314         }
5315
5316       qsort (sorted_sym_hash, sym_count,
5317              sizeof (struct elf_link_hash_entry *),
5318              elf_sort_symbol);
5319
5320       while (weaks != NULL)
5321         {
5322           struct elf_link_hash_entry *hlook;
5323           asection *slook;
5324           bfd_vma vlook;
5325           size_t i, j, idx = 0;
5326
5327           hlook = weaks;
5328           weaks = hlook->u.alias;
5329           hlook->u.alias = NULL;
5330
5331           if (hlook->root.type != bfd_link_hash_defined
5332               && hlook->root.type != bfd_link_hash_defweak)
5333             continue;
5334
5335           slook = hlook->root.u.def.section;
5336           vlook = hlook->root.u.def.value;
5337
5338           i = 0;
5339           j = sym_count;
5340           while (i != j)
5341             {
5342               bfd_signed_vma vdiff;
5343               idx = (i + j) / 2;
5344               h = sorted_sym_hash[idx];
5345               vdiff = vlook - h->root.u.def.value;
5346               if (vdiff < 0)
5347                 j = idx;
5348               else if (vdiff > 0)
5349                 i = idx + 1;
5350               else
5351                 {
5352                   int sdiff = slook->id - h->root.u.def.section->id;
5353                   if (sdiff < 0)
5354                     j = idx;
5355                   else if (sdiff > 0)
5356                     i = idx + 1;
5357                   else
5358                     break;
5359                 }
5360             }
5361
5362           /* We didn't find a value/section match.  */
5363           if (i == j)
5364             continue;
5365
5366           /* With multiple aliases, or when the weak symbol is already
5367              strongly defined, we have multiple matching symbols and
5368              the binary search above may land on any of them.  Step
5369              one past the matching symbol(s).  */
5370           while (++idx != j)
5371             {
5372               h = sorted_sym_hash[idx];
5373               if (h->root.u.def.section != slook
5374                   || h->root.u.def.value != vlook)
5375                 break;
5376             }
5377
5378           /* Now look back over the aliases.  Since we sorted by size
5379              as well as value and section, we'll choose the one with
5380              the largest size.  */
5381           while (idx-- != i)
5382             {
5383               h = sorted_sym_hash[idx];
5384
5385               /* Stop if value or section doesn't match.  */
5386               if (h->root.u.def.section != slook
5387                   || h->root.u.def.value != vlook)
5388                 break;
5389               else if (h != hlook)
5390                 {
5391                   struct elf_link_hash_entry *t;
5392
5393                   hlook->u.alias = h;
5394                   hlook->is_weakalias = 1;
5395                   t = h;
5396                   if (t->u.alias != NULL)
5397                     while (t->u.alias != h)
5398                       t = t->u.alias;
5399                   t->u.alias = hlook;
5400
5401                   /* If the weak definition is in the list of dynamic
5402                      symbols, make sure the real definition is put
5403                      there as well.  */
5404                   if (hlook->dynindx != -1 && h->dynindx == -1)
5405                     {
5406                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
5407                         {
5408                         err_free_sym_hash:
5409                           free (sorted_sym_hash);
5410                           goto error_return;
5411                         }
5412                     }
5413
5414                   /* If the real definition is in the list of dynamic
5415                      symbols, make sure the weak definition is put
5416                      there as well.  If we don't do this, then the
5417                      dynamic loader might not merge the entries for the
5418                      real definition and the weak definition.  */
5419                   if (h->dynindx != -1 && hlook->dynindx == -1)
5420                     {
5421                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
5422                         goto err_free_sym_hash;
5423                     }
5424                   break;
5425                 }
5426             }
5427         }
5428
5429       free (sorted_sym_hash);
5430     }
5431
5432   if (bed->check_directives
5433       && !(*bed->check_directives) (abfd, info))
5434     return FALSE;
5435
5436   /* If this is a non-traditional link, try to optimize the handling
5437      of the .stab/.stabstr sections.  */
5438   if (! dynamic
5439       && ! info->traditional_format
5440       && is_elf_hash_table (htab)
5441       && (info->strip != strip_all && info->strip != strip_debugger))
5442     {
5443       asection *stabstr;
5444
5445       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
5446       if (stabstr != NULL)
5447         {
5448           bfd_size_type string_offset = 0;
5449           asection *stab;
5450
5451           for (stab = abfd->sections; stab; stab = stab->next)
5452             if (CONST_STRNEQ (stab->name, ".stab")
5453                 && (!stab->name[5] ||
5454                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
5455                 && (stab->flags & SEC_MERGE) == 0
5456                 && !bfd_is_abs_section (stab->output_section))
5457               {
5458                 struct bfd_elf_section_data *secdata;
5459
5460                 secdata = elf_section_data (stab);
5461                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
5462                                                stabstr, &secdata->sec_info,
5463                                                &string_offset))
5464                   goto error_return;
5465                 if (secdata->sec_info)
5466                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
5467             }
5468         }
5469     }
5470
5471   if (is_elf_hash_table (htab) && add_needed)
5472     {
5473       /* Add this bfd to the loaded list.  */
5474       struct elf_link_loaded_list *n;
5475
5476       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
5477       if (n == NULL)
5478         goto error_return;
5479       n->abfd = abfd;
5480       n->next = htab->loaded;
5481       htab->loaded = n;
5482     }
5483
5484   return TRUE;
5485
5486  error_free_vers:
5487   if (old_tab != NULL)
5488     free (old_tab);
5489   if (old_strtab != NULL)
5490     free (old_strtab);
5491   if (nondeflt_vers != NULL)
5492     free (nondeflt_vers);
5493   if (extversym != NULL)
5494     free (extversym);
5495  error_free_sym:
5496   if (isymbuf != NULL)
5497     free (isymbuf);
5498  error_return:
5499   return FALSE;
5500 }
5501
5502 /* Return the linker hash table entry of a symbol that might be
5503    satisfied by an archive symbol.  Return -1 on error.  */
5504
5505 struct elf_link_hash_entry *
5506 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5507                                 struct bfd_link_info *info,
5508                                 const char *name)
5509 {
5510   struct elf_link_hash_entry *h;
5511   char *p, *copy;
5512   size_t len, first;
5513
5514   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5515   if (h != NULL)
5516     return h;
5517
5518   /* If this is a default version (the name contains @@), look up the
5519      symbol again with only one `@' as well as without the version.
5520      The effect is that references to the symbol with and without the
5521      version will be matched by the default symbol in the archive.  */
5522
5523   p = strchr (name, ELF_VER_CHR);
5524   if (p == NULL || p[1] != ELF_VER_CHR)
5525     return h;
5526
5527   /* First check with only one `@'.  */
5528   len = strlen (name);
5529   copy = (char *) bfd_alloc (abfd, len);
5530   if (copy == NULL)
5531     return (struct elf_link_hash_entry *) -1;
5532
5533   first = p - name + 1;
5534   memcpy (copy, name, first);
5535   memcpy (copy + first, name + first + 1, len - first);
5536
5537   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5538   if (h == NULL)
5539     {
5540       /* We also need to check references to the symbol without the
5541          version.  */
5542       copy[first - 1] = '\0';
5543       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5544                                 FALSE, FALSE, TRUE);
5545     }
5546
5547   bfd_release (abfd, copy);
5548   return h;
5549 }
5550
5551 /* Add symbols from an ELF archive file to the linker hash table.  We
5552    don't use _bfd_generic_link_add_archive_symbols because we need to
5553    handle versioned symbols.
5554
5555    Fortunately, ELF archive handling is simpler than that done by
5556    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5557    oddities.  In ELF, if we find a symbol in the archive map, and the
5558    symbol is currently undefined, we know that we must pull in that
5559    object file.
5560
5561    Unfortunately, we do have to make multiple passes over the symbol
5562    table until nothing further is resolved.  */
5563
5564 static bfd_boolean
5565 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5566 {
5567   symindex c;
5568   unsigned char *included = NULL;
5569   carsym *symdefs;
5570   bfd_boolean loop;
5571   bfd_size_type amt;
5572   const struct elf_backend_data *bed;
5573   struct elf_link_hash_entry * (*archive_symbol_lookup)
5574     (bfd *, struct bfd_link_info *, const char *);
5575
5576   if (! bfd_has_map (abfd))
5577     {
5578       /* An empty archive is a special case.  */
5579       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5580         return TRUE;
5581       bfd_set_error (bfd_error_no_armap);
5582       return FALSE;
5583     }
5584
5585   /* Keep track of all symbols we know to be already defined, and all
5586      files we know to be already included.  This is to speed up the
5587      second and subsequent passes.  */
5588   c = bfd_ardata (abfd)->symdef_count;
5589   if (c == 0)
5590     return TRUE;
5591   amt = c;
5592   amt *= sizeof (*included);
5593   included = (unsigned char *) bfd_zmalloc (amt);
5594   if (included == NULL)
5595     return FALSE;
5596
5597   symdefs = bfd_ardata (abfd)->symdefs;
5598   bed = get_elf_backend_data (abfd);
5599   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5600
5601   do
5602     {
5603       file_ptr last;
5604       symindex i;
5605       carsym *symdef;
5606       carsym *symdefend;
5607
5608       loop = FALSE;
5609       last = -1;
5610
5611       symdef = symdefs;
5612       symdefend = symdef + c;
5613       for (i = 0; symdef < symdefend; symdef++, i++)
5614         {
5615           struct elf_link_hash_entry *h;
5616           bfd *element;
5617           struct bfd_link_hash_entry *undefs_tail;
5618           symindex mark;
5619
5620           if (included[i])
5621             continue;
5622           if (symdef->file_offset == last)
5623             {
5624               included[i] = TRUE;
5625               continue;
5626             }
5627
5628           h = archive_symbol_lookup (abfd, info, symdef->name);
5629           if (h == (struct elf_link_hash_entry *) -1)
5630             goto error_return;
5631
5632           if (h == NULL)
5633             continue;
5634
5635           if (h->root.type == bfd_link_hash_common)
5636             {
5637               /* We currently have a common symbol.  The archive map contains
5638                  a reference to this symbol, so we may want to include it.  We
5639                  only want to include it however, if this archive element
5640                  contains a definition of the symbol, not just another common
5641                  declaration of it.
5642
5643                  Unfortunately some archivers (including GNU ar) will put
5644                  declarations of common symbols into their archive maps, as
5645                  well as real definitions, so we cannot just go by the archive
5646                  map alone.  Instead we must read in the element's symbol
5647                  table and check that to see what kind of symbol definition
5648                  this is.  */
5649               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5650                 continue;
5651             }
5652           else if (h->root.type != bfd_link_hash_undefined)
5653             {
5654               if (h->root.type != bfd_link_hash_undefweak)
5655                 /* Symbol must be defined.  Don't check it again.  */
5656                 included[i] = TRUE;
5657               continue;
5658             }
5659
5660           /* We need to include this archive member.  */
5661           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5662           if (element == NULL)
5663             goto error_return;
5664
5665           if (! bfd_check_format (element, bfd_object))
5666             goto error_return;
5667
5668           undefs_tail = info->hash->undefs_tail;
5669
5670           if (!(*info->callbacks
5671                 ->add_archive_element) (info, element, symdef->name, &element))
5672             continue;
5673           if (!bfd_link_add_symbols (element, info))
5674             goto error_return;
5675
5676           /* If there are any new undefined symbols, we need to make
5677              another pass through the archive in order to see whether
5678              they can be defined.  FIXME: This isn't perfect, because
5679              common symbols wind up on undefs_tail and because an
5680              undefined symbol which is defined later on in this pass
5681              does not require another pass.  This isn't a bug, but it
5682              does make the code less efficient than it could be.  */
5683           if (undefs_tail != info->hash->undefs_tail)
5684             loop = TRUE;
5685
5686           /* Look backward to mark all symbols from this object file
5687              which we have already seen in this pass.  */
5688           mark = i;
5689           do
5690             {
5691               included[mark] = TRUE;
5692               if (mark == 0)
5693                 break;
5694               --mark;
5695             }
5696           while (symdefs[mark].file_offset == symdef->file_offset);
5697
5698           /* We mark subsequent symbols from this object file as we go
5699              on through the loop.  */
5700           last = symdef->file_offset;
5701         }
5702     }
5703   while (loop);
5704
5705   free (included);
5706
5707   return TRUE;
5708
5709  error_return:
5710   if (included != NULL)
5711     free (included);
5712   return FALSE;
5713 }
5714
5715 /* Given an ELF BFD, add symbols to the global hash table as
5716    appropriate.  */
5717
5718 bfd_boolean
5719 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5720 {
5721   switch (bfd_get_format (abfd))
5722     {
5723     case bfd_object:
5724       return elf_link_add_object_symbols (abfd, info);
5725     case bfd_archive:
5726       return elf_link_add_archive_symbols (abfd, info);
5727     default:
5728       bfd_set_error (bfd_error_wrong_format);
5729       return FALSE;
5730     }
5731 }
5732 \f
5733 struct hash_codes_info
5734 {
5735   unsigned long *hashcodes;
5736   bfd_boolean error;
5737 };
5738
5739 /* This function will be called though elf_link_hash_traverse to store
5740    all hash value of the exported symbols in an array.  */
5741
5742 static bfd_boolean
5743 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5744 {
5745   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5746   const char *name;
5747   unsigned long ha;
5748   char *alc = NULL;
5749
5750   /* Ignore indirect symbols.  These are added by the versioning code.  */
5751   if (h->dynindx == -1)
5752     return TRUE;
5753
5754   name = h->root.root.string;
5755   if (h->versioned >= versioned)
5756     {
5757       char *p = strchr (name, ELF_VER_CHR);
5758       if (p != NULL)
5759         {
5760           alc = (char *) bfd_malloc (p - name + 1);
5761           if (alc == NULL)
5762             {
5763               inf->error = TRUE;
5764               return FALSE;
5765             }
5766           memcpy (alc, name, p - name);
5767           alc[p - name] = '\0';
5768           name = alc;
5769         }
5770     }
5771
5772   /* Compute the hash value.  */
5773   ha = bfd_elf_hash (name);
5774
5775   /* Store the found hash value in the array given as the argument.  */
5776   *(inf->hashcodes)++ = ha;
5777
5778   /* And store it in the struct so that we can put it in the hash table
5779      later.  */
5780   h->u.elf_hash_value = ha;
5781
5782   if (alc != NULL)
5783     free (alc);
5784
5785   return TRUE;
5786 }
5787
5788 struct collect_gnu_hash_codes
5789 {
5790   bfd *output_bfd;
5791   const struct elf_backend_data *bed;
5792   unsigned long int nsyms;
5793   unsigned long int maskbits;
5794   unsigned long int *hashcodes;
5795   unsigned long int *hashval;
5796   unsigned long int *indx;
5797   unsigned long int *counts;
5798   bfd_vma *bitmask;
5799   bfd_byte *contents;
5800   long int min_dynindx;
5801   unsigned long int bucketcount;
5802   unsigned long int symindx;
5803   long int local_indx;
5804   long int shift1, shift2;
5805   unsigned long int mask;
5806   bfd_boolean error;
5807 };
5808
5809 /* This function will be called though elf_link_hash_traverse to store
5810    all hash value of the exported symbols in an array.  */
5811
5812 static bfd_boolean
5813 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5814 {
5815   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5816   const char *name;
5817   unsigned long ha;
5818   char *alc = NULL;
5819
5820   /* Ignore indirect symbols.  These are added by the versioning code.  */
5821   if (h->dynindx == -1)
5822     return TRUE;
5823
5824   /* Ignore also local symbols and undefined symbols.  */
5825   if (! (*s->bed->elf_hash_symbol) (h))
5826     return TRUE;
5827
5828   name = h->root.root.string;
5829   if (h->versioned >= versioned)
5830     {
5831       char *p = strchr (name, ELF_VER_CHR);
5832       if (p != NULL)
5833         {
5834           alc = (char *) bfd_malloc (p - name + 1);
5835           if (alc == NULL)
5836             {
5837               s->error = TRUE;
5838               return FALSE;
5839             }
5840           memcpy (alc, name, p - name);
5841           alc[p - name] = '\0';
5842           name = alc;
5843         }
5844     }
5845
5846   /* Compute the hash value.  */
5847   ha = bfd_elf_gnu_hash (name);
5848
5849   /* Store the found hash value in the array for compute_bucket_count,
5850      and also for .dynsym reordering purposes.  */
5851   s->hashcodes[s->nsyms] = ha;
5852   s->hashval[h->dynindx] = ha;
5853   ++s->nsyms;
5854   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5855     s->min_dynindx = h->dynindx;
5856
5857   if (alc != NULL)
5858     free (alc);
5859
5860   return TRUE;
5861 }
5862
5863 /* This function will be called though elf_link_hash_traverse to do
5864    final dynaminc symbol renumbering.  */
5865
5866 static bfd_boolean
5867 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5868 {
5869   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5870   unsigned long int bucket;
5871   unsigned long int val;
5872
5873   /* Ignore indirect symbols.  */
5874   if (h->dynindx == -1)
5875     return TRUE;
5876
5877   /* Ignore also local symbols and undefined symbols.  */
5878   if (! (*s->bed->elf_hash_symbol) (h))
5879     {
5880       if (h->dynindx >= s->min_dynindx)
5881         h->dynindx = s->local_indx++;
5882       return TRUE;
5883     }
5884
5885   bucket = s->hashval[h->dynindx] % s->bucketcount;
5886   val = (s->hashval[h->dynindx] >> s->shift1)
5887         & ((s->maskbits >> s->shift1) - 1);
5888   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5889   s->bitmask[val]
5890     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5891   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5892   if (s->counts[bucket] == 1)
5893     /* Last element terminates the chain.  */
5894     val |= 1;
5895   bfd_put_32 (s->output_bfd, val,
5896               s->contents + (s->indx[bucket] - s->symindx) * 4);
5897   --s->counts[bucket];
5898   h->dynindx = s->indx[bucket]++;
5899   return TRUE;
5900 }
5901
5902 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5903
5904 bfd_boolean
5905 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5906 {
5907   return !(h->forced_local
5908            || h->root.type == bfd_link_hash_undefined
5909            || h->root.type == bfd_link_hash_undefweak
5910            || ((h->root.type == bfd_link_hash_defined
5911                 || h->root.type == bfd_link_hash_defweak)
5912                && h->root.u.def.section->output_section == NULL));
5913 }
5914
5915 /* Array used to determine the number of hash table buckets to use
5916    based on the number of symbols there are.  If there are fewer than
5917    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5918    fewer than 37 we use 17 buckets, and so forth.  We never use more
5919    than 32771 buckets.  */
5920
5921 static const size_t elf_buckets[] =
5922 {
5923   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5924   16411, 32771, 0
5925 };
5926
5927 /* Compute bucket count for hashing table.  We do not use a static set
5928    of possible tables sizes anymore.  Instead we determine for all
5929    possible reasonable sizes of the table the outcome (i.e., the
5930    number of collisions etc) and choose the best solution.  The
5931    weighting functions are not too simple to allow the table to grow
5932    without bounds.  Instead one of the weighting factors is the size.
5933    Therefore the result is always a good payoff between few collisions
5934    (= short chain lengths) and table size.  */
5935 static size_t
5936 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5937                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5938                       unsigned long int nsyms,
5939                       int gnu_hash)
5940 {
5941   size_t best_size = 0;
5942   unsigned long int i;
5943
5944   /* We have a problem here.  The following code to optimize the table
5945      size requires an integer type with more the 32 bits.  If
5946      BFD_HOST_U_64_BIT is set we know about such a type.  */
5947 #ifdef BFD_HOST_U_64_BIT
5948   if (info->optimize)
5949     {
5950       size_t minsize;
5951       size_t maxsize;
5952       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5953       bfd *dynobj = elf_hash_table (info)->dynobj;
5954       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5955       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5956       unsigned long int *counts;
5957       bfd_size_type amt;
5958       unsigned int no_improvement_count = 0;
5959
5960       /* Possible optimization parameters: if we have NSYMS symbols we say
5961          that the hashing table must at least have NSYMS/4 and at most
5962          2*NSYMS buckets.  */
5963       minsize = nsyms / 4;
5964       if (minsize == 0)
5965         minsize = 1;
5966       best_size = maxsize = nsyms * 2;
5967       if (gnu_hash)
5968         {
5969           if (minsize < 2)
5970             minsize = 2;
5971           if ((best_size & 31) == 0)
5972             ++best_size;
5973         }
5974
5975       /* Create array where we count the collisions in.  We must use bfd_malloc
5976          since the size could be large.  */
5977       amt = maxsize;
5978       amt *= sizeof (unsigned long int);
5979       counts = (unsigned long int *) bfd_malloc (amt);
5980       if (counts == NULL)
5981         return 0;
5982
5983       /* Compute the "optimal" size for the hash table.  The criteria is a
5984          minimal chain length.  The minor criteria is (of course) the size
5985          of the table.  */
5986       for (i = minsize; i < maxsize; ++i)
5987         {
5988           /* Walk through the array of hashcodes and count the collisions.  */
5989           BFD_HOST_U_64_BIT max;
5990           unsigned long int j;
5991           unsigned long int fact;
5992
5993           if (gnu_hash && (i & 31) == 0)
5994             continue;
5995
5996           memset (counts, '\0', i * sizeof (unsigned long int));
5997
5998           /* Determine how often each hash bucket is used.  */
5999           for (j = 0; j < nsyms; ++j)
6000             ++counts[hashcodes[j] % i];
6001
6002           /* For the weight function we need some information about the
6003              pagesize on the target.  This is information need not be 100%
6004              accurate.  Since this information is not available (so far) we
6005              define it here to a reasonable default value.  If it is crucial
6006              to have a better value some day simply define this value.  */
6007 # ifndef BFD_TARGET_PAGESIZE
6008 #  define BFD_TARGET_PAGESIZE   (4096)
6009 # endif
6010
6011           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
6012              and the chains.  */
6013           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
6014
6015 # if 1
6016           /* Variant 1: optimize for short chains.  We add the squares
6017              of all the chain lengths (which favors many small chain
6018              over a few long chains).  */
6019           for (j = 0; j < i; ++j)
6020             max += counts[j] * counts[j];
6021
6022           /* This adds penalties for the overall size of the table.  */
6023           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
6024           max *= fact * fact;
6025 # else
6026           /* Variant 2: Optimize a lot more for small table.  Here we
6027              also add squares of the size but we also add penalties for
6028              empty slots (the +1 term).  */
6029           for (j = 0; j < i; ++j)
6030             max += (1 + counts[j]) * (1 + counts[j]);
6031
6032           /* The overall size of the table is considered, but not as
6033              strong as in variant 1, where it is squared.  */
6034           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
6035           max *= fact;
6036 # endif
6037
6038           /* Compare with current best results.  */
6039           if (max < best_chlen)
6040             {
6041               best_chlen = max;
6042               best_size = i;
6043               no_improvement_count = 0;
6044             }
6045           /* PR 11843: Avoid futile long searches for the best bucket size
6046              when there are a large number of symbols.  */
6047           else if (++no_improvement_count == 100)
6048             break;
6049         }
6050
6051       free (counts);
6052     }
6053   else
6054 #endif /* defined (BFD_HOST_U_64_BIT) */
6055     {
6056       /* This is the fallback solution if no 64bit type is available or if we
6057          are not supposed to spend much time on optimizations.  We select the
6058          bucket count using a fixed set of numbers.  */
6059       for (i = 0; elf_buckets[i] != 0; i++)
6060         {
6061           best_size = elf_buckets[i];
6062           if (nsyms < elf_buckets[i + 1])
6063             break;
6064         }
6065       if (gnu_hash && best_size < 2)
6066         best_size = 2;
6067     }
6068
6069   return best_size;
6070 }
6071
6072 /* Size any SHT_GROUP section for ld -r.  */
6073
6074 bfd_boolean
6075 _bfd_elf_size_group_sections (struct bfd_link_info *info)
6076 {
6077   bfd *ibfd;
6078   asection *s;
6079
6080   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
6081     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
6082         && (s = ibfd->sections) != NULL
6083         && s->sec_info_type != SEC_INFO_TYPE_JUST_SYMS
6084         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
6085       return FALSE;
6086   return TRUE;
6087 }
6088
6089 /* Set a default stack segment size.  The value in INFO wins.  If it
6090    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
6091    undefined it is initialized.  */
6092
6093 bfd_boolean
6094 bfd_elf_stack_segment_size (bfd *output_bfd,
6095                             struct bfd_link_info *info,
6096                             const char *legacy_symbol,
6097                             bfd_vma default_size)
6098 {
6099   struct elf_link_hash_entry *h = NULL;
6100
6101   /* Look for legacy symbol.  */
6102   if (legacy_symbol)
6103     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
6104                               FALSE, FALSE, FALSE);
6105   if (h && (h->root.type == bfd_link_hash_defined
6106             || h->root.type == bfd_link_hash_defweak)
6107       && h->def_regular
6108       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
6109     {
6110       /* The symbol has no type if specified on the command line.  */
6111       h->type = STT_OBJECT;
6112       if (info->stacksize)
6113         /* xgettext:c-format */
6114         _bfd_error_handler (_("%pB: stack size specified and %s set"),
6115                             output_bfd, legacy_symbol);
6116       else if (h->root.u.def.section != bfd_abs_section_ptr)
6117         /* xgettext:c-format */
6118         _bfd_error_handler (_("%pB: %s not absolute"),
6119                             output_bfd, legacy_symbol);
6120       else
6121         info->stacksize = h->root.u.def.value;
6122     }
6123
6124   if (!info->stacksize)
6125     /* If the user didn't set a size, or explicitly inhibit the
6126        size, set it now.  */
6127     info->stacksize = default_size;
6128
6129   /* Provide the legacy symbol, if it is referenced.  */
6130   if (h && (h->root.type == bfd_link_hash_undefined
6131             || h->root.type == bfd_link_hash_undefweak))
6132     {
6133       struct bfd_link_hash_entry *bh = NULL;
6134
6135       if (!(_bfd_generic_link_add_one_symbol
6136             (info, output_bfd, legacy_symbol,
6137              BSF_GLOBAL, bfd_abs_section_ptr,
6138              info->stacksize >= 0 ? info->stacksize : 0,
6139              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
6140         return FALSE;
6141
6142       h = (struct elf_link_hash_entry *) bh;
6143       h->def_regular = 1;
6144       h->type = STT_OBJECT;
6145     }
6146
6147   return TRUE;
6148 }
6149
6150 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
6151
6152 struct elf_gc_sweep_symbol_info
6153 {
6154   struct bfd_link_info *info;
6155   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
6156                        bfd_boolean);
6157 };
6158
6159 static bfd_boolean
6160 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
6161 {
6162   if (!h->mark
6163       && (((h->root.type == bfd_link_hash_defined
6164             || h->root.type == bfd_link_hash_defweak)
6165            && !((h->def_regular || ELF_COMMON_DEF_P (h))
6166                 && h->root.u.def.section->gc_mark))
6167           || h->root.type == bfd_link_hash_undefined
6168           || h->root.type == bfd_link_hash_undefweak))
6169     {
6170       struct elf_gc_sweep_symbol_info *inf;
6171
6172       inf = (struct elf_gc_sweep_symbol_info *) data;
6173       (*inf->hide_symbol) (inf->info, h, TRUE);
6174       h->def_regular = 0;
6175       h->ref_regular = 0;
6176       h->ref_regular_nonweak = 0;
6177     }
6178
6179   return TRUE;
6180 }
6181
6182 /* Set up the sizes and contents of the ELF dynamic sections.  This is
6183    called by the ELF linker emulation before_allocation routine.  We
6184    must set the sizes of the sections before the linker sets the
6185    addresses of the various sections.  */
6186
6187 bfd_boolean
6188 bfd_elf_size_dynamic_sections (bfd *output_bfd,
6189                                const char *soname,
6190                                const char *rpath,
6191                                const char *filter_shlib,
6192                                const char *audit,
6193                                const char *depaudit,
6194                                const char * const *auxiliary_filters,
6195                                struct bfd_link_info *info,
6196                                asection **sinterpptr)
6197 {
6198   bfd *dynobj;
6199   const struct elf_backend_data *bed;
6200
6201   *sinterpptr = NULL;
6202
6203   if (!is_elf_hash_table (info->hash))
6204     return TRUE;
6205
6206   dynobj = elf_hash_table (info)->dynobj;
6207
6208   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6209     {
6210       struct bfd_elf_version_tree *verdefs;
6211       struct elf_info_failed asvinfo;
6212       struct bfd_elf_version_tree *t;
6213       struct bfd_elf_version_expr *d;
6214       asection *s;
6215       size_t soname_indx;
6216
6217       /* If we are supposed to export all symbols into the dynamic symbol
6218          table (this is not the normal case), then do so.  */
6219       if (info->export_dynamic
6220           || (bfd_link_executable (info) && info->dynamic))
6221         {
6222           struct elf_info_failed eif;
6223
6224           eif.info = info;
6225           eif.failed = FALSE;
6226           elf_link_hash_traverse (elf_hash_table (info),
6227                                   _bfd_elf_export_symbol,
6228                                   &eif);
6229           if (eif.failed)
6230             return FALSE;
6231         }
6232
6233       if (soname != NULL)
6234         {
6235           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6236                                              soname, TRUE);
6237           if (soname_indx == (size_t) -1
6238               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
6239             return FALSE;
6240         }
6241       else
6242         soname_indx = (size_t) -1;
6243
6244       /* Make all global versions with definition.  */
6245       for (t = info->version_info; t != NULL; t = t->next)
6246         for (d = t->globals.list; d != NULL; d = d->next)
6247           if (!d->symver && d->literal)
6248             {
6249               const char *verstr, *name;
6250               size_t namelen, verlen, newlen;
6251               char *newname, *p, leading_char;
6252               struct elf_link_hash_entry *newh;
6253
6254               leading_char = bfd_get_symbol_leading_char (output_bfd);
6255               name = d->pattern;
6256               namelen = strlen (name) + (leading_char != '\0');
6257               verstr = t->name;
6258               verlen = strlen (verstr);
6259               newlen = namelen + verlen + 3;
6260
6261               newname = (char *) bfd_malloc (newlen);
6262               if (newname == NULL)
6263                 return FALSE;
6264               newname[0] = leading_char;
6265               memcpy (newname + (leading_char != '\0'), name, namelen);
6266
6267               /* Check the hidden versioned definition.  */
6268               p = newname + namelen;
6269               *p++ = ELF_VER_CHR;
6270               memcpy (p, verstr, verlen + 1);
6271               newh = elf_link_hash_lookup (elf_hash_table (info),
6272                                            newname, FALSE, FALSE,
6273                                            FALSE);
6274               if (newh == NULL
6275                   || (newh->root.type != bfd_link_hash_defined
6276                       && newh->root.type != bfd_link_hash_defweak))
6277                 {
6278                   /* Check the default versioned definition.  */
6279                   *p++ = ELF_VER_CHR;
6280                   memcpy (p, verstr, verlen + 1);
6281                   newh = elf_link_hash_lookup (elf_hash_table (info),
6282                                                newname, FALSE, FALSE,
6283                                                FALSE);
6284                 }
6285               free (newname);
6286
6287               /* Mark this version if there is a definition and it is
6288                  not defined in a shared object.  */
6289               if (newh != NULL
6290                   && !newh->def_dynamic
6291                   && (newh->root.type == bfd_link_hash_defined
6292                       || newh->root.type == bfd_link_hash_defweak))
6293                 d->symver = 1;
6294             }
6295
6296       /* Attach all the symbols to their version information.  */
6297       asvinfo.info = info;
6298       asvinfo.failed = FALSE;
6299
6300       elf_link_hash_traverse (elf_hash_table (info),
6301                               _bfd_elf_link_assign_sym_version,
6302                               &asvinfo);
6303       if (asvinfo.failed)
6304         return FALSE;
6305
6306       if (!info->allow_undefined_version)
6307         {
6308           /* Check if all global versions have a definition.  */
6309           bfd_boolean all_defined = TRUE;
6310           for (t = info->version_info; t != NULL; t = t->next)
6311             for (d = t->globals.list; d != NULL; d = d->next)
6312               if (d->literal && !d->symver && !d->script)
6313                 {
6314                   _bfd_error_handler
6315                     (_("%s: undefined version: %s"),
6316                      d->pattern, t->name);
6317                   all_defined = FALSE;
6318                 }
6319
6320           if (!all_defined)
6321             {
6322               bfd_set_error (bfd_error_bad_value);
6323               return FALSE;
6324             }
6325         }
6326
6327       /* Set up the version definition section.  */
6328       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6329       BFD_ASSERT (s != NULL);
6330
6331       /* We may have created additional version definitions if we are
6332          just linking a regular application.  */
6333       verdefs = info->version_info;
6334
6335       /* Skip anonymous version tag.  */
6336       if (verdefs != NULL && verdefs->vernum == 0)
6337         verdefs = verdefs->next;
6338
6339       if (verdefs == NULL && !info->create_default_symver)
6340         s->flags |= SEC_EXCLUDE;
6341       else
6342         {
6343           unsigned int cdefs;
6344           bfd_size_type size;
6345           bfd_byte *p;
6346           Elf_Internal_Verdef def;
6347           Elf_Internal_Verdaux defaux;
6348           struct bfd_link_hash_entry *bh;
6349           struct elf_link_hash_entry *h;
6350           const char *name;
6351
6352           cdefs = 0;
6353           size = 0;
6354
6355           /* Make space for the base version.  */
6356           size += sizeof (Elf_External_Verdef);
6357           size += sizeof (Elf_External_Verdaux);
6358           ++cdefs;
6359
6360           /* Make space for the default version.  */
6361           if (info->create_default_symver)
6362             {
6363               size += sizeof (Elf_External_Verdef);
6364               ++cdefs;
6365             }
6366
6367           for (t = verdefs; t != NULL; t = t->next)
6368             {
6369               struct bfd_elf_version_deps *n;
6370
6371               /* Don't emit base version twice.  */
6372               if (t->vernum == 0)
6373                 continue;
6374
6375               size += sizeof (Elf_External_Verdef);
6376               size += sizeof (Elf_External_Verdaux);
6377               ++cdefs;
6378
6379               for (n = t->deps; n != NULL; n = n->next)
6380                 size += sizeof (Elf_External_Verdaux);
6381             }
6382
6383           s->size = size;
6384           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6385           if (s->contents == NULL && s->size != 0)
6386             return FALSE;
6387
6388           /* Fill in the version definition section.  */
6389
6390           p = s->contents;
6391
6392           def.vd_version = VER_DEF_CURRENT;
6393           def.vd_flags = VER_FLG_BASE;
6394           def.vd_ndx = 1;
6395           def.vd_cnt = 1;
6396           if (info->create_default_symver)
6397             {
6398               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6399               def.vd_next = sizeof (Elf_External_Verdef);
6400             }
6401           else
6402             {
6403               def.vd_aux = sizeof (Elf_External_Verdef);
6404               def.vd_next = (sizeof (Elf_External_Verdef)
6405                              + sizeof (Elf_External_Verdaux));
6406             }
6407
6408           if (soname_indx != (size_t) -1)
6409             {
6410               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6411                                       soname_indx);
6412               def.vd_hash = bfd_elf_hash (soname);
6413               defaux.vda_name = soname_indx;
6414               name = soname;
6415             }
6416           else
6417             {
6418               size_t indx;
6419
6420               name = lbasename (output_bfd->filename);
6421               def.vd_hash = bfd_elf_hash (name);
6422               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6423                                           name, FALSE);
6424               if (indx == (size_t) -1)
6425                 return FALSE;
6426               defaux.vda_name = indx;
6427             }
6428           defaux.vda_next = 0;
6429
6430           _bfd_elf_swap_verdef_out (output_bfd, &def,
6431                                     (Elf_External_Verdef *) p);
6432           p += sizeof (Elf_External_Verdef);
6433           if (info->create_default_symver)
6434             {
6435               /* Add a symbol representing this version.  */
6436               bh = NULL;
6437               if (! (_bfd_generic_link_add_one_symbol
6438                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6439                       0, NULL, FALSE,
6440                       get_elf_backend_data (dynobj)->collect, &bh)))
6441                 return FALSE;
6442               h = (struct elf_link_hash_entry *) bh;
6443               h->non_elf = 0;
6444               h->def_regular = 1;
6445               h->type = STT_OBJECT;
6446               h->verinfo.vertree = NULL;
6447
6448               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6449                 return FALSE;
6450
6451               /* Create a duplicate of the base version with the same
6452                  aux block, but different flags.  */
6453               def.vd_flags = 0;
6454               def.vd_ndx = 2;
6455               def.vd_aux = sizeof (Elf_External_Verdef);
6456               if (verdefs)
6457                 def.vd_next = (sizeof (Elf_External_Verdef)
6458                                + sizeof (Elf_External_Verdaux));
6459               else
6460                 def.vd_next = 0;
6461               _bfd_elf_swap_verdef_out (output_bfd, &def,
6462                                         (Elf_External_Verdef *) p);
6463               p += sizeof (Elf_External_Verdef);
6464             }
6465           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6466                                      (Elf_External_Verdaux *) p);
6467           p += sizeof (Elf_External_Verdaux);
6468
6469           for (t = verdefs; t != NULL; t = t->next)
6470             {
6471               unsigned int cdeps;
6472               struct bfd_elf_version_deps *n;
6473
6474               /* Don't emit the base version twice.  */
6475               if (t->vernum == 0)
6476                 continue;
6477
6478               cdeps = 0;
6479               for (n = t->deps; n != NULL; n = n->next)
6480                 ++cdeps;
6481
6482               /* Add a symbol representing this version.  */
6483               bh = NULL;
6484               if (! (_bfd_generic_link_add_one_symbol
6485                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6486                       0, NULL, FALSE,
6487                       get_elf_backend_data (dynobj)->collect, &bh)))
6488                 return FALSE;
6489               h = (struct elf_link_hash_entry *) bh;
6490               h->non_elf = 0;
6491               h->def_regular = 1;
6492               h->type = STT_OBJECT;
6493               h->verinfo.vertree = t;
6494
6495               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6496                 return FALSE;
6497
6498               def.vd_version = VER_DEF_CURRENT;
6499               def.vd_flags = 0;
6500               if (t->globals.list == NULL
6501                   && t->locals.list == NULL
6502                   && ! t->used)
6503                 def.vd_flags |= VER_FLG_WEAK;
6504               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6505               def.vd_cnt = cdeps + 1;
6506               def.vd_hash = bfd_elf_hash (t->name);
6507               def.vd_aux = sizeof (Elf_External_Verdef);
6508               def.vd_next = 0;
6509
6510               /* If a basever node is next, it *must* be the last node in
6511                  the chain, otherwise Verdef construction breaks.  */
6512               if (t->next != NULL && t->next->vernum == 0)
6513                 BFD_ASSERT (t->next->next == NULL);
6514
6515               if (t->next != NULL && t->next->vernum != 0)
6516                 def.vd_next = (sizeof (Elf_External_Verdef)
6517                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6518
6519               _bfd_elf_swap_verdef_out (output_bfd, &def,
6520                                         (Elf_External_Verdef *) p);
6521               p += sizeof (Elf_External_Verdef);
6522
6523               defaux.vda_name = h->dynstr_index;
6524               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6525                                       h->dynstr_index);
6526               defaux.vda_next = 0;
6527               if (t->deps != NULL)
6528                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6529               t->name_indx = defaux.vda_name;
6530
6531               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6532                                          (Elf_External_Verdaux *) p);
6533               p += sizeof (Elf_External_Verdaux);
6534
6535               for (n = t->deps; n != NULL; n = n->next)
6536                 {
6537                   if (n->version_needed == NULL)
6538                     {
6539                       /* This can happen if there was an error in the
6540                          version script.  */
6541                       defaux.vda_name = 0;
6542                     }
6543                   else
6544                     {
6545                       defaux.vda_name = n->version_needed->name_indx;
6546                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6547                                               defaux.vda_name);
6548                     }
6549                   if (n->next == NULL)
6550                     defaux.vda_next = 0;
6551                   else
6552                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6553
6554                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6555                                              (Elf_External_Verdaux *) p);
6556                   p += sizeof (Elf_External_Verdaux);
6557                 }
6558             }
6559
6560           elf_tdata (output_bfd)->cverdefs = cdefs;
6561         }
6562     }
6563
6564   bed = get_elf_backend_data (output_bfd);
6565
6566   if (info->gc_sections && bed->can_gc_sections)
6567     {
6568       struct elf_gc_sweep_symbol_info sweep_info;
6569
6570       /* Remove the symbols that were in the swept sections from the
6571          dynamic symbol table.  */
6572       sweep_info.info = info;
6573       sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
6574       elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
6575                               &sweep_info);
6576     }
6577
6578   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6579     {
6580       asection *s;
6581       struct elf_find_verdep_info sinfo;
6582
6583       /* Work out the size of the version reference section.  */
6584
6585       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6586       BFD_ASSERT (s != NULL);
6587
6588       sinfo.info = info;
6589       sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6590       if (sinfo.vers == 0)
6591         sinfo.vers = 1;
6592       sinfo.failed = FALSE;
6593
6594       elf_link_hash_traverse (elf_hash_table (info),
6595                               _bfd_elf_link_find_version_dependencies,
6596                               &sinfo);
6597       if (sinfo.failed)
6598         return FALSE;
6599
6600       if (elf_tdata (output_bfd)->verref == NULL)
6601         s->flags |= SEC_EXCLUDE;
6602       else
6603         {
6604           Elf_Internal_Verneed *vn;
6605           unsigned int size;
6606           unsigned int crefs;
6607           bfd_byte *p;
6608
6609           /* Build the version dependency section.  */
6610           size = 0;
6611           crefs = 0;
6612           for (vn = elf_tdata (output_bfd)->verref;
6613                vn != NULL;
6614                vn = vn->vn_nextref)
6615             {
6616               Elf_Internal_Vernaux *a;
6617
6618               size += sizeof (Elf_External_Verneed);
6619               ++crefs;
6620               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6621                 size += sizeof (Elf_External_Vernaux);
6622             }
6623
6624           s->size = size;
6625           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6626           if (s->contents == NULL)
6627             return FALSE;
6628
6629           p = s->contents;
6630           for (vn = elf_tdata (output_bfd)->verref;
6631                vn != NULL;
6632                vn = vn->vn_nextref)
6633             {
6634               unsigned int caux;
6635               Elf_Internal_Vernaux *a;
6636               size_t indx;
6637
6638               caux = 0;
6639               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6640                 ++caux;
6641
6642               vn->vn_version = VER_NEED_CURRENT;
6643               vn->vn_cnt = caux;
6644               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6645                                           elf_dt_name (vn->vn_bfd) != NULL
6646                                           ? elf_dt_name (vn->vn_bfd)
6647                                           : lbasename (vn->vn_bfd->filename),
6648                                           FALSE);
6649               if (indx == (size_t) -1)
6650                 return FALSE;
6651               vn->vn_file = indx;
6652               vn->vn_aux = sizeof (Elf_External_Verneed);
6653               if (vn->vn_nextref == NULL)
6654                 vn->vn_next = 0;
6655               else
6656                 vn->vn_next = (sizeof (Elf_External_Verneed)
6657                                + caux * sizeof (Elf_External_Vernaux));
6658
6659               _bfd_elf_swap_verneed_out (output_bfd, vn,
6660                                          (Elf_External_Verneed *) p);
6661               p += sizeof (Elf_External_Verneed);
6662
6663               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6664                 {
6665                   a->vna_hash = bfd_elf_hash (a->vna_nodename);
6666                   indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6667                                               a->vna_nodename, FALSE);
6668                   if (indx == (size_t) -1)
6669                     return FALSE;
6670                   a->vna_name = indx;
6671                   if (a->vna_nextptr == NULL)
6672                     a->vna_next = 0;
6673                   else
6674                     a->vna_next = sizeof (Elf_External_Vernaux);
6675
6676                   _bfd_elf_swap_vernaux_out (output_bfd, a,
6677                                              (Elf_External_Vernaux *) p);
6678                   p += sizeof (Elf_External_Vernaux);
6679                 }
6680             }
6681
6682           elf_tdata (output_bfd)->cverrefs = crefs;
6683         }
6684     }
6685
6686   /* Any syms created from now on start with -1 in
6687      got.refcount/offset and plt.refcount/offset.  */
6688   elf_hash_table (info)->init_got_refcount
6689     = elf_hash_table (info)->init_got_offset;
6690   elf_hash_table (info)->init_plt_refcount
6691     = elf_hash_table (info)->init_plt_offset;
6692
6693   if (bfd_link_relocatable (info)
6694       && !_bfd_elf_size_group_sections (info))
6695     return FALSE;
6696
6697   /* The backend may have to create some sections regardless of whether
6698      we're dynamic or not.  */
6699   if (bed->elf_backend_always_size_sections
6700       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
6701     return FALSE;
6702
6703   /* Determine any GNU_STACK segment requirements, after the backend
6704      has had a chance to set a default segment size.  */
6705   if (info->execstack)
6706     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
6707   else if (info->noexecstack)
6708     elf_stack_flags (output_bfd) = PF_R | PF_W;
6709   else
6710     {
6711       bfd *inputobj;
6712       asection *notesec = NULL;
6713       int exec = 0;
6714
6715       for (inputobj = info->input_bfds;
6716            inputobj;
6717            inputobj = inputobj->link.next)
6718         {
6719           asection *s;
6720
6721           if (inputobj->flags
6722               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
6723             continue;
6724           s = inputobj->sections;
6725           if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
6726             continue;
6727
6728           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
6729           if (s)
6730             {
6731               if (s->flags & SEC_CODE)
6732                 exec = PF_X;
6733               notesec = s;
6734             }
6735           else if (bed->default_execstack)
6736             exec = PF_X;
6737         }
6738       if (notesec || info->stacksize > 0)
6739         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
6740       if (notesec && exec && bfd_link_relocatable (info)
6741           && notesec->output_section != bfd_abs_section_ptr)
6742         notesec->output_section->flags |= SEC_CODE;
6743     }
6744
6745   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6746     {
6747       struct elf_info_failed eif;
6748       struct elf_link_hash_entry *h;
6749       asection *dynstr;
6750       asection *s;
6751
6752       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
6753       BFD_ASSERT (*sinterpptr != NULL || !bfd_link_executable (info) || info->nointerp);
6754
6755       if (info->symbolic)
6756         {
6757           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
6758             return FALSE;
6759           info->flags |= DF_SYMBOLIC;
6760         }
6761
6762       if (rpath != NULL)
6763         {
6764           size_t indx;
6765           bfd_vma tag;
6766
6767           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
6768                                       TRUE);
6769           if (indx == (size_t) -1)
6770             return FALSE;
6771
6772           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
6773           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
6774             return FALSE;
6775         }
6776
6777       if (filter_shlib != NULL)
6778         {
6779           size_t indx;
6780
6781           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6782                                       filter_shlib, TRUE);
6783           if (indx == (size_t) -1
6784               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
6785             return FALSE;
6786         }
6787
6788       if (auxiliary_filters != NULL)
6789         {
6790           const char * const *p;
6791
6792           for (p = auxiliary_filters; *p != NULL; p++)
6793             {
6794               size_t indx;
6795
6796               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6797                                           *p, TRUE);
6798               if (indx == (size_t) -1
6799                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
6800                 return FALSE;
6801             }
6802         }
6803
6804       if (audit != NULL)
6805         {
6806           size_t indx;
6807
6808           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
6809                                       TRUE);
6810           if (indx == (size_t) -1
6811               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
6812             return FALSE;
6813         }
6814
6815       if (depaudit != NULL)
6816         {
6817           size_t indx;
6818
6819           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
6820                                       TRUE);
6821           if (indx == (size_t) -1
6822               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
6823             return FALSE;
6824         }
6825
6826       eif.info = info;
6827       eif.failed = FALSE;
6828
6829       /* Find all symbols which were defined in a dynamic object and make
6830          the backend pick a reasonable value for them.  */
6831       elf_link_hash_traverse (elf_hash_table (info),
6832                               _bfd_elf_adjust_dynamic_symbol,
6833                               &eif);
6834       if (eif.failed)
6835         return FALSE;
6836
6837       /* Add some entries to the .dynamic section.  We fill in some of the
6838          values later, in bfd_elf_final_link, but we must add the entries
6839          now so that we know the final size of the .dynamic section.  */
6840
6841       /* If there are initialization and/or finalization functions to
6842          call then add the corresponding DT_INIT/DT_FINI entries.  */
6843       h = (info->init_function
6844            ? elf_link_hash_lookup (elf_hash_table (info),
6845                                    info->init_function, FALSE,
6846                                    FALSE, FALSE)
6847            : NULL);
6848       if (h != NULL
6849           && (h->ref_regular
6850               || h->def_regular))
6851         {
6852           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
6853             return FALSE;
6854         }
6855       h = (info->fini_function
6856            ? elf_link_hash_lookup (elf_hash_table (info),
6857                                    info->fini_function, FALSE,
6858                                    FALSE, FALSE)
6859            : NULL);
6860       if (h != NULL
6861           && (h->ref_regular
6862               || h->def_regular))
6863         {
6864           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
6865             return FALSE;
6866         }
6867
6868       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
6869       if (s != NULL && s->linker_has_input)
6870         {
6871           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
6872           if (! bfd_link_executable (info))
6873             {
6874               bfd *sub;
6875               asection *o;
6876
6877               for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
6878                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour
6879                     && (o = sub->sections) != NULL
6880                     && o->sec_info_type != SEC_INFO_TYPE_JUST_SYMS)
6881                   for (o = sub->sections; o != NULL; o = o->next)
6882                     if (elf_section_data (o)->this_hdr.sh_type
6883                         == SHT_PREINIT_ARRAY)
6884                       {
6885                         _bfd_error_handler
6886                           (_("%pB: .preinit_array section is not allowed in DSO"),
6887                            sub);
6888                         break;
6889                       }
6890
6891               bfd_set_error (bfd_error_nonrepresentable_section);
6892               return FALSE;
6893             }
6894
6895           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6896               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6897             return FALSE;
6898         }
6899       s = bfd_get_section_by_name (output_bfd, ".init_array");
6900       if (s != NULL && s->linker_has_input)
6901         {
6902           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6903               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6904             return FALSE;
6905         }
6906       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6907       if (s != NULL && s->linker_has_input)
6908         {
6909           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6910               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6911             return FALSE;
6912         }
6913
6914       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6915       /* If .dynstr is excluded from the link, we don't want any of
6916          these tags.  Strictly, we should be checking each section
6917          individually;  This quick check covers for the case where
6918          someone does a /DISCARD/ : { *(*) }.  */
6919       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6920         {
6921           bfd_size_type strsize;
6922
6923           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6924           if ((info->emit_hash
6925                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6926               || (info->emit_gnu_hash
6927                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6928               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6929               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6930               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6931               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6932                                               bed->s->sizeof_sym))
6933             return FALSE;
6934         }
6935     }
6936
6937   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6938     return FALSE;
6939
6940   /* The backend must work out the sizes of all the other dynamic
6941      sections.  */
6942   if (dynobj != NULL
6943       && bed->elf_backend_size_dynamic_sections != NULL
6944       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6945     return FALSE;
6946
6947   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6948     {
6949       if (elf_tdata (output_bfd)->cverdefs)
6950         {
6951           unsigned int crefs = elf_tdata (output_bfd)->cverdefs;
6952
6953           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6954               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, crefs))
6955             return FALSE;
6956         }
6957
6958       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6959         {
6960           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6961             return FALSE;
6962         }
6963       else if (info->flags & DF_BIND_NOW)
6964         {
6965           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6966             return FALSE;
6967         }
6968
6969       if (info->flags_1)
6970         {
6971           if (bfd_link_executable (info))
6972             info->flags_1 &= ~ (DF_1_INITFIRST
6973                                 | DF_1_NODELETE
6974                                 | DF_1_NOOPEN);
6975           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6976             return FALSE;
6977         }
6978
6979       if (elf_tdata (output_bfd)->cverrefs)
6980         {
6981           unsigned int crefs = elf_tdata (output_bfd)->cverrefs;
6982
6983           if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6984               || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6985             return FALSE;
6986         }
6987
6988       if ((elf_tdata (output_bfd)->cverrefs == 0
6989            && elf_tdata (output_bfd)->cverdefs == 0)
6990           || _bfd_elf_link_renumber_dynsyms (output_bfd, info, NULL) <= 1)
6991         {
6992           asection *s;
6993
6994           s = bfd_get_linker_section (dynobj, ".gnu.version");
6995           s->flags |= SEC_EXCLUDE;
6996         }
6997     }
6998   return TRUE;
6999 }
7000
7001 /* Find the first non-excluded output section.  We'll use its
7002    section symbol for some emitted relocs.  */
7003 void
7004 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
7005 {
7006   asection *s;
7007
7008   for (s = output_bfd->sections; s != NULL; s = s->next)
7009     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
7010         && !_bfd_elf_omit_section_dynsym_default (output_bfd, info, s))
7011       {
7012         elf_hash_table (info)->text_index_section = s;
7013         break;
7014       }
7015 }
7016
7017 /* Find two non-excluded output sections, one for code, one for data.
7018    We'll use their section symbols for some emitted relocs.  */
7019 void
7020 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
7021 {
7022   asection *s;
7023
7024   /* Data first, since setting text_index_section changes
7025      _bfd_elf_omit_section_dynsym_default.  */
7026   for (s = output_bfd->sections; s != NULL; s = s->next)
7027     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
7028         && !_bfd_elf_omit_section_dynsym_default (output_bfd, info, s))
7029       {
7030         elf_hash_table (info)->data_index_section = s;
7031         break;
7032       }
7033
7034   for (s = output_bfd->sections; s != NULL; s = s->next)
7035     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
7036          == (SEC_ALLOC | SEC_READONLY))
7037         && !_bfd_elf_omit_section_dynsym_default (output_bfd, info, s))
7038       {
7039         elf_hash_table (info)->text_index_section = s;
7040         break;
7041       }
7042
7043   if (elf_hash_table (info)->text_index_section == NULL)
7044     elf_hash_table (info)->text_index_section
7045       = elf_hash_table (info)->data_index_section;
7046 }
7047
7048 bfd_boolean
7049 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
7050 {
7051   const struct elf_backend_data *bed;
7052   unsigned long section_sym_count;
7053   bfd_size_type dynsymcount = 0;
7054
7055   if (!is_elf_hash_table (info->hash))
7056     return TRUE;
7057
7058   bed = get_elf_backend_data (output_bfd);
7059   (*bed->elf_backend_init_index_section) (output_bfd, info);
7060
7061   /* Assign dynsym indices.  In a shared library we generate a section
7062      symbol for each output section, which come first.  Next come all
7063      of the back-end allocated local dynamic syms, followed by the rest
7064      of the global symbols.
7065
7066      This is usually not needed for static binaries, however backends
7067      can request to always do it, e.g. the MIPS backend uses dynamic
7068      symbol counts to lay out GOT, which will be produced in the
7069      presence of GOT relocations even in static binaries (holding fixed
7070      data in that case, to satisfy those relocations).  */
7071
7072   if (elf_hash_table (info)->dynamic_sections_created
7073       || bed->always_renumber_dynsyms)
7074     dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
7075                                                   &section_sym_count);
7076
7077   if (elf_hash_table (info)->dynamic_sections_created)
7078     {
7079       bfd *dynobj;
7080       asection *s;
7081       unsigned int dtagcount;
7082
7083       dynobj = elf_hash_table (info)->dynobj;
7084
7085       /* Work out the size of the symbol version section.  */
7086       s = bfd_get_linker_section (dynobj, ".gnu.version");
7087       BFD_ASSERT (s != NULL);
7088       if ((s->flags & SEC_EXCLUDE) == 0)
7089         {
7090           s->size = dynsymcount * sizeof (Elf_External_Versym);
7091           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7092           if (s->contents == NULL)
7093             return FALSE;
7094
7095           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
7096             return FALSE;
7097         }
7098
7099       /* Set the size of the .dynsym and .hash sections.  We counted
7100          the number of dynamic symbols in elf_link_add_object_symbols.
7101          We will build the contents of .dynsym and .hash when we build
7102          the final symbol table, because until then we do not know the
7103          correct value to give the symbols.  We built the .dynstr
7104          section as we went along in elf_link_add_object_symbols.  */
7105       s = elf_hash_table (info)->dynsym;
7106       BFD_ASSERT (s != NULL);
7107       s->size = dynsymcount * bed->s->sizeof_sym;
7108
7109       s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
7110       if (s->contents == NULL)
7111         return FALSE;
7112
7113       /* The first entry in .dynsym is a dummy symbol.  Clear all the
7114          section syms, in case we don't output them all.  */
7115       ++section_sym_count;
7116       memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
7117
7118       elf_hash_table (info)->bucketcount = 0;
7119
7120       /* Compute the size of the hashing table.  As a side effect this
7121          computes the hash values for all the names we export.  */
7122       if (info->emit_hash)
7123         {
7124           unsigned long int *hashcodes;
7125           struct hash_codes_info hashinf;
7126           bfd_size_type amt;
7127           unsigned long int nsyms;
7128           size_t bucketcount;
7129           size_t hash_entry_size;
7130
7131           /* Compute the hash values for all exported symbols.  At the same
7132              time store the values in an array so that we could use them for
7133              optimizations.  */
7134           amt = dynsymcount * sizeof (unsigned long int);
7135           hashcodes = (unsigned long int *) bfd_malloc (amt);
7136           if (hashcodes == NULL)
7137             return FALSE;
7138           hashinf.hashcodes = hashcodes;
7139           hashinf.error = FALSE;
7140
7141           /* Put all hash values in HASHCODES.  */
7142           elf_link_hash_traverse (elf_hash_table (info),
7143                                   elf_collect_hash_codes, &hashinf);
7144           if (hashinf.error)
7145             {
7146               free (hashcodes);
7147               return FALSE;
7148             }
7149
7150           nsyms = hashinf.hashcodes - hashcodes;
7151           bucketcount
7152             = compute_bucket_count (info, hashcodes, nsyms, 0);
7153           free (hashcodes);
7154
7155           if (bucketcount == 0 && nsyms > 0)
7156             return FALSE;
7157
7158           elf_hash_table (info)->bucketcount = bucketcount;
7159
7160           s = bfd_get_linker_section (dynobj, ".hash");
7161           BFD_ASSERT (s != NULL);
7162           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
7163           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
7164           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7165           if (s->contents == NULL)
7166             return FALSE;
7167
7168           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
7169           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
7170                    s->contents + hash_entry_size);
7171         }
7172
7173       if (info->emit_gnu_hash)
7174         {
7175           size_t i, cnt;
7176           unsigned char *contents;
7177           struct collect_gnu_hash_codes cinfo;
7178           bfd_size_type amt;
7179           size_t bucketcount;
7180
7181           memset (&cinfo, 0, sizeof (cinfo));
7182
7183           /* Compute the hash values for all exported symbols.  At the same
7184              time store the values in an array so that we could use them for
7185              optimizations.  */
7186           amt = dynsymcount * 2 * sizeof (unsigned long int);
7187           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
7188           if (cinfo.hashcodes == NULL)
7189             return FALSE;
7190
7191           cinfo.hashval = cinfo.hashcodes + dynsymcount;
7192           cinfo.min_dynindx = -1;
7193           cinfo.output_bfd = output_bfd;
7194           cinfo.bed = bed;
7195
7196           /* Put all hash values in HASHCODES.  */
7197           elf_link_hash_traverse (elf_hash_table (info),
7198                                   elf_collect_gnu_hash_codes, &cinfo);
7199           if (cinfo.error)
7200             {
7201               free (cinfo.hashcodes);
7202               return FALSE;
7203             }
7204
7205           bucketcount
7206             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
7207
7208           if (bucketcount == 0)
7209             {
7210               free (cinfo.hashcodes);
7211               return FALSE;
7212             }
7213
7214           s = bfd_get_linker_section (dynobj, ".gnu.hash");
7215           BFD_ASSERT (s != NULL);
7216
7217           if (cinfo.nsyms == 0)
7218             {
7219               /* Empty .gnu.hash section is special.  */
7220               BFD_ASSERT (cinfo.min_dynindx == -1);
7221               free (cinfo.hashcodes);
7222               s->size = 5 * 4 + bed->s->arch_size / 8;
7223               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7224               if (contents == NULL)
7225                 return FALSE;
7226               s->contents = contents;
7227               /* 1 empty bucket.  */
7228               bfd_put_32 (output_bfd, 1, contents);
7229               /* SYMIDX above the special symbol 0.  */
7230               bfd_put_32 (output_bfd, 1, contents + 4);
7231               /* Just one word for bitmask.  */
7232               bfd_put_32 (output_bfd, 1, contents + 8);
7233               /* Only hash fn bloom filter.  */
7234               bfd_put_32 (output_bfd, 0, contents + 12);
7235               /* No hashes are valid - empty bitmask.  */
7236               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
7237               /* No hashes in the only bucket.  */
7238               bfd_put_32 (output_bfd, 0,
7239                           contents + 16 + bed->s->arch_size / 8);
7240             }
7241           else
7242             {
7243               unsigned long int maskwords, maskbitslog2, x;
7244               BFD_ASSERT (cinfo.min_dynindx != -1);
7245
7246               x = cinfo.nsyms;
7247               maskbitslog2 = 1;
7248               while ((x >>= 1) != 0)
7249                 ++maskbitslog2;
7250               if (maskbitslog2 < 3)
7251                 maskbitslog2 = 5;
7252               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
7253                 maskbitslog2 = maskbitslog2 + 3;
7254               else
7255                 maskbitslog2 = maskbitslog2 + 2;
7256               if (bed->s->arch_size == 64)
7257                 {
7258                   if (maskbitslog2 == 5)
7259                     maskbitslog2 = 6;
7260                   cinfo.shift1 = 6;
7261                 }
7262               else
7263                 cinfo.shift1 = 5;
7264               cinfo.mask = (1 << cinfo.shift1) - 1;
7265               cinfo.shift2 = maskbitslog2;
7266               cinfo.maskbits = 1 << maskbitslog2;
7267               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
7268               amt = bucketcount * sizeof (unsigned long int) * 2;
7269               amt += maskwords * sizeof (bfd_vma);
7270               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
7271               if (cinfo.bitmask == NULL)
7272                 {
7273                   free (cinfo.hashcodes);
7274                   return FALSE;
7275                 }
7276
7277               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
7278               cinfo.indx = cinfo.counts + bucketcount;
7279               cinfo.symindx = dynsymcount - cinfo.nsyms;
7280               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
7281
7282               /* Determine how often each hash bucket is used.  */
7283               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
7284               for (i = 0; i < cinfo.nsyms; ++i)
7285                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
7286
7287               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
7288                 if (cinfo.counts[i] != 0)
7289                   {
7290                     cinfo.indx[i] = cnt;
7291                     cnt += cinfo.counts[i];
7292                   }
7293               BFD_ASSERT (cnt == dynsymcount);
7294               cinfo.bucketcount = bucketcount;
7295               cinfo.local_indx = cinfo.min_dynindx;
7296
7297               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
7298               s->size += cinfo.maskbits / 8;
7299               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7300               if (contents == NULL)
7301                 {
7302                   free (cinfo.bitmask);
7303                   free (cinfo.hashcodes);
7304                   return FALSE;
7305                 }
7306
7307               s->contents = contents;
7308               bfd_put_32 (output_bfd, bucketcount, contents);
7309               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
7310               bfd_put_32 (output_bfd, maskwords, contents + 8);
7311               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
7312               contents += 16 + cinfo.maskbits / 8;
7313
7314               for (i = 0; i < bucketcount; ++i)
7315                 {
7316                   if (cinfo.counts[i] == 0)
7317                     bfd_put_32 (output_bfd, 0, contents);
7318                   else
7319                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
7320                   contents += 4;
7321                 }
7322
7323               cinfo.contents = contents;
7324
7325               /* Renumber dynamic symbols, populate .gnu.hash section.  */
7326               elf_link_hash_traverse (elf_hash_table (info),
7327                                       elf_renumber_gnu_hash_syms, &cinfo);
7328
7329               contents = s->contents + 16;
7330               for (i = 0; i < maskwords; ++i)
7331                 {
7332                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
7333                            contents);
7334                   contents += bed->s->arch_size / 8;
7335                 }
7336
7337               free (cinfo.bitmask);
7338               free (cinfo.hashcodes);
7339             }
7340         }
7341
7342       s = bfd_get_linker_section (dynobj, ".dynstr");
7343       BFD_ASSERT (s != NULL);
7344
7345       elf_finalize_dynstr (output_bfd, info);
7346
7347       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
7348
7349       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
7350         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
7351           return FALSE;
7352     }
7353
7354   return TRUE;
7355 }
7356 \f
7357 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
7358
7359 static void
7360 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
7361                             asection *sec)
7362 {
7363   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
7364   sec->sec_info_type = SEC_INFO_TYPE_NONE;
7365 }
7366
7367 /* Finish SHF_MERGE section merging.  */
7368
7369 bfd_boolean
7370 _bfd_elf_merge_sections (bfd *obfd, struct bfd_link_info *info)
7371 {
7372   bfd *ibfd;
7373   asection *sec;
7374
7375   if (!is_elf_hash_table (info->hash))
7376     return FALSE;
7377
7378   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
7379     if ((ibfd->flags & DYNAMIC) == 0
7380         && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
7381         && (elf_elfheader (ibfd)->e_ident[EI_CLASS]
7382             == get_elf_backend_data (obfd)->s->elfclass))
7383       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
7384         if ((sec->flags & SEC_MERGE) != 0
7385             && !bfd_is_abs_section (sec->output_section))
7386           {
7387             struct bfd_elf_section_data *secdata;
7388
7389             secdata = elf_section_data (sec);
7390             if (! _bfd_add_merge_section (obfd,
7391                                           &elf_hash_table (info)->merge_info,
7392                                           sec, &secdata->sec_info))
7393               return FALSE;
7394             else if (secdata->sec_info)
7395               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
7396           }
7397
7398   if (elf_hash_table (info)->merge_info != NULL)
7399     _bfd_merge_sections (obfd, info, elf_hash_table (info)->merge_info,
7400                          merge_sections_remove_hook);
7401   return TRUE;
7402 }
7403
7404 /* Create an entry in an ELF linker hash table.  */
7405
7406 struct bfd_hash_entry *
7407 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
7408                             struct bfd_hash_table *table,
7409                             const char *string)
7410 {
7411   /* Allocate the structure if it has not already been allocated by a
7412      subclass.  */
7413   if (entry == NULL)
7414     {
7415       entry = (struct bfd_hash_entry *)
7416         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
7417       if (entry == NULL)
7418         return entry;
7419     }
7420
7421   /* Call the allocation method of the superclass.  */
7422   entry = _bfd_link_hash_newfunc (entry, table, string);
7423   if (entry != NULL)
7424     {
7425       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
7426       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
7427
7428       /* Set local fields.  */
7429       ret->indx = -1;
7430       ret->dynindx = -1;
7431       ret->got = htab->init_got_refcount;
7432       ret->plt = htab->init_plt_refcount;
7433       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
7434                               - offsetof (struct elf_link_hash_entry, size)));
7435       /* Assume that we have been called by a non-ELF symbol reader.
7436          This flag is then reset by the code which reads an ELF input
7437          file.  This ensures that a symbol created by a non-ELF symbol
7438          reader will have the flag set correctly.  */
7439       ret->non_elf = 1;
7440     }
7441
7442   return entry;
7443 }
7444
7445 /* Copy data from an indirect symbol to its direct symbol, hiding the
7446    old indirect symbol.  Also used for copying flags to a weakdef.  */
7447
7448 void
7449 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
7450                                   struct elf_link_hash_entry *dir,
7451                                   struct elf_link_hash_entry *ind)
7452 {
7453   struct elf_link_hash_table *htab;
7454
7455   /* Copy down any references that we may have already seen to the
7456      symbol which just became indirect.  */
7457
7458   if (dir->versioned != versioned_hidden)
7459     dir->ref_dynamic |= ind->ref_dynamic;
7460   dir->ref_regular |= ind->ref_regular;
7461   dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
7462   dir->non_got_ref |= ind->non_got_ref;
7463   dir->needs_plt |= ind->needs_plt;
7464   dir->pointer_equality_needed |= ind->pointer_equality_needed;
7465
7466   if (ind->root.type != bfd_link_hash_indirect)
7467     return;
7468
7469   /* Copy over the global and procedure linkage table refcount entries.
7470      These may have been already set up by a check_relocs routine.  */
7471   htab = elf_hash_table (info);
7472   if (ind->got.refcount > htab->init_got_refcount.refcount)
7473     {
7474       if (dir->got.refcount < 0)
7475         dir->got.refcount = 0;
7476       dir->got.refcount += ind->got.refcount;
7477       ind->got.refcount = htab->init_got_refcount.refcount;
7478     }
7479
7480   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
7481     {
7482       if (dir->plt.refcount < 0)
7483         dir->plt.refcount = 0;
7484       dir->plt.refcount += ind->plt.refcount;
7485       ind->plt.refcount = htab->init_plt_refcount.refcount;
7486     }
7487
7488   if (ind->dynindx != -1)
7489     {
7490       if (dir->dynindx != -1)
7491         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
7492       dir->dynindx = ind->dynindx;
7493       dir->dynstr_index = ind->dynstr_index;
7494       ind->dynindx = -1;
7495       ind->dynstr_index = 0;
7496     }
7497 }
7498
7499 void
7500 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
7501                                 struct elf_link_hash_entry *h,
7502                                 bfd_boolean force_local)
7503 {
7504   /* STT_GNU_IFUNC symbol must go through PLT.  */
7505   if (h->type != STT_GNU_IFUNC)
7506     {
7507       h->plt = elf_hash_table (info)->init_plt_offset;
7508       h->needs_plt = 0;
7509     }
7510   if (force_local)
7511     {
7512       h->forced_local = 1;
7513       if (h->dynindx != -1)
7514         {
7515           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
7516                                   h->dynstr_index);
7517           h->dynindx = -1;
7518           h->dynstr_index = 0;
7519         }
7520     }
7521 }
7522
7523 /* Hide a symbol. */
7524
7525 void
7526 _bfd_elf_link_hide_symbol (bfd *output_bfd,
7527                            struct bfd_link_info *info,
7528                            struct bfd_link_hash_entry *h)
7529 {
7530   if (is_elf_hash_table (info->hash))
7531     {
7532       const struct elf_backend_data *bed
7533         = get_elf_backend_data (output_bfd);
7534       struct elf_link_hash_entry *eh
7535         = (struct elf_link_hash_entry *) h;
7536       bed->elf_backend_hide_symbol (info, eh, TRUE);
7537       eh->def_dynamic = 0;
7538       eh->ref_dynamic = 0;
7539       eh->dynamic_def = 0;
7540     }
7541 }
7542
7543 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
7544    caller.  */
7545
7546 bfd_boolean
7547 _bfd_elf_link_hash_table_init
7548   (struct elf_link_hash_table *table,
7549    bfd *abfd,
7550    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
7551                                       struct bfd_hash_table *,
7552                                       const char *),
7553    unsigned int entsize,
7554    enum elf_target_id target_id)
7555 {
7556   bfd_boolean ret;
7557   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
7558
7559   table->init_got_refcount.refcount = can_refcount - 1;
7560   table->init_plt_refcount.refcount = can_refcount - 1;
7561   table->init_got_offset.offset = -(bfd_vma) 1;
7562   table->init_plt_offset.offset = -(bfd_vma) 1;
7563   /* The first dynamic symbol is a dummy.  */
7564   table->dynsymcount = 1;
7565
7566   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
7567
7568   table->root.type = bfd_link_elf_hash_table;
7569   table->hash_table_id = target_id;
7570
7571   return ret;
7572 }
7573
7574 /* Create an ELF linker hash table.  */
7575
7576 struct bfd_link_hash_table *
7577 _bfd_elf_link_hash_table_create (bfd *abfd)
7578 {
7579   struct elf_link_hash_table *ret;
7580   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7581
7582   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7583   if (ret == NULL)
7584     return NULL;
7585
7586   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7587                                        sizeof (struct elf_link_hash_entry),
7588                                        GENERIC_ELF_DATA))
7589     {
7590       free (ret);
7591       return NULL;
7592     }
7593   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7594
7595   return &ret->root;
7596 }
7597
7598 /* Destroy an ELF linker hash table.  */
7599
7600 void
7601 _bfd_elf_link_hash_table_free (bfd *obfd)
7602 {
7603   struct elf_link_hash_table *htab;
7604
7605   htab = (struct elf_link_hash_table *) obfd->link.hash;
7606   if (htab->dynstr != NULL)
7607     _bfd_elf_strtab_free (htab->dynstr);
7608   _bfd_merge_sections_free (htab->merge_info);
7609   _bfd_generic_link_hash_table_free (obfd);
7610 }
7611
7612 /* This is a hook for the ELF emulation code in the generic linker to
7613    tell the backend linker what file name to use for the DT_NEEDED
7614    entry for a dynamic object.  */
7615
7616 void
7617 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7618 {
7619   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7620       && bfd_get_format (abfd) == bfd_object)
7621     elf_dt_name (abfd) = name;
7622 }
7623
7624 int
7625 bfd_elf_get_dyn_lib_class (bfd *abfd)
7626 {
7627   int lib_class;
7628   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7629       && bfd_get_format (abfd) == bfd_object)
7630     lib_class = elf_dyn_lib_class (abfd);
7631   else
7632     lib_class = 0;
7633   return lib_class;
7634 }
7635
7636 void
7637 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7638 {
7639   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7640       && bfd_get_format (abfd) == bfd_object)
7641     elf_dyn_lib_class (abfd) = lib_class;
7642 }
7643
7644 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7645    the linker ELF emulation code.  */
7646
7647 struct bfd_link_needed_list *
7648 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7649                          struct bfd_link_info *info)
7650 {
7651   if (! is_elf_hash_table (info->hash))
7652     return NULL;
7653   return elf_hash_table (info)->needed;
7654 }
7655
7656 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7657    hook for the linker ELF emulation code.  */
7658
7659 struct bfd_link_needed_list *
7660 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7661                           struct bfd_link_info *info)
7662 {
7663   if (! is_elf_hash_table (info->hash))
7664     return NULL;
7665   return elf_hash_table (info)->runpath;
7666 }
7667
7668 /* Get the name actually used for a dynamic object for a link.  This
7669    is the SONAME entry if there is one.  Otherwise, it is the string
7670    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7671
7672 const char *
7673 bfd_elf_get_dt_soname (bfd *abfd)
7674 {
7675   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7676       && bfd_get_format (abfd) == bfd_object)
7677     return elf_dt_name (abfd);
7678   return NULL;
7679 }
7680
7681 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7682    the ELF linker emulation code.  */
7683
7684 bfd_boolean
7685 bfd_elf_get_bfd_needed_list (bfd *abfd,
7686                              struct bfd_link_needed_list **pneeded)
7687 {
7688   asection *s;
7689   bfd_byte *dynbuf = NULL;
7690   unsigned int elfsec;
7691   unsigned long shlink;
7692   bfd_byte *extdyn, *extdynend;
7693   size_t extdynsize;
7694   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7695
7696   *pneeded = NULL;
7697
7698   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7699       || bfd_get_format (abfd) != bfd_object)
7700     return TRUE;
7701
7702   s = bfd_get_section_by_name (abfd, ".dynamic");
7703   if (s == NULL || s->size == 0)
7704     return TRUE;
7705
7706   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7707     goto error_return;
7708
7709   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7710   if (elfsec == SHN_BAD)
7711     goto error_return;
7712
7713   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7714
7715   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7716   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7717
7718   extdyn = dynbuf;
7719   extdynend = extdyn + s->size;
7720   for (; extdyn < extdynend; extdyn += extdynsize)
7721     {
7722       Elf_Internal_Dyn dyn;
7723
7724       (*swap_dyn_in) (abfd, extdyn, &dyn);
7725
7726       if (dyn.d_tag == DT_NULL)
7727         break;
7728
7729       if (dyn.d_tag == DT_NEEDED)
7730         {
7731           const char *string;
7732           struct bfd_link_needed_list *l;
7733           unsigned int tagv = dyn.d_un.d_val;
7734           bfd_size_type amt;
7735
7736           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7737           if (string == NULL)
7738             goto error_return;
7739
7740           amt = sizeof *l;
7741           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7742           if (l == NULL)
7743             goto error_return;
7744
7745           l->by = abfd;
7746           l->name = string;
7747           l->next = *pneeded;
7748           *pneeded = l;
7749         }
7750     }
7751
7752   free (dynbuf);
7753
7754   return TRUE;
7755
7756  error_return:
7757   if (dynbuf != NULL)
7758     free (dynbuf);
7759   return FALSE;
7760 }
7761
7762 struct elf_symbuf_symbol
7763 {
7764   unsigned long st_name;        /* Symbol name, index in string tbl */
7765   unsigned char st_info;        /* Type and binding attributes */
7766   unsigned char st_other;       /* Visibilty, and target specific */
7767 };
7768
7769 struct elf_symbuf_head
7770 {
7771   struct elf_symbuf_symbol *ssym;
7772   size_t count;
7773   unsigned int st_shndx;
7774 };
7775
7776 struct elf_symbol
7777 {
7778   union
7779     {
7780       Elf_Internal_Sym *isym;
7781       struct elf_symbuf_symbol *ssym;
7782     } u;
7783   const char *name;
7784 };
7785
7786 /* Sort references to symbols by ascending section number.  */
7787
7788 static int
7789 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7790 {
7791   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7792   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7793
7794   return s1->st_shndx - s2->st_shndx;
7795 }
7796
7797 static int
7798 elf_sym_name_compare (const void *arg1, const void *arg2)
7799 {
7800   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7801   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7802   return strcmp (s1->name, s2->name);
7803 }
7804
7805 static struct elf_symbuf_head *
7806 elf_create_symbuf (size_t symcount, Elf_Internal_Sym *isymbuf)
7807 {
7808   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7809   struct elf_symbuf_symbol *ssym;
7810   struct elf_symbuf_head *ssymbuf, *ssymhead;
7811   size_t i, shndx_count, total_size;
7812
7813   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7814   if (indbuf == NULL)
7815     return NULL;
7816
7817   for (ind = indbuf, i = 0; i < symcount; i++)
7818     if (isymbuf[i].st_shndx != SHN_UNDEF)
7819       *ind++ = &isymbuf[i];
7820   indbufend = ind;
7821
7822   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7823          elf_sort_elf_symbol);
7824
7825   shndx_count = 0;
7826   if (indbufend > indbuf)
7827     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7828       if (ind[0]->st_shndx != ind[1]->st_shndx)
7829         shndx_count++;
7830
7831   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7832                 + (indbufend - indbuf) * sizeof (*ssym));
7833   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7834   if (ssymbuf == NULL)
7835     {
7836       free (indbuf);
7837       return NULL;
7838     }
7839
7840   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7841   ssymbuf->ssym = NULL;
7842   ssymbuf->count = shndx_count;
7843   ssymbuf->st_shndx = 0;
7844   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7845     {
7846       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7847         {
7848           ssymhead++;
7849           ssymhead->ssym = ssym;
7850           ssymhead->count = 0;
7851           ssymhead->st_shndx = (*ind)->st_shndx;
7852         }
7853       ssym->st_name = (*ind)->st_name;
7854       ssym->st_info = (*ind)->st_info;
7855       ssym->st_other = (*ind)->st_other;
7856       ssymhead->count++;
7857     }
7858   BFD_ASSERT ((size_t) (ssymhead - ssymbuf) == shndx_count
7859               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7860                   == total_size));
7861
7862   free (indbuf);
7863   return ssymbuf;
7864 }
7865
7866 /* Check if 2 sections define the same set of local and global
7867    symbols.  */
7868
7869 static bfd_boolean
7870 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7871                                    struct bfd_link_info *info)
7872 {
7873   bfd *bfd1, *bfd2;
7874   const struct elf_backend_data *bed1, *bed2;
7875   Elf_Internal_Shdr *hdr1, *hdr2;
7876   size_t symcount1, symcount2;
7877   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7878   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7879   Elf_Internal_Sym *isym, *isymend;
7880   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7881   size_t count1, count2, i;
7882   unsigned int shndx1, shndx2;
7883   bfd_boolean result;
7884
7885   bfd1 = sec1->owner;
7886   bfd2 = sec2->owner;
7887
7888   /* Both sections have to be in ELF.  */
7889   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7890       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7891     return FALSE;
7892
7893   if (elf_section_type (sec1) != elf_section_type (sec2))
7894     return FALSE;
7895
7896   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7897   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7898   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7899     return FALSE;
7900
7901   bed1 = get_elf_backend_data (bfd1);
7902   bed2 = get_elf_backend_data (bfd2);
7903   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7904   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7905   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7906   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7907
7908   if (symcount1 == 0 || symcount2 == 0)
7909     return FALSE;
7910
7911   result = FALSE;
7912   isymbuf1 = NULL;
7913   isymbuf2 = NULL;
7914   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7915   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7916
7917   if (ssymbuf1 == NULL)
7918     {
7919       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7920                                        NULL, NULL, NULL);
7921       if (isymbuf1 == NULL)
7922         goto done;
7923
7924       if (!info->reduce_memory_overheads)
7925         elf_tdata (bfd1)->symbuf = ssymbuf1
7926           = elf_create_symbuf (symcount1, isymbuf1);
7927     }
7928
7929   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7930     {
7931       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7932                                        NULL, NULL, NULL);
7933       if (isymbuf2 == NULL)
7934         goto done;
7935
7936       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7937         elf_tdata (bfd2)->symbuf = ssymbuf2
7938           = elf_create_symbuf (symcount2, isymbuf2);
7939     }
7940
7941   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7942     {
7943       /* Optimized faster version.  */
7944       size_t lo, hi, mid;
7945       struct elf_symbol *symp;
7946       struct elf_symbuf_symbol *ssym, *ssymend;
7947
7948       lo = 0;
7949       hi = ssymbuf1->count;
7950       ssymbuf1++;
7951       count1 = 0;
7952       while (lo < hi)
7953         {
7954           mid = (lo + hi) / 2;
7955           if (shndx1 < ssymbuf1[mid].st_shndx)
7956             hi = mid;
7957           else if (shndx1 > ssymbuf1[mid].st_shndx)
7958             lo = mid + 1;
7959           else
7960             {
7961               count1 = ssymbuf1[mid].count;
7962               ssymbuf1 += mid;
7963               break;
7964             }
7965         }
7966
7967       lo = 0;
7968       hi = ssymbuf2->count;
7969       ssymbuf2++;
7970       count2 = 0;
7971       while (lo < hi)
7972         {
7973           mid = (lo + hi) / 2;
7974           if (shndx2 < ssymbuf2[mid].st_shndx)
7975             hi = mid;
7976           else if (shndx2 > ssymbuf2[mid].st_shndx)
7977             lo = mid + 1;
7978           else
7979             {
7980               count2 = ssymbuf2[mid].count;
7981               ssymbuf2 += mid;
7982               break;
7983             }
7984         }
7985
7986       if (count1 == 0 || count2 == 0 || count1 != count2)
7987         goto done;
7988
7989       symtable1
7990         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
7991       symtable2
7992         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
7993       if (symtable1 == NULL || symtable2 == NULL)
7994         goto done;
7995
7996       symp = symtable1;
7997       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7998            ssym < ssymend; ssym++, symp++)
7999         {
8000           symp->u.ssym = ssym;
8001           symp->name = bfd_elf_string_from_elf_section (bfd1,
8002                                                         hdr1->sh_link,
8003                                                         ssym->st_name);
8004         }
8005
8006       symp = symtable2;
8007       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
8008            ssym < ssymend; ssym++, symp++)
8009         {
8010           symp->u.ssym = ssym;
8011           symp->name = bfd_elf_string_from_elf_section (bfd2,
8012                                                         hdr2->sh_link,
8013                                                         ssym->st_name);
8014         }
8015
8016       /* Sort symbol by name.  */
8017       qsort (symtable1, count1, sizeof (struct elf_symbol),
8018              elf_sym_name_compare);
8019       qsort (symtable2, count1, sizeof (struct elf_symbol),
8020              elf_sym_name_compare);
8021
8022       for (i = 0; i < count1; i++)
8023         /* Two symbols must have the same binding, type and name.  */
8024         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
8025             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
8026             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
8027           goto done;
8028
8029       result = TRUE;
8030       goto done;
8031     }
8032
8033   symtable1 = (struct elf_symbol *)
8034       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
8035   symtable2 = (struct elf_symbol *)
8036       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
8037   if (symtable1 == NULL || symtable2 == NULL)
8038     goto done;
8039
8040   /* Count definitions in the section.  */
8041   count1 = 0;
8042   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
8043     if (isym->st_shndx == shndx1)
8044       symtable1[count1++].u.isym = isym;
8045
8046   count2 = 0;
8047   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
8048     if (isym->st_shndx == shndx2)
8049       symtable2[count2++].u.isym = isym;
8050
8051   if (count1 == 0 || count2 == 0 || count1 != count2)
8052     goto done;
8053
8054   for (i = 0; i < count1; i++)
8055     symtable1[i].name
8056       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
8057                                          symtable1[i].u.isym->st_name);
8058
8059   for (i = 0; i < count2; i++)
8060     symtable2[i].name
8061       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
8062                                          symtable2[i].u.isym->st_name);
8063
8064   /* Sort symbol by name.  */
8065   qsort (symtable1, count1, sizeof (struct elf_symbol),
8066          elf_sym_name_compare);
8067   qsort (symtable2, count1, sizeof (struct elf_symbol),
8068          elf_sym_name_compare);
8069
8070   for (i = 0; i < count1; i++)
8071     /* Two symbols must have the same binding, type and name.  */
8072     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
8073         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
8074         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
8075       goto done;
8076
8077   result = TRUE;
8078
8079 done:
8080   if (symtable1)
8081     free (symtable1);
8082   if (symtable2)
8083     free (symtable2);
8084   if (isymbuf1)
8085     free (isymbuf1);
8086   if (isymbuf2)
8087     free (isymbuf2);
8088
8089   return result;
8090 }
8091
8092 /* Return TRUE if 2 section types are compatible.  */
8093
8094 bfd_boolean
8095 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
8096                                  bfd *bbfd, const asection *bsec)
8097 {
8098   if (asec == NULL
8099       || bsec == NULL
8100       || abfd->xvec->flavour != bfd_target_elf_flavour
8101       || bbfd->xvec->flavour != bfd_target_elf_flavour)
8102     return TRUE;
8103
8104   return elf_section_type (asec) == elf_section_type (bsec);
8105 }
8106 \f
8107 /* Final phase of ELF linker.  */
8108
8109 /* A structure we use to avoid passing large numbers of arguments.  */
8110
8111 struct elf_final_link_info
8112 {
8113   /* General link information.  */
8114   struct bfd_link_info *info;
8115   /* Output BFD.  */
8116   bfd *output_bfd;
8117   /* Symbol string table.  */
8118   struct elf_strtab_hash *symstrtab;
8119   /* .hash section.  */
8120   asection *hash_sec;
8121   /* symbol version section (.gnu.version).  */
8122   asection *symver_sec;
8123   /* Buffer large enough to hold contents of any section.  */
8124   bfd_byte *contents;
8125   /* Buffer large enough to hold external relocs of any section.  */
8126   void *external_relocs;
8127   /* Buffer large enough to hold internal relocs of any section.  */
8128   Elf_Internal_Rela *internal_relocs;
8129   /* Buffer large enough to hold external local symbols of any input
8130      BFD.  */
8131   bfd_byte *external_syms;
8132   /* And a buffer for symbol section indices.  */
8133   Elf_External_Sym_Shndx *locsym_shndx;
8134   /* Buffer large enough to hold internal local symbols of any input
8135      BFD.  */
8136   Elf_Internal_Sym *internal_syms;
8137   /* Array large enough to hold a symbol index for each local symbol
8138      of any input BFD.  */
8139   long *indices;
8140   /* Array large enough to hold a section pointer for each local
8141      symbol of any input BFD.  */
8142   asection **sections;
8143   /* Buffer for SHT_SYMTAB_SHNDX section.  */
8144   Elf_External_Sym_Shndx *symshndxbuf;
8145   /* Number of STT_FILE syms seen.  */
8146   size_t filesym_count;
8147 };
8148
8149 /* This struct is used to pass information to elf_link_output_extsym.  */
8150
8151 struct elf_outext_info
8152 {
8153   bfd_boolean failed;
8154   bfd_boolean localsyms;
8155   bfd_boolean file_sym_done;
8156   struct elf_final_link_info *flinfo;
8157 };
8158
8159
8160 /* Support for evaluating a complex relocation.
8161
8162    Complex relocations are generalized, self-describing relocations.  The
8163    implementation of them consists of two parts: complex symbols, and the
8164    relocations themselves.
8165
8166    The relocations are use a reserved elf-wide relocation type code (R_RELC
8167    external / BFD_RELOC_RELC internal) and an encoding of relocation field
8168    information (start bit, end bit, word width, etc) into the addend.  This
8169    information is extracted from CGEN-generated operand tables within gas.
8170
8171    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
8172    internal) representing prefix-notation expressions, including but not
8173    limited to those sorts of expressions normally encoded as addends in the
8174    addend field.  The symbol mangling format is:
8175
8176    <node> := <literal>
8177           |  <unary-operator> ':' <node>
8178           |  <binary-operator> ':' <node> ':' <node>
8179           ;
8180
8181    <literal> := 's' <digits=N> ':' <N character symbol name>
8182              |  'S' <digits=N> ':' <N character section name>
8183              |  '#' <hexdigits>
8184              ;
8185
8186    <binary-operator> := as in C
8187    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
8188
8189 static void
8190 set_symbol_value (bfd *bfd_with_globals,
8191                   Elf_Internal_Sym *isymbuf,
8192                   size_t locsymcount,
8193                   size_t symidx,
8194                   bfd_vma val)
8195 {
8196   struct elf_link_hash_entry **sym_hashes;
8197   struct elf_link_hash_entry *h;
8198   size_t extsymoff = locsymcount;
8199
8200   if (symidx < locsymcount)
8201     {
8202       Elf_Internal_Sym *sym;
8203
8204       sym = isymbuf + symidx;
8205       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
8206         {
8207           /* It is a local symbol: move it to the
8208              "absolute" section and give it a value.  */
8209           sym->st_shndx = SHN_ABS;
8210           sym->st_value = val;
8211           return;
8212         }
8213       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
8214       extsymoff = 0;
8215     }
8216
8217   /* It is a global symbol: set its link type
8218      to "defined" and give it a value.  */
8219
8220   sym_hashes = elf_sym_hashes (bfd_with_globals);
8221   h = sym_hashes [symidx - extsymoff];
8222   while (h->root.type == bfd_link_hash_indirect
8223          || h->root.type == bfd_link_hash_warning)
8224     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8225   h->root.type = bfd_link_hash_defined;
8226   h->root.u.def.value = val;
8227   h->root.u.def.section = bfd_abs_section_ptr;
8228 }
8229
8230 static bfd_boolean
8231 resolve_symbol (const char *name,
8232                 bfd *input_bfd,
8233                 struct elf_final_link_info *flinfo,
8234                 bfd_vma *result,
8235                 Elf_Internal_Sym *isymbuf,
8236                 size_t locsymcount)
8237 {
8238   Elf_Internal_Sym *sym;
8239   struct bfd_link_hash_entry *global_entry;
8240   const char *candidate = NULL;
8241   Elf_Internal_Shdr *symtab_hdr;
8242   size_t i;
8243
8244   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
8245
8246   for (i = 0; i < locsymcount; ++ i)
8247     {
8248       sym = isymbuf + i;
8249
8250       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
8251         continue;
8252
8253       candidate = bfd_elf_string_from_elf_section (input_bfd,
8254                                                    symtab_hdr->sh_link,
8255                                                    sym->st_name);
8256 #ifdef DEBUG
8257       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
8258               name, candidate, (unsigned long) sym->st_value);
8259 #endif
8260       if (candidate && strcmp (candidate, name) == 0)
8261         {
8262           asection *sec = flinfo->sections [i];
8263
8264           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
8265           *result += sec->output_offset + sec->output_section->vma;
8266 #ifdef DEBUG
8267           printf ("Found symbol with value %8.8lx\n",
8268                   (unsigned long) *result);
8269 #endif
8270           return TRUE;
8271         }
8272     }
8273
8274   /* Hmm, haven't found it yet. perhaps it is a global.  */
8275   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
8276                                        FALSE, FALSE, TRUE);
8277   if (!global_entry)
8278     return FALSE;
8279
8280   if (global_entry->type == bfd_link_hash_defined
8281       || global_entry->type == bfd_link_hash_defweak)
8282     {
8283       *result = (global_entry->u.def.value
8284                  + global_entry->u.def.section->output_section->vma
8285                  + global_entry->u.def.section->output_offset);
8286 #ifdef DEBUG
8287       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
8288               global_entry->root.string, (unsigned long) *result);
8289 #endif
8290       return TRUE;
8291     }
8292
8293   return FALSE;
8294 }
8295
8296 /* Looks up NAME in SECTIONS.  If found sets RESULT to NAME's address (in
8297    bytes) and returns TRUE, otherwise returns FALSE.  Accepts pseudo-section
8298    names like "foo.end" which is the end address of section "foo".  */
8299
8300 static bfd_boolean
8301 resolve_section (const char *name,
8302                  asection *sections,
8303                  bfd_vma *result,
8304                  bfd * abfd)
8305 {
8306   asection *curr;
8307   unsigned int len;
8308
8309   for (curr = sections; curr; curr = curr->next)
8310     if (strcmp (curr->name, name) == 0)
8311       {
8312         *result = curr->vma;
8313         return TRUE;
8314       }
8315
8316   /* Hmm. still haven't found it. try pseudo-section names.  */
8317   /* FIXME: This could be coded more efficiently...  */
8318   for (curr = sections; curr; curr = curr->next)
8319     {
8320       len = strlen (curr->name);
8321       if (len > strlen (name))
8322         continue;
8323
8324       if (strncmp (curr->name, name, len) == 0)
8325         {
8326           if (strncmp (".end", name + len, 4) == 0)
8327             {
8328               *result = curr->vma + curr->size / bfd_octets_per_byte (abfd);
8329               return TRUE;
8330             }
8331
8332           /* Insert more pseudo-section names here, if you like.  */
8333         }
8334     }
8335
8336   return FALSE;
8337 }
8338
8339 static void
8340 undefined_reference (const char *reftype, const char *name)
8341 {
8342   /* xgettext:c-format */
8343   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
8344                       reftype, name);
8345 }
8346
8347 static bfd_boolean
8348 eval_symbol (bfd_vma *result,
8349              const char **symp,
8350              bfd *input_bfd,
8351              struct elf_final_link_info *flinfo,
8352              bfd_vma dot,
8353              Elf_Internal_Sym *isymbuf,
8354              size_t locsymcount,
8355              int signed_p)
8356 {
8357   size_t len;
8358   size_t symlen;
8359   bfd_vma a;
8360   bfd_vma b;
8361   char symbuf[4096];
8362   const char *sym = *symp;
8363   const char *symend;
8364   bfd_boolean symbol_is_section = FALSE;
8365
8366   len = strlen (sym);
8367   symend = sym + len;
8368
8369   if (len < 1 || len > sizeof (symbuf))
8370     {
8371       bfd_set_error (bfd_error_invalid_operation);
8372       return FALSE;
8373     }
8374
8375   switch (* sym)
8376     {
8377     case '.':
8378       *result = dot;
8379       *symp = sym + 1;
8380       return TRUE;
8381
8382     case '#':
8383       ++sym;
8384       *result = strtoul (sym, (char **) symp, 16);
8385       return TRUE;
8386
8387     case 'S':
8388       symbol_is_section = TRUE;
8389       /* Fall through.  */
8390     case 's':
8391       ++sym;
8392       symlen = strtol (sym, (char **) symp, 10);
8393       sym = *symp + 1; /* Skip the trailing ':'.  */
8394
8395       if (symend < sym || symlen + 1 > sizeof (symbuf))
8396         {
8397           bfd_set_error (bfd_error_invalid_operation);
8398           return FALSE;
8399         }
8400
8401       memcpy (symbuf, sym, symlen);
8402       symbuf[symlen] = '\0';
8403       *symp = sym + symlen;
8404
8405       /* Is it always possible, with complex symbols, that gas "mis-guessed"
8406          the symbol as a section, or vice-versa. so we're pretty liberal in our
8407          interpretation here; section means "try section first", not "must be a
8408          section", and likewise with symbol.  */
8409
8410       if (symbol_is_section)
8411         {
8412           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result, input_bfd)
8413               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
8414                                   isymbuf, locsymcount))
8415             {
8416               undefined_reference ("section", symbuf);
8417               return FALSE;
8418             }
8419         }
8420       else
8421         {
8422           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
8423                                isymbuf, locsymcount)
8424               && !resolve_section (symbuf, flinfo->output_bfd->sections,
8425                                    result, input_bfd))
8426             {
8427               undefined_reference ("symbol", symbuf);
8428               return FALSE;
8429             }
8430         }
8431
8432       return TRUE;
8433
8434       /* All that remains are operators.  */
8435
8436 #define UNARY_OP(op)                                            \
8437   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8438     {                                                           \
8439       sym += strlen (#op);                                      \
8440       if (*sym == ':')                                          \
8441         ++sym;                                                  \
8442       *symp = sym;                                              \
8443       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8444                         isymbuf, locsymcount, signed_p))        \
8445         return FALSE;                                           \
8446       if (signed_p)                                             \
8447         *result = op ((bfd_signed_vma) a);                      \
8448       else                                                      \
8449         *result = op a;                                         \
8450       return TRUE;                                              \
8451     }
8452
8453 #define BINARY_OP(op)                                           \
8454   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8455     {                                                           \
8456       sym += strlen (#op);                                      \
8457       if (*sym == ':')                                          \
8458         ++sym;                                                  \
8459       *symp = sym;                                              \
8460       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8461                         isymbuf, locsymcount, signed_p))        \
8462         return FALSE;                                           \
8463       ++*symp;                                                  \
8464       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
8465                         isymbuf, locsymcount, signed_p))        \
8466         return FALSE;                                           \
8467       if (signed_p)                                             \
8468         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
8469       else                                                      \
8470         *result = a op b;                                       \
8471       return TRUE;                                              \
8472     }
8473
8474     default:
8475       UNARY_OP  (0-);
8476       BINARY_OP (<<);
8477       BINARY_OP (>>);
8478       BINARY_OP (==);
8479       BINARY_OP (!=);
8480       BINARY_OP (<=);
8481       BINARY_OP (>=);
8482       BINARY_OP (&&);
8483       BINARY_OP (||);
8484       UNARY_OP  (~);
8485       UNARY_OP  (!);
8486       BINARY_OP (*);
8487       BINARY_OP (/);
8488       BINARY_OP (%);
8489       BINARY_OP (^);
8490       BINARY_OP (|);
8491       BINARY_OP (&);
8492       BINARY_OP (+);
8493       BINARY_OP (-);
8494       BINARY_OP (<);
8495       BINARY_OP (>);
8496 #undef UNARY_OP
8497 #undef BINARY_OP
8498       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
8499       bfd_set_error (bfd_error_invalid_operation);
8500       return FALSE;
8501     }
8502 }
8503
8504 static void
8505 put_value (bfd_vma size,
8506            unsigned long chunksz,
8507            bfd *input_bfd,
8508            bfd_vma x,
8509            bfd_byte *location)
8510 {
8511   location += (size - chunksz);
8512
8513   for (; size; size -= chunksz, location -= chunksz)
8514     {
8515       switch (chunksz)
8516         {
8517         case 1:
8518           bfd_put_8 (input_bfd, x, location);
8519           x >>= 8;
8520           break;
8521         case 2:
8522           bfd_put_16 (input_bfd, x, location);
8523           x >>= 16;
8524           break;
8525         case 4:
8526           bfd_put_32 (input_bfd, x, location);
8527           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
8528           x >>= 16;
8529           x >>= 16;
8530           break;
8531 #ifdef BFD64
8532         case 8:
8533           bfd_put_64 (input_bfd, x, location);
8534           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
8535           x >>= 32;
8536           x >>= 32;
8537           break;
8538 #endif
8539         default:
8540           abort ();
8541           break;
8542         }
8543     }
8544 }
8545
8546 static bfd_vma
8547 get_value (bfd_vma size,
8548            unsigned long chunksz,
8549            bfd *input_bfd,
8550            bfd_byte *location)
8551 {
8552   int shift;
8553   bfd_vma x = 0;
8554
8555   /* Sanity checks.  */
8556   BFD_ASSERT (chunksz <= sizeof (x)
8557               && size >= chunksz
8558               && chunksz != 0
8559               && (size % chunksz) == 0
8560               && input_bfd != NULL
8561               && location != NULL);
8562
8563   if (chunksz == sizeof (x))
8564     {
8565       BFD_ASSERT (size == chunksz);
8566
8567       /* Make sure that we do not perform an undefined shift operation.
8568          We know that size == chunksz so there will only be one iteration
8569          of the loop below.  */
8570       shift = 0;
8571     }
8572   else
8573     shift = 8 * chunksz;
8574
8575   for (; size; size -= chunksz, location += chunksz)
8576     {
8577       switch (chunksz)
8578         {
8579         case 1:
8580           x = (x << shift) | bfd_get_8 (input_bfd, location);
8581           break;
8582         case 2:
8583           x = (x << shift) | bfd_get_16 (input_bfd, location);
8584           break;
8585         case 4:
8586           x = (x << shift) | bfd_get_32 (input_bfd, location);
8587           break;
8588 #ifdef BFD64
8589         case 8:
8590           x = (x << shift) | bfd_get_64 (input_bfd, location);
8591           break;
8592 #endif
8593         default:
8594           abort ();
8595         }
8596     }
8597   return x;
8598 }
8599
8600 static void
8601 decode_complex_addend (unsigned long *start,   /* in bits */
8602                        unsigned long *oplen,   /* in bits */
8603                        unsigned long *len,     /* in bits */
8604                        unsigned long *wordsz,  /* in bytes */
8605                        unsigned long *chunksz, /* in bytes */
8606                        unsigned long *lsb0_p,
8607                        unsigned long *signed_p,
8608                        unsigned long *trunc_p,
8609                        unsigned long encoded)
8610 {
8611   * start     =  encoded        & 0x3F;
8612   * len       = (encoded >>  6) & 0x3F;
8613   * oplen     = (encoded >> 12) & 0x3F;
8614   * wordsz    = (encoded >> 18) & 0xF;
8615   * chunksz   = (encoded >> 22) & 0xF;
8616   * lsb0_p    = (encoded >> 27) & 1;
8617   * signed_p  = (encoded >> 28) & 1;
8618   * trunc_p   = (encoded >> 29) & 1;
8619 }
8620
8621 bfd_reloc_status_type
8622 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8623                                     asection *input_section ATTRIBUTE_UNUSED,
8624                                     bfd_byte *contents,
8625                                     Elf_Internal_Rela *rel,
8626                                     bfd_vma relocation)
8627 {
8628   bfd_vma shift, x, mask;
8629   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8630   bfd_reloc_status_type r;
8631
8632   /*  Perform this reloc, since it is complex.
8633       (this is not to say that it necessarily refers to a complex
8634       symbol; merely that it is a self-describing CGEN based reloc.
8635       i.e. the addend has the complete reloc information (bit start, end,
8636       word size, etc) encoded within it.).  */
8637
8638   decode_complex_addend (&start, &oplen, &len, &wordsz,
8639                          &chunksz, &lsb0_p, &signed_p,
8640                          &trunc_p, rel->r_addend);
8641
8642   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8643
8644   if (lsb0_p)
8645     shift = (start + 1) - len;
8646   else
8647     shift = (8 * wordsz) - (start + len);
8648
8649   x = get_value (wordsz, chunksz, input_bfd,
8650                  contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8651
8652 #ifdef DEBUG
8653   printf ("Doing complex reloc: "
8654           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8655           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8656           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8657           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8658           oplen, (unsigned long) x, (unsigned long) mask,
8659           (unsigned long) relocation);
8660 #endif
8661
8662   r = bfd_reloc_ok;
8663   if (! trunc_p)
8664     /* Now do an overflow check.  */
8665     r = bfd_check_overflow ((signed_p
8666                              ? complain_overflow_signed
8667                              : complain_overflow_unsigned),
8668                             len, 0, (8 * wordsz),
8669                             relocation);
8670
8671   /* Do the deed.  */
8672   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8673
8674 #ifdef DEBUG
8675   printf ("           relocation: %8.8lx\n"
8676           "         shifted mask: %8.8lx\n"
8677           " shifted/masked reloc: %8.8lx\n"
8678           "               result: %8.8lx\n",
8679           (unsigned long) relocation, (unsigned long) (mask << shift),
8680           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8681 #endif
8682   put_value (wordsz, chunksz, input_bfd, x,
8683              contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8684   return r;
8685 }
8686
8687 /* Functions to read r_offset from external (target order) reloc
8688    entry.  Faster than bfd_getl32 et al, because we let the compiler
8689    know the value is aligned.  */
8690
8691 static bfd_vma
8692 ext32l_r_offset (const void *p)
8693 {
8694   union aligned32
8695   {
8696     uint32_t v;
8697     unsigned char c[4];
8698   };
8699   const union aligned32 *a
8700     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8701
8702   uint32_t aval = (  (uint32_t) a->c[0]
8703                    | (uint32_t) a->c[1] << 8
8704                    | (uint32_t) a->c[2] << 16
8705                    | (uint32_t) a->c[3] << 24);
8706   return aval;
8707 }
8708
8709 static bfd_vma
8710 ext32b_r_offset (const void *p)
8711 {
8712   union aligned32
8713   {
8714     uint32_t v;
8715     unsigned char c[4];
8716   };
8717   const union aligned32 *a
8718     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8719
8720   uint32_t aval = (  (uint32_t) a->c[0] << 24
8721                    | (uint32_t) a->c[1] << 16
8722                    | (uint32_t) a->c[2] << 8
8723                    | (uint32_t) a->c[3]);
8724   return aval;
8725 }
8726
8727 #ifdef BFD_HOST_64_BIT
8728 static bfd_vma
8729 ext64l_r_offset (const void *p)
8730 {
8731   union aligned64
8732   {
8733     uint64_t v;
8734     unsigned char c[8];
8735   };
8736   const union aligned64 *a
8737     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8738
8739   uint64_t aval = (  (uint64_t) a->c[0]
8740                    | (uint64_t) a->c[1] << 8
8741                    | (uint64_t) a->c[2] << 16
8742                    | (uint64_t) a->c[3] << 24
8743                    | (uint64_t) a->c[4] << 32
8744                    | (uint64_t) a->c[5] << 40
8745                    | (uint64_t) a->c[6] << 48
8746                    | (uint64_t) a->c[7] << 56);
8747   return aval;
8748 }
8749
8750 static bfd_vma
8751 ext64b_r_offset (const void *p)
8752 {
8753   union aligned64
8754   {
8755     uint64_t v;
8756     unsigned char c[8];
8757   };
8758   const union aligned64 *a
8759     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8760
8761   uint64_t aval = (  (uint64_t) a->c[0] << 56
8762                    | (uint64_t) a->c[1] << 48
8763                    | (uint64_t) a->c[2] << 40
8764                    | (uint64_t) a->c[3] << 32
8765                    | (uint64_t) a->c[4] << 24
8766                    | (uint64_t) a->c[5] << 16
8767                    | (uint64_t) a->c[6] << 8
8768                    | (uint64_t) a->c[7]);
8769   return aval;
8770 }
8771 #endif
8772
8773 /* When performing a relocatable link, the input relocations are
8774    preserved.  But, if they reference global symbols, the indices
8775    referenced must be updated.  Update all the relocations found in
8776    RELDATA.  */
8777
8778 static bfd_boolean
8779 elf_link_adjust_relocs (bfd *abfd,
8780                         asection *sec,
8781                         struct bfd_elf_section_reloc_data *reldata,
8782                         bfd_boolean sort,
8783                         struct bfd_link_info *info)
8784 {
8785   unsigned int i;
8786   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8787   bfd_byte *erela;
8788   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8789   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8790   bfd_vma r_type_mask;
8791   int r_sym_shift;
8792   unsigned int count = reldata->count;
8793   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8794
8795   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8796     {
8797       swap_in = bed->s->swap_reloc_in;
8798       swap_out = bed->s->swap_reloc_out;
8799     }
8800   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8801     {
8802       swap_in = bed->s->swap_reloca_in;
8803       swap_out = bed->s->swap_reloca_out;
8804     }
8805   else
8806     abort ();
8807
8808   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8809     abort ();
8810
8811   if (bed->s->arch_size == 32)
8812     {
8813       r_type_mask = 0xff;
8814       r_sym_shift = 8;
8815     }
8816   else
8817     {
8818       r_type_mask = 0xffffffff;
8819       r_sym_shift = 32;
8820     }
8821
8822   erela = reldata->hdr->contents;
8823   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8824     {
8825       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8826       unsigned int j;
8827
8828       if (*rel_hash == NULL)
8829         continue;
8830
8831       if ((*rel_hash)->indx == -2
8832           && info->gc_sections
8833           && ! info->gc_keep_exported)
8834         {
8835           /* PR 21524: Let the user know if a symbol was removed by garbage collection.  */
8836           _bfd_error_handler (_("%pB:%pA: error: relocation references symbol %s which was removed by garbage collection"),
8837                               abfd, sec,
8838                               (*rel_hash)->root.root.string);
8839           _bfd_error_handler (_("%pB:%pA: error: try relinking with --gc-keep-exported enabled"),
8840                               abfd, sec);
8841           bfd_set_error (bfd_error_invalid_operation);
8842           return FALSE;
8843         }
8844       BFD_ASSERT ((*rel_hash)->indx >= 0);
8845
8846       (*swap_in) (abfd, erela, irela);
8847       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8848         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8849                            | (irela[j].r_info & r_type_mask));
8850       (*swap_out) (abfd, irela, erela);
8851     }
8852
8853   if (bed->elf_backend_update_relocs)
8854     (*bed->elf_backend_update_relocs) (sec, reldata);
8855
8856   if (sort && count != 0)
8857     {
8858       bfd_vma (*ext_r_off) (const void *);
8859       bfd_vma r_off;
8860       size_t elt_size;
8861       bfd_byte *base, *end, *p, *loc;
8862       bfd_byte *buf = NULL;
8863
8864       if (bed->s->arch_size == 32)
8865         {
8866           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8867             ext_r_off = ext32l_r_offset;
8868           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8869             ext_r_off = ext32b_r_offset;
8870           else
8871             abort ();
8872         }
8873       else
8874         {
8875 #ifdef BFD_HOST_64_BIT
8876           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8877             ext_r_off = ext64l_r_offset;
8878           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8879             ext_r_off = ext64b_r_offset;
8880           else
8881 #endif
8882             abort ();
8883         }
8884
8885       /*  Must use a stable sort here.  A modified insertion sort,
8886           since the relocs are mostly sorted already.  */
8887       elt_size = reldata->hdr->sh_entsize;
8888       base = reldata->hdr->contents;
8889       end = base + count * elt_size;
8890       if (elt_size > sizeof (Elf64_External_Rela))
8891         abort ();
8892
8893       /* Ensure the first element is lowest.  This acts as a sentinel,
8894          speeding the main loop below.  */
8895       r_off = (*ext_r_off) (base);
8896       for (p = loc = base; (p += elt_size) < end; )
8897         {
8898           bfd_vma r_off2 = (*ext_r_off) (p);
8899           if (r_off > r_off2)
8900             {
8901               r_off = r_off2;
8902               loc = p;
8903             }
8904         }
8905       if (loc != base)
8906         {
8907           /* Don't just swap *base and *loc as that changes the order
8908              of the original base[0] and base[1] if they happen to
8909              have the same r_offset.  */
8910           bfd_byte onebuf[sizeof (Elf64_External_Rela)];
8911           memcpy (onebuf, loc, elt_size);
8912           memmove (base + elt_size, base, loc - base);
8913           memcpy (base, onebuf, elt_size);
8914         }
8915
8916       for (p = base + elt_size; (p += elt_size) < end; )
8917         {
8918           /* base to p is sorted, *p is next to insert.  */
8919           r_off = (*ext_r_off) (p);
8920           /* Search the sorted region for location to insert.  */
8921           loc = p - elt_size;
8922           while (r_off < (*ext_r_off) (loc))
8923             loc -= elt_size;
8924           loc += elt_size;
8925           if (loc != p)
8926             {
8927               /* Chances are there is a run of relocs to insert here,
8928                  from one of more input files.  Files are not always
8929                  linked in order due to the way elf_link_input_bfd is
8930                  called.  See pr17666.  */
8931               size_t sortlen = p - loc;
8932               bfd_vma r_off2 = (*ext_r_off) (loc);
8933               size_t runlen = elt_size;
8934               size_t buf_size = 96 * 1024;
8935               while (p + runlen < end
8936                      && (sortlen <= buf_size
8937                          || runlen + elt_size <= buf_size)
8938                      && r_off2 > (*ext_r_off) (p + runlen))
8939                 runlen += elt_size;
8940               if (buf == NULL)
8941                 {
8942                   buf = bfd_malloc (buf_size);
8943                   if (buf == NULL)
8944                     return FALSE;
8945                 }
8946               if (runlen < sortlen)
8947                 {
8948                   memcpy (buf, p, runlen);
8949                   memmove (loc + runlen, loc, sortlen);
8950                   memcpy (loc, buf, runlen);
8951                 }
8952               else
8953                 {
8954                   memcpy (buf, loc, sortlen);
8955                   memmove (loc, p, runlen);
8956                   memcpy (loc + runlen, buf, sortlen);
8957                 }
8958               p += runlen - elt_size;
8959             }
8960         }
8961       /* Hashes are no longer valid.  */
8962       free (reldata->hashes);
8963       reldata->hashes = NULL;
8964       free (buf);
8965     }
8966   return TRUE;
8967 }
8968
8969 struct elf_link_sort_rela
8970 {
8971   union {
8972     bfd_vma offset;
8973     bfd_vma sym_mask;
8974   } u;
8975   enum elf_reloc_type_class type;
8976   /* We use this as an array of size int_rels_per_ext_rel.  */
8977   Elf_Internal_Rela rela[1];
8978 };
8979
8980 static int
8981 elf_link_sort_cmp1 (const void *A, const void *B)
8982 {
8983   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8984   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8985   int relativea, relativeb;
8986
8987   relativea = a->type == reloc_class_relative;
8988   relativeb = b->type == reloc_class_relative;
8989
8990   if (relativea < relativeb)
8991     return 1;
8992   if (relativea > relativeb)
8993     return -1;
8994   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8995     return -1;
8996   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8997     return 1;
8998   if (a->rela->r_offset < b->rela->r_offset)
8999     return -1;
9000   if (a->rela->r_offset > b->rela->r_offset)
9001     return 1;
9002   return 0;
9003 }
9004
9005 static int
9006 elf_link_sort_cmp2 (const void *A, const void *B)
9007 {
9008   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
9009   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
9010
9011   if (a->type < b->type)
9012     return -1;
9013   if (a->type > b->type)
9014     return 1;
9015   if (a->u.offset < b->u.offset)
9016     return -1;
9017   if (a->u.offset > b->u.offset)
9018     return 1;
9019   if (a->rela->r_offset < b->rela->r_offset)
9020     return -1;
9021   if (a->rela->r_offset > b->rela->r_offset)
9022     return 1;
9023   return 0;
9024 }
9025
9026 static size_t
9027 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
9028 {
9029   asection *dynamic_relocs;
9030   asection *rela_dyn;
9031   asection *rel_dyn;
9032   bfd_size_type count, size;
9033   size_t i, ret, sort_elt, ext_size;
9034   bfd_byte *sort, *s_non_relative, *p;
9035   struct elf_link_sort_rela *sq;
9036   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
9037   int i2e = bed->s->int_rels_per_ext_rel;
9038   unsigned int opb = bfd_octets_per_byte (abfd);
9039   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
9040   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
9041   struct bfd_link_order *lo;
9042   bfd_vma r_sym_mask;
9043   bfd_boolean use_rela;
9044
9045   /* Find a dynamic reloc section.  */
9046   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
9047   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
9048   if (rela_dyn != NULL && rela_dyn->size > 0
9049       && rel_dyn != NULL && rel_dyn->size > 0)
9050     {
9051       bfd_boolean use_rela_initialised = FALSE;
9052
9053       /* This is just here to stop gcc from complaining.
9054          Its initialization checking code is not perfect.  */
9055       use_rela = TRUE;
9056
9057       /* Both sections are present.  Examine the sizes
9058          of the indirect sections to help us choose.  */
9059       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
9060         if (lo->type == bfd_indirect_link_order)
9061           {
9062             asection *o = lo->u.indirect.section;
9063
9064             if ((o->size % bed->s->sizeof_rela) == 0)
9065               {
9066                 if ((o->size % bed->s->sizeof_rel) == 0)
9067                   /* Section size is divisible by both rel and rela sizes.
9068                      It is of no help to us.  */
9069                   ;
9070                 else
9071                   {
9072                     /* Section size is only divisible by rela.  */
9073                     if (use_rela_initialised && !use_rela)
9074                       {
9075                         _bfd_error_handler (_("%pB: unable to sort relocs - "
9076                                               "they are in more than one size"),
9077                                             abfd);
9078                         bfd_set_error (bfd_error_invalid_operation);
9079                         return 0;
9080                       }
9081                     else
9082                       {
9083                         use_rela = TRUE;
9084                         use_rela_initialised = TRUE;
9085                       }
9086                   }
9087               }
9088             else if ((o->size % bed->s->sizeof_rel) == 0)
9089               {
9090                 /* Section size is only divisible by rel.  */
9091                 if (use_rela_initialised && use_rela)
9092                   {
9093                     _bfd_error_handler (_("%pB: unable to sort relocs - "
9094                                           "they are in more than one size"),
9095                                         abfd);
9096                     bfd_set_error (bfd_error_invalid_operation);
9097                     return 0;
9098                   }
9099                 else
9100                   {
9101                     use_rela = FALSE;
9102                     use_rela_initialised = TRUE;
9103                   }
9104               }
9105             else
9106               {
9107                 /* The section size is not divisible by either -
9108                    something is wrong.  */
9109                 _bfd_error_handler (_("%pB: unable to sort relocs - "
9110                                       "they are of an unknown size"), abfd);
9111                 bfd_set_error (bfd_error_invalid_operation);
9112                 return 0;
9113               }
9114           }
9115
9116       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
9117         if (lo->type == bfd_indirect_link_order)
9118           {
9119             asection *o = lo->u.indirect.section;
9120
9121             if ((o->size % bed->s->sizeof_rela) == 0)
9122               {
9123                 if ((o->size % bed->s->sizeof_rel) == 0)
9124                   /* Section size is divisible by both rel and rela sizes.
9125                      It is of no help to us.  */
9126                   ;
9127                 else
9128                   {
9129                     /* Section size is only divisible by rela.  */
9130                     if (use_rela_initialised && !use_rela)
9131                       {
9132                         _bfd_error_handler (_("%pB: unable to sort relocs - "
9133                                               "they are in more than one size"),
9134                                             abfd);
9135                         bfd_set_error (bfd_error_invalid_operation);
9136                         return 0;
9137                       }
9138                     else
9139                       {
9140                         use_rela = TRUE;
9141                         use_rela_initialised = TRUE;
9142                       }
9143                   }
9144               }
9145             else if ((o->size % bed->s->sizeof_rel) == 0)
9146               {
9147                 /* Section size is only divisible by rel.  */
9148                 if (use_rela_initialised && use_rela)
9149                   {
9150                     _bfd_error_handler (_("%pB: unable to sort relocs - "
9151                                           "they are in more than one size"),
9152                                         abfd);
9153                     bfd_set_error (bfd_error_invalid_operation);
9154                     return 0;
9155                   }
9156                 else
9157                   {
9158                     use_rela = FALSE;
9159                     use_rela_initialised = TRUE;
9160                   }
9161               }
9162             else
9163               {
9164                 /* The section size is not divisible by either -
9165                    something is wrong.  */
9166                 _bfd_error_handler (_("%pB: unable to sort relocs - "
9167                                       "they are of an unknown size"), abfd);
9168                 bfd_set_error (bfd_error_invalid_operation);
9169                 return 0;
9170               }
9171           }
9172
9173       if (! use_rela_initialised)
9174         /* Make a guess.  */
9175         use_rela = TRUE;
9176     }
9177   else if (rela_dyn != NULL && rela_dyn->size > 0)
9178     use_rela = TRUE;
9179   else if (rel_dyn != NULL && rel_dyn->size > 0)
9180     use_rela = FALSE;
9181   else
9182     return 0;
9183
9184   if (use_rela)
9185     {
9186       dynamic_relocs = rela_dyn;
9187       ext_size = bed->s->sizeof_rela;
9188       swap_in = bed->s->swap_reloca_in;
9189       swap_out = bed->s->swap_reloca_out;
9190     }
9191   else
9192     {
9193       dynamic_relocs = rel_dyn;
9194       ext_size = bed->s->sizeof_rel;
9195       swap_in = bed->s->swap_reloc_in;
9196       swap_out = bed->s->swap_reloc_out;
9197     }
9198
9199   size = 0;
9200   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9201     if (lo->type == bfd_indirect_link_order)
9202       size += lo->u.indirect.section->size;
9203
9204   if (size != dynamic_relocs->size)
9205     return 0;
9206
9207   sort_elt = (sizeof (struct elf_link_sort_rela)
9208               + (i2e - 1) * sizeof (Elf_Internal_Rela));
9209
9210   count = dynamic_relocs->size / ext_size;
9211   if (count == 0)
9212     return 0;
9213   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
9214
9215   if (sort == NULL)
9216     {
9217       (*info->callbacks->warning)
9218         (info, _("not enough memory to sort relocations"), 0, abfd, 0, 0);
9219       return 0;
9220     }
9221
9222   if (bed->s->arch_size == 32)
9223     r_sym_mask = ~(bfd_vma) 0xff;
9224   else
9225     r_sym_mask = ~(bfd_vma) 0xffffffff;
9226
9227   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9228     if (lo->type == bfd_indirect_link_order)
9229       {
9230         bfd_byte *erel, *erelend;
9231         asection *o = lo->u.indirect.section;
9232
9233         if (o->contents == NULL && o->size != 0)
9234           {
9235             /* This is a reloc section that is being handled as a normal
9236                section.  See bfd_section_from_shdr.  We can't combine
9237                relocs in this case.  */
9238             free (sort);
9239             return 0;
9240           }
9241         erel = o->contents;
9242         erelend = o->contents + o->size;
9243         p = sort + o->output_offset * opb / ext_size * sort_elt;
9244
9245         while (erel < erelend)
9246           {
9247             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9248
9249             (*swap_in) (abfd, erel, s->rela);
9250             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
9251             s->u.sym_mask = r_sym_mask;
9252             p += sort_elt;
9253             erel += ext_size;
9254           }
9255       }
9256
9257   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
9258
9259   for (i = 0, p = sort; i < count; i++, p += sort_elt)
9260     {
9261       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9262       if (s->type != reloc_class_relative)
9263         break;
9264     }
9265   ret = i;
9266   s_non_relative = p;
9267
9268   sq = (struct elf_link_sort_rela *) s_non_relative;
9269   for (; i < count; i++, p += sort_elt)
9270     {
9271       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
9272       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
9273         sq = sp;
9274       sp->u.offset = sq->rela->r_offset;
9275     }
9276
9277   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
9278
9279   struct elf_link_hash_table *htab = elf_hash_table (info);
9280   if (htab->srelplt && htab->srelplt->output_section == dynamic_relocs)
9281     {
9282       /* We have plt relocs in .rela.dyn.  */
9283       sq = (struct elf_link_sort_rela *) sort;
9284       for (i = 0; i < count; i++)
9285         if (sq[count - i - 1].type != reloc_class_plt)
9286           break;
9287       if (i != 0 && htab->srelplt->size == i * ext_size)
9288         {
9289           struct bfd_link_order **plo;
9290           /* Put srelplt link_order last.  This is so the output_offset
9291              set in the next loop is correct for DT_JMPREL.  */
9292           for (plo = &dynamic_relocs->map_head.link_order; *plo != NULL; )
9293             if ((*plo)->type == bfd_indirect_link_order
9294                 && (*plo)->u.indirect.section == htab->srelplt)
9295               {
9296                 lo = *plo;
9297                 *plo = lo->next;
9298               }
9299             else
9300               plo = &(*plo)->next;
9301           *plo = lo;
9302           lo->next = NULL;
9303           dynamic_relocs->map_tail.link_order = lo;
9304         }
9305     }
9306
9307   p = sort;
9308   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9309     if (lo->type == bfd_indirect_link_order)
9310       {
9311         bfd_byte *erel, *erelend;
9312         asection *o = lo->u.indirect.section;
9313
9314         erel = o->contents;
9315         erelend = o->contents + o->size;
9316         o->output_offset = (p - sort) / sort_elt * ext_size / opb;
9317         while (erel < erelend)
9318           {
9319             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9320             (*swap_out) (abfd, s->rela, erel);
9321             p += sort_elt;
9322             erel += ext_size;
9323           }
9324       }
9325
9326   free (sort);
9327   *psec = dynamic_relocs;
9328   return ret;
9329 }
9330
9331 /* Add a symbol to the output symbol string table.  */
9332
9333 static int
9334 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
9335                            const char *name,
9336                            Elf_Internal_Sym *elfsym,
9337                            asection *input_sec,
9338                            struct elf_link_hash_entry *h)
9339 {
9340   int (*output_symbol_hook)
9341     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
9342      struct elf_link_hash_entry *);
9343   struct elf_link_hash_table *hash_table;
9344   const struct elf_backend_data *bed;
9345   bfd_size_type strtabsize;
9346
9347   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9348
9349   bed = get_elf_backend_data (flinfo->output_bfd);
9350   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
9351   if (output_symbol_hook != NULL)
9352     {
9353       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
9354       if (ret != 1)
9355         return ret;
9356     }
9357
9358   if (name == NULL
9359       || *name == '\0'
9360       || (input_sec->flags & SEC_EXCLUDE))
9361     elfsym->st_name = (unsigned long) -1;
9362   else
9363     {
9364       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
9365          to get the final offset for st_name.  */
9366       elfsym->st_name
9367         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
9368                                                name, FALSE);
9369       if (elfsym->st_name == (unsigned long) -1)
9370         return 0;
9371     }
9372
9373   hash_table = elf_hash_table (flinfo->info);
9374   strtabsize = hash_table->strtabsize;
9375   if (strtabsize <= hash_table->strtabcount)
9376     {
9377       strtabsize += strtabsize;
9378       hash_table->strtabsize = strtabsize;
9379       strtabsize *= sizeof (*hash_table->strtab);
9380       hash_table->strtab
9381         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
9382                                                  strtabsize);
9383       if (hash_table->strtab == NULL)
9384         return 0;
9385     }
9386   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
9387   hash_table->strtab[hash_table->strtabcount].dest_index
9388     = hash_table->strtabcount;
9389   hash_table->strtab[hash_table->strtabcount].destshndx_index
9390     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
9391
9392   bfd_get_symcount (flinfo->output_bfd) += 1;
9393   hash_table->strtabcount += 1;
9394
9395   return 1;
9396 }
9397
9398 /* Swap symbols out to the symbol table and flush the output symbols to
9399    the file.  */
9400
9401 static bfd_boolean
9402 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
9403 {
9404   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
9405   bfd_size_type amt;
9406   size_t i;
9407   const struct elf_backend_data *bed;
9408   bfd_byte *symbuf;
9409   Elf_Internal_Shdr *hdr;
9410   file_ptr pos;
9411   bfd_boolean ret;
9412
9413   if (!hash_table->strtabcount)
9414     return TRUE;
9415
9416   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9417
9418   bed = get_elf_backend_data (flinfo->output_bfd);
9419
9420   amt = bed->s->sizeof_sym * hash_table->strtabcount;
9421   symbuf = (bfd_byte *) bfd_malloc (amt);
9422   if (symbuf == NULL)
9423     return FALSE;
9424
9425   if (flinfo->symshndxbuf)
9426     {
9427       amt = sizeof (Elf_External_Sym_Shndx);
9428       amt *= bfd_get_symcount (flinfo->output_bfd);
9429       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
9430       if (flinfo->symshndxbuf == NULL)
9431         {
9432           free (symbuf);
9433           return FALSE;
9434         }
9435     }
9436
9437   for (i = 0; i < hash_table->strtabcount; i++)
9438     {
9439       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
9440       if (elfsym->sym.st_name == (unsigned long) -1)
9441         elfsym->sym.st_name = 0;
9442       else
9443         elfsym->sym.st_name
9444           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
9445                                                     elfsym->sym.st_name);
9446       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
9447                                ((bfd_byte *) symbuf
9448                                 + (elfsym->dest_index
9449                                    * bed->s->sizeof_sym)),
9450                                (flinfo->symshndxbuf
9451                                 + elfsym->destshndx_index));
9452     }
9453
9454   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
9455   pos = hdr->sh_offset + hdr->sh_size;
9456   amt = hash_table->strtabcount * bed->s->sizeof_sym;
9457   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
9458       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
9459     {
9460       hdr->sh_size += amt;
9461       ret = TRUE;
9462     }
9463   else
9464     ret = FALSE;
9465
9466   free (symbuf);
9467
9468   free (hash_table->strtab);
9469   hash_table->strtab = NULL;
9470
9471   return ret;
9472 }
9473
9474 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
9475
9476 static bfd_boolean
9477 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
9478 {
9479   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
9480       && sym->st_shndx < SHN_LORESERVE)
9481     {
9482       /* The gABI doesn't support dynamic symbols in output sections
9483          beyond 64k.  */
9484       _bfd_error_handler
9485         /* xgettext:c-format */
9486         (_("%pB: too many sections: %d (>= %d)"),
9487          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
9488       bfd_set_error (bfd_error_nonrepresentable_section);
9489       return FALSE;
9490     }
9491   return TRUE;
9492 }
9493
9494 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
9495    allowing an unsatisfied unversioned symbol in the DSO to match a
9496    versioned symbol that would normally require an explicit version.
9497    We also handle the case that a DSO references a hidden symbol
9498    which may be satisfied by a versioned symbol in another DSO.  */
9499
9500 static bfd_boolean
9501 elf_link_check_versioned_symbol (struct bfd_link_info *info,
9502                                  const struct elf_backend_data *bed,
9503                                  struct elf_link_hash_entry *h)
9504 {
9505   bfd *abfd;
9506   struct elf_link_loaded_list *loaded;
9507
9508   if (!is_elf_hash_table (info->hash))
9509     return FALSE;
9510
9511   /* Check indirect symbol.  */
9512   while (h->root.type == bfd_link_hash_indirect)
9513     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9514
9515   switch (h->root.type)
9516     {
9517     default:
9518       abfd = NULL;
9519       break;
9520
9521     case bfd_link_hash_undefined:
9522     case bfd_link_hash_undefweak:
9523       abfd = h->root.u.undef.abfd;
9524       if (abfd == NULL
9525           || (abfd->flags & DYNAMIC) == 0
9526           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
9527         return FALSE;
9528       break;
9529
9530     case bfd_link_hash_defined:
9531     case bfd_link_hash_defweak:
9532       abfd = h->root.u.def.section->owner;
9533       break;
9534
9535     case bfd_link_hash_common:
9536       abfd = h->root.u.c.p->section->owner;
9537       break;
9538     }
9539   BFD_ASSERT (abfd != NULL);
9540
9541   for (loaded = elf_hash_table (info)->loaded;
9542        loaded != NULL;
9543        loaded = loaded->next)
9544     {
9545       bfd *input;
9546       Elf_Internal_Shdr *hdr;
9547       size_t symcount;
9548       size_t extsymcount;
9549       size_t extsymoff;
9550       Elf_Internal_Shdr *versymhdr;
9551       Elf_Internal_Sym *isym;
9552       Elf_Internal_Sym *isymend;
9553       Elf_Internal_Sym *isymbuf;
9554       Elf_External_Versym *ever;
9555       Elf_External_Versym *extversym;
9556
9557       input = loaded->abfd;
9558
9559       /* We check each DSO for a possible hidden versioned definition.  */
9560       if (input == abfd
9561           || (input->flags & DYNAMIC) == 0
9562           || elf_dynversym (input) == 0)
9563         continue;
9564
9565       hdr = &elf_tdata (input)->dynsymtab_hdr;
9566
9567       symcount = hdr->sh_size / bed->s->sizeof_sym;
9568       if (elf_bad_symtab (input))
9569         {
9570           extsymcount = symcount;
9571           extsymoff = 0;
9572         }
9573       else
9574         {
9575           extsymcount = symcount - hdr->sh_info;
9576           extsymoff = hdr->sh_info;
9577         }
9578
9579       if (extsymcount == 0)
9580         continue;
9581
9582       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
9583                                       NULL, NULL, NULL);
9584       if (isymbuf == NULL)
9585         return FALSE;
9586
9587       /* Read in any version definitions.  */
9588       versymhdr = &elf_tdata (input)->dynversym_hdr;
9589       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
9590       if (extversym == NULL)
9591         goto error_ret;
9592
9593       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
9594           || (bfd_bread (extversym, versymhdr->sh_size, input)
9595               != versymhdr->sh_size))
9596         {
9597           free (extversym);
9598         error_ret:
9599           free (isymbuf);
9600           return FALSE;
9601         }
9602
9603       ever = extversym + extsymoff;
9604       isymend = isymbuf + extsymcount;
9605       for (isym = isymbuf; isym < isymend; isym++, ever++)
9606         {
9607           const char *name;
9608           Elf_Internal_Versym iver;
9609           unsigned short version_index;
9610
9611           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
9612               || isym->st_shndx == SHN_UNDEF)
9613             continue;
9614
9615           name = bfd_elf_string_from_elf_section (input,
9616                                                   hdr->sh_link,
9617                                                   isym->st_name);
9618           if (strcmp (name, h->root.root.string) != 0)
9619             continue;
9620
9621           _bfd_elf_swap_versym_in (input, ever, &iver);
9622
9623           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
9624               && !(h->def_regular
9625                    && h->forced_local))
9626             {
9627               /* If we have a non-hidden versioned sym, then it should
9628                  have provided a definition for the undefined sym unless
9629                  it is defined in a non-shared object and forced local.
9630                */
9631               abort ();
9632             }
9633
9634           version_index = iver.vs_vers & VERSYM_VERSION;
9635           if (version_index == 1 || version_index == 2)
9636             {
9637               /* This is the base or first version.  We can use it.  */
9638               free (extversym);
9639               free (isymbuf);
9640               return TRUE;
9641             }
9642         }
9643
9644       free (extversym);
9645       free (isymbuf);
9646     }
9647
9648   return FALSE;
9649 }
9650
9651 /* Convert ELF common symbol TYPE.  */
9652
9653 static int
9654 elf_link_convert_common_type (struct bfd_link_info *info, int type)
9655 {
9656   /* Commom symbol can only appear in relocatable link.  */
9657   if (!bfd_link_relocatable (info))
9658     abort ();
9659   switch (info->elf_stt_common)
9660     {
9661     case unchanged:
9662       break;
9663     case elf_stt_common:
9664       type = STT_COMMON;
9665       break;
9666     case no_elf_stt_common:
9667       type = STT_OBJECT;
9668       break;
9669     }
9670   return type;
9671 }
9672
9673 /* Add an external symbol to the symbol table.  This is called from
9674    the hash table traversal routine.  When generating a shared object,
9675    we go through the symbol table twice.  The first time we output
9676    anything that might have been forced to local scope in a version
9677    script.  The second time we output the symbols that are still
9678    global symbols.  */
9679
9680 static bfd_boolean
9681 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
9682 {
9683   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
9684   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
9685   struct elf_final_link_info *flinfo = eoinfo->flinfo;
9686   bfd_boolean strip;
9687   Elf_Internal_Sym sym;
9688   asection *input_sec;
9689   const struct elf_backend_data *bed;
9690   long indx;
9691   int ret;
9692   unsigned int type;
9693
9694   if (h->root.type == bfd_link_hash_warning)
9695     {
9696       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9697       if (h->root.type == bfd_link_hash_new)
9698         return TRUE;
9699     }
9700
9701   /* Decide whether to output this symbol in this pass.  */
9702   if (eoinfo->localsyms)
9703     {
9704       if (!h->forced_local)
9705         return TRUE;
9706     }
9707   else
9708     {
9709       if (h->forced_local)
9710         return TRUE;
9711     }
9712
9713   bed = get_elf_backend_data (flinfo->output_bfd);
9714
9715   if (h->root.type == bfd_link_hash_undefined)
9716     {
9717       /* If we have an undefined symbol reference here then it must have
9718          come from a shared library that is being linked in.  (Undefined
9719          references in regular files have already been handled unless
9720          they are in unreferenced sections which are removed by garbage
9721          collection).  */
9722       bfd_boolean ignore_undef = FALSE;
9723
9724       /* Some symbols may be special in that the fact that they're
9725          undefined can be safely ignored - let backend determine that.  */
9726       if (bed->elf_backend_ignore_undef_symbol)
9727         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9728
9729       /* If we are reporting errors for this situation then do so now.  */
9730       if (!ignore_undef
9731           && h->ref_dynamic
9732           && (!h->ref_regular || flinfo->info->gc_sections)
9733           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9734           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9735         (*flinfo->info->callbacks->undefined_symbol)
9736           (flinfo->info, h->root.root.string,
9737            h->ref_regular ? NULL : h->root.u.undef.abfd,
9738            NULL, 0,
9739            flinfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR);
9740
9741       /* Strip a global symbol defined in a discarded section.  */
9742       if (h->indx == -3)
9743         return TRUE;
9744     }
9745
9746   /* We should also warn if a forced local symbol is referenced from
9747      shared libraries.  */
9748   if (bfd_link_executable (flinfo->info)
9749       && h->forced_local
9750       && h->ref_dynamic
9751       && h->def_regular
9752       && !h->dynamic_def
9753       && h->ref_dynamic_nonweak
9754       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9755     {
9756       bfd *def_bfd;
9757       const char *msg;
9758       struct elf_link_hash_entry *hi = h;
9759
9760       /* Check indirect symbol.  */
9761       while (hi->root.type == bfd_link_hash_indirect)
9762         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9763
9764       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9765         /* xgettext:c-format */
9766         msg = _("%pB: internal symbol `%s' in %pB is referenced by DSO");
9767       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9768         /* xgettext:c-format */
9769         msg = _("%pB: hidden symbol `%s' in %pB is referenced by DSO");
9770       else
9771         /* xgettext:c-format */
9772         msg = _("%pB: local symbol `%s' in %pB is referenced by DSO");
9773       def_bfd = flinfo->output_bfd;
9774       if (hi->root.u.def.section != bfd_abs_section_ptr)
9775         def_bfd = hi->root.u.def.section->owner;
9776       _bfd_error_handler (msg, flinfo->output_bfd,
9777                           h->root.root.string, def_bfd);
9778       bfd_set_error (bfd_error_bad_value);
9779       eoinfo->failed = TRUE;
9780       return FALSE;
9781     }
9782
9783   /* We don't want to output symbols that have never been mentioned by
9784      a regular file, or that we have been told to strip.  However, if
9785      h->indx is set to -2, the symbol is used by a reloc and we must
9786      output it.  */
9787   strip = FALSE;
9788   if (h->indx == -2)
9789     ;
9790   else if ((h->def_dynamic
9791             || h->ref_dynamic
9792             || h->root.type == bfd_link_hash_new)
9793            && !h->def_regular
9794            && !h->ref_regular)
9795     strip = TRUE;
9796   else if (flinfo->info->strip == strip_all)
9797     strip = TRUE;
9798   else if (flinfo->info->strip == strip_some
9799            && bfd_hash_lookup (flinfo->info->keep_hash,
9800                                h->root.root.string, FALSE, FALSE) == NULL)
9801     strip = TRUE;
9802   else if ((h->root.type == bfd_link_hash_defined
9803             || h->root.type == bfd_link_hash_defweak)
9804            && ((flinfo->info->strip_discarded
9805                 && discarded_section (h->root.u.def.section))
9806                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9807                    && h->root.u.def.section->owner != NULL
9808                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9809     strip = TRUE;
9810   else if ((h->root.type == bfd_link_hash_undefined
9811             || h->root.type == bfd_link_hash_undefweak)
9812            && h->root.u.undef.abfd != NULL
9813            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9814     strip = TRUE;
9815
9816   type = h->type;
9817
9818   /* If we're stripping it, and it's not a dynamic symbol, there's
9819      nothing else to do.   However, if it is a forced local symbol or
9820      an ifunc symbol we need to give the backend finish_dynamic_symbol
9821      function a chance to make it dynamic.  */
9822   if (strip
9823       && h->dynindx == -1
9824       && type != STT_GNU_IFUNC
9825       && !h->forced_local)
9826     return TRUE;
9827
9828   sym.st_value = 0;
9829   sym.st_size = h->size;
9830   sym.st_other = h->other;
9831   switch (h->root.type)
9832     {
9833     default:
9834     case bfd_link_hash_new:
9835     case bfd_link_hash_warning:
9836       abort ();
9837       return FALSE;
9838
9839     case bfd_link_hash_undefined:
9840     case bfd_link_hash_undefweak:
9841       input_sec = bfd_und_section_ptr;
9842       sym.st_shndx = SHN_UNDEF;
9843       break;
9844
9845     case bfd_link_hash_defined:
9846     case bfd_link_hash_defweak:
9847       {
9848         input_sec = h->root.u.def.section;
9849         if (input_sec->output_section != NULL)
9850           {
9851             sym.st_shndx =
9852               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9853                                                  input_sec->output_section);
9854             if (sym.st_shndx == SHN_BAD)
9855               {
9856                 _bfd_error_handler
9857                   /* xgettext:c-format */
9858                   (_("%pB: could not find output section %pA for input section %pA"),
9859                    flinfo->output_bfd, input_sec->output_section, input_sec);
9860                 bfd_set_error (bfd_error_nonrepresentable_section);
9861                 eoinfo->failed = TRUE;
9862                 return FALSE;
9863               }
9864
9865             /* ELF symbols in relocatable files are section relative,
9866                but in nonrelocatable files they are virtual
9867                addresses.  */
9868             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9869             if (!bfd_link_relocatable (flinfo->info))
9870               {
9871                 sym.st_value += input_sec->output_section->vma;
9872                 if (h->type == STT_TLS)
9873                   {
9874                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9875                     if (tls_sec != NULL)
9876                       sym.st_value -= tls_sec->vma;
9877                   }
9878               }
9879           }
9880         else
9881           {
9882             BFD_ASSERT (input_sec->owner == NULL
9883                         || (input_sec->owner->flags & DYNAMIC) != 0);
9884             sym.st_shndx = SHN_UNDEF;
9885             input_sec = bfd_und_section_ptr;
9886           }
9887       }
9888       break;
9889
9890     case bfd_link_hash_common:
9891       input_sec = h->root.u.c.p->section;
9892       sym.st_shndx = bed->common_section_index (input_sec);
9893       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9894       break;
9895
9896     case bfd_link_hash_indirect:
9897       /* These symbols are created by symbol versioning.  They point
9898          to the decorated version of the name.  For example, if the
9899          symbol foo@@GNU_1.2 is the default, which should be used when
9900          foo is used with no version, then we add an indirect symbol
9901          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9902          since the indirected symbol is already in the hash table.  */
9903       return TRUE;
9904     }
9905
9906   if (type == STT_COMMON || type == STT_OBJECT)
9907     switch (h->root.type)
9908       {
9909       case bfd_link_hash_common:
9910         type = elf_link_convert_common_type (flinfo->info, type);
9911         break;
9912       case bfd_link_hash_defined:
9913       case bfd_link_hash_defweak:
9914         if (bed->common_definition (&sym))
9915           type = elf_link_convert_common_type (flinfo->info, type);
9916         else
9917           type = STT_OBJECT;
9918         break;
9919       case bfd_link_hash_undefined:
9920       case bfd_link_hash_undefweak:
9921         break;
9922       default:
9923         abort ();
9924       }
9925
9926   if (h->forced_local)
9927     {
9928       sym.st_info = ELF_ST_INFO (STB_LOCAL, type);
9929       /* Turn off visibility on local symbol.  */
9930       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9931     }
9932   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9933   else if (h->unique_global && h->def_regular)
9934     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, type);
9935   else if (h->root.type == bfd_link_hash_undefweak
9936            || h->root.type == bfd_link_hash_defweak)
9937     sym.st_info = ELF_ST_INFO (STB_WEAK, type);
9938   else
9939     sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9940   sym.st_target_internal = h->target_internal;
9941
9942   /* Give the processor backend a chance to tweak the symbol value,
9943      and also to finish up anything that needs to be done for this
9944      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9945      forced local syms when non-shared is due to a historical quirk.
9946      STT_GNU_IFUNC symbol must go through PLT.  */
9947   if ((h->type == STT_GNU_IFUNC
9948        && h->def_regular
9949        && !bfd_link_relocatable (flinfo->info))
9950       || ((h->dynindx != -1
9951            || h->forced_local)
9952           && ((bfd_link_pic (flinfo->info)
9953                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9954                    || h->root.type != bfd_link_hash_undefweak))
9955               || !h->forced_local)
9956           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9957     {
9958       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9959              (flinfo->output_bfd, flinfo->info, h, &sym)))
9960         {
9961           eoinfo->failed = TRUE;
9962           return FALSE;
9963         }
9964     }
9965
9966   /* If we are marking the symbol as undefined, and there are no
9967      non-weak references to this symbol from a regular object, then
9968      mark the symbol as weak undefined; if there are non-weak
9969      references, mark the symbol as strong.  We can't do this earlier,
9970      because it might not be marked as undefined until the
9971      finish_dynamic_symbol routine gets through with it.  */
9972   if (sym.st_shndx == SHN_UNDEF
9973       && h->ref_regular
9974       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9975           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9976     {
9977       int bindtype;
9978       type = ELF_ST_TYPE (sym.st_info);
9979
9980       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9981       if (type == STT_GNU_IFUNC)
9982         type = STT_FUNC;
9983
9984       if (h->ref_regular_nonweak)
9985         bindtype = STB_GLOBAL;
9986       else
9987         bindtype = STB_WEAK;
9988       sym.st_info = ELF_ST_INFO (bindtype, type);
9989     }
9990
9991   /* If this is a symbol defined in a dynamic library, don't use the
9992      symbol size from the dynamic library.  Relinking an executable
9993      against a new library may introduce gratuitous changes in the
9994      executable's symbols if we keep the size.  */
9995   if (sym.st_shndx == SHN_UNDEF
9996       && !h->def_regular
9997       && h->def_dynamic)
9998     sym.st_size = 0;
9999
10000   /* If a non-weak symbol with non-default visibility is not defined
10001      locally, it is a fatal error.  */
10002   if (!bfd_link_relocatable (flinfo->info)
10003       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
10004       && ELF_ST_BIND (sym.st_info) != STB_WEAK
10005       && h->root.type == bfd_link_hash_undefined
10006       && !h->def_regular)
10007     {
10008       const char *msg;
10009
10010       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
10011         /* xgettext:c-format */
10012         msg = _("%pB: protected symbol `%s' isn't defined");
10013       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
10014         /* xgettext:c-format */
10015         msg = _("%pB: internal symbol `%s' isn't defined");
10016       else
10017         /* xgettext:c-format */
10018         msg = _("%pB: hidden symbol `%s' isn't defined");
10019       _bfd_error_handler (msg, flinfo->output_bfd, h->root.root.string);
10020       bfd_set_error (bfd_error_bad_value);
10021       eoinfo->failed = TRUE;
10022       return FALSE;
10023     }
10024
10025   /* If this symbol should be put in the .dynsym section, then put it
10026      there now.  We already know the symbol index.  We also fill in
10027      the entry in the .hash section.  */
10028   if (h->dynindx != -1
10029       && elf_hash_table (flinfo->info)->dynamic_sections_created
10030       && elf_hash_table (flinfo->info)->dynsym != NULL
10031       && !discarded_section (elf_hash_table (flinfo->info)->dynsym))
10032     {
10033       bfd_byte *esym;
10034
10035       /* Since there is no version information in the dynamic string,
10036          if there is no version info in symbol version section, we will
10037          have a run-time problem if not linking executable, referenced
10038          by shared library, or not bound locally.  */
10039       if (h->verinfo.verdef == NULL
10040           && (!bfd_link_executable (flinfo->info)
10041               || h->ref_dynamic
10042               || !h->def_regular))
10043         {
10044           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
10045
10046           if (p && p [1] != '\0')
10047             {
10048               _bfd_error_handler
10049                 /* xgettext:c-format */
10050                 (_("%pB: no symbol version section for versioned symbol `%s'"),
10051                  flinfo->output_bfd, h->root.root.string);
10052               eoinfo->failed = TRUE;
10053               return FALSE;
10054             }
10055         }
10056
10057       sym.st_name = h->dynstr_index;
10058       esym = (elf_hash_table (flinfo->info)->dynsym->contents
10059               + h->dynindx * bed->s->sizeof_sym);
10060       if (!check_dynsym (flinfo->output_bfd, &sym))
10061         {
10062           eoinfo->failed = TRUE;
10063           return FALSE;
10064         }
10065       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
10066
10067       if (flinfo->hash_sec != NULL)
10068         {
10069           size_t hash_entry_size;
10070           bfd_byte *bucketpos;
10071           bfd_vma chain;
10072           size_t bucketcount;
10073           size_t bucket;
10074
10075           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
10076           bucket = h->u.elf_hash_value % bucketcount;
10077
10078           hash_entry_size
10079             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
10080           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
10081                        + (bucket + 2) * hash_entry_size);
10082           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
10083           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
10084                    bucketpos);
10085           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
10086                    ((bfd_byte *) flinfo->hash_sec->contents
10087                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
10088         }
10089
10090       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
10091         {
10092           Elf_Internal_Versym iversym;
10093           Elf_External_Versym *eversym;
10094
10095           if (!h->def_regular)
10096             {
10097               if (h->verinfo.verdef == NULL
10098                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
10099                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
10100                 iversym.vs_vers = 0;
10101               else
10102                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
10103             }
10104           else
10105             {
10106               if (h->verinfo.vertree == NULL)
10107                 iversym.vs_vers = 1;
10108               else
10109                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
10110               if (flinfo->info->create_default_symver)
10111                 iversym.vs_vers++;
10112             }
10113
10114           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
10115              defined locally.  */
10116           if (h->versioned == versioned_hidden && h->def_regular)
10117             iversym.vs_vers |= VERSYM_HIDDEN;
10118
10119           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
10120           eversym += h->dynindx;
10121           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
10122         }
10123     }
10124
10125   /* If the symbol is undefined, and we didn't output it to .dynsym,
10126      strip it from .symtab too.  Obviously we can't do this for
10127      relocatable output or when needed for --emit-relocs.  */
10128   else if (input_sec == bfd_und_section_ptr
10129            && h->indx != -2
10130            /* PR 22319 Do not strip global undefined symbols marked as being needed.  */
10131            && (h->mark != 1 || ELF_ST_BIND (sym.st_info) != STB_GLOBAL)
10132            && !bfd_link_relocatable (flinfo->info))
10133     return TRUE;
10134
10135   /* Also strip others that we couldn't earlier due to dynamic symbol
10136      processing.  */
10137   if (strip)
10138     return TRUE;
10139   if ((input_sec->flags & SEC_EXCLUDE) != 0)
10140     return TRUE;
10141
10142   /* Output a FILE symbol so that following locals are not associated
10143      with the wrong input file.  We need one for forced local symbols
10144      if we've seen more than one FILE symbol or when we have exactly
10145      one FILE symbol but global symbols are present in a file other
10146      than the one with the FILE symbol.  We also need one if linker
10147      defined symbols are present.  In practice these conditions are
10148      always met, so just emit the FILE symbol unconditionally.  */
10149   if (eoinfo->localsyms
10150       && !eoinfo->file_sym_done
10151       && eoinfo->flinfo->filesym_count != 0)
10152     {
10153       Elf_Internal_Sym fsym;
10154
10155       memset (&fsym, 0, sizeof (fsym));
10156       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10157       fsym.st_shndx = SHN_ABS;
10158       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
10159                                       bfd_und_section_ptr, NULL))
10160         return FALSE;
10161
10162       eoinfo->file_sym_done = TRUE;
10163     }
10164
10165   indx = bfd_get_symcount (flinfo->output_bfd);
10166   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
10167                                    input_sec, h);
10168   if (ret == 0)
10169     {
10170       eoinfo->failed = TRUE;
10171       return FALSE;
10172     }
10173   else if (ret == 1)
10174     h->indx = indx;
10175   else if (h->indx == -2)
10176     abort();
10177
10178   return TRUE;
10179 }
10180
10181 /* Return TRUE if special handling is done for relocs in SEC against
10182    symbols defined in discarded sections.  */
10183
10184 static bfd_boolean
10185 elf_section_ignore_discarded_relocs (asection *sec)
10186 {
10187   const struct elf_backend_data *bed;
10188
10189   switch (sec->sec_info_type)
10190     {
10191     case SEC_INFO_TYPE_STABS:
10192     case SEC_INFO_TYPE_EH_FRAME:
10193     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10194       return TRUE;
10195     default:
10196       break;
10197     }
10198
10199   bed = get_elf_backend_data (sec->owner);
10200   if (bed->elf_backend_ignore_discarded_relocs != NULL
10201       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
10202     return TRUE;
10203
10204   return FALSE;
10205 }
10206
10207 /* Return a mask saying how ld should treat relocations in SEC against
10208    symbols defined in discarded sections.  If this function returns
10209    COMPLAIN set, ld will issue a warning message.  If this function
10210    returns PRETEND set, and the discarded section was link-once and the
10211    same size as the kept link-once section, ld will pretend that the
10212    symbol was actually defined in the kept section.  Otherwise ld will
10213    zero the reloc (at least that is the intent, but some cooperation by
10214    the target dependent code is needed, particularly for REL targets).  */
10215
10216 unsigned int
10217 _bfd_elf_default_action_discarded (asection *sec)
10218 {
10219   if (sec->flags & SEC_DEBUGGING)
10220     return PRETEND;
10221
10222   if (strcmp (".eh_frame", sec->name) == 0)
10223     return 0;
10224
10225   if (strcmp (".gcc_except_table", sec->name) == 0)
10226     return 0;
10227
10228   return COMPLAIN | PRETEND;
10229 }
10230
10231 /* Find a match between a section and a member of a section group.  */
10232
10233 static asection *
10234 match_group_member (asection *sec, asection *group,
10235                     struct bfd_link_info *info)
10236 {
10237   asection *first = elf_next_in_group (group);
10238   asection *s = first;
10239
10240   while (s != NULL)
10241     {
10242       if (bfd_elf_match_symbols_in_sections (s, sec, info))
10243         return s;
10244
10245       s = elf_next_in_group (s);
10246       if (s == first)
10247         break;
10248     }
10249
10250   return NULL;
10251 }
10252
10253 /* Check if the kept section of a discarded section SEC can be used
10254    to replace it.  Return the replacement if it is OK.  Otherwise return
10255    NULL.  */
10256
10257 asection *
10258 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
10259 {
10260   asection *kept;
10261
10262   kept = sec->kept_section;
10263   if (kept != NULL)
10264     {
10265       if ((kept->flags & SEC_GROUP) != 0)
10266         kept = match_group_member (sec, kept, info);
10267       if (kept != NULL
10268           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
10269               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
10270         kept = NULL;
10271       sec->kept_section = kept;
10272     }
10273   return kept;
10274 }
10275
10276 /* Link an input file into the linker output file.  This function
10277    handles all the sections and relocations of the input file at once.
10278    This is so that we only have to read the local symbols once, and
10279    don't have to keep them in memory.  */
10280
10281 static bfd_boolean
10282 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
10283 {
10284   int (*relocate_section)
10285     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
10286      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
10287   bfd *output_bfd;
10288   Elf_Internal_Shdr *symtab_hdr;
10289   size_t locsymcount;
10290   size_t extsymoff;
10291   Elf_Internal_Sym *isymbuf;
10292   Elf_Internal_Sym *isym;
10293   Elf_Internal_Sym *isymend;
10294   long *pindex;
10295   asection **ppsection;
10296   asection *o;
10297   const struct elf_backend_data *bed;
10298   struct elf_link_hash_entry **sym_hashes;
10299   bfd_size_type address_size;
10300   bfd_vma r_type_mask;
10301   int r_sym_shift;
10302   bfd_boolean have_file_sym = FALSE;
10303
10304   output_bfd = flinfo->output_bfd;
10305   bed = get_elf_backend_data (output_bfd);
10306   relocate_section = bed->elf_backend_relocate_section;
10307
10308   /* If this is a dynamic object, we don't want to do anything here:
10309      we don't want the local symbols, and we don't want the section
10310      contents.  */
10311   if ((input_bfd->flags & DYNAMIC) != 0)
10312     return TRUE;
10313
10314   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
10315   if (elf_bad_symtab (input_bfd))
10316     {
10317       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
10318       extsymoff = 0;
10319     }
10320   else
10321     {
10322       locsymcount = symtab_hdr->sh_info;
10323       extsymoff = symtab_hdr->sh_info;
10324     }
10325
10326   /* Read the local symbols.  */
10327   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
10328   if (isymbuf == NULL && locsymcount != 0)
10329     {
10330       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
10331                                       flinfo->internal_syms,
10332                                       flinfo->external_syms,
10333                                       flinfo->locsym_shndx);
10334       if (isymbuf == NULL)
10335         return FALSE;
10336     }
10337
10338   /* Find local symbol sections and adjust values of symbols in
10339      SEC_MERGE sections.  Write out those local symbols we know are
10340      going into the output file.  */
10341   isymend = isymbuf + locsymcount;
10342   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
10343        isym < isymend;
10344        isym++, pindex++, ppsection++)
10345     {
10346       asection *isec;
10347       const char *name;
10348       Elf_Internal_Sym osym;
10349       long indx;
10350       int ret;
10351
10352       *pindex = -1;
10353
10354       if (elf_bad_symtab (input_bfd))
10355         {
10356           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
10357             {
10358               *ppsection = NULL;
10359               continue;
10360             }
10361         }
10362
10363       if (isym->st_shndx == SHN_UNDEF)
10364         isec = bfd_und_section_ptr;
10365       else if (isym->st_shndx == SHN_ABS)
10366         isec = bfd_abs_section_ptr;
10367       else if (isym->st_shndx == SHN_COMMON)
10368         isec = bfd_com_section_ptr;
10369       else
10370         {
10371           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
10372           if (isec == NULL)
10373             {
10374               /* Don't attempt to output symbols with st_shnx in the
10375                  reserved range other than SHN_ABS and SHN_COMMON.  */
10376               *ppsection = NULL;
10377               continue;
10378             }
10379           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
10380                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
10381             isym->st_value =
10382               _bfd_merged_section_offset (output_bfd, &isec,
10383                                           elf_section_data (isec)->sec_info,
10384                                           isym->st_value);
10385         }
10386
10387       *ppsection = isec;
10388
10389       /* Don't output the first, undefined, symbol.  In fact, don't
10390          output any undefined local symbol.  */
10391       if (isec == bfd_und_section_ptr)
10392         continue;
10393
10394       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
10395         {
10396           /* We never output section symbols.  Instead, we use the
10397              section symbol of the corresponding section in the output
10398              file.  */
10399           continue;
10400         }
10401
10402       /* If we are stripping all symbols, we don't want to output this
10403          one.  */
10404       if (flinfo->info->strip == strip_all)
10405         continue;
10406
10407       /* If we are discarding all local symbols, we don't want to
10408          output this one.  If we are generating a relocatable output
10409          file, then some of the local symbols may be required by
10410          relocs; we output them below as we discover that they are
10411          needed.  */
10412       if (flinfo->info->discard == discard_all)
10413         continue;
10414
10415       /* If this symbol is defined in a section which we are
10416          discarding, we don't need to keep it.  */
10417       if (isym->st_shndx != SHN_UNDEF
10418           && isym->st_shndx < SHN_LORESERVE
10419           && bfd_section_removed_from_list (output_bfd,
10420                                             isec->output_section))
10421         continue;
10422
10423       /* Get the name of the symbol.  */
10424       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
10425                                               isym->st_name);
10426       if (name == NULL)
10427         return FALSE;
10428
10429       /* See if we are discarding symbols with this name.  */
10430       if ((flinfo->info->strip == strip_some
10431            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
10432                == NULL))
10433           || (((flinfo->info->discard == discard_sec_merge
10434                 && (isec->flags & SEC_MERGE)
10435                 && !bfd_link_relocatable (flinfo->info))
10436                || flinfo->info->discard == discard_l)
10437               && bfd_is_local_label_name (input_bfd, name)))
10438         continue;
10439
10440       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
10441         {
10442           if (input_bfd->lto_output)
10443             /* -flto puts a temp file name here.  This means builds
10444                are not reproducible.  Discard the symbol.  */
10445             continue;
10446           have_file_sym = TRUE;
10447           flinfo->filesym_count += 1;
10448         }
10449       if (!have_file_sym)
10450         {
10451           /* In the absence of debug info, bfd_find_nearest_line uses
10452              FILE symbols to determine the source file for local
10453              function symbols.  Provide a FILE symbol here if input
10454              files lack such, so that their symbols won't be
10455              associated with a previous input file.  It's not the
10456              source file, but the best we can do.  */
10457           have_file_sym = TRUE;
10458           flinfo->filesym_count += 1;
10459           memset (&osym, 0, sizeof (osym));
10460           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10461           osym.st_shndx = SHN_ABS;
10462           if (!elf_link_output_symstrtab (flinfo,
10463                                           (input_bfd->lto_output ? NULL
10464                                            : input_bfd->filename),
10465                                           &osym, bfd_abs_section_ptr,
10466                                           NULL))
10467             return FALSE;
10468         }
10469
10470       osym = *isym;
10471
10472       /* Adjust the section index for the output file.  */
10473       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10474                                                          isec->output_section);
10475       if (osym.st_shndx == SHN_BAD)
10476         return FALSE;
10477
10478       /* ELF symbols in relocatable files are section relative, but
10479          in executable files they are virtual addresses.  Note that
10480          this code assumes that all ELF sections have an associated
10481          BFD section with a reasonable value for output_offset; below
10482          we assume that they also have a reasonable value for
10483          output_section.  Any special sections must be set up to meet
10484          these requirements.  */
10485       osym.st_value += isec->output_offset;
10486       if (!bfd_link_relocatable (flinfo->info))
10487         {
10488           osym.st_value += isec->output_section->vma;
10489           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
10490             {
10491               /* STT_TLS symbols are relative to PT_TLS segment base.  */
10492               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
10493               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
10494             }
10495         }
10496
10497       indx = bfd_get_symcount (output_bfd);
10498       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
10499       if (ret == 0)
10500         return FALSE;
10501       else if (ret == 1)
10502         *pindex = indx;
10503     }
10504
10505   if (bed->s->arch_size == 32)
10506     {
10507       r_type_mask = 0xff;
10508       r_sym_shift = 8;
10509       address_size = 4;
10510     }
10511   else
10512     {
10513       r_type_mask = 0xffffffff;
10514       r_sym_shift = 32;
10515       address_size = 8;
10516     }
10517
10518   /* Relocate the contents of each section.  */
10519   sym_hashes = elf_sym_hashes (input_bfd);
10520   for (o = input_bfd->sections; o != NULL; o = o->next)
10521     {
10522       bfd_byte *contents;
10523
10524       if (! o->linker_mark)
10525         {
10526           /* This section was omitted from the link.  */
10527           continue;
10528         }
10529
10530       if (!flinfo->info->resolve_section_groups
10531           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
10532         {
10533           /* Deal with the group signature symbol.  */
10534           struct bfd_elf_section_data *sec_data = elf_section_data (o);
10535           unsigned long symndx = sec_data->this_hdr.sh_info;
10536           asection *osec = o->output_section;
10537
10538           BFD_ASSERT (bfd_link_relocatable (flinfo->info));
10539           if (symndx >= locsymcount
10540               || (elf_bad_symtab (input_bfd)
10541                   && flinfo->sections[symndx] == NULL))
10542             {
10543               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
10544               while (h->root.type == bfd_link_hash_indirect
10545                      || h->root.type == bfd_link_hash_warning)
10546                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
10547               /* Arrange for symbol to be output.  */
10548               h->indx = -2;
10549               elf_section_data (osec)->this_hdr.sh_info = -2;
10550             }
10551           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
10552             {
10553               /* We'll use the output section target_index.  */
10554               asection *sec = flinfo->sections[symndx]->output_section;
10555               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
10556             }
10557           else
10558             {
10559               if (flinfo->indices[symndx] == -1)
10560                 {
10561                   /* Otherwise output the local symbol now.  */
10562                   Elf_Internal_Sym sym = isymbuf[symndx];
10563                   asection *sec = flinfo->sections[symndx]->output_section;
10564                   const char *name;
10565                   long indx;
10566                   int ret;
10567
10568                   name = bfd_elf_string_from_elf_section (input_bfd,
10569                                                           symtab_hdr->sh_link,
10570                                                           sym.st_name);
10571                   if (name == NULL)
10572                     return FALSE;
10573
10574                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10575                                                                     sec);
10576                   if (sym.st_shndx == SHN_BAD)
10577                     return FALSE;
10578
10579                   sym.st_value += o->output_offset;
10580
10581                   indx = bfd_get_symcount (output_bfd);
10582                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
10583                                                    NULL);
10584                   if (ret == 0)
10585                     return FALSE;
10586                   else if (ret == 1)
10587                     flinfo->indices[symndx] = indx;
10588                   else
10589                     abort ();
10590                 }
10591               elf_section_data (osec)->this_hdr.sh_info
10592                 = flinfo->indices[symndx];
10593             }
10594         }
10595
10596       if ((o->flags & SEC_HAS_CONTENTS) == 0
10597           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
10598         continue;
10599
10600       if ((o->flags & SEC_LINKER_CREATED) != 0)
10601         {
10602           /* Section was created by _bfd_elf_link_create_dynamic_sections
10603              or somesuch.  */
10604           continue;
10605         }
10606
10607       /* Get the contents of the section.  They have been cached by a
10608          relaxation routine.  Note that o is a section in an input
10609          file, so the contents field will not have been set by any of
10610          the routines which work on output files.  */
10611       if (elf_section_data (o)->this_hdr.contents != NULL)
10612         {
10613           contents = elf_section_data (o)->this_hdr.contents;
10614           if (bed->caches_rawsize
10615               && o->rawsize != 0
10616               && o->rawsize < o->size)
10617             {
10618               memcpy (flinfo->contents, contents, o->rawsize);
10619               contents = flinfo->contents;
10620             }
10621         }
10622       else
10623         {
10624           contents = flinfo->contents;
10625           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
10626             return FALSE;
10627         }
10628
10629       if ((o->flags & SEC_RELOC) != 0)
10630         {
10631           Elf_Internal_Rela *internal_relocs;
10632           Elf_Internal_Rela *rel, *relend;
10633           int action_discarded;
10634           int ret;
10635
10636           /* Get the swapped relocs.  */
10637           internal_relocs
10638             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
10639                                          flinfo->internal_relocs, FALSE);
10640           if (internal_relocs == NULL
10641               && o->reloc_count > 0)
10642             return FALSE;
10643
10644           /* We need to reverse-copy input .ctors/.dtors sections if
10645              they are placed in .init_array/.finit_array for output.  */
10646           if (o->size > address_size
10647               && ((strncmp (o->name, ".ctors", 6) == 0
10648                    && strcmp (o->output_section->name,
10649                               ".init_array") == 0)
10650                   || (strncmp (o->name, ".dtors", 6) == 0
10651                       && strcmp (o->output_section->name,
10652                                  ".fini_array") == 0))
10653               && (o->name[6] == 0 || o->name[6] == '.'))
10654             {
10655               if (o->size * bed->s->int_rels_per_ext_rel
10656                   != o->reloc_count * address_size)
10657                 {
10658                   _bfd_error_handler
10659                     /* xgettext:c-format */
10660                     (_("error: %pB: size of section %pA is not "
10661                        "multiple of address size"),
10662                      input_bfd, o);
10663                   bfd_set_error (bfd_error_bad_value);
10664                   return FALSE;
10665                 }
10666               o->flags |= SEC_ELF_REVERSE_COPY;
10667             }
10668
10669           action_discarded = -1;
10670           if (!elf_section_ignore_discarded_relocs (o))
10671             action_discarded = (*bed->action_discarded) (o);
10672
10673           /* Run through the relocs evaluating complex reloc symbols and
10674              looking for relocs against symbols from discarded sections
10675              or section symbols from removed link-once sections.
10676              Complain about relocs against discarded sections.  Zero
10677              relocs against removed link-once sections.  */
10678
10679           rel = internal_relocs;
10680           relend = rel + o->reloc_count;
10681           for ( ; rel < relend; rel++)
10682             {
10683               unsigned long r_symndx = rel->r_info >> r_sym_shift;
10684               unsigned int s_type;
10685               asection **ps, *sec;
10686               struct elf_link_hash_entry *h = NULL;
10687               const char *sym_name;
10688
10689               if (r_symndx == STN_UNDEF)
10690                 continue;
10691
10692               if (r_symndx >= locsymcount
10693                   || (elf_bad_symtab (input_bfd)
10694                       && flinfo->sections[r_symndx] == NULL))
10695                 {
10696                   h = sym_hashes[r_symndx - extsymoff];
10697
10698                   /* Badly formatted input files can contain relocs that
10699                      reference non-existant symbols.  Check here so that
10700                      we do not seg fault.  */
10701                   if (h == NULL)
10702                     {
10703                       _bfd_error_handler
10704                         /* xgettext:c-format */
10705                         (_("error: %pB contains a reloc (%#" PRIx64 ") for section %pA "
10706                            "that references a non-existent global symbol"),
10707                          input_bfd, (uint64_t) rel->r_info, o);
10708                       bfd_set_error (bfd_error_bad_value);
10709                       return FALSE;
10710                     }
10711
10712                   while (h->root.type == bfd_link_hash_indirect
10713                          || h->root.type == bfd_link_hash_warning)
10714                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10715
10716                   s_type = h->type;
10717
10718                   /* If a plugin symbol is referenced from a non-IR file,
10719                      mark the symbol as undefined.  Note that the
10720                      linker may attach linker created dynamic sections
10721                      to the plugin bfd.  Symbols defined in linker
10722                      created sections are not plugin symbols.  */
10723                   if ((h->root.non_ir_ref_regular
10724                        || h->root.non_ir_ref_dynamic)
10725                       && (h->root.type == bfd_link_hash_defined
10726                           || h->root.type == bfd_link_hash_defweak)
10727                       && (h->root.u.def.section->flags
10728                           & SEC_LINKER_CREATED) == 0
10729                       && h->root.u.def.section->owner != NULL
10730                       && (h->root.u.def.section->owner->flags
10731                           & BFD_PLUGIN) != 0)
10732                     {
10733                       h->root.type = bfd_link_hash_undefined;
10734                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10735                     }
10736
10737                   ps = NULL;
10738                   if (h->root.type == bfd_link_hash_defined
10739                       || h->root.type == bfd_link_hash_defweak)
10740                     ps = &h->root.u.def.section;
10741
10742                   sym_name = h->root.root.string;
10743                 }
10744               else
10745                 {
10746                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10747
10748                   s_type = ELF_ST_TYPE (sym->st_info);
10749                   ps = &flinfo->sections[r_symndx];
10750                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10751                                                sym, *ps);
10752                 }
10753
10754               if ((s_type == STT_RELC || s_type == STT_SRELC)
10755                   && !bfd_link_relocatable (flinfo->info))
10756                 {
10757                   bfd_vma val;
10758                   bfd_vma dot = (rel->r_offset
10759                                  + o->output_offset + o->output_section->vma);
10760 #ifdef DEBUG
10761                   printf ("Encountered a complex symbol!");
10762                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10763                           input_bfd->filename, o->name,
10764                           (long) (rel - internal_relocs));
10765                   printf (" symbol: idx  %8.8lx, name %s\n",
10766                           r_symndx, sym_name);
10767                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10768                           (unsigned long) rel->r_info,
10769                           (unsigned long) rel->r_offset);
10770 #endif
10771                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10772                                     isymbuf, locsymcount, s_type == STT_SRELC))
10773                     return FALSE;
10774
10775                   /* Symbol evaluated OK.  Update to absolute value.  */
10776                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10777                                     r_symndx, val);
10778                   continue;
10779                 }
10780
10781               if (action_discarded != -1 && ps != NULL)
10782                 {
10783                   /* Complain if the definition comes from a
10784                      discarded section.  */
10785                   if ((sec = *ps) != NULL && discarded_section (sec))
10786                     {
10787                       BFD_ASSERT (r_symndx != STN_UNDEF);
10788                       if (action_discarded & COMPLAIN)
10789                         (*flinfo->info->callbacks->einfo)
10790                           /* xgettext:c-format */
10791                           (_("%X`%s' referenced in section `%pA' of %pB: "
10792                              "defined in discarded section `%pA' of %pB\n"),
10793                            sym_name, o, input_bfd, sec, sec->owner);
10794
10795                       /* Try to do the best we can to support buggy old
10796                          versions of gcc.  Pretend that the symbol is
10797                          really defined in the kept linkonce section.
10798                          FIXME: This is quite broken.  Modifying the
10799                          symbol here means we will be changing all later
10800                          uses of the symbol, not just in this section.  */
10801                       if (action_discarded & PRETEND)
10802                         {
10803                           asection *kept;
10804
10805                           kept = _bfd_elf_check_kept_section (sec,
10806                                                               flinfo->info);
10807                           if (kept != NULL)
10808                             {
10809                               *ps = kept;
10810                               continue;
10811                             }
10812                         }
10813                     }
10814                 }
10815             }
10816
10817           /* Relocate the section by invoking a back end routine.
10818
10819              The back end routine is responsible for adjusting the
10820              section contents as necessary, and (if using Rela relocs
10821              and generating a relocatable output file) adjusting the
10822              reloc addend as necessary.
10823
10824              The back end routine does not have to worry about setting
10825              the reloc address or the reloc symbol index.
10826
10827              The back end routine is given a pointer to the swapped in
10828              internal symbols, and can access the hash table entries
10829              for the external symbols via elf_sym_hashes (input_bfd).
10830
10831              When generating relocatable output, the back end routine
10832              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10833              output symbol is going to be a section symbol
10834              corresponding to the output section, which will require
10835              the addend to be adjusted.  */
10836
10837           ret = (*relocate_section) (output_bfd, flinfo->info,
10838                                      input_bfd, o, contents,
10839                                      internal_relocs,
10840                                      isymbuf,
10841                                      flinfo->sections);
10842           if (!ret)
10843             return FALSE;
10844
10845           if (ret == 2
10846               || bfd_link_relocatable (flinfo->info)
10847               || flinfo->info->emitrelocations)
10848             {
10849               Elf_Internal_Rela *irela;
10850               Elf_Internal_Rela *irelaend, *irelamid;
10851               bfd_vma last_offset;
10852               struct elf_link_hash_entry **rel_hash;
10853               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10854               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10855               unsigned int next_erel;
10856               bfd_boolean rela_normal;
10857               struct bfd_elf_section_data *esdi, *esdo;
10858
10859               esdi = elf_section_data (o);
10860               esdo = elf_section_data (o->output_section);
10861               rela_normal = FALSE;
10862
10863               /* Adjust the reloc addresses and symbol indices.  */
10864
10865               irela = internal_relocs;
10866               irelaend = irela + o->reloc_count;
10867               rel_hash = esdo->rel.hashes + esdo->rel.count;
10868               /* We start processing the REL relocs, if any.  When we reach
10869                  IRELAMID in the loop, we switch to the RELA relocs.  */
10870               irelamid = irela;
10871               if (esdi->rel.hdr != NULL)
10872                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10873                              * bed->s->int_rels_per_ext_rel);
10874               rel_hash_list = rel_hash;
10875               rela_hash_list = NULL;
10876               last_offset = o->output_offset;
10877               if (!bfd_link_relocatable (flinfo->info))
10878                 last_offset += o->output_section->vma;
10879               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10880                 {
10881                   unsigned long r_symndx;
10882                   asection *sec;
10883                   Elf_Internal_Sym sym;
10884
10885                   if (next_erel == bed->s->int_rels_per_ext_rel)
10886                     {
10887                       rel_hash++;
10888                       next_erel = 0;
10889                     }
10890
10891                   if (irela == irelamid)
10892                     {
10893                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10894                       rela_hash_list = rel_hash;
10895                       rela_normal = bed->rela_normal;
10896                     }
10897
10898                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10899                                                              flinfo->info, o,
10900                                                              irela->r_offset);
10901                   if (irela->r_offset >= (bfd_vma) -2)
10902                     {
10903                       /* This is a reloc for a deleted entry or somesuch.
10904                          Turn it into an R_*_NONE reloc, at the same
10905                          offset as the last reloc.  elf_eh_frame.c and
10906                          bfd_elf_discard_info rely on reloc offsets
10907                          being ordered.  */
10908                       irela->r_offset = last_offset;
10909                       irela->r_info = 0;
10910                       irela->r_addend = 0;
10911                       continue;
10912                     }
10913
10914                   irela->r_offset += o->output_offset;
10915
10916                   /* Relocs in an executable have to be virtual addresses.  */
10917                   if (!bfd_link_relocatable (flinfo->info))
10918                     irela->r_offset += o->output_section->vma;
10919
10920                   last_offset = irela->r_offset;
10921
10922                   r_symndx = irela->r_info >> r_sym_shift;
10923                   if (r_symndx == STN_UNDEF)
10924                     continue;
10925
10926                   if (r_symndx >= locsymcount
10927                       || (elf_bad_symtab (input_bfd)
10928                           && flinfo->sections[r_symndx] == NULL))
10929                     {
10930                       struct elf_link_hash_entry *rh;
10931                       unsigned long indx;
10932
10933                       /* This is a reloc against a global symbol.  We
10934                          have not yet output all the local symbols, so
10935                          we do not know the symbol index of any global
10936                          symbol.  We set the rel_hash entry for this
10937                          reloc to point to the global hash table entry
10938                          for this symbol.  The symbol index is then
10939                          set at the end of bfd_elf_final_link.  */
10940                       indx = r_symndx - extsymoff;
10941                       rh = elf_sym_hashes (input_bfd)[indx];
10942                       while (rh->root.type == bfd_link_hash_indirect
10943                              || rh->root.type == bfd_link_hash_warning)
10944                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10945
10946                       /* Setting the index to -2 tells
10947                          elf_link_output_extsym that this symbol is
10948                          used by a reloc.  */
10949                       BFD_ASSERT (rh->indx < 0);
10950                       rh->indx = -2;
10951                       *rel_hash = rh;
10952
10953                       continue;
10954                     }
10955
10956                   /* This is a reloc against a local symbol.  */
10957
10958                   *rel_hash = NULL;
10959                   sym = isymbuf[r_symndx];
10960                   sec = flinfo->sections[r_symndx];
10961                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10962                     {
10963                       /* I suppose the backend ought to fill in the
10964                          section of any STT_SECTION symbol against a
10965                          processor specific section.  */
10966                       r_symndx = STN_UNDEF;
10967                       if (bfd_is_abs_section (sec))
10968                         ;
10969                       else if (sec == NULL || sec->owner == NULL)
10970                         {
10971                           bfd_set_error (bfd_error_bad_value);
10972                           return FALSE;
10973                         }
10974                       else
10975                         {
10976                           asection *osec = sec->output_section;
10977
10978                           /* If we have discarded a section, the output
10979                              section will be the absolute section.  In
10980                              case of discarded SEC_MERGE sections, use
10981                              the kept section.  relocate_section should
10982                              have already handled discarded linkonce
10983                              sections.  */
10984                           if (bfd_is_abs_section (osec)
10985                               && sec->kept_section != NULL
10986                               && sec->kept_section->output_section != NULL)
10987                             {
10988                               osec = sec->kept_section->output_section;
10989                               irela->r_addend -= osec->vma;
10990                             }
10991
10992                           if (!bfd_is_abs_section (osec))
10993                             {
10994                               r_symndx = osec->target_index;
10995                               if (r_symndx == STN_UNDEF)
10996                                 {
10997                                   irela->r_addend += osec->vma;
10998                                   osec = _bfd_nearby_section (output_bfd, osec,
10999                                                               osec->vma);
11000                                   irela->r_addend -= osec->vma;
11001                                   r_symndx = osec->target_index;
11002                                 }
11003                             }
11004                         }
11005
11006                       /* Adjust the addend according to where the
11007                          section winds up in the output section.  */
11008                       if (rela_normal)
11009                         irela->r_addend += sec->output_offset;
11010                     }
11011                   else
11012                     {
11013                       if (flinfo->indices[r_symndx] == -1)
11014                         {
11015                           unsigned long shlink;
11016                           const char *name;
11017                           asection *osec;
11018                           long indx;
11019
11020                           if (flinfo->info->strip == strip_all)
11021                             {
11022                               /* You can't do ld -r -s.  */
11023                               bfd_set_error (bfd_error_invalid_operation);
11024                               return FALSE;
11025                             }
11026
11027                           /* This symbol was skipped earlier, but
11028                              since it is needed by a reloc, we
11029                              must output it now.  */
11030                           shlink = symtab_hdr->sh_link;
11031                           name = (bfd_elf_string_from_elf_section
11032                                   (input_bfd, shlink, sym.st_name));
11033                           if (name == NULL)
11034                             return FALSE;
11035
11036                           osec = sec->output_section;
11037                           sym.st_shndx =
11038                             _bfd_elf_section_from_bfd_section (output_bfd,
11039                                                                osec);
11040                           if (sym.st_shndx == SHN_BAD)
11041                             return FALSE;
11042
11043                           sym.st_value += sec->output_offset;
11044                           if (!bfd_link_relocatable (flinfo->info))
11045                             {
11046                               sym.st_value += osec->vma;
11047                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
11048                                 {
11049                                   /* STT_TLS symbols are relative to PT_TLS
11050                                      segment base.  */
11051                                   BFD_ASSERT (elf_hash_table (flinfo->info)
11052                                               ->tls_sec != NULL);
11053                                   sym.st_value -= (elf_hash_table (flinfo->info)
11054                                                    ->tls_sec->vma);
11055                                 }
11056                             }
11057
11058                           indx = bfd_get_symcount (output_bfd);
11059                           ret = elf_link_output_symstrtab (flinfo, name,
11060                                                            &sym, sec,
11061                                                            NULL);
11062                           if (ret == 0)
11063                             return FALSE;
11064                           else if (ret == 1)
11065                             flinfo->indices[r_symndx] = indx;
11066                           else
11067                             abort ();
11068                         }
11069
11070                       r_symndx = flinfo->indices[r_symndx];
11071                     }
11072
11073                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
11074                                    | (irela->r_info & r_type_mask));
11075                 }
11076
11077               /* Swap out the relocs.  */
11078               input_rel_hdr = esdi->rel.hdr;
11079               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
11080                 {
11081                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
11082                                                      input_rel_hdr,
11083                                                      internal_relocs,
11084                                                      rel_hash_list))
11085                     return FALSE;
11086                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
11087                                       * bed->s->int_rels_per_ext_rel);
11088                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
11089                 }
11090
11091               input_rela_hdr = esdi->rela.hdr;
11092               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
11093                 {
11094                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
11095                                                      input_rela_hdr,
11096                                                      internal_relocs,
11097                                                      rela_hash_list))
11098                     return FALSE;
11099                 }
11100             }
11101         }
11102
11103       /* Write out the modified section contents.  */
11104       if (bed->elf_backend_write_section
11105           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
11106                                                 contents))
11107         {
11108           /* Section written out.  */
11109         }
11110       else switch (o->sec_info_type)
11111         {
11112         case SEC_INFO_TYPE_STABS:
11113           if (! (_bfd_write_section_stabs
11114                  (output_bfd,
11115                   &elf_hash_table (flinfo->info)->stab_info,
11116                   o, &elf_section_data (o)->sec_info, contents)))
11117             return FALSE;
11118           break;
11119         case SEC_INFO_TYPE_MERGE:
11120           if (! _bfd_write_merged_section (output_bfd, o,
11121                                            elf_section_data (o)->sec_info))
11122             return FALSE;
11123           break;
11124         case SEC_INFO_TYPE_EH_FRAME:
11125           {
11126             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
11127                                                    o, contents))
11128               return FALSE;
11129           }
11130           break;
11131         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
11132           {
11133             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
11134                                                          flinfo->info,
11135                                                          o, contents))
11136               return FALSE;
11137           }
11138           break;
11139         default:
11140           {
11141             if (! (o->flags & SEC_EXCLUDE))
11142               {
11143                 file_ptr offset = (file_ptr) o->output_offset;
11144                 bfd_size_type todo = o->size;
11145
11146                 offset *= bfd_octets_per_byte (output_bfd);
11147
11148                 if ((o->flags & SEC_ELF_REVERSE_COPY))
11149                   {
11150                     /* Reverse-copy input section to output.  */
11151                     do
11152                       {
11153                         todo -= address_size;
11154                         if (! bfd_set_section_contents (output_bfd,
11155                                                         o->output_section,
11156                                                         contents + todo,
11157                                                         offset,
11158                                                         address_size))
11159                           return FALSE;
11160                         if (todo == 0)
11161                           break;
11162                         offset += address_size;
11163                       }
11164                     while (1);
11165                   }
11166                 else if (! bfd_set_section_contents (output_bfd,
11167                                                      o->output_section,
11168                                                      contents,
11169                                                      offset, todo))
11170                   return FALSE;
11171               }
11172           }
11173           break;
11174         }
11175     }
11176
11177   return TRUE;
11178 }
11179
11180 /* Generate a reloc when linking an ELF file.  This is a reloc
11181    requested by the linker, and does not come from any input file.  This
11182    is used to build constructor and destructor tables when linking
11183    with -Ur.  */
11184
11185 static bfd_boolean
11186 elf_reloc_link_order (bfd *output_bfd,
11187                       struct bfd_link_info *info,
11188                       asection *output_section,
11189                       struct bfd_link_order *link_order)
11190 {
11191   reloc_howto_type *howto;
11192   long indx;
11193   bfd_vma offset;
11194   bfd_vma addend;
11195   struct bfd_elf_section_reloc_data *reldata;
11196   struct elf_link_hash_entry **rel_hash_ptr;
11197   Elf_Internal_Shdr *rel_hdr;
11198   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
11199   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
11200   bfd_byte *erel;
11201   unsigned int i;
11202   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
11203
11204   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
11205   if (howto == NULL)
11206     {
11207       bfd_set_error (bfd_error_bad_value);
11208       return FALSE;
11209     }
11210
11211   addend = link_order->u.reloc.p->addend;
11212
11213   if (esdo->rel.hdr)
11214     reldata = &esdo->rel;
11215   else if (esdo->rela.hdr)
11216     reldata = &esdo->rela;
11217   else
11218     {
11219       reldata = NULL;
11220       BFD_ASSERT (0);
11221     }
11222
11223   /* Figure out the symbol index.  */
11224   rel_hash_ptr = reldata->hashes + reldata->count;
11225   if (link_order->type == bfd_section_reloc_link_order)
11226     {
11227       indx = link_order->u.reloc.p->u.section->target_index;
11228       BFD_ASSERT (indx != 0);
11229       *rel_hash_ptr = NULL;
11230     }
11231   else
11232     {
11233       struct elf_link_hash_entry *h;
11234
11235       /* Treat a reloc against a defined symbol as though it were
11236          actually against the section.  */
11237       h = ((struct elf_link_hash_entry *)
11238            bfd_wrapped_link_hash_lookup (output_bfd, info,
11239                                          link_order->u.reloc.p->u.name,
11240                                          FALSE, FALSE, TRUE));
11241       if (h != NULL
11242           && (h->root.type == bfd_link_hash_defined
11243               || h->root.type == bfd_link_hash_defweak))
11244         {
11245           asection *section;
11246
11247           section = h->root.u.def.section;
11248           indx = section->output_section->target_index;
11249           *rel_hash_ptr = NULL;
11250           /* It seems that we ought to add the symbol value to the
11251              addend here, but in practice it has already been added
11252              because it was passed to constructor_callback.  */
11253           addend += section->output_section->vma + section->output_offset;
11254         }
11255       else if (h != NULL)
11256         {
11257           /* Setting the index to -2 tells elf_link_output_extsym that
11258              this symbol is used by a reloc.  */
11259           h->indx = -2;
11260           *rel_hash_ptr = h;
11261           indx = 0;
11262         }
11263       else
11264         {
11265           (*info->callbacks->unattached_reloc)
11266             (info, link_order->u.reloc.p->u.name, NULL, NULL, 0);
11267           indx = 0;
11268         }
11269     }
11270
11271   /* If this is an inplace reloc, we must write the addend into the
11272      object file.  */
11273   if (howto->partial_inplace && addend != 0)
11274     {
11275       bfd_size_type size;
11276       bfd_reloc_status_type rstat;
11277       bfd_byte *buf;
11278       bfd_boolean ok;
11279       const char *sym_name;
11280
11281       size = (bfd_size_type) bfd_get_reloc_size (howto);
11282       buf = (bfd_byte *) bfd_zmalloc (size);
11283       if (buf == NULL && size != 0)
11284         return FALSE;
11285       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
11286       switch (rstat)
11287         {
11288         case bfd_reloc_ok:
11289           break;
11290
11291         default:
11292         case bfd_reloc_outofrange:
11293           abort ();
11294
11295         case bfd_reloc_overflow:
11296           if (link_order->type == bfd_section_reloc_link_order)
11297             sym_name = bfd_section_name (output_bfd,
11298                                          link_order->u.reloc.p->u.section);
11299           else
11300             sym_name = link_order->u.reloc.p->u.name;
11301           (*info->callbacks->reloc_overflow) (info, NULL, sym_name,
11302                                               howto->name, addend, NULL, NULL,
11303                                               (bfd_vma) 0);
11304           break;
11305         }
11306
11307       ok = bfd_set_section_contents (output_bfd, output_section, buf,
11308                                      link_order->offset
11309                                      * bfd_octets_per_byte (output_bfd),
11310                                      size);
11311       free (buf);
11312       if (! ok)
11313         return FALSE;
11314     }
11315
11316   /* The address of a reloc is relative to the section in a
11317      relocatable file, and is a virtual address in an executable
11318      file.  */
11319   offset = link_order->offset;
11320   if (! bfd_link_relocatable (info))
11321     offset += output_section->vma;
11322
11323   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
11324     {
11325       irel[i].r_offset = offset;
11326       irel[i].r_info = 0;
11327       irel[i].r_addend = 0;
11328     }
11329   if (bed->s->arch_size == 32)
11330     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
11331   else
11332     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
11333
11334   rel_hdr = reldata->hdr;
11335   erel = rel_hdr->contents;
11336   if (rel_hdr->sh_type == SHT_REL)
11337     {
11338       erel += reldata->count * bed->s->sizeof_rel;
11339       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
11340     }
11341   else
11342     {
11343       irel[0].r_addend = addend;
11344       erel += reldata->count * bed->s->sizeof_rela;
11345       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
11346     }
11347
11348   ++reldata->count;
11349
11350   return TRUE;
11351 }
11352
11353
11354 /* Get the output vma of the section pointed to by the sh_link field.  */
11355
11356 static bfd_vma
11357 elf_get_linked_section_vma (struct bfd_link_order *p)
11358 {
11359   Elf_Internal_Shdr **elf_shdrp;
11360   asection *s;
11361   int elfsec;
11362
11363   s = p->u.indirect.section;
11364   elf_shdrp = elf_elfsections (s->owner);
11365   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
11366   elfsec = elf_shdrp[elfsec]->sh_link;
11367   /* PR 290:
11368      The Intel C compiler generates SHT_IA_64_UNWIND with
11369      SHF_LINK_ORDER.  But it doesn't set the sh_link or
11370      sh_info fields.  Hence we could get the situation
11371      where elfsec is 0.  */
11372   if (elfsec == 0)
11373     {
11374       const struct elf_backend_data *bed
11375         = get_elf_backend_data (s->owner);
11376       if (bed->link_order_error_handler)
11377         bed->link_order_error_handler
11378           /* xgettext:c-format */
11379           (_("%pB: warning: sh_link not set for section `%pA'"), s->owner, s);
11380       return 0;
11381     }
11382   else
11383     {
11384       s = elf_shdrp[elfsec]->bfd_section;
11385       return s->output_section->vma + s->output_offset;
11386     }
11387 }
11388
11389
11390 /* Compare two sections based on the locations of the sections they are
11391    linked to.  Used by elf_fixup_link_order.  */
11392
11393 static int
11394 compare_link_order (const void * a, const void * b)
11395 {
11396   bfd_vma apos;
11397   bfd_vma bpos;
11398
11399   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
11400   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
11401   if (apos < bpos)
11402     return -1;
11403   return apos > bpos;
11404 }
11405
11406
11407 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
11408    order as their linked sections.  Returns false if this could not be done
11409    because an output section includes both ordered and unordered
11410    sections.  Ideally we'd do this in the linker proper.  */
11411
11412 static bfd_boolean
11413 elf_fixup_link_order (bfd *abfd, asection *o)
11414 {
11415   int seen_linkorder;
11416   int seen_other;
11417   int n;
11418   struct bfd_link_order *p;
11419   bfd *sub;
11420   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11421   unsigned elfsec;
11422   struct bfd_link_order **sections;
11423   asection *s, *other_sec, *linkorder_sec;
11424   bfd_vma offset;
11425
11426   other_sec = NULL;
11427   linkorder_sec = NULL;
11428   seen_other = 0;
11429   seen_linkorder = 0;
11430   for (p = o->map_head.link_order; p != NULL; p = p->next)
11431     {
11432       if (p->type == bfd_indirect_link_order)
11433         {
11434           s = p->u.indirect.section;
11435           sub = s->owner;
11436           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11437               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
11438               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
11439               && elfsec < elf_numsections (sub)
11440               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
11441               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
11442             {
11443               seen_linkorder++;
11444               linkorder_sec = s;
11445             }
11446           else
11447             {
11448               seen_other++;
11449               other_sec = s;
11450             }
11451         }
11452       else
11453         seen_other++;
11454
11455       if (seen_other && seen_linkorder)
11456         {
11457           if (other_sec && linkorder_sec)
11458             _bfd_error_handler
11459               /* xgettext:c-format */
11460               (_("%pA has both ordered [`%pA' in %pB] "
11461                  "and unordered [`%pA' in %pB] sections"),
11462                o, linkorder_sec, linkorder_sec->owner,
11463                other_sec, other_sec->owner);
11464           else
11465             _bfd_error_handler
11466               (_("%pA has both ordered and unordered sections"), o);
11467           bfd_set_error (bfd_error_bad_value);
11468           return FALSE;
11469         }
11470     }
11471
11472   if (!seen_linkorder)
11473     return TRUE;
11474
11475   sections = (struct bfd_link_order **)
11476     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
11477   if (sections == NULL)
11478     return FALSE;
11479   seen_linkorder = 0;
11480
11481   for (p = o->map_head.link_order; p != NULL; p = p->next)
11482     {
11483       sections[seen_linkorder++] = p;
11484     }
11485   /* Sort the input sections in the order of their linked section.  */
11486   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
11487          compare_link_order);
11488
11489   /* Change the offsets of the sections.  */
11490   offset = 0;
11491   for (n = 0; n < seen_linkorder; n++)
11492     {
11493       s = sections[n]->u.indirect.section;
11494       offset &= ~(bfd_vma) 0 << s->alignment_power;
11495       s->output_offset = offset / bfd_octets_per_byte (abfd);
11496       sections[n]->offset = offset;
11497       offset += sections[n]->size;
11498     }
11499
11500   free (sections);
11501   return TRUE;
11502 }
11503
11504 /* Generate an import library in INFO->implib_bfd from symbols in ABFD.
11505    Returns TRUE upon success, FALSE otherwise.  */
11506
11507 static bfd_boolean
11508 elf_output_implib (bfd *abfd, struct bfd_link_info *info)
11509 {
11510   bfd_boolean ret = FALSE;
11511   bfd *implib_bfd;
11512   const struct elf_backend_data *bed;
11513   flagword flags;
11514   enum bfd_architecture arch;
11515   unsigned int mach;
11516   asymbol **sympp = NULL;
11517   long symsize;
11518   long symcount;
11519   long src_count;
11520   elf_symbol_type *osymbuf;
11521
11522   implib_bfd = info->out_implib_bfd;
11523   bed = get_elf_backend_data (abfd);
11524
11525   if (!bfd_set_format (implib_bfd, bfd_object))
11526     return FALSE;
11527
11528   /* Use flag from executable but make it a relocatable object.  */
11529   flags = bfd_get_file_flags (abfd);
11530   flags &= ~HAS_RELOC;
11531   if (!bfd_set_start_address (implib_bfd, 0)
11532       || !bfd_set_file_flags (implib_bfd, flags & ~EXEC_P))
11533     return FALSE;
11534
11535   /* Copy architecture of output file to import library file.  */
11536   arch = bfd_get_arch (abfd);
11537   mach = bfd_get_mach (abfd);
11538   if (!bfd_set_arch_mach (implib_bfd, arch, mach)
11539       && (abfd->target_defaulted
11540           || bfd_get_arch (abfd) != bfd_get_arch (implib_bfd)))
11541     return FALSE;
11542
11543   /* Get symbol table size.  */
11544   symsize = bfd_get_symtab_upper_bound (abfd);
11545   if (symsize < 0)
11546     return FALSE;
11547
11548   /* Read in the symbol table.  */
11549   sympp = (asymbol **) xmalloc (symsize);
11550   symcount = bfd_canonicalize_symtab (abfd, sympp);
11551   if (symcount < 0)
11552     goto free_sym_buf;
11553
11554   /* Allow the BFD backend to copy any private header data it
11555      understands from the output BFD to the import library BFD.  */
11556   if (! bfd_copy_private_header_data (abfd, implib_bfd))
11557     goto free_sym_buf;
11558
11559   /* Filter symbols to appear in the import library.  */
11560   if (bed->elf_backend_filter_implib_symbols)
11561     symcount = bed->elf_backend_filter_implib_symbols (abfd, info, sympp,
11562                                                        symcount);
11563   else
11564     symcount = _bfd_elf_filter_global_symbols (abfd, info, sympp, symcount);
11565   if (symcount == 0)
11566     {
11567       bfd_set_error (bfd_error_no_symbols);
11568       _bfd_error_handler (_("%pB: no symbol found for import library"),
11569                           implib_bfd);
11570       goto free_sym_buf;
11571     }
11572
11573
11574   /* Make symbols absolute.  */
11575   osymbuf = (elf_symbol_type *) bfd_alloc2 (implib_bfd, symcount,
11576                                             sizeof (*osymbuf));
11577   for (src_count = 0; src_count < symcount; src_count++)
11578     {
11579       memcpy (&osymbuf[src_count], (elf_symbol_type *) sympp[src_count],
11580               sizeof (*osymbuf));
11581       osymbuf[src_count].symbol.section = bfd_abs_section_ptr;
11582       osymbuf[src_count].internal_elf_sym.st_shndx = SHN_ABS;
11583       osymbuf[src_count].symbol.value += sympp[src_count]->section->vma;
11584       osymbuf[src_count].internal_elf_sym.st_value =
11585         osymbuf[src_count].symbol.value;
11586       sympp[src_count] = &osymbuf[src_count].symbol;
11587     }
11588
11589   bfd_set_symtab (implib_bfd, sympp, symcount);
11590
11591   /* Allow the BFD backend to copy any private data it understands
11592      from the output BFD to the import library BFD.  This is done last
11593      to permit the routine to look at the filtered symbol table.  */
11594   if (! bfd_copy_private_bfd_data (abfd, implib_bfd))
11595     goto free_sym_buf;
11596
11597   if (!bfd_close (implib_bfd))
11598     goto free_sym_buf;
11599
11600   ret = TRUE;
11601
11602 free_sym_buf:
11603   free (sympp);
11604   return ret;
11605 }
11606
11607 static void
11608 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
11609 {
11610   asection *o;
11611
11612   if (flinfo->symstrtab != NULL)
11613     _bfd_elf_strtab_free (flinfo->symstrtab);
11614   if (flinfo->contents != NULL)
11615     free (flinfo->contents);
11616   if (flinfo->external_relocs != NULL)
11617     free (flinfo->external_relocs);
11618   if (flinfo->internal_relocs != NULL)
11619     free (flinfo->internal_relocs);
11620   if (flinfo->external_syms != NULL)
11621     free (flinfo->external_syms);
11622   if (flinfo->locsym_shndx != NULL)
11623     free (flinfo->locsym_shndx);
11624   if (flinfo->internal_syms != NULL)
11625     free (flinfo->internal_syms);
11626   if (flinfo->indices != NULL)
11627     free (flinfo->indices);
11628   if (flinfo->sections != NULL)
11629     free (flinfo->sections);
11630   if (flinfo->symshndxbuf != NULL)
11631     free (flinfo->symshndxbuf);
11632   for (o = obfd->sections; o != NULL; o = o->next)
11633     {
11634       struct bfd_elf_section_data *esdo = elf_section_data (o);
11635       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11636         free (esdo->rel.hashes);
11637       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11638         free (esdo->rela.hashes);
11639     }
11640 }
11641
11642 /* Do the final step of an ELF link.  */
11643
11644 bfd_boolean
11645 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
11646 {
11647   bfd_boolean dynamic;
11648   bfd_boolean emit_relocs;
11649   bfd *dynobj;
11650   struct elf_final_link_info flinfo;
11651   asection *o;
11652   struct bfd_link_order *p;
11653   bfd *sub;
11654   bfd_size_type max_contents_size;
11655   bfd_size_type max_external_reloc_size;
11656   bfd_size_type max_internal_reloc_count;
11657   bfd_size_type max_sym_count;
11658   bfd_size_type max_sym_shndx_count;
11659   Elf_Internal_Sym elfsym;
11660   unsigned int i;
11661   Elf_Internal_Shdr *symtab_hdr;
11662   Elf_Internal_Shdr *symtab_shndx_hdr;
11663   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11664   struct elf_outext_info eoinfo;
11665   bfd_boolean merged;
11666   size_t relativecount = 0;
11667   asection *reldyn = 0;
11668   bfd_size_type amt;
11669   asection *attr_section = NULL;
11670   bfd_vma attr_size = 0;
11671   const char *std_attrs_section;
11672   struct elf_link_hash_table *htab = elf_hash_table (info);
11673
11674   if (!is_elf_hash_table (htab))
11675     return FALSE;
11676
11677   if (bfd_link_pic (info))
11678     abfd->flags |= DYNAMIC;
11679
11680   dynamic = htab->dynamic_sections_created;
11681   dynobj = htab->dynobj;
11682
11683   emit_relocs = (bfd_link_relocatable (info)
11684                  || info->emitrelocations);
11685
11686   flinfo.info = info;
11687   flinfo.output_bfd = abfd;
11688   flinfo.symstrtab = _bfd_elf_strtab_init ();
11689   if (flinfo.symstrtab == NULL)
11690     return FALSE;
11691
11692   if (! dynamic)
11693     {
11694       flinfo.hash_sec = NULL;
11695       flinfo.symver_sec = NULL;
11696     }
11697   else
11698     {
11699       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
11700       /* Note that dynsym_sec can be NULL (on VMS).  */
11701       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
11702       /* Note that it is OK if symver_sec is NULL.  */
11703     }
11704
11705   flinfo.contents = NULL;
11706   flinfo.external_relocs = NULL;
11707   flinfo.internal_relocs = NULL;
11708   flinfo.external_syms = NULL;
11709   flinfo.locsym_shndx = NULL;
11710   flinfo.internal_syms = NULL;
11711   flinfo.indices = NULL;
11712   flinfo.sections = NULL;
11713   flinfo.symshndxbuf = NULL;
11714   flinfo.filesym_count = 0;
11715
11716   /* The object attributes have been merged.  Remove the input
11717      sections from the link, and set the contents of the output
11718      secton.  */
11719   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
11720   for (o = abfd->sections; o != NULL; o = o->next)
11721     {
11722       bfd_boolean remove_section = FALSE;
11723
11724       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
11725           || strcmp (o->name, ".gnu.attributes") == 0)
11726         {
11727           for (p = o->map_head.link_order; p != NULL; p = p->next)
11728             {
11729               asection *input_section;
11730
11731               if (p->type != bfd_indirect_link_order)
11732                 continue;
11733               input_section = p->u.indirect.section;
11734               /* Hack: reset the SEC_HAS_CONTENTS flag so that
11735                  elf_link_input_bfd ignores this section.  */
11736               input_section->flags &= ~SEC_HAS_CONTENTS;
11737             }
11738
11739           attr_size = bfd_elf_obj_attr_size (abfd);
11740           bfd_set_section_size (abfd, o, attr_size);
11741           /* Skip this section later on.  */
11742           o->map_head.link_order = NULL;
11743           if (attr_size)
11744             attr_section = o;
11745           else
11746             remove_section = TRUE;
11747         }
11748       else if ((o->flags & SEC_GROUP) != 0 && o->size == 0)
11749         {
11750           /* Remove empty group section from linker output.  */
11751           remove_section = TRUE;
11752         }
11753       if (remove_section)
11754         {
11755           o->flags |= SEC_EXCLUDE;
11756           bfd_section_list_remove (abfd, o);
11757           abfd->section_count--;
11758         }
11759     }
11760
11761   /* Count up the number of relocations we will output for each output
11762      section, so that we know the sizes of the reloc sections.  We
11763      also figure out some maximum sizes.  */
11764   max_contents_size = 0;
11765   max_external_reloc_size = 0;
11766   max_internal_reloc_count = 0;
11767   max_sym_count = 0;
11768   max_sym_shndx_count = 0;
11769   merged = FALSE;
11770   for (o = abfd->sections; o != NULL; o = o->next)
11771     {
11772       struct bfd_elf_section_data *esdo = elf_section_data (o);
11773       o->reloc_count = 0;
11774
11775       for (p = o->map_head.link_order; p != NULL; p = p->next)
11776         {
11777           unsigned int reloc_count = 0;
11778           unsigned int additional_reloc_count = 0;
11779           struct bfd_elf_section_data *esdi = NULL;
11780
11781           if (p->type == bfd_section_reloc_link_order
11782               || p->type == bfd_symbol_reloc_link_order)
11783             reloc_count = 1;
11784           else if (p->type == bfd_indirect_link_order)
11785             {
11786               asection *sec;
11787
11788               sec = p->u.indirect.section;
11789
11790               /* Mark all sections which are to be included in the
11791                  link.  This will normally be every section.  We need
11792                  to do this so that we can identify any sections which
11793                  the linker has decided to not include.  */
11794               sec->linker_mark = TRUE;
11795
11796               if (sec->flags & SEC_MERGE)
11797                 merged = TRUE;
11798
11799               if (sec->rawsize > max_contents_size)
11800                 max_contents_size = sec->rawsize;
11801               if (sec->size > max_contents_size)
11802                 max_contents_size = sec->size;
11803
11804               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
11805                   && (sec->owner->flags & DYNAMIC) == 0)
11806                 {
11807                   size_t sym_count;
11808
11809                   /* We are interested in just local symbols, not all
11810                      symbols.  */
11811                   if (elf_bad_symtab (sec->owner))
11812                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
11813                                  / bed->s->sizeof_sym);
11814                   else
11815                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
11816
11817                   if (sym_count > max_sym_count)
11818                     max_sym_count = sym_count;
11819
11820                   if (sym_count > max_sym_shndx_count
11821                       && elf_symtab_shndx_list (sec->owner) != NULL)
11822                     max_sym_shndx_count = sym_count;
11823
11824                   if (esdo->this_hdr.sh_type == SHT_REL
11825                       || esdo->this_hdr.sh_type == SHT_RELA)
11826                     /* Some backends use reloc_count in relocation sections
11827                        to count particular types of relocs.  Of course,
11828                        reloc sections themselves can't have relocations.  */
11829                     ;
11830                   else if (emit_relocs)
11831                     {
11832                       reloc_count = sec->reloc_count;
11833                       if (bed->elf_backend_count_additional_relocs)
11834                         {
11835                           int c;
11836                           c = (*bed->elf_backend_count_additional_relocs) (sec);
11837                           additional_reloc_count += c;
11838                         }
11839                     }
11840                   else if (bed->elf_backend_count_relocs)
11841                     reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
11842
11843                   esdi = elf_section_data (sec);
11844
11845                   if ((sec->flags & SEC_RELOC) != 0)
11846                     {
11847                       size_t ext_size = 0;
11848
11849                       if (esdi->rel.hdr != NULL)
11850                         ext_size = esdi->rel.hdr->sh_size;
11851                       if (esdi->rela.hdr != NULL)
11852                         ext_size += esdi->rela.hdr->sh_size;
11853
11854                       if (ext_size > max_external_reloc_size)
11855                         max_external_reloc_size = ext_size;
11856                       if (sec->reloc_count > max_internal_reloc_count)
11857                         max_internal_reloc_count = sec->reloc_count;
11858                     }
11859                 }
11860             }
11861
11862           if (reloc_count == 0)
11863             continue;
11864
11865           reloc_count += additional_reloc_count;
11866           o->reloc_count += reloc_count;
11867
11868           if (p->type == bfd_indirect_link_order && emit_relocs)
11869             {
11870               if (esdi->rel.hdr)
11871                 {
11872                   esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11873                   esdo->rel.count += additional_reloc_count;
11874                 }
11875               if (esdi->rela.hdr)
11876                 {
11877                   esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11878                   esdo->rela.count += additional_reloc_count;
11879                 }
11880             }
11881           else
11882             {
11883               if (o->use_rela_p)
11884                 esdo->rela.count += reloc_count;
11885               else
11886                 esdo->rel.count += reloc_count;
11887             }
11888         }
11889
11890       if (o->reloc_count > 0)
11891         o->flags |= SEC_RELOC;
11892       else
11893         {
11894           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11895              set it (this is probably a bug) and if it is set
11896              assign_section_numbers will create a reloc section.  */
11897           o->flags &=~ SEC_RELOC;
11898         }
11899
11900       /* If the SEC_ALLOC flag is not set, force the section VMA to
11901          zero.  This is done in elf_fake_sections as well, but forcing
11902          the VMA to 0 here will ensure that relocs against these
11903          sections are handled correctly.  */
11904       if ((o->flags & SEC_ALLOC) == 0
11905           && ! o->user_set_vma)
11906         o->vma = 0;
11907     }
11908
11909   if (! bfd_link_relocatable (info) && merged)
11910     elf_link_hash_traverse (htab, _bfd_elf_link_sec_merge_syms, abfd);
11911
11912   /* Figure out the file positions for everything but the symbol table
11913      and the relocs.  We set symcount to force assign_section_numbers
11914      to create a symbol table.  */
11915   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11916   BFD_ASSERT (! abfd->output_has_begun);
11917   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11918     goto error_return;
11919
11920   /* Set sizes, and assign file positions for reloc sections.  */
11921   for (o = abfd->sections; o != NULL; o = o->next)
11922     {
11923       struct bfd_elf_section_data *esdo = elf_section_data (o);
11924       if ((o->flags & SEC_RELOC) != 0)
11925         {
11926           if (esdo->rel.hdr
11927               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11928             goto error_return;
11929
11930           if (esdo->rela.hdr
11931               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11932             goto error_return;
11933         }
11934
11935       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
11936          to count upwards while actually outputting the relocations.  */
11937       esdo->rel.count = 0;
11938       esdo->rela.count = 0;
11939
11940       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
11941         {
11942           /* Cache the section contents so that they can be compressed
11943              later.  Use bfd_malloc since it will be freed by
11944              bfd_compress_section_contents.  */
11945           unsigned char *contents = esdo->this_hdr.contents;
11946           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
11947             abort ();
11948           contents
11949             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
11950           if (contents == NULL)
11951             goto error_return;
11952           esdo->this_hdr.contents = contents;
11953         }
11954     }
11955
11956   /* We have now assigned file positions for all the sections except
11957      .symtab, .strtab, and non-loaded reloc sections.  We start the
11958      .symtab section at the current file position, and write directly
11959      to it.  We build the .strtab section in memory.  */
11960   bfd_get_symcount (abfd) = 0;
11961   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11962   /* sh_name is set in prep_headers.  */
11963   symtab_hdr->sh_type = SHT_SYMTAB;
11964   /* sh_flags, sh_addr and sh_size all start off zero.  */
11965   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
11966   /* sh_link is set in assign_section_numbers.  */
11967   /* sh_info is set below.  */
11968   /* sh_offset is set just below.  */
11969   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
11970
11971   if (max_sym_count < 20)
11972     max_sym_count = 20;
11973   htab->strtabsize = max_sym_count;
11974   amt = max_sym_count * sizeof (struct elf_sym_strtab);
11975   htab->strtab = (struct elf_sym_strtab *) bfd_malloc (amt);
11976   if (htab->strtab == NULL)
11977     goto error_return;
11978   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
11979   flinfo.symshndxbuf
11980     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
11981        ? (Elf_External_Sym_Shndx *) -1 : NULL);
11982
11983   if (info->strip != strip_all || emit_relocs)
11984     {
11985       file_ptr off = elf_next_file_pos (abfd);
11986
11987       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
11988
11989       /* Note that at this point elf_next_file_pos (abfd) is
11990          incorrect.  We do not yet know the size of the .symtab section.
11991          We correct next_file_pos below, after we do know the size.  */
11992
11993       /* Start writing out the symbol table.  The first symbol is always a
11994          dummy symbol.  */
11995       elfsym.st_value = 0;
11996       elfsym.st_size = 0;
11997       elfsym.st_info = 0;
11998       elfsym.st_other = 0;
11999       elfsym.st_shndx = SHN_UNDEF;
12000       elfsym.st_target_internal = 0;
12001       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
12002                                      bfd_und_section_ptr, NULL) != 1)
12003         goto error_return;
12004
12005       /* Output a symbol for each section.  We output these even if we are
12006          discarding local symbols, since they are used for relocs.  These
12007          symbols have no names.  We store the index of each one in the
12008          index field of the section, so that we can find it again when
12009          outputting relocs.  */
12010
12011       elfsym.st_size = 0;
12012       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
12013       elfsym.st_other = 0;
12014       elfsym.st_value = 0;
12015       elfsym.st_target_internal = 0;
12016       for (i = 1; i < elf_numsections (abfd); i++)
12017         {
12018           o = bfd_section_from_elf_index (abfd, i);
12019           if (o != NULL)
12020             {
12021               o->target_index = bfd_get_symcount (abfd);
12022               elfsym.st_shndx = i;
12023               if (!bfd_link_relocatable (info))
12024                 elfsym.st_value = o->vma;
12025               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
12026                                              NULL) != 1)
12027                 goto error_return;
12028             }
12029         }
12030     }
12031
12032   /* Allocate some memory to hold information read in from the input
12033      files.  */
12034   if (max_contents_size != 0)
12035     {
12036       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
12037       if (flinfo.contents == NULL)
12038         goto error_return;
12039     }
12040
12041   if (max_external_reloc_size != 0)
12042     {
12043       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
12044       if (flinfo.external_relocs == NULL)
12045         goto error_return;
12046     }
12047
12048   if (max_internal_reloc_count != 0)
12049     {
12050       amt = max_internal_reloc_count * sizeof (Elf_Internal_Rela);
12051       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
12052       if (flinfo.internal_relocs == NULL)
12053         goto error_return;
12054     }
12055
12056   if (max_sym_count != 0)
12057     {
12058       amt = max_sym_count * bed->s->sizeof_sym;
12059       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
12060       if (flinfo.external_syms == NULL)
12061         goto error_return;
12062
12063       amt = max_sym_count * sizeof (Elf_Internal_Sym);
12064       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
12065       if (flinfo.internal_syms == NULL)
12066         goto error_return;
12067
12068       amt = max_sym_count * sizeof (long);
12069       flinfo.indices = (long int *) bfd_malloc (amt);
12070       if (flinfo.indices == NULL)
12071         goto error_return;
12072
12073       amt = max_sym_count * sizeof (asection *);
12074       flinfo.sections = (asection **) bfd_malloc (amt);
12075       if (flinfo.sections == NULL)
12076         goto error_return;
12077     }
12078
12079   if (max_sym_shndx_count != 0)
12080     {
12081       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
12082       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
12083       if (flinfo.locsym_shndx == NULL)
12084         goto error_return;
12085     }
12086
12087   if (htab->tls_sec)
12088     {
12089       bfd_vma base, end = 0;
12090       asection *sec;
12091
12092       for (sec = htab->tls_sec;
12093            sec && (sec->flags & SEC_THREAD_LOCAL);
12094            sec = sec->next)
12095         {
12096           bfd_size_type size = sec->size;
12097
12098           if (size == 0
12099               && (sec->flags & SEC_HAS_CONTENTS) == 0)
12100             {
12101               struct bfd_link_order *ord = sec->map_tail.link_order;
12102
12103               if (ord != NULL)
12104                 size = ord->offset + ord->size;
12105             }
12106           end = sec->vma + size;
12107         }
12108       base = htab->tls_sec->vma;
12109       /* Only align end of TLS section if static TLS doesn't have special
12110          alignment requirements.  */
12111       if (bed->static_tls_alignment == 1)
12112         end = align_power (end, htab->tls_sec->alignment_power);
12113       htab->tls_size = end - base;
12114     }
12115
12116   /* Reorder SHF_LINK_ORDER sections.  */
12117   for (o = abfd->sections; o != NULL; o = o->next)
12118     {
12119       if (!elf_fixup_link_order (abfd, o))
12120         return FALSE;
12121     }
12122
12123   if (!_bfd_elf_fixup_eh_frame_hdr (info))
12124     return FALSE;
12125
12126   /* Since ELF permits relocations to be against local symbols, we
12127      must have the local symbols available when we do the relocations.
12128      Since we would rather only read the local symbols once, and we
12129      would rather not keep them in memory, we handle all the
12130      relocations for a single input file at the same time.
12131
12132      Unfortunately, there is no way to know the total number of local
12133      symbols until we have seen all of them, and the local symbol
12134      indices precede the global symbol indices.  This means that when
12135      we are generating relocatable output, and we see a reloc against
12136      a global symbol, we can not know the symbol index until we have
12137      finished examining all the local symbols to see which ones we are
12138      going to output.  To deal with this, we keep the relocations in
12139      memory, and don't output them until the end of the link.  This is
12140      an unfortunate waste of memory, but I don't see a good way around
12141      it.  Fortunately, it only happens when performing a relocatable
12142      link, which is not the common case.  FIXME: If keep_memory is set
12143      we could write the relocs out and then read them again; I don't
12144      know how bad the memory loss will be.  */
12145
12146   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12147     sub->output_has_begun = FALSE;
12148   for (o = abfd->sections; o != NULL; o = o->next)
12149     {
12150       for (p = o->map_head.link_order; p != NULL; p = p->next)
12151         {
12152           if (p->type == bfd_indirect_link_order
12153               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
12154                   == bfd_target_elf_flavour)
12155               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
12156             {
12157               if (! sub->output_has_begun)
12158                 {
12159                   if (! elf_link_input_bfd (&flinfo, sub))
12160                     goto error_return;
12161                   sub->output_has_begun = TRUE;
12162                 }
12163             }
12164           else if (p->type == bfd_section_reloc_link_order
12165                    || p->type == bfd_symbol_reloc_link_order)
12166             {
12167               if (! elf_reloc_link_order (abfd, info, o, p))
12168                 goto error_return;
12169             }
12170           else
12171             {
12172               if (! _bfd_default_link_order (abfd, info, o, p))
12173                 {
12174                   if (p->type == bfd_indirect_link_order
12175                       && (bfd_get_flavour (sub)
12176                           == bfd_target_elf_flavour)
12177                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
12178                           != bed->s->elfclass))
12179                     {
12180                       const char *iclass, *oclass;
12181
12182                       switch (bed->s->elfclass)
12183                         {
12184                         case ELFCLASS64: oclass = "ELFCLASS64"; break;
12185                         case ELFCLASS32: oclass = "ELFCLASS32"; break;
12186                         case ELFCLASSNONE: oclass = "ELFCLASSNONE"; break;
12187                         default: abort ();
12188                         }
12189
12190                       switch (elf_elfheader (sub)->e_ident[EI_CLASS])
12191                         {
12192                         case ELFCLASS64: iclass = "ELFCLASS64"; break;
12193                         case ELFCLASS32: iclass = "ELFCLASS32"; break;
12194                         case ELFCLASSNONE: iclass = "ELFCLASSNONE"; break;
12195                         default: abort ();
12196                         }
12197
12198                       bfd_set_error (bfd_error_wrong_format);
12199                       _bfd_error_handler
12200                         /* xgettext:c-format */
12201                         (_("%pB: file class %s incompatible with %s"),
12202                          sub, iclass, oclass);
12203                     }
12204
12205                   goto error_return;
12206                 }
12207             }
12208         }
12209     }
12210
12211   /* Free symbol buffer if needed.  */
12212   if (!info->reduce_memory_overheads)
12213     {
12214       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12215         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
12216             && elf_tdata (sub)->symbuf)
12217           {
12218             free (elf_tdata (sub)->symbuf);
12219             elf_tdata (sub)->symbuf = NULL;
12220           }
12221     }
12222
12223   /* Output any global symbols that got converted to local in a
12224      version script or due to symbol visibility.  We do this in a
12225      separate step since ELF requires all local symbols to appear
12226      prior to any global symbols.  FIXME: We should only do this if
12227      some global symbols were, in fact, converted to become local.
12228      FIXME: Will this work correctly with the Irix 5 linker?  */
12229   eoinfo.failed = FALSE;
12230   eoinfo.flinfo = &flinfo;
12231   eoinfo.localsyms = TRUE;
12232   eoinfo.file_sym_done = FALSE;
12233   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12234   if (eoinfo.failed)
12235     return FALSE;
12236
12237   /* If backend needs to output some local symbols not present in the hash
12238      table, do it now.  */
12239   if (bed->elf_backend_output_arch_local_syms
12240       && (info->strip != strip_all || emit_relocs))
12241     {
12242       typedef int (*out_sym_func)
12243         (void *, const char *, Elf_Internal_Sym *, asection *,
12244          struct elf_link_hash_entry *);
12245
12246       if (! ((*bed->elf_backend_output_arch_local_syms)
12247              (abfd, info, &flinfo,
12248               (out_sym_func) elf_link_output_symstrtab)))
12249         return FALSE;
12250     }
12251
12252   /* That wrote out all the local symbols.  Finish up the symbol table
12253      with the global symbols. Even if we want to strip everything we
12254      can, we still need to deal with those global symbols that got
12255      converted to local in a version script.  */
12256
12257   /* The sh_info field records the index of the first non local symbol.  */
12258   symtab_hdr->sh_info = bfd_get_symcount (abfd);
12259
12260   if (dynamic
12261       && htab->dynsym != NULL
12262       && htab->dynsym->output_section != bfd_abs_section_ptr)
12263     {
12264       Elf_Internal_Sym sym;
12265       bfd_byte *dynsym = htab->dynsym->contents;
12266
12267       o = htab->dynsym->output_section;
12268       elf_section_data (o)->this_hdr.sh_info = htab->local_dynsymcount + 1;
12269
12270       /* Write out the section symbols for the output sections.  */
12271       if (bfd_link_pic (info)
12272           || htab->is_relocatable_executable)
12273         {
12274           asection *s;
12275
12276           sym.st_size = 0;
12277           sym.st_name = 0;
12278           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
12279           sym.st_other = 0;
12280           sym.st_target_internal = 0;
12281
12282           for (s = abfd->sections; s != NULL; s = s->next)
12283             {
12284               int indx;
12285               bfd_byte *dest;
12286               long dynindx;
12287
12288               dynindx = elf_section_data (s)->dynindx;
12289               if (dynindx <= 0)
12290                 continue;
12291               indx = elf_section_data (s)->this_idx;
12292               BFD_ASSERT (indx > 0);
12293               sym.st_shndx = indx;
12294               if (! check_dynsym (abfd, &sym))
12295                 return FALSE;
12296               sym.st_value = s->vma;
12297               dest = dynsym + dynindx * bed->s->sizeof_sym;
12298               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12299             }
12300         }
12301
12302       /* Write out the local dynsyms.  */
12303       if (htab->dynlocal)
12304         {
12305           struct elf_link_local_dynamic_entry *e;
12306           for (e = htab->dynlocal; e ; e = e->next)
12307             {
12308               asection *s;
12309               bfd_byte *dest;
12310
12311               /* Copy the internal symbol and turn off visibility.
12312                  Note that we saved a word of storage and overwrote
12313                  the original st_name with the dynstr_index.  */
12314               sym = e->isym;
12315               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
12316
12317               s = bfd_section_from_elf_index (e->input_bfd,
12318                                               e->isym.st_shndx);
12319               if (s != NULL)
12320                 {
12321                   sym.st_shndx =
12322                     elf_section_data (s->output_section)->this_idx;
12323                   if (! check_dynsym (abfd, &sym))
12324                     return FALSE;
12325                   sym.st_value = (s->output_section->vma
12326                                   + s->output_offset
12327                                   + e->isym.st_value);
12328                 }
12329
12330               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
12331               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12332             }
12333         }
12334     }
12335
12336   /* We get the global symbols from the hash table.  */
12337   eoinfo.failed = FALSE;
12338   eoinfo.localsyms = FALSE;
12339   eoinfo.flinfo = &flinfo;
12340   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12341   if (eoinfo.failed)
12342     return FALSE;
12343
12344   /* If backend needs to output some symbols not present in the hash
12345      table, do it now.  */
12346   if (bed->elf_backend_output_arch_syms
12347       && (info->strip != strip_all || emit_relocs))
12348     {
12349       typedef int (*out_sym_func)
12350         (void *, const char *, Elf_Internal_Sym *, asection *,
12351          struct elf_link_hash_entry *);
12352
12353       if (! ((*bed->elf_backend_output_arch_syms)
12354              (abfd, info, &flinfo,
12355               (out_sym_func) elf_link_output_symstrtab)))
12356         return FALSE;
12357     }
12358
12359   /* Finalize the .strtab section.  */
12360   _bfd_elf_strtab_finalize (flinfo.symstrtab);
12361
12362   /* Swap out the .strtab section. */
12363   if (!elf_link_swap_symbols_out (&flinfo))
12364     return FALSE;
12365
12366   /* Now we know the size of the symtab section.  */
12367   if (bfd_get_symcount (abfd) > 0)
12368     {
12369       /* Finish up and write out the symbol string table (.strtab)
12370          section.  */
12371       Elf_Internal_Shdr *symstrtab_hdr = NULL;
12372       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
12373
12374       if (elf_symtab_shndx_list (abfd))
12375         {
12376           symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
12377
12378           if (symtab_shndx_hdr != NULL && symtab_shndx_hdr->sh_name != 0)
12379             {
12380               symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
12381               symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
12382               symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
12383               amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
12384               symtab_shndx_hdr->sh_size = amt;
12385
12386               off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
12387                                                                off, TRUE);
12388
12389               if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
12390                   || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
12391                 return FALSE;
12392             }
12393         }
12394
12395       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
12396       /* sh_name was set in prep_headers.  */
12397       symstrtab_hdr->sh_type = SHT_STRTAB;
12398       symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
12399       symstrtab_hdr->sh_addr = 0;
12400       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
12401       symstrtab_hdr->sh_entsize = 0;
12402       symstrtab_hdr->sh_link = 0;
12403       symstrtab_hdr->sh_info = 0;
12404       /* sh_offset is set just below.  */
12405       symstrtab_hdr->sh_addralign = 1;
12406
12407       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
12408                                                        off, TRUE);
12409       elf_next_file_pos (abfd) = off;
12410
12411       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
12412           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
12413         return FALSE;
12414     }
12415
12416   if (info->out_implib_bfd && !elf_output_implib (abfd, info))
12417     {
12418       _bfd_error_handler (_("%pB: failed to generate import library"),
12419                           info->out_implib_bfd);
12420       return FALSE;
12421     }
12422
12423   /* Adjust the relocs to have the correct symbol indices.  */
12424   for (o = abfd->sections; o != NULL; o = o->next)
12425     {
12426       struct bfd_elf_section_data *esdo = elf_section_data (o);
12427       bfd_boolean sort;
12428
12429       if ((o->flags & SEC_RELOC) == 0)
12430         continue;
12431
12432       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
12433       if (esdo->rel.hdr != NULL
12434           && !elf_link_adjust_relocs (abfd, o, &esdo->rel, sort, info))
12435         return FALSE;
12436       if (esdo->rela.hdr != NULL
12437           && !elf_link_adjust_relocs (abfd, o, &esdo->rela, sort, info))
12438         return FALSE;
12439
12440       /* Set the reloc_count field to 0 to prevent write_relocs from
12441          trying to swap the relocs out itself.  */
12442       o->reloc_count = 0;
12443     }
12444
12445   if (dynamic && info->combreloc && dynobj != NULL)
12446     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
12447
12448   /* If we are linking against a dynamic object, or generating a
12449      shared library, finish up the dynamic linking information.  */
12450   if (dynamic)
12451     {
12452       bfd_byte *dyncon, *dynconend;
12453
12454       /* Fix up .dynamic entries.  */
12455       o = bfd_get_linker_section (dynobj, ".dynamic");
12456       BFD_ASSERT (o != NULL);
12457
12458       dyncon = o->contents;
12459       dynconend = o->contents + o->size;
12460       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12461         {
12462           Elf_Internal_Dyn dyn;
12463           const char *name;
12464           unsigned int type;
12465           bfd_size_type sh_size;
12466           bfd_vma sh_addr;
12467
12468           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12469
12470           switch (dyn.d_tag)
12471             {
12472             default:
12473               continue;
12474             case DT_NULL:
12475               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
12476                 {
12477                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
12478                     {
12479                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
12480                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
12481                     default: continue;
12482                     }
12483                   dyn.d_un.d_val = relativecount;
12484                   relativecount = 0;
12485                   break;
12486                 }
12487               continue;
12488
12489             case DT_INIT:
12490               name = info->init_function;
12491               goto get_sym;
12492             case DT_FINI:
12493               name = info->fini_function;
12494             get_sym:
12495               {
12496                 struct elf_link_hash_entry *h;
12497
12498                 h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
12499                 if (h != NULL
12500                     && (h->root.type == bfd_link_hash_defined
12501                         || h->root.type == bfd_link_hash_defweak))
12502                   {
12503                     dyn.d_un.d_ptr = h->root.u.def.value;
12504                     o = h->root.u.def.section;
12505                     if (o->output_section != NULL)
12506                       dyn.d_un.d_ptr += (o->output_section->vma
12507                                          + o->output_offset);
12508                     else
12509                       {
12510                         /* The symbol is imported from another shared
12511                            library and does not apply to this one.  */
12512                         dyn.d_un.d_ptr = 0;
12513                       }
12514                     break;
12515                   }
12516               }
12517               continue;
12518
12519             case DT_PREINIT_ARRAYSZ:
12520               name = ".preinit_array";
12521               goto get_out_size;
12522             case DT_INIT_ARRAYSZ:
12523               name = ".init_array";
12524               goto get_out_size;
12525             case DT_FINI_ARRAYSZ:
12526               name = ".fini_array";
12527             get_out_size:
12528               o = bfd_get_section_by_name (abfd, name);
12529               if (o == NULL)
12530                 {
12531                   _bfd_error_handler
12532                     (_("could not find section %s"), name);
12533                   goto error_return;
12534                 }
12535               if (o->size == 0)
12536                 _bfd_error_handler
12537                   (_("warning: %s section has zero size"), name);
12538               dyn.d_un.d_val = o->size;
12539               break;
12540
12541             case DT_PREINIT_ARRAY:
12542               name = ".preinit_array";
12543               goto get_out_vma;
12544             case DT_INIT_ARRAY:
12545               name = ".init_array";
12546               goto get_out_vma;
12547             case DT_FINI_ARRAY:
12548               name = ".fini_array";
12549             get_out_vma:
12550               o = bfd_get_section_by_name (abfd, name);
12551               goto do_vma;
12552
12553             case DT_HASH:
12554               name = ".hash";
12555               goto get_vma;
12556             case DT_GNU_HASH:
12557               name = ".gnu.hash";
12558               goto get_vma;
12559             case DT_STRTAB:
12560               name = ".dynstr";
12561               goto get_vma;
12562             case DT_SYMTAB:
12563               name = ".dynsym";
12564               goto get_vma;
12565             case DT_VERDEF:
12566               name = ".gnu.version_d";
12567               goto get_vma;
12568             case DT_VERNEED:
12569               name = ".gnu.version_r";
12570               goto get_vma;
12571             case DT_VERSYM:
12572               name = ".gnu.version";
12573             get_vma:
12574               o = bfd_get_linker_section (dynobj, name);
12575             do_vma:
12576               if (o == NULL || bfd_is_abs_section (o->output_section))
12577                 {
12578                   _bfd_error_handler
12579                     (_("could not find section %s"), name);
12580                   goto error_return;
12581                 }
12582               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
12583                 {
12584                   _bfd_error_handler
12585                     (_("warning: section '%s' is being made into a note"), name);
12586                   bfd_set_error (bfd_error_nonrepresentable_section);
12587                   goto error_return;
12588                 }
12589               dyn.d_un.d_ptr = o->output_section->vma + o->output_offset;
12590               break;
12591
12592             case DT_REL:
12593             case DT_RELA:
12594             case DT_RELSZ:
12595             case DT_RELASZ:
12596               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
12597                 type = SHT_REL;
12598               else
12599                 type = SHT_RELA;
12600               sh_size = 0;
12601               sh_addr = 0;
12602               for (i = 1; i < elf_numsections (abfd); i++)
12603                 {
12604                   Elf_Internal_Shdr *hdr;
12605
12606                   hdr = elf_elfsections (abfd)[i];
12607                   if (hdr->sh_type == type
12608                       && (hdr->sh_flags & SHF_ALLOC) != 0)
12609                     {
12610                       sh_size += hdr->sh_size;
12611                       if (sh_addr == 0
12612                           || sh_addr > hdr->sh_addr)
12613                         sh_addr = hdr->sh_addr;
12614                     }
12615                 }
12616
12617               if (bed->dtrel_excludes_plt && htab->srelplt != NULL)
12618                 {
12619                   /* Don't count procedure linkage table relocs in the
12620                      overall reloc count.  */
12621                   sh_size -= htab->srelplt->size;
12622                   if (sh_size == 0)
12623                     /* If the size is zero, make the address zero too.
12624                        This is to avoid a glibc bug.  If the backend
12625                        emits DT_RELA/DT_RELASZ even when DT_RELASZ is
12626                        zero, then we'll put DT_RELA at the end of
12627                        DT_JMPREL.  glibc will interpret the end of
12628                        DT_RELA matching the end of DT_JMPREL as the
12629                        case where DT_RELA includes DT_JMPREL, and for
12630                        LD_BIND_NOW will decide that processing DT_RELA
12631                        will process the PLT relocs too.  Net result:
12632                        No PLT relocs applied.  */
12633                     sh_addr = 0;
12634
12635                   /* If .rela.plt is the first .rela section, exclude
12636                      it from DT_RELA.  */
12637                   else if (sh_addr == (htab->srelplt->output_section->vma
12638                                        + htab->srelplt->output_offset))
12639                     sh_addr += htab->srelplt->size;
12640                 }
12641
12642               if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
12643                 dyn.d_un.d_val = sh_size;
12644               else
12645                 dyn.d_un.d_ptr = sh_addr;
12646               break;
12647             }
12648           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
12649         }
12650     }
12651
12652   /* If we have created any dynamic sections, then output them.  */
12653   if (dynobj != NULL)
12654     {
12655       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
12656         goto error_return;
12657
12658       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
12659       if (((info->warn_shared_textrel && bfd_link_pic (info))
12660            || info->error_textrel)
12661           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
12662         {
12663           bfd_byte *dyncon, *dynconend;
12664
12665           dyncon = o->contents;
12666           dynconend = o->contents + o->size;
12667           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12668             {
12669               Elf_Internal_Dyn dyn;
12670
12671               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12672
12673               if (dyn.d_tag == DT_TEXTREL)
12674                 {
12675                   if (info->error_textrel)
12676                     info->callbacks->einfo
12677                       (_("%P%X: read-only segment has dynamic relocations\n"));
12678                   else
12679                     info->callbacks->einfo
12680                       (_("%P: warning: creating a DT_TEXTREL in a shared object\n"));
12681                   break;
12682                 }
12683             }
12684         }
12685
12686       for (o = dynobj->sections; o != NULL; o = o->next)
12687         {
12688           if ((o->flags & SEC_HAS_CONTENTS) == 0
12689               || o->size == 0
12690               || o->output_section == bfd_abs_section_ptr)
12691             continue;
12692           if ((o->flags & SEC_LINKER_CREATED) == 0)
12693             {
12694               /* At this point, we are only interested in sections
12695                  created by _bfd_elf_link_create_dynamic_sections.  */
12696               continue;
12697             }
12698           if (htab->stab_info.stabstr == o)
12699             continue;
12700           if (htab->eh_info.hdr_sec == o)
12701             continue;
12702           if (strcmp (o->name, ".dynstr") != 0)
12703             {
12704               if (! bfd_set_section_contents (abfd, o->output_section,
12705                                               o->contents,
12706                                               (file_ptr) o->output_offset
12707                                               * bfd_octets_per_byte (abfd),
12708                                               o->size))
12709                 goto error_return;
12710             }
12711           else
12712             {
12713               /* The contents of the .dynstr section are actually in a
12714                  stringtab.  */
12715               file_ptr off;
12716
12717               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
12718               if (bfd_seek (abfd, off, SEEK_SET) != 0
12719                   || !_bfd_elf_strtab_emit (abfd, htab->dynstr))
12720                 goto error_return;
12721             }
12722         }
12723     }
12724
12725   if (!info->resolve_section_groups)
12726     {
12727       bfd_boolean failed = FALSE;
12728
12729       BFD_ASSERT (bfd_link_relocatable (info));
12730       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
12731       if (failed)
12732         goto error_return;
12733     }
12734
12735   /* If we have optimized stabs strings, output them.  */
12736   if (htab->stab_info.stabstr != NULL)
12737     {
12738       if (!_bfd_write_stab_strings (abfd, &htab->stab_info))
12739         goto error_return;
12740     }
12741
12742   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
12743     goto error_return;
12744
12745   elf_final_link_free (abfd, &flinfo);
12746
12747   elf_linker (abfd) = TRUE;
12748
12749   if (attr_section)
12750     {
12751       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
12752       if (contents == NULL)
12753         return FALSE;   /* Bail out and fail.  */
12754       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
12755       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
12756       free (contents);
12757     }
12758
12759   return TRUE;
12760
12761  error_return:
12762   elf_final_link_free (abfd, &flinfo);
12763   return FALSE;
12764 }
12765 \f
12766 /* Initialize COOKIE for input bfd ABFD.  */
12767
12768 static bfd_boolean
12769 init_reloc_cookie (struct elf_reloc_cookie *cookie,
12770                    struct bfd_link_info *info, bfd *abfd)
12771 {
12772   Elf_Internal_Shdr *symtab_hdr;
12773   const struct elf_backend_data *bed;
12774
12775   bed = get_elf_backend_data (abfd);
12776   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12777
12778   cookie->abfd = abfd;
12779   cookie->sym_hashes = elf_sym_hashes (abfd);
12780   cookie->bad_symtab = elf_bad_symtab (abfd);
12781   if (cookie->bad_symtab)
12782     {
12783       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12784       cookie->extsymoff = 0;
12785     }
12786   else
12787     {
12788       cookie->locsymcount = symtab_hdr->sh_info;
12789       cookie->extsymoff = symtab_hdr->sh_info;
12790     }
12791
12792   if (bed->s->arch_size == 32)
12793     cookie->r_sym_shift = 8;
12794   else
12795     cookie->r_sym_shift = 32;
12796
12797   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
12798   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
12799     {
12800       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12801                                               cookie->locsymcount, 0,
12802                                               NULL, NULL, NULL);
12803       if (cookie->locsyms == NULL)
12804         {
12805           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
12806           return FALSE;
12807         }
12808       if (info->keep_memory)
12809         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
12810     }
12811   return TRUE;
12812 }
12813
12814 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
12815
12816 static void
12817 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
12818 {
12819   Elf_Internal_Shdr *symtab_hdr;
12820
12821   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12822   if (cookie->locsyms != NULL
12823       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
12824     free (cookie->locsyms);
12825 }
12826
12827 /* Initialize the relocation information in COOKIE for input section SEC
12828    of input bfd ABFD.  */
12829
12830 static bfd_boolean
12831 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12832                         struct bfd_link_info *info, bfd *abfd,
12833                         asection *sec)
12834 {
12835   if (sec->reloc_count == 0)
12836     {
12837       cookie->rels = NULL;
12838       cookie->relend = NULL;
12839     }
12840   else
12841     {
12842       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
12843                                                 info->keep_memory);
12844       if (cookie->rels == NULL)
12845         return FALSE;
12846       cookie->rel = cookie->rels;
12847       cookie->relend = cookie->rels + sec->reloc_count;
12848     }
12849   cookie->rel = cookie->rels;
12850   return TRUE;
12851 }
12852
12853 /* Free the memory allocated by init_reloc_cookie_rels,
12854    if appropriate.  */
12855
12856 static void
12857 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12858                         asection *sec)
12859 {
12860   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
12861     free (cookie->rels);
12862 }
12863
12864 /* Initialize the whole of COOKIE for input section SEC.  */
12865
12866 static bfd_boolean
12867 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12868                                struct bfd_link_info *info,
12869                                asection *sec)
12870 {
12871   if (!init_reloc_cookie (cookie, info, sec->owner))
12872     goto error1;
12873   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
12874     goto error2;
12875   return TRUE;
12876
12877  error2:
12878   fini_reloc_cookie (cookie, sec->owner);
12879  error1:
12880   return FALSE;
12881 }
12882
12883 /* Free the memory allocated by init_reloc_cookie_for_section,
12884    if appropriate.  */
12885
12886 static void
12887 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12888                                asection *sec)
12889 {
12890   fini_reloc_cookie_rels (cookie, sec);
12891   fini_reloc_cookie (cookie, sec->owner);
12892 }
12893 \f
12894 /* Garbage collect unused sections.  */
12895
12896 /* Default gc_mark_hook.  */
12897
12898 asection *
12899 _bfd_elf_gc_mark_hook (asection *sec,
12900                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12901                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12902                        struct elf_link_hash_entry *h,
12903                        Elf_Internal_Sym *sym)
12904 {
12905   if (h != NULL)
12906     {
12907       switch (h->root.type)
12908         {
12909         case bfd_link_hash_defined:
12910         case bfd_link_hash_defweak:
12911           return h->root.u.def.section;
12912
12913         case bfd_link_hash_common:
12914           return h->root.u.c.p->section;
12915
12916         default:
12917           break;
12918         }
12919     }
12920   else
12921     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12922
12923   return NULL;
12924 }
12925
12926 /* Return the debug definition section.  */
12927
12928 static asection *
12929 elf_gc_mark_debug_section (asection *sec ATTRIBUTE_UNUSED,
12930                            struct bfd_link_info *info ATTRIBUTE_UNUSED,
12931                            Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12932                            struct elf_link_hash_entry *h,
12933                            Elf_Internal_Sym *sym)
12934 {
12935   if (h != NULL)
12936     {
12937       /* Return the global debug definition section.  */
12938       if ((h->root.type == bfd_link_hash_defined
12939            || h->root.type == bfd_link_hash_defweak)
12940           && (h->root.u.def.section->flags & SEC_DEBUGGING) != 0)
12941         return h->root.u.def.section;
12942     }
12943   else
12944     {
12945       /* Return the local debug definition section.  */
12946       asection *isec = bfd_section_from_elf_index (sec->owner,
12947                                                    sym->st_shndx);
12948       if ((isec->flags & SEC_DEBUGGING) != 0)
12949         return isec;
12950     }
12951
12952   return NULL;
12953 }
12954
12955 /* COOKIE->rel describes a relocation against section SEC, which is
12956    a section we've decided to keep.  Return the section that contains
12957    the relocation symbol, or NULL if no section contains it.  */
12958
12959 asection *
12960 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
12961                        elf_gc_mark_hook_fn gc_mark_hook,
12962                        struct elf_reloc_cookie *cookie,
12963                        bfd_boolean *start_stop)
12964 {
12965   unsigned long r_symndx;
12966   struct elf_link_hash_entry *h;
12967
12968   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
12969   if (r_symndx == STN_UNDEF)
12970     return NULL;
12971
12972   if (r_symndx >= cookie->locsymcount
12973       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12974     {
12975       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
12976       if (h == NULL)
12977         {
12978           info->callbacks->einfo (_("%F%P: corrupt input: %pB\n"),
12979                                   sec->owner);
12980           return NULL;
12981         }
12982       while (h->root.type == bfd_link_hash_indirect
12983              || h->root.type == bfd_link_hash_warning)
12984         h = (struct elf_link_hash_entry *) h->root.u.i.link;
12985       h->mark = 1;
12986       /* If this symbol is weak and there is a non-weak definition, we
12987          keep the non-weak definition because many backends put
12988          dynamic reloc info on the non-weak definition for code
12989          handling copy relocs.  */
12990       if (h->is_weakalias)
12991         weakdef (h)->mark = 1;
12992
12993       if (start_stop != NULL)
12994         {
12995           /* To work around a glibc bug, mark XXX input sections
12996              when there is a reference to __start_XXX or __stop_XXX
12997              symbols.  */
12998           if (h->start_stop)
12999             {
13000               asection *s = h->u2.start_stop_section;
13001               *start_stop = !s->gc_mark;
13002               return s;
13003             }
13004         }
13005
13006       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
13007     }
13008
13009   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
13010                           &cookie->locsyms[r_symndx]);
13011 }
13012
13013 /* COOKIE->rel describes a relocation against section SEC, which is
13014    a section we've decided to keep.  Mark the section that contains
13015    the relocation symbol.  */
13016
13017 bfd_boolean
13018 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
13019                         asection *sec,
13020                         elf_gc_mark_hook_fn gc_mark_hook,
13021                         struct elf_reloc_cookie *cookie)
13022 {
13023   asection *rsec;
13024   bfd_boolean start_stop = FALSE;
13025
13026   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie, &start_stop);
13027   while (rsec != NULL)
13028     {
13029       if (!rsec->gc_mark)
13030         {
13031           if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
13032               || (rsec->owner->flags & DYNAMIC) != 0)
13033             rsec->gc_mark = 1;
13034           else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
13035             return FALSE;
13036         }
13037       if (!start_stop)
13038         break;
13039       rsec = bfd_get_next_section_by_name (rsec->owner, rsec);
13040     }
13041   return TRUE;
13042 }
13043
13044 /* The mark phase of garbage collection.  For a given section, mark
13045    it and any sections in this section's group, and all the sections
13046    which define symbols to which it refers.  */
13047
13048 bfd_boolean
13049 _bfd_elf_gc_mark (struct bfd_link_info *info,
13050                   asection *sec,
13051                   elf_gc_mark_hook_fn gc_mark_hook)
13052 {
13053   bfd_boolean ret;
13054   asection *group_sec, *eh_frame;
13055
13056   sec->gc_mark = 1;
13057
13058   /* Mark all the sections in the group.  */
13059   group_sec = elf_section_data (sec)->next_in_group;
13060   if (group_sec && !group_sec->gc_mark)
13061     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
13062       return FALSE;
13063
13064   /* Look through the section relocs.  */
13065   ret = TRUE;
13066   eh_frame = elf_eh_frame_section (sec->owner);
13067   if ((sec->flags & SEC_RELOC) != 0
13068       && sec->reloc_count > 0
13069       && sec != eh_frame)
13070     {
13071       struct elf_reloc_cookie cookie;
13072
13073       if (!init_reloc_cookie_for_section (&cookie, info, sec))
13074         ret = FALSE;
13075       else
13076         {
13077           for (; cookie.rel < cookie.relend; cookie.rel++)
13078             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
13079               {
13080                 ret = FALSE;
13081                 break;
13082               }
13083           fini_reloc_cookie_for_section (&cookie, sec);
13084         }
13085     }
13086
13087   if (ret && eh_frame && elf_fde_list (sec))
13088     {
13089       struct elf_reloc_cookie cookie;
13090
13091       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
13092         ret = FALSE;
13093       else
13094         {
13095           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
13096                                       gc_mark_hook, &cookie))
13097             ret = FALSE;
13098           fini_reloc_cookie_for_section (&cookie, eh_frame);
13099         }
13100     }
13101
13102   eh_frame = elf_section_eh_frame_entry (sec);
13103   if (ret && eh_frame && !eh_frame->gc_mark)
13104     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
13105       ret = FALSE;
13106
13107   return ret;
13108 }
13109
13110 /* Scan and mark sections in a special or debug section group.  */
13111
13112 static void
13113 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
13114 {
13115   /* Point to first section of section group.  */
13116   asection *ssec;
13117   /* Used to iterate the section group.  */
13118   asection *msec;
13119
13120   bfd_boolean is_special_grp = TRUE;
13121   bfd_boolean is_debug_grp = TRUE;
13122
13123   /* First scan to see if group contains any section other than debug
13124      and special section.  */
13125   ssec = msec = elf_next_in_group (grp);
13126   do
13127     {
13128       if ((msec->flags & SEC_DEBUGGING) == 0)
13129         is_debug_grp = FALSE;
13130
13131       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
13132         is_special_grp = FALSE;
13133
13134       msec = elf_next_in_group (msec);
13135     }
13136   while (msec != ssec);
13137
13138   /* If this is a pure debug section group or pure special section group,
13139      keep all sections in this group.  */
13140   if (is_debug_grp || is_special_grp)
13141     {
13142       do
13143         {
13144           msec->gc_mark = 1;
13145           msec = elf_next_in_group (msec);
13146         }
13147       while (msec != ssec);
13148     }
13149 }
13150
13151 /* Keep debug and special sections.  */
13152
13153 bfd_boolean
13154 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
13155                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
13156 {
13157   bfd *ibfd;
13158
13159   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13160     {
13161       asection *isec;
13162       bfd_boolean some_kept;
13163       bfd_boolean debug_frag_seen;
13164       bfd_boolean has_kept_debug_info;
13165
13166       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13167         continue;
13168       isec = ibfd->sections;
13169       if (isec == NULL || isec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13170         continue;
13171
13172       /* Ensure all linker created sections are kept,
13173          see if any other section is already marked,
13174          and note if we have any fragmented debug sections.  */
13175       debug_frag_seen = some_kept = has_kept_debug_info = FALSE;
13176       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13177         {
13178           if ((isec->flags & SEC_LINKER_CREATED) != 0)
13179             isec->gc_mark = 1;
13180           else if (isec->gc_mark
13181                    && (isec->flags & SEC_ALLOC) != 0
13182                    && elf_section_type (isec) != SHT_NOTE)
13183             some_kept = TRUE;
13184
13185           if (!debug_frag_seen
13186               && (isec->flags & SEC_DEBUGGING)
13187               && CONST_STRNEQ (isec->name, ".debug_line."))
13188             debug_frag_seen = TRUE;
13189         }
13190
13191       /* If no non-note alloc section in this file will be kept, then
13192          we can toss out the debug and special sections.  */
13193       if (!some_kept)
13194         continue;
13195
13196       /* Keep debug and special sections like .comment when they are
13197          not part of a group.  Also keep section groups that contain
13198          just debug sections or special sections.  */
13199       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13200         {
13201           if ((isec->flags & SEC_GROUP) != 0)
13202             _bfd_elf_gc_mark_debug_special_section_group (isec);
13203           else if (((isec->flags & SEC_DEBUGGING) != 0
13204                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
13205                    && elf_next_in_group (isec) == NULL)
13206             isec->gc_mark = 1;
13207           if (isec->gc_mark && (isec->flags & SEC_DEBUGGING) != 0)
13208             has_kept_debug_info = TRUE;
13209         }
13210
13211       /* Look for CODE sections which are going to be discarded,
13212          and find and discard any fragmented debug sections which
13213          are associated with that code section.  */
13214       if (debug_frag_seen)
13215         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13216           if ((isec->flags & SEC_CODE) != 0
13217               && isec->gc_mark == 0)
13218             {
13219               unsigned int ilen;
13220               asection *dsec;
13221
13222               ilen = strlen (isec->name);
13223
13224               /* Association is determined by the name of the debug
13225                  section containing the name of the code section as
13226                  a suffix.  For example .debug_line.text.foo is a
13227                  debug section associated with .text.foo.  */
13228               for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
13229                 {
13230                   unsigned int dlen;
13231
13232                   if (dsec->gc_mark == 0
13233                       || (dsec->flags & SEC_DEBUGGING) == 0)
13234                     continue;
13235
13236                   dlen = strlen (dsec->name);
13237
13238                   if (dlen > ilen
13239                       && strncmp (dsec->name + (dlen - ilen),
13240                                   isec->name, ilen) == 0)
13241                     dsec->gc_mark = 0;
13242                 }
13243           }
13244
13245       /* Mark debug sections referenced by kept debug sections.  */
13246       if (has_kept_debug_info)
13247         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13248           if (isec->gc_mark
13249               && (isec->flags & SEC_DEBUGGING) != 0)
13250             if (!_bfd_elf_gc_mark (info, isec,
13251                                    elf_gc_mark_debug_section))
13252               return FALSE;
13253     }
13254   return TRUE;
13255 }
13256
13257 static bfd_boolean
13258 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
13259 {
13260   bfd *sub;
13261   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13262
13263   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13264     {
13265       asection *o;
13266
13267       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13268           || elf_object_id (sub) != elf_hash_table_id (elf_hash_table (info))
13269           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13270         continue;
13271       o = sub->sections;
13272       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13273         continue;
13274
13275       for (o = sub->sections; o != NULL; o = o->next)
13276         {
13277           /* When any section in a section group is kept, we keep all
13278              sections in the section group.  If the first member of
13279              the section group is excluded, we will also exclude the
13280              group section.  */
13281           if (o->flags & SEC_GROUP)
13282             {
13283               asection *first = elf_next_in_group (o);
13284               o->gc_mark = first->gc_mark;
13285             }
13286
13287           if (o->gc_mark)
13288             continue;
13289
13290           /* Skip sweeping sections already excluded.  */
13291           if (o->flags & SEC_EXCLUDE)
13292             continue;
13293
13294           /* Since this is early in the link process, it is simple
13295              to remove a section from the output.  */
13296           o->flags |= SEC_EXCLUDE;
13297
13298           if (info->print_gc_sections && o->size != 0)
13299             /* xgettext:c-format */
13300             _bfd_error_handler (_("removing unused section '%pA' in file '%pB'"),
13301                                 o, sub);
13302         }
13303     }
13304
13305   return TRUE;
13306 }
13307
13308 /* Propagate collected vtable information.  This is called through
13309    elf_link_hash_traverse.  */
13310
13311 static bfd_boolean
13312 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
13313 {
13314   /* Those that are not vtables.  */
13315   if (h->start_stop
13316       || h->u2.vtable == NULL
13317       || h->u2.vtable->parent == NULL)
13318     return TRUE;
13319
13320   /* Those vtables that do not have parents, we cannot merge.  */
13321   if (h->u2.vtable->parent == (struct elf_link_hash_entry *) -1)
13322     return TRUE;
13323
13324   /* If we've already been done, exit.  */
13325   if (h->u2.vtable->used && h->u2.vtable->used[-1])
13326     return TRUE;
13327
13328   /* Make sure the parent's table is up to date.  */
13329   elf_gc_propagate_vtable_entries_used (h->u2.vtable->parent, okp);
13330
13331   if (h->u2.vtable->used == NULL)
13332     {
13333       /* None of this table's entries were referenced.  Re-use the
13334          parent's table.  */
13335       h->u2.vtable->used = h->u2.vtable->parent->u2.vtable->used;
13336       h->u2.vtable->size = h->u2.vtable->parent->u2.vtable->size;
13337     }
13338   else
13339     {
13340       size_t n;
13341       bfd_boolean *cu, *pu;
13342
13343       /* Or the parent's entries into ours.  */
13344       cu = h->u2.vtable->used;
13345       cu[-1] = TRUE;
13346       pu = h->u2.vtable->parent->u2.vtable->used;
13347       if (pu != NULL)
13348         {
13349           const struct elf_backend_data *bed;
13350           unsigned int log_file_align;
13351
13352           bed = get_elf_backend_data (h->root.u.def.section->owner);
13353           log_file_align = bed->s->log_file_align;
13354           n = h->u2.vtable->parent->u2.vtable->size >> log_file_align;
13355           while (n--)
13356             {
13357               if (*pu)
13358                 *cu = TRUE;
13359               pu++;
13360               cu++;
13361             }
13362         }
13363     }
13364
13365   return TRUE;
13366 }
13367
13368 static bfd_boolean
13369 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
13370 {
13371   asection *sec;
13372   bfd_vma hstart, hend;
13373   Elf_Internal_Rela *relstart, *relend, *rel;
13374   const struct elf_backend_data *bed;
13375   unsigned int log_file_align;
13376
13377   /* Take care of both those symbols that do not describe vtables as
13378      well as those that are not loaded.  */
13379   if (h->start_stop
13380       || h->u2.vtable == NULL
13381       || h->u2.vtable->parent == NULL)
13382     return TRUE;
13383
13384   BFD_ASSERT (h->root.type == bfd_link_hash_defined
13385               || h->root.type == bfd_link_hash_defweak);
13386
13387   sec = h->root.u.def.section;
13388   hstart = h->root.u.def.value;
13389   hend = hstart + h->size;
13390
13391   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
13392   if (!relstart)
13393     return *(bfd_boolean *) okp = FALSE;
13394   bed = get_elf_backend_data (sec->owner);
13395   log_file_align = bed->s->log_file_align;
13396
13397   relend = relstart + sec->reloc_count;
13398
13399   for (rel = relstart; rel < relend; ++rel)
13400     if (rel->r_offset >= hstart && rel->r_offset < hend)
13401       {
13402         /* If the entry is in use, do nothing.  */
13403         if (h->u2.vtable->used
13404             && (rel->r_offset - hstart) < h->u2.vtable->size)
13405           {
13406             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
13407             if (h->u2.vtable->used[entry])
13408               continue;
13409           }
13410         /* Otherwise, kill it.  */
13411         rel->r_offset = rel->r_info = rel->r_addend = 0;
13412       }
13413
13414   return TRUE;
13415 }
13416
13417 /* Mark sections containing dynamically referenced symbols.  When
13418    building shared libraries, we must assume that any visible symbol is
13419    referenced.  */
13420
13421 bfd_boolean
13422 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
13423 {
13424   struct bfd_link_info *info = (struct bfd_link_info *) inf;
13425   struct bfd_elf_dynamic_list *d = info->dynamic_list;
13426
13427   if ((h->root.type == bfd_link_hash_defined
13428        || h->root.type == bfd_link_hash_defweak)
13429       && ((h->ref_dynamic && !h->forced_local)
13430           || ((h->def_regular || ELF_COMMON_DEF_P (h))
13431               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
13432               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
13433               && (!bfd_link_executable (info)
13434                   || info->gc_keep_exported
13435                   || info->export_dynamic
13436                   || (h->dynamic
13437                       && d != NULL
13438                       && (*d->match) (&d->head, NULL, h->root.root.string)))
13439               && (h->versioned >= versioned
13440                   || !bfd_hide_sym_by_version (info->version_info,
13441                                                h->root.root.string)))))
13442     h->root.u.def.section->flags |= SEC_KEEP;
13443
13444   return TRUE;
13445 }
13446
13447 /* Keep all sections containing symbols undefined on the command-line,
13448    and the section containing the entry symbol.  */
13449
13450 void
13451 _bfd_elf_gc_keep (struct bfd_link_info *info)
13452 {
13453   struct bfd_sym_chain *sym;
13454
13455   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
13456     {
13457       struct elf_link_hash_entry *h;
13458
13459       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
13460                                 FALSE, FALSE, FALSE);
13461
13462       if (h != NULL
13463           && (h->root.type == bfd_link_hash_defined
13464               || h->root.type == bfd_link_hash_defweak)
13465           && !bfd_is_abs_section (h->root.u.def.section)
13466           && !bfd_is_und_section (h->root.u.def.section))
13467         h->root.u.def.section->flags |= SEC_KEEP;
13468     }
13469 }
13470
13471 bfd_boolean
13472 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
13473                                 struct bfd_link_info *info)
13474 {
13475   bfd *ibfd = info->input_bfds;
13476
13477   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13478     {
13479       asection *sec;
13480       struct elf_reloc_cookie cookie;
13481
13482       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13483         continue;
13484       sec = ibfd->sections;
13485       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13486         continue;
13487
13488       if (!init_reloc_cookie (&cookie, info, ibfd))
13489         return FALSE;
13490
13491       for (sec = ibfd->sections; sec; sec = sec->next)
13492         {
13493           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
13494               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
13495             {
13496               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
13497               fini_reloc_cookie_rels (&cookie, sec);
13498             }
13499         }
13500     }
13501   return TRUE;
13502 }
13503
13504 /* Do mark and sweep of unused sections.  */
13505
13506 bfd_boolean
13507 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
13508 {
13509   bfd_boolean ok = TRUE;
13510   bfd *sub;
13511   elf_gc_mark_hook_fn gc_mark_hook;
13512   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13513   struct elf_link_hash_table *htab;
13514
13515   if (!bed->can_gc_sections
13516       || !is_elf_hash_table (info->hash))
13517     {
13518       _bfd_error_handler(_("warning: gc-sections option ignored"));
13519       return TRUE;
13520     }
13521
13522   bed->gc_keep (info);
13523   htab = elf_hash_table (info);
13524
13525   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
13526      at the .eh_frame section if we can mark the FDEs individually.  */
13527   for (sub = info->input_bfds;
13528        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
13529        sub = sub->link.next)
13530     {
13531       asection *sec;
13532       struct elf_reloc_cookie cookie;
13533
13534       sec = sub->sections;
13535       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13536         continue;
13537       sec = bfd_get_section_by_name (sub, ".eh_frame");
13538       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
13539         {
13540           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
13541           if (elf_section_data (sec)->sec_info
13542               && (sec->flags & SEC_LINKER_CREATED) == 0)
13543             elf_eh_frame_section (sub) = sec;
13544           fini_reloc_cookie_for_section (&cookie, sec);
13545           sec = bfd_get_next_section_by_name (NULL, sec);
13546         }
13547     }
13548
13549   /* Apply transitive closure to the vtable entry usage info.  */
13550   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
13551   if (!ok)
13552     return FALSE;
13553
13554   /* Kill the vtable relocations that were not used.  */
13555   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
13556   if (!ok)
13557     return FALSE;
13558
13559   /* Mark dynamically referenced symbols.  */
13560   if (htab->dynamic_sections_created || info->gc_keep_exported)
13561     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
13562
13563   /* Grovel through relocs to find out who stays ...  */
13564   gc_mark_hook = bed->gc_mark_hook;
13565   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13566     {
13567       asection *o;
13568
13569       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13570           || elf_object_id (sub) != elf_hash_table_id (htab)
13571           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13572         continue;
13573
13574       o = sub->sections;
13575       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13576         continue;
13577
13578       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
13579          Also treat note sections as a root, if the section is not part
13580          of a group.  We must keep all PREINIT_ARRAY, INIT_ARRAY as
13581          well as FINI_ARRAY sections for ld -r.  */
13582       for (o = sub->sections; o != NULL; o = o->next)
13583         if (!o->gc_mark
13584             && (o->flags & SEC_EXCLUDE) == 0
13585             && ((o->flags & SEC_KEEP) != 0
13586                 || (bfd_link_relocatable (info)
13587                     && ((elf_section_data (o)->this_hdr.sh_type
13588                          == SHT_PREINIT_ARRAY)
13589                         || (elf_section_data (o)->this_hdr.sh_type
13590                             == SHT_INIT_ARRAY)
13591                         || (elf_section_data (o)->this_hdr.sh_type
13592                             == SHT_FINI_ARRAY)))
13593                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
13594                     && elf_next_in_group (o) == NULL )))
13595           {
13596             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
13597               return FALSE;
13598           }
13599     }
13600
13601   /* Allow the backend to mark additional target specific sections.  */
13602   bed->gc_mark_extra_sections (info, gc_mark_hook);
13603
13604   /* ... and mark SEC_EXCLUDE for those that go.  */
13605   return elf_gc_sweep (abfd, info);
13606 }
13607 \f
13608 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
13609
13610 bfd_boolean
13611 bfd_elf_gc_record_vtinherit (bfd *abfd,
13612                              asection *sec,
13613                              struct elf_link_hash_entry *h,
13614                              bfd_vma offset)
13615 {
13616   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
13617   struct elf_link_hash_entry **search, *child;
13618   size_t extsymcount;
13619   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13620
13621   /* The sh_info field of the symtab header tells us where the
13622      external symbols start.  We don't care about the local symbols at
13623      this point.  */
13624   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
13625   if (!elf_bad_symtab (abfd))
13626     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
13627
13628   sym_hashes = elf_sym_hashes (abfd);
13629   sym_hashes_end = sym_hashes + extsymcount;
13630
13631   /* Hunt down the child symbol, which is in this section at the same
13632      offset as the relocation.  */
13633   for (search = sym_hashes; search != sym_hashes_end; ++search)
13634     {
13635       if ((child = *search) != NULL
13636           && (child->root.type == bfd_link_hash_defined
13637               || child->root.type == bfd_link_hash_defweak)
13638           && child->root.u.def.section == sec
13639           && child->root.u.def.value == offset)
13640         goto win;
13641     }
13642
13643   /* xgettext:c-format */
13644   _bfd_error_handler (_("%pB: %pA+%#" PRIx64 ": no symbol found for INHERIT"),
13645                       abfd, sec, (uint64_t) offset);
13646   bfd_set_error (bfd_error_invalid_operation);
13647   return FALSE;
13648
13649  win:
13650   if (!child->u2.vtable)
13651     {
13652       child->u2.vtable = ((struct elf_link_virtual_table_entry *)
13653                           bfd_zalloc (abfd, sizeof (*child->u2.vtable)));
13654       if (!child->u2.vtable)
13655         return FALSE;
13656     }
13657   if (!h)
13658     {
13659       /* This *should* only be the absolute section.  It could potentially
13660          be that someone has defined a non-global vtable though, which
13661          would be bad.  It isn't worth paging in the local symbols to be
13662          sure though; that case should simply be handled by the assembler.  */
13663
13664       child->u2.vtable->parent = (struct elf_link_hash_entry *) -1;
13665     }
13666   else
13667     child->u2.vtable->parent = h;
13668
13669   return TRUE;
13670 }
13671
13672 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
13673
13674 bfd_boolean
13675 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
13676                            asection *sec ATTRIBUTE_UNUSED,
13677                            struct elf_link_hash_entry *h,
13678                            bfd_vma addend)
13679 {
13680   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13681   unsigned int log_file_align = bed->s->log_file_align;
13682
13683   if (!h->u2.vtable)
13684     {
13685       h->u2.vtable = ((struct elf_link_virtual_table_entry *)
13686                       bfd_zalloc (abfd, sizeof (*h->u2.vtable)));
13687       if (!h->u2.vtable)
13688         return FALSE;
13689     }
13690
13691   if (addend >= h->u2.vtable->size)
13692     {
13693       size_t size, bytes, file_align;
13694       bfd_boolean *ptr = h->u2.vtable->used;
13695
13696       /* While the symbol is undefined, we have to be prepared to handle
13697          a zero size.  */
13698       file_align = 1 << log_file_align;
13699       if (h->root.type == bfd_link_hash_undefined)
13700         size = addend + file_align;
13701       else
13702         {
13703           size = h->size;
13704           if (addend >= size)
13705             {
13706               /* Oops!  We've got a reference past the defined end of
13707                  the table.  This is probably a bug -- shall we warn?  */
13708               size = addend + file_align;
13709             }
13710         }
13711       size = (size + file_align - 1) & -file_align;
13712
13713       /* Allocate one extra entry for use as a "done" flag for the
13714          consolidation pass.  */
13715       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
13716
13717       if (ptr)
13718         {
13719           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
13720
13721           if (ptr != NULL)
13722             {
13723               size_t oldbytes;
13724
13725               oldbytes = (((h->u2.vtable->size >> log_file_align) + 1)
13726                           * sizeof (bfd_boolean));
13727               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
13728             }
13729         }
13730       else
13731         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
13732
13733       if (ptr == NULL)
13734         return FALSE;
13735
13736       /* And arrange for that done flag to be at index -1.  */
13737       h->u2.vtable->used = ptr + 1;
13738       h->u2.vtable->size = size;
13739     }
13740
13741   h->u2.vtable->used[addend >> log_file_align] = TRUE;
13742
13743   return TRUE;
13744 }
13745
13746 /* Map an ELF section header flag to its corresponding string.  */
13747 typedef struct
13748 {
13749   char *flag_name;
13750   flagword flag_value;
13751 } elf_flags_to_name_table;
13752
13753 static elf_flags_to_name_table elf_flags_to_names [] =
13754 {
13755   { "SHF_WRITE", SHF_WRITE },
13756   { "SHF_ALLOC", SHF_ALLOC },
13757   { "SHF_EXECINSTR", SHF_EXECINSTR },
13758   { "SHF_MERGE", SHF_MERGE },
13759   { "SHF_STRINGS", SHF_STRINGS },
13760   { "SHF_INFO_LINK", SHF_INFO_LINK},
13761   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
13762   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
13763   { "SHF_GROUP", SHF_GROUP },
13764   { "SHF_TLS", SHF_TLS },
13765   { "SHF_MASKOS", SHF_MASKOS },
13766   { "SHF_EXCLUDE", SHF_EXCLUDE },
13767 };
13768
13769 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
13770 bfd_boolean
13771 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
13772                               struct flag_info *flaginfo,
13773                               asection *section)
13774 {
13775   const bfd_vma sh_flags = elf_section_flags (section);
13776
13777   if (!flaginfo->flags_initialized)
13778     {
13779       bfd *obfd = info->output_bfd;
13780       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13781       struct flag_info_list *tf = flaginfo->flag_list;
13782       int with_hex = 0;
13783       int without_hex = 0;
13784
13785       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
13786         {
13787           unsigned i;
13788           flagword (*lookup) (char *);
13789
13790           lookup = bed->elf_backend_lookup_section_flags_hook;
13791           if (lookup != NULL)
13792             {
13793               flagword hexval = (*lookup) ((char *) tf->name);
13794
13795               if (hexval != 0)
13796                 {
13797                   if (tf->with == with_flags)
13798                     with_hex |= hexval;
13799                   else if (tf->with == without_flags)
13800                     without_hex |= hexval;
13801                   tf->valid = TRUE;
13802                   continue;
13803                 }
13804             }
13805           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
13806             {
13807               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
13808                 {
13809                   if (tf->with == with_flags)
13810                     with_hex |= elf_flags_to_names[i].flag_value;
13811                   else if (tf->with == without_flags)
13812                     without_hex |= elf_flags_to_names[i].flag_value;
13813                   tf->valid = TRUE;
13814                   break;
13815                 }
13816             }
13817           if (!tf->valid)
13818             {
13819               info->callbacks->einfo
13820                 (_("unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
13821               return FALSE;
13822             }
13823         }
13824       flaginfo->flags_initialized = TRUE;
13825       flaginfo->only_with_flags |= with_hex;
13826       flaginfo->not_with_flags |= without_hex;
13827     }
13828
13829   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
13830     return FALSE;
13831
13832   if ((flaginfo->not_with_flags & sh_flags) != 0)
13833     return FALSE;
13834
13835   return TRUE;
13836 }
13837
13838 struct alloc_got_off_arg {
13839   bfd_vma gotoff;
13840   struct bfd_link_info *info;
13841 };
13842
13843 /* We need a special top-level link routine to convert got reference counts
13844    to real got offsets.  */
13845
13846 static bfd_boolean
13847 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
13848 {
13849   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
13850   bfd *obfd = gofarg->info->output_bfd;
13851   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13852
13853   if (h->got.refcount > 0)
13854     {
13855       h->got.offset = gofarg->gotoff;
13856       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
13857     }
13858   else
13859     h->got.offset = (bfd_vma) -1;
13860
13861   return TRUE;
13862 }
13863
13864 /* And an accompanying bit to work out final got entry offsets once
13865    we're done.  Should be called from final_link.  */
13866
13867 bfd_boolean
13868 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
13869                                         struct bfd_link_info *info)
13870 {
13871   bfd *i;
13872   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13873   bfd_vma gotoff;
13874   struct alloc_got_off_arg gofarg;
13875
13876   BFD_ASSERT (abfd == info->output_bfd);
13877
13878   if (! is_elf_hash_table (info->hash))
13879     return FALSE;
13880
13881   /* The GOT offset is relative to the .got section, but the GOT header is
13882      put into the .got.plt section, if the backend uses it.  */
13883   if (bed->want_got_plt)
13884     gotoff = 0;
13885   else
13886     gotoff = bed->got_header_size;
13887
13888   /* Do the local .got entries first.  */
13889   for (i = info->input_bfds; i; i = i->link.next)
13890     {
13891       bfd_signed_vma *local_got;
13892       size_t j, locsymcount;
13893       Elf_Internal_Shdr *symtab_hdr;
13894
13895       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13896         continue;
13897
13898       local_got = elf_local_got_refcounts (i);
13899       if (!local_got)
13900         continue;
13901
13902       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13903       if (elf_bad_symtab (i))
13904         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13905       else
13906         locsymcount = symtab_hdr->sh_info;
13907
13908       for (j = 0; j < locsymcount; ++j)
13909         {
13910           if (local_got[j] > 0)
13911             {
13912               local_got[j] = gotoff;
13913               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13914             }
13915           else
13916             local_got[j] = (bfd_vma) -1;
13917         }
13918     }
13919
13920   /* Then the global .got entries.  .plt refcounts are handled by
13921      adjust_dynamic_symbol  */
13922   gofarg.gotoff = gotoff;
13923   gofarg.info = info;
13924   elf_link_hash_traverse (elf_hash_table (info),
13925                           elf_gc_allocate_got_offsets,
13926                           &gofarg);
13927   return TRUE;
13928 }
13929
13930 /* Many folk need no more in the way of final link than this, once
13931    got entry reference counting is enabled.  */
13932
13933 bfd_boolean
13934 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
13935 {
13936   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
13937     return FALSE;
13938
13939   /* Invoke the regular ELF backend linker to do all the work.  */
13940   return bfd_elf_final_link (abfd, info);
13941 }
13942
13943 bfd_boolean
13944 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
13945 {
13946   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
13947
13948   if (rcookie->bad_symtab)
13949     rcookie->rel = rcookie->rels;
13950
13951   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
13952     {
13953       unsigned long r_symndx;
13954
13955       if (! rcookie->bad_symtab)
13956         if (rcookie->rel->r_offset > offset)
13957           return FALSE;
13958       if (rcookie->rel->r_offset != offset)
13959         continue;
13960
13961       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
13962       if (r_symndx == STN_UNDEF)
13963         return TRUE;
13964
13965       if (r_symndx >= rcookie->locsymcount
13966           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13967         {
13968           struct elf_link_hash_entry *h;
13969
13970           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
13971
13972           while (h->root.type == bfd_link_hash_indirect
13973                  || h->root.type == bfd_link_hash_warning)
13974             h = (struct elf_link_hash_entry *) h->root.u.i.link;
13975
13976           if ((h->root.type == bfd_link_hash_defined
13977                || h->root.type == bfd_link_hash_defweak)
13978               && (h->root.u.def.section->owner != rcookie->abfd
13979                   || h->root.u.def.section->kept_section != NULL
13980                   || discarded_section (h->root.u.def.section)))
13981             return TRUE;
13982         }
13983       else
13984         {
13985           /* It's not a relocation against a global symbol,
13986              but it could be a relocation against a local
13987              symbol for a discarded section.  */
13988           asection *isec;
13989           Elf_Internal_Sym *isym;
13990
13991           /* Need to: get the symbol; get the section.  */
13992           isym = &rcookie->locsyms[r_symndx];
13993           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
13994           if (isec != NULL
13995               && (isec->kept_section != NULL
13996                   || discarded_section (isec)))
13997             return TRUE;
13998         }
13999       return FALSE;
14000     }
14001   return FALSE;
14002 }
14003
14004 /* Discard unneeded references to discarded sections.
14005    Returns -1 on error, 1 if any section's size was changed, 0 if
14006    nothing changed.  This function assumes that the relocations are in
14007    sorted order, which is true for all known assemblers.  */
14008
14009 int
14010 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
14011 {
14012   struct elf_reloc_cookie cookie;
14013   asection *o;
14014   bfd *abfd;
14015   int changed = 0;
14016
14017   if (info->traditional_format
14018       || !is_elf_hash_table (info->hash))
14019     return 0;
14020
14021   o = bfd_get_section_by_name (output_bfd, ".stab");
14022   if (o != NULL)
14023     {
14024       asection *i;
14025
14026       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
14027         {
14028           if (i->size == 0
14029               || i->reloc_count == 0
14030               || i->sec_info_type != SEC_INFO_TYPE_STABS)
14031             continue;
14032
14033           abfd = i->owner;
14034           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
14035             continue;
14036
14037           if (!init_reloc_cookie_for_section (&cookie, info, i))
14038             return -1;
14039
14040           if (_bfd_discard_section_stabs (abfd, i,
14041                                           elf_section_data (i)->sec_info,
14042                                           bfd_elf_reloc_symbol_deleted_p,
14043                                           &cookie))
14044             changed = 1;
14045
14046           fini_reloc_cookie_for_section (&cookie, i);
14047         }
14048     }
14049
14050   o = NULL;
14051   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
14052     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
14053   if (o != NULL)
14054     {
14055       asection *i;
14056       int eh_changed = 0;
14057       unsigned int eh_alignment;
14058
14059       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
14060         {
14061           if (i->size == 0)
14062             continue;
14063
14064           abfd = i->owner;
14065           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
14066             continue;
14067
14068           if (!init_reloc_cookie_for_section (&cookie, info, i))
14069             return -1;
14070
14071           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
14072           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
14073                                                  bfd_elf_reloc_symbol_deleted_p,
14074                                                  &cookie))
14075             {
14076               eh_changed = 1;
14077               if (i->size != i->rawsize)
14078                 changed = 1;
14079             }
14080
14081           fini_reloc_cookie_for_section (&cookie, i);
14082         }
14083
14084       eh_alignment = 1 << o->alignment_power;
14085       /* Skip over zero terminator, and prevent empty sections from
14086          adding alignment padding at the end.  */
14087       for (i = o->map_tail.s; i != NULL; i = i->map_tail.s)
14088         if (i->size == 0)
14089           i->flags |= SEC_EXCLUDE;
14090         else if (i->size > 4)
14091           break;
14092       /* The last non-empty eh_frame section doesn't need padding.  */
14093       if (i != NULL)
14094         i = i->map_tail.s;
14095       /* Any prior sections must pad the last FDE out to the output
14096          section alignment.  Otherwise we might have zero padding
14097          between sections, which would be seen as a terminator.  */
14098       for (; i != NULL; i = i->map_tail.s)
14099         if (i->size == 4)
14100           /* All but the last zero terminator should have been removed.  */
14101           BFD_FAIL ();
14102         else
14103           {
14104             bfd_size_type size
14105               = (i->size + eh_alignment - 1) & -eh_alignment;
14106             if (i->size != size)
14107               {
14108                 i->size = size;
14109                 changed = 1;
14110                 eh_changed = 1;
14111               }
14112           }
14113       if (eh_changed)
14114         elf_link_hash_traverse (elf_hash_table (info),
14115                                 _bfd_elf_adjust_eh_frame_global_symbol, NULL);
14116     }
14117
14118   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
14119     {
14120       const struct elf_backend_data *bed;
14121       asection *s;
14122
14123       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
14124         continue;
14125       s = abfd->sections;
14126       if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
14127         continue;
14128
14129       bed = get_elf_backend_data (abfd);
14130
14131       if (bed->elf_backend_discard_info != NULL)
14132         {
14133           if (!init_reloc_cookie (&cookie, info, abfd))
14134             return -1;
14135
14136           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
14137             changed = 1;
14138
14139           fini_reloc_cookie (&cookie, abfd);
14140         }
14141     }
14142
14143   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
14144     _bfd_elf_end_eh_frame_parsing (info);
14145
14146   if (info->eh_frame_hdr_type
14147       && !bfd_link_relocatable (info)
14148       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
14149     changed = 1;
14150
14151   return changed;
14152 }
14153
14154 bfd_boolean
14155 _bfd_elf_section_already_linked (bfd *abfd,
14156                                  asection *sec,
14157                                  struct bfd_link_info *info)
14158 {
14159   flagword flags;
14160   const char *name, *key;
14161   struct bfd_section_already_linked *l;
14162   struct bfd_section_already_linked_hash_entry *already_linked_list;
14163
14164   if (sec->output_section == bfd_abs_section_ptr)
14165     return FALSE;
14166
14167   flags = sec->flags;
14168
14169   /* Return if it isn't a linkonce section.  A comdat group section
14170      also has SEC_LINK_ONCE set.  */
14171   if ((flags & SEC_LINK_ONCE) == 0)
14172     return FALSE;
14173
14174   /* Don't put group member sections on our list of already linked
14175      sections.  They are handled as a group via their group section.  */
14176   if (elf_sec_group (sec) != NULL)
14177     return FALSE;
14178
14179   /* For a SHT_GROUP section, use the group signature as the key.  */
14180   name = sec->name;
14181   if ((flags & SEC_GROUP) != 0
14182       && elf_next_in_group (sec) != NULL
14183       && elf_group_name (elf_next_in_group (sec)) != NULL)
14184     key = elf_group_name (elf_next_in_group (sec));
14185   else
14186     {
14187       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
14188       if (CONST_STRNEQ (name, ".gnu.linkonce.")
14189           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
14190         key++;
14191       else
14192         /* Must be a user linkonce section that doesn't follow gcc's
14193            naming convention.  In this case we won't be matching
14194            single member groups.  */
14195         key = name;
14196     }
14197
14198   already_linked_list = bfd_section_already_linked_table_lookup (key);
14199
14200   for (l = already_linked_list->entry; l != NULL; l = l->next)
14201     {
14202       /* We may have 2 different types of sections on the list: group
14203          sections with a signature of <key> (<key> is some string),
14204          and linkonce sections named .gnu.linkonce.<type>.<key>.
14205          Match like sections.  LTO plugin sections are an exception.
14206          They are always named .gnu.linkonce.t.<key> and match either
14207          type of section.  */
14208       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
14209            && ((flags & SEC_GROUP) != 0
14210                || strcmp (name, l->sec->name) == 0))
14211           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
14212         {
14213           /* The section has already been linked.  See if we should
14214              issue a warning.  */
14215           if (!_bfd_handle_already_linked (sec, l, info))
14216             return FALSE;
14217
14218           if (flags & SEC_GROUP)
14219             {
14220               asection *first = elf_next_in_group (sec);
14221               asection *s = first;
14222
14223               while (s != NULL)
14224                 {
14225                   s->output_section = bfd_abs_section_ptr;
14226                   /* Record which group discards it.  */
14227                   s->kept_section = l->sec;
14228                   s = elf_next_in_group (s);
14229                   /* These lists are circular.  */
14230                   if (s == first)
14231                     break;
14232                 }
14233             }
14234
14235           return TRUE;
14236         }
14237     }
14238
14239   /* A single member comdat group section may be discarded by a
14240      linkonce section and vice versa.  */
14241   if ((flags & SEC_GROUP) != 0)
14242     {
14243       asection *first = elf_next_in_group (sec);
14244
14245       if (first != NULL && elf_next_in_group (first) == first)
14246         /* Check this single member group against linkonce sections.  */
14247         for (l = already_linked_list->entry; l != NULL; l = l->next)
14248           if ((l->sec->flags & SEC_GROUP) == 0
14249               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
14250             {
14251               first->output_section = bfd_abs_section_ptr;
14252               first->kept_section = l->sec;
14253               sec->output_section = bfd_abs_section_ptr;
14254               break;
14255             }
14256     }
14257   else
14258     /* Check this linkonce section against single member groups.  */
14259     for (l = already_linked_list->entry; l != NULL; l = l->next)
14260       if (l->sec->flags & SEC_GROUP)
14261         {
14262           asection *first = elf_next_in_group (l->sec);
14263
14264           if (first != NULL
14265               && elf_next_in_group (first) == first
14266               && bfd_elf_match_symbols_in_sections (first, sec, info))
14267             {
14268               sec->output_section = bfd_abs_section_ptr;
14269               sec->kept_section = first;
14270               break;
14271             }
14272         }
14273
14274   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
14275      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
14276      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
14277      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
14278      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
14279      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
14280      `.gnu.linkonce.t.F' section from a different bfd not requiring any
14281      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
14282      The reverse order cannot happen as there is never a bfd with only the
14283      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
14284      matter as here were are looking only for cross-bfd sections.  */
14285
14286   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
14287     for (l = already_linked_list->entry; l != NULL; l = l->next)
14288       if ((l->sec->flags & SEC_GROUP) == 0
14289           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
14290         {
14291           if (abfd != l->sec->owner)
14292             sec->output_section = bfd_abs_section_ptr;
14293           break;
14294         }
14295
14296   /* This is the first section with this name.  Record it.  */
14297   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
14298     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
14299   return sec->output_section == bfd_abs_section_ptr;
14300 }
14301
14302 bfd_boolean
14303 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
14304 {
14305   return sym->st_shndx == SHN_COMMON;
14306 }
14307
14308 unsigned int
14309 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
14310 {
14311   return SHN_COMMON;
14312 }
14313
14314 asection *
14315 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
14316 {
14317   return bfd_com_section_ptr;
14318 }
14319
14320 bfd_vma
14321 _bfd_elf_default_got_elt_size (bfd *abfd,
14322                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
14323                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
14324                                bfd *ibfd ATTRIBUTE_UNUSED,
14325                                unsigned long symndx ATTRIBUTE_UNUSED)
14326 {
14327   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14328   return bed->s->arch_size / 8;
14329 }
14330
14331 /* Routines to support the creation of dynamic relocs.  */
14332
14333 /* Returns the name of the dynamic reloc section associated with SEC.  */
14334
14335 static const char *
14336 get_dynamic_reloc_section_name (bfd *       abfd,
14337                                 asection *  sec,
14338                                 bfd_boolean is_rela)
14339 {
14340   char *name;
14341   const char *old_name = bfd_get_section_name (NULL, sec);
14342   const char *prefix = is_rela ? ".rela" : ".rel";
14343
14344   if (old_name == NULL)
14345     return NULL;
14346
14347   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
14348   sprintf (name, "%s%s", prefix, old_name);
14349
14350   return name;
14351 }
14352
14353 /* Returns the dynamic reloc section associated with SEC.
14354    If necessary compute the name of the dynamic reloc section based
14355    on SEC's name (looked up in ABFD's string table) and the setting
14356    of IS_RELA.  */
14357
14358 asection *
14359 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
14360                                     asection *  sec,
14361                                     bfd_boolean is_rela)
14362 {
14363   asection * reloc_sec = elf_section_data (sec)->sreloc;
14364
14365   if (reloc_sec == NULL)
14366     {
14367       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14368
14369       if (name != NULL)
14370         {
14371           reloc_sec = bfd_get_linker_section (abfd, name);
14372
14373           if (reloc_sec != NULL)
14374             elf_section_data (sec)->sreloc = reloc_sec;
14375         }
14376     }
14377
14378   return reloc_sec;
14379 }
14380
14381 /* Returns the dynamic reloc section associated with SEC.  If the
14382    section does not exist it is created and attached to the DYNOBJ
14383    bfd and stored in the SRELOC field of SEC's elf_section_data
14384    structure.
14385
14386    ALIGNMENT is the alignment for the newly created section and
14387    IS_RELA defines whether the name should be .rela.<SEC's name>
14388    or .rel.<SEC's name>.  The section name is looked up in the
14389    string table associated with ABFD.  */
14390
14391 asection *
14392 _bfd_elf_make_dynamic_reloc_section (asection *sec,
14393                                      bfd *dynobj,
14394                                      unsigned int alignment,
14395                                      bfd *abfd,
14396                                      bfd_boolean is_rela)
14397 {
14398   asection * reloc_sec = elf_section_data (sec)->sreloc;
14399
14400   if (reloc_sec == NULL)
14401     {
14402       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14403
14404       if (name == NULL)
14405         return NULL;
14406
14407       reloc_sec = bfd_get_linker_section (dynobj, name);
14408
14409       if (reloc_sec == NULL)
14410         {
14411           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
14412                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
14413           if ((sec->flags & SEC_ALLOC) != 0)
14414             flags |= SEC_ALLOC | SEC_LOAD;
14415
14416           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
14417           if (reloc_sec != NULL)
14418             {
14419               /* _bfd_elf_get_sec_type_attr chooses a section type by
14420                  name.  Override as it may be wrong, eg. for a user
14421                  section named "auto" we'll get ".relauto" which is
14422                  seen to be a .rela section.  */
14423               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
14424               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
14425                 reloc_sec = NULL;
14426             }
14427         }
14428
14429       elf_section_data (sec)->sreloc = reloc_sec;
14430     }
14431
14432   return reloc_sec;
14433 }
14434
14435 /* Copy the ELF symbol type and other attributes for a linker script
14436    assignment from HSRC to HDEST.  Generally this should be treated as
14437    if we found a strong non-dynamic definition for HDEST (except that
14438    ld ignores multiple definition errors).  */
14439 void
14440 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
14441                                      struct bfd_link_hash_entry *hdest,
14442                                      struct bfd_link_hash_entry *hsrc)
14443 {
14444   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
14445   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
14446   Elf_Internal_Sym isym;
14447
14448   ehdest->type = ehsrc->type;
14449   ehdest->target_internal = ehsrc->target_internal;
14450
14451   isym.st_other = ehsrc->other;
14452   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
14453 }
14454
14455 /* Append a RELA relocation REL to section S in BFD.  */
14456
14457 void
14458 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14459 {
14460   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14461   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
14462   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
14463   bed->s->swap_reloca_out (abfd, rel, loc);
14464 }
14465
14466 /* Append a REL relocation REL to section S in BFD.  */
14467
14468 void
14469 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14470 {
14471   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14472   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
14473   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
14474   bed->s->swap_reloc_out (abfd, rel, loc);
14475 }
14476
14477 /* Define __start, __stop, .startof. or .sizeof. symbol.  */
14478
14479 struct bfd_link_hash_entry *
14480 bfd_elf_define_start_stop (struct bfd_link_info *info,
14481                            const char *symbol, asection *sec)
14482 {
14483   struct elf_link_hash_entry *h;
14484
14485   h = elf_link_hash_lookup (elf_hash_table (info), symbol,
14486                             FALSE, FALSE, TRUE);
14487   if (h != NULL
14488       && (h->root.type == bfd_link_hash_undefined
14489           || h->root.type == bfd_link_hash_undefweak
14490           || ((h->ref_regular || h->def_dynamic) && !h->def_regular)))
14491     {
14492       bfd_boolean was_dynamic = h->ref_dynamic || h->def_dynamic;
14493       h->root.type = bfd_link_hash_defined;
14494       h->root.u.def.section = sec;
14495       h->root.u.def.value = 0;
14496       h->def_regular = 1;
14497       h->def_dynamic = 0;
14498       h->start_stop = 1;
14499       h->u2.start_stop_section = sec;
14500       if (symbol[0] == '.')
14501         {
14502           /* .startof. and .sizeof. symbols are local.  */
14503           const struct elf_backend_data *bed;
14504           bed = get_elf_backend_data (info->output_bfd);
14505           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
14506         }
14507       else
14508         {
14509           if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
14510             h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_PROTECTED;
14511           if (was_dynamic)
14512             bfd_elf_link_record_dynamic_symbol (info, h);
14513         }
14514       return &h->root;
14515     }
14516   return NULL;
14517 }