[BFD][PR21703]Override the new defined symbol with the old normal symbol when --allow...
[external/binutils.git] / bfd / elflink.c
1 /* ELF linking support for BFD.
2    Copyright (C) 1995-2017 Free Software Foundation, Inc.
3
4    This file is part of BFD, the Binary File Descriptor library.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
19    MA 02110-1301, USA.  */
20
21 #include "sysdep.h"
22 #include "bfd.h"
23 #include "bfd_stdint.h"
24 #include "bfdlink.h"
25 #include "libbfd.h"
26 #define ARCH_SIZE 0
27 #include "elf-bfd.h"
28 #include "safe-ctype.h"
29 #include "libiberty.h"
30 #include "objalloc.h"
31 #if BFD_SUPPORTS_PLUGINS
32 #include "plugin-api.h"
33 #include "plugin.h"
34 #endif
35
36 /* This struct is used to pass information to routines called via
37    elf_link_hash_traverse which must return failure.  */
38
39 struct elf_info_failed
40 {
41   struct bfd_link_info *info;
42   bfd_boolean failed;
43 };
44
45 /* This structure is used to pass information to
46    _bfd_elf_link_find_version_dependencies.  */
47
48 struct elf_find_verdep_info
49 {
50   /* General link information.  */
51   struct bfd_link_info *info;
52   /* The number of dependencies.  */
53   unsigned int vers;
54   /* Whether we had a failure.  */
55   bfd_boolean failed;
56 };
57
58 static bfd_boolean _bfd_elf_fix_symbol_flags
59   (struct elf_link_hash_entry *, struct elf_info_failed *);
60
61 asection *
62 _bfd_elf_section_for_symbol (struct elf_reloc_cookie *cookie,
63                              unsigned long r_symndx,
64                              bfd_boolean discard)
65 {
66   if (r_symndx >= cookie->locsymcount
67       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
68     {
69       struct elf_link_hash_entry *h;
70
71       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
72
73       while (h->root.type == bfd_link_hash_indirect
74              || h->root.type == bfd_link_hash_warning)
75         h = (struct elf_link_hash_entry *) h->root.u.i.link;
76
77       if ((h->root.type == bfd_link_hash_defined
78            || h->root.type == bfd_link_hash_defweak)
79            && discarded_section (h->root.u.def.section))
80         return h->root.u.def.section;
81       else
82         return NULL;
83     }
84   else
85     {
86       /* It's not a relocation against a global symbol,
87          but it could be a relocation against a local
88          symbol for a discarded section.  */
89       asection *isec;
90       Elf_Internal_Sym *isym;
91
92       /* Need to: get the symbol; get the section.  */
93       isym = &cookie->locsyms[r_symndx];
94       isec = bfd_section_from_elf_index (cookie->abfd, isym->st_shndx);
95       if (isec != NULL
96           && discard ? discarded_section (isec) : 1)
97         return isec;
98      }
99   return NULL;
100 }
101
102 /* Define a symbol in a dynamic linkage section.  */
103
104 struct elf_link_hash_entry *
105 _bfd_elf_define_linkage_sym (bfd *abfd,
106                              struct bfd_link_info *info,
107                              asection *sec,
108                              const char *name)
109 {
110   struct elf_link_hash_entry *h;
111   struct bfd_link_hash_entry *bh;
112   const struct elf_backend_data *bed;
113
114   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
115   if (h != NULL)
116     {
117       /* Zap symbol defined in an as-needed lib that wasn't linked.
118          This is a symptom of a larger problem:  Absolute symbols
119          defined in shared libraries can't be overridden, because we
120          lose the link to the bfd which is via the symbol section.  */
121       h->root.type = bfd_link_hash_new;
122       bh = &h->root;
123     }
124   else
125     bh = NULL;
126
127   bed = get_elf_backend_data (abfd);
128   if (!_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL,
129                                          sec, 0, NULL, FALSE, bed->collect,
130                                          &bh))
131     return NULL;
132   h = (struct elf_link_hash_entry *) bh;
133   BFD_ASSERT (h != NULL);
134   h->def_regular = 1;
135   h->non_elf = 0;
136   h->root.linker_def = 1;
137   h->type = STT_OBJECT;
138   if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
139     h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
140
141   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
142   return h;
143 }
144
145 bfd_boolean
146 _bfd_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
147 {
148   flagword flags;
149   asection *s;
150   struct elf_link_hash_entry *h;
151   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
152   struct elf_link_hash_table *htab = elf_hash_table (info);
153
154   /* This function may be called more than once.  */
155   if (htab->sgot != NULL)
156     return TRUE;
157
158   flags = bed->dynamic_sec_flags;
159
160   s = bfd_make_section_anyway_with_flags (abfd,
161                                           (bed->rela_plts_and_copies_p
162                                            ? ".rela.got" : ".rel.got"),
163                                           (bed->dynamic_sec_flags
164                                            | SEC_READONLY));
165   if (s == NULL
166       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
167     return FALSE;
168   htab->srelgot = s;
169
170   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
171   if (s == NULL
172       || !bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
173     return FALSE;
174   htab->sgot = s;
175
176   if (bed->want_got_plt)
177     {
178       s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
179       if (s == NULL
180           || !bfd_set_section_alignment (abfd, s,
181                                          bed->s->log_file_align))
182         return FALSE;
183       htab->sgotplt = s;
184     }
185
186   /* The first bit of the global offset table is the header.  */
187   s->size += bed->got_header_size;
188
189   if (bed->want_got_sym)
190     {
191       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
192          (or .got.plt) section.  We don't do this in the linker script
193          because we don't want to define the symbol if we are not creating
194          a global offset table.  */
195       h = _bfd_elf_define_linkage_sym (abfd, info, s,
196                                        "_GLOBAL_OFFSET_TABLE_");
197       elf_hash_table (info)->hgot = h;
198       if (h == NULL)
199         return FALSE;
200     }
201
202   return TRUE;
203 }
204 \f
205 /* Create a strtab to hold the dynamic symbol names.  */
206 static bfd_boolean
207 _bfd_elf_link_create_dynstrtab (bfd *abfd, struct bfd_link_info *info)
208 {
209   struct elf_link_hash_table *hash_table;
210
211   hash_table = elf_hash_table (info);
212   if (hash_table->dynobj == NULL)
213     {
214       /* We may not set dynobj, an input file holding linker created
215          dynamic sections to abfd, which may be a dynamic object with
216          its own dynamic sections.  We need to find a normal input file
217          to hold linker created sections if possible.  */
218       if ((abfd->flags & (DYNAMIC | BFD_PLUGIN)) != 0)
219         {
220           bfd *ibfd;
221           asection *s;
222           for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link.next)
223             if ((ibfd->flags
224                  & (DYNAMIC | BFD_LINKER_CREATED | BFD_PLUGIN)) == 0
225                 && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
226                 && !((s = ibfd->sections) != NULL
227                      && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS))
228               {
229                 abfd = ibfd;
230                 break;
231               }
232         }
233       hash_table->dynobj = abfd;
234     }
235
236   if (hash_table->dynstr == NULL)
237     {
238       hash_table->dynstr = _bfd_elf_strtab_init ();
239       if (hash_table->dynstr == NULL)
240         return FALSE;
241     }
242   return TRUE;
243 }
244
245 /* Create some sections which will be filled in with dynamic linking
246    information.  ABFD is an input file which requires dynamic sections
247    to be created.  The dynamic sections take up virtual memory space
248    when the final executable is run, so we need to create them before
249    addresses are assigned to the output sections.  We work out the
250    actual contents and size of these sections later.  */
251
252 bfd_boolean
253 _bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
254 {
255   flagword flags;
256   asection *s;
257   const struct elf_backend_data *bed;
258   struct elf_link_hash_entry *h;
259
260   if (! is_elf_hash_table (info->hash))
261     return FALSE;
262
263   if (elf_hash_table (info)->dynamic_sections_created)
264     return TRUE;
265
266   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
267     return FALSE;
268
269   abfd = elf_hash_table (info)->dynobj;
270   bed = get_elf_backend_data (abfd);
271
272   flags = bed->dynamic_sec_flags;
273
274   /* A dynamically linked executable has a .interp section, but a
275      shared library does not.  */
276   if (bfd_link_executable (info) && !info->nointerp)
277     {
278       s = bfd_make_section_anyway_with_flags (abfd, ".interp",
279                                               flags | SEC_READONLY);
280       if (s == NULL)
281         return FALSE;
282     }
283
284   /* Create sections to hold version informations.  These are removed
285      if they are not needed.  */
286   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_d",
287                                           flags | SEC_READONLY);
288   if (s == NULL
289       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
290     return FALSE;
291
292   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version",
293                                           flags | SEC_READONLY);
294   if (s == NULL
295       || ! bfd_set_section_alignment (abfd, s, 1))
296     return FALSE;
297
298   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_r",
299                                           flags | SEC_READONLY);
300   if (s == NULL
301       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
302     return FALSE;
303
304   s = bfd_make_section_anyway_with_flags (abfd, ".dynsym",
305                                           flags | SEC_READONLY);
306   if (s == NULL
307       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
308     return FALSE;
309   elf_hash_table (info)->dynsym = s;
310
311   s = bfd_make_section_anyway_with_flags (abfd, ".dynstr",
312                                           flags | SEC_READONLY);
313   if (s == NULL)
314     return FALSE;
315
316   s = bfd_make_section_anyway_with_flags (abfd, ".dynamic", flags);
317   if (s == NULL
318       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
319     return FALSE;
320
321   /* The special symbol _DYNAMIC is always set to the start of the
322      .dynamic section.  We could set _DYNAMIC in a linker script, but we
323      only want to define it if we are, in fact, creating a .dynamic
324      section.  We don't want to define it if there is no .dynamic
325      section, since on some ELF platforms the start up code examines it
326      to decide how to initialize the process.  */
327   h = _bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC");
328   elf_hash_table (info)->hdynamic = h;
329   if (h == NULL)
330     return FALSE;
331
332   if (info->emit_hash)
333     {
334       s = bfd_make_section_anyway_with_flags (abfd, ".hash",
335                                               flags | SEC_READONLY);
336       if (s == NULL
337           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
338         return FALSE;
339       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
340     }
341
342   if (info->emit_gnu_hash)
343     {
344       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
345                                               flags | SEC_READONLY);
346       if (s == NULL
347           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
348         return FALSE;
349       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
350          4 32-bit words followed by variable count of 64-bit words, then
351          variable count of 32-bit words.  */
352       if (bed->s->arch_size == 64)
353         elf_section_data (s)->this_hdr.sh_entsize = 0;
354       else
355         elf_section_data (s)->this_hdr.sh_entsize = 4;
356     }
357
358   /* Let the backend create the rest of the sections.  This lets the
359      backend set the right flags.  The backend will normally create
360      the .got and .plt sections.  */
361   if (bed->elf_backend_create_dynamic_sections == NULL
362       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
363     return FALSE;
364
365   elf_hash_table (info)->dynamic_sections_created = TRUE;
366
367   return TRUE;
368 }
369
370 /* Create dynamic sections when linking against a dynamic object.  */
371
372 bfd_boolean
373 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
374 {
375   flagword flags, pltflags;
376   struct elf_link_hash_entry *h;
377   asection *s;
378   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
379   struct elf_link_hash_table *htab = elf_hash_table (info);
380
381   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
382      .rel[a].bss sections.  */
383   flags = bed->dynamic_sec_flags;
384
385   pltflags = flags;
386   if (bed->plt_not_loaded)
387     /* We do not clear SEC_ALLOC here because we still want the OS to
388        allocate space for the section; it's just that there's nothing
389        to read in from the object file.  */
390     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
391   else
392     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
393   if (bed->plt_readonly)
394     pltflags |= SEC_READONLY;
395
396   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
397   if (s == NULL
398       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
399     return FALSE;
400   htab->splt = s;
401
402   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
403      .plt section.  */
404   if (bed->want_plt_sym)
405     {
406       h = _bfd_elf_define_linkage_sym (abfd, info, s,
407                                        "_PROCEDURE_LINKAGE_TABLE_");
408       elf_hash_table (info)->hplt = h;
409       if (h == NULL)
410         return FALSE;
411     }
412
413   s = bfd_make_section_anyway_with_flags (abfd,
414                                           (bed->rela_plts_and_copies_p
415                                            ? ".rela.plt" : ".rel.plt"),
416                                           flags | SEC_READONLY);
417   if (s == NULL
418       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
419     return FALSE;
420   htab->srelplt = s;
421
422   if (! _bfd_elf_create_got_section (abfd, info))
423     return FALSE;
424
425   if (bed->want_dynbss)
426     {
427       /* The .dynbss section is a place to put symbols which are defined
428          by dynamic objects, are referenced by regular objects, and are
429          not functions.  We must allocate space for them in the process
430          image and use a R_*_COPY reloc to tell the dynamic linker to
431          initialize them at run time.  The linker script puts the .dynbss
432          section into the .bss section of the final image.  */
433       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
434                                               SEC_ALLOC | SEC_LINKER_CREATED);
435       if (s == NULL)
436         return FALSE;
437       htab->sdynbss = s;
438
439       if (bed->want_dynrelro)
440         {
441           /* Similarly, but for symbols that were originally in read-only
442              sections.  This section doesn't really need to have contents,
443              but make it like other .data.rel.ro sections.  */
444           s = bfd_make_section_anyway_with_flags (abfd, ".data.rel.ro",
445                                                   flags);
446           if (s == NULL)
447             return FALSE;
448           htab->sdynrelro = s;
449         }
450
451       /* The .rel[a].bss section holds copy relocs.  This section is not
452          normally needed.  We need to create it here, though, so that the
453          linker will map it to an output section.  We can't just create it
454          only if we need it, because we will not know whether we need it
455          until we have seen all the input files, and the first time the
456          main linker code calls BFD after examining all the input files
457          (size_dynamic_sections) the input sections have already been
458          mapped to the output sections.  If the section turns out not to
459          be needed, we can discard it later.  We will never need this
460          section when generating a shared object, since they do not use
461          copy relocs.  */
462       if (bfd_link_executable (info))
463         {
464           s = bfd_make_section_anyway_with_flags (abfd,
465                                                   (bed->rela_plts_and_copies_p
466                                                    ? ".rela.bss" : ".rel.bss"),
467                                                   flags | SEC_READONLY);
468           if (s == NULL
469               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
470             return FALSE;
471           htab->srelbss = s;
472
473           if (bed->want_dynrelro)
474             {
475               s = (bfd_make_section_anyway_with_flags
476                    (abfd, (bed->rela_plts_and_copies_p
477                            ? ".rela.data.rel.ro" : ".rel.data.rel.ro"),
478                     flags | SEC_READONLY));
479               if (s == NULL
480                   || ! bfd_set_section_alignment (abfd, s,
481                                                   bed->s->log_file_align))
482                 return FALSE;
483               htab->sreldynrelro = s;
484             }
485         }
486     }
487
488   return TRUE;
489 }
490 \f
491 /* Record a new dynamic symbol.  We record the dynamic symbols as we
492    read the input files, since we need to have a list of all of them
493    before we can determine the final sizes of the output sections.
494    Note that we may actually call this function even though we are not
495    going to output any dynamic symbols; in some cases we know that a
496    symbol should be in the dynamic symbol table, but only if there is
497    one.  */
498
499 bfd_boolean
500 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
501                                     struct elf_link_hash_entry *h)
502 {
503   if (h->dynindx == -1)
504     {
505       struct elf_strtab_hash *dynstr;
506       char *p;
507       const char *name;
508       size_t indx;
509
510       /* XXX: The ABI draft says the linker must turn hidden and
511          internal symbols into STB_LOCAL symbols when producing the
512          DSO. However, if ld.so honors st_other in the dynamic table,
513          this would not be necessary.  */
514       switch (ELF_ST_VISIBILITY (h->other))
515         {
516         case STV_INTERNAL:
517         case STV_HIDDEN:
518           if (h->root.type != bfd_link_hash_undefined
519               && h->root.type != bfd_link_hash_undefweak)
520             {
521               h->forced_local = 1;
522               if (!elf_hash_table (info)->is_relocatable_executable)
523                 return TRUE;
524             }
525
526         default:
527           break;
528         }
529
530       h->dynindx = elf_hash_table (info)->dynsymcount;
531       ++elf_hash_table (info)->dynsymcount;
532
533       dynstr = elf_hash_table (info)->dynstr;
534       if (dynstr == NULL)
535         {
536           /* Create a strtab to hold the dynamic symbol names.  */
537           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
538           if (dynstr == NULL)
539             return FALSE;
540         }
541
542       /* We don't put any version information in the dynamic string
543          table.  */
544       name = h->root.root.string;
545       p = strchr (name, ELF_VER_CHR);
546       if (p != NULL)
547         /* We know that the p points into writable memory.  In fact,
548            there are only a few symbols that have read-only names, being
549            those like _GLOBAL_OFFSET_TABLE_ that are created specially
550            by the backends.  Most symbols will have names pointing into
551            an ELF string table read from a file, or to objalloc memory.  */
552         *p = 0;
553
554       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
555
556       if (p != NULL)
557         *p = ELF_VER_CHR;
558
559       if (indx == (size_t) -1)
560         return FALSE;
561       h->dynstr_index = indx;
562     }
563
564   return TRUE;
565 }
566 \f
567 /* Mark a symbol dynamic.  */
568
569 static void
570 bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
571                                   struct elf_link_hash_entry *h,
572                                   Elf_Internal_Sym *sym)
573 {
574   struct bfd_elf_dynamic_list *d = info->dynamic_list;
575
576   /* It may be called more than once on the same H.  */
577   if(h->dynamic || bfd_link_relocatable (info))
578     return;
579
580   if ((info->dynamic_data
581        && (h->type == STT_OBJECT
582            || h->type == STT_COMMON
583            || (sym != NULL
584                && (ELF_ST_TYPE (sym->st_info) == STT_OBJECT
585                    || ELF_ST_TYPE (sym->st_info) == STT_COMMON))))
586       || (d != NULL
587           && h->non_elf
588           && (*d->match) (&d->head, NULL, h->root.root.string)))
589     h->dynamic = 1;
590 }
591
592 /* Record an assignment to a symbol made by a linker script.  We need
593    this in case some dynamic object refers to this symbol.  */
594
595 bfd_boolean
596 bfd_elf_record_link_assignment (bfd *output_bfd,
597                                 struct bfd_link_info *info,
598                                 const char *name,
599                                 bfd_boolean provide,
600                                 bfd_boolean hidden)
601 {
602   struct elf_link_hash_entry *h, *hv;
603   struct elf_link_hash_table *htab;
604   const struct elf_backend_data *bed;
605
606   if (!is_elf_hash_table (info->hash))
607     return TRUE;
608
609   htab = elf_hash_table (info);
610   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
611   if (h == NULL)
612     return provide;
613
614   if (h->root.type == bfd_link_hash_warning)
615     h = (struct elf_link_hash_entry *) h->root.u.i.link;
616
617   if (h->versioned == unknown)
618     {
619       /* Set versioned if symbol version is unknown.  */
620       char *version = strrchr (name, ELF_VER_CHR);
621       if (version)
622         {
623           if (version > name && version[-1] != ELF_VER_CHR)
624             h->versioned = versioned_hidden;
625           else
626             h->versioned = versioned;
627         }
628     }
629
630   /* Symbols defined in a linker script but not referenced anywhere
631      else will have non_elf set.  */
632   if (h->non_elf)
633     {
634       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
635       h->non_elf = 0;
636     }
637
638   switch (h->root.type)
639     {
640     case bfd_link_hash_defined:
641     case bfd_link_hash_defweak:
642     case bfd_link_hash_common:
643       break;
644     case bfd_link_hash_undefweak:
645     case bfd_link_hash_undefined:
646       /* Since we're defining the symbol, don't let it seem to have not
647          been defined.  record_dynamic_symbol and size_dynamic_sections
648          may depend on this.  */
649       h->root.type = bfd_link_hash_new;
650       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
651         bfd_link_repair_undef_list (&htab->root);
652       break;
653     case bfd_link_hash_new:
654       break;
655     case bfd_link_hash_indirect:
656       /* We had a versioned symbol in a dynamic library.  We make the
657          the versioned symbol point to this one.  */
658       bed = get_elf_backend_data (output_bfd);
659       hv = h;
660       while (hv->root.type == bfd_link_hash_indirect
661              || hv->root.type == bfd_link_hash_warning)
662         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
663       /* We don't need to update h->root.u since linker will set them
664          later.  */
665       h->root.type = bfd_link_hash_undefined;
666       hv->root.type = bfd_link_hash_indirect;
667       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
668       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
669       break;
670     default:
671       BFD_FAIL ();
672       return FALSE;
673     }
674
675   /* If this symbol is being provided by the linker script, and it is
676      currently defined by a dynamic object, but not by a regular
677      object, then mark it as undefined so that the generic linker will
678      force the correct value.  */
679   if (provide
680       && h->def_dynamic
681       && !h->def_regular)
682     h->root.type = bfd_link_hash_undefined;
683
684   /* If this symbol is not being provided by the linker script, and it is
685      currently defined by a dynamic object, but not by a regular object,
686      then clear out any version information because the symbol will not be
687      associated with the dynamic object any more.  */
688   if (!provide
689       && h->def_dynamic
690       && !h->def_regular)
691     h->verinfo.verdef = NULL;
692
693   /* Make sure this symbol is not garbage collected.  */
694   h->mark = 1;
695
696   h->def_regular = 1;
697
698   if (hidden)
699     {
700       bed = get_elf_backend_data (output_bfd);
701       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
702         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
703       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
704     }
705
706   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
707      and executables.  */
708   if (!bfd_link_relocatable (info)
709       && h->dynindx != -1
710       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
711           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
712     h->forced_local = 1;
713
714   if ((h->def_dynamic
715        || h->ref_dynamic
716        || bfd_link_dll (info)
717        || elf_hash_table (info)->is_relocatable_executable)
718       && h->dynindx == -1)
719     {
720       if (! bfd_elf_link_record_dynamic_symbol (info, h))
721         return FALSE;
722
723       /* If this is a weak defined symbol, and we know a corresponding
724          real symbol from the same dynamic object, make sure the real
725          symbol is also made into a dynamic symbol.  */
726       if (h->u.weakdef != NULL
727           && h->u.weakdef->dynindx == -1)
728         {
729           if (! bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
730             return FALSE;
731         }
732     }
733
734   return TRUE;
735 }
736
737 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
738    success, and 2 on a failure caused by attempting to record a symbol
739    in a discarded section, eg. a discarded link-once section symbol.  */
740
741 int
742 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
743                                           bfd *input_bfd,
744                                           long input_indx)
745 {
746   bfd_size_type amt;
747   struct elf_link_local_dynamic_entry *entry;
748   struct elf_link_hash_table *eht;
749   struct elf_strtab_hash *dynstr;
750   size_t dynstr_index;
751   char *name;
752   Elf_External_Sym_Shndx eshndx;
753   char esym[sizeof (Elf64_External_Sym)];
754
755   if (! is_elf_hash_table (info->hash))
756     return 0;
757
758   /* See if the entry exists already.  */
759   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
760     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
761       return 1;
762
763   amt = sizeof (*entry);
764   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
765   if (entry == NULL)
766     return 0;
767
768   /* Go find the symbol, so that we can find it's name.  */
769   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
770                              1, input_indx, &entry->isym, esym, &eshndx))
771     {
772       bfd_release (input_bfd, entry);
773       return 0;
774     }
775
776   if (entry->isym.st_shndx != SHN_UNDEF
777       && entry->isym.st_shndx < SHN_LORESERVE)
778     {
779       asection *s;
780
781       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
782       if (s == NULL || bfd_is_abs_section (s->output_section))
783         {
784           /* We can still bfd_release here as nothing has done another
785              bfd_alloc.  We can't do this later in this function.  */
786           bfd_release (input_bfd, entry);
787           return 2;
788         }
789     }
790
791   name = (bfd_elf_string_from_elf_section
792           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
793            entry->isym.st_name));
794
795   dynstr = elf_hash_table (info)->dynstr;
796   if (dynstr == NULL)
797     {
798       /* Create a strtab to hold the dynamic symbol names.  */
799       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
800       if (dynstr == NULL)
801         return 0;
802     }
803
804   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
805   if (dynstr_index == (size_t) -1)
806     return 0;
807   entry->isym.st_name = dynstr_index;
808
809   eht = elf_hash_table (info);
810
811   entry->next = eht->dynlocal;
812   eht->dynlocal = entry;
813   entry->input_bfd = input_bfd;
814   entry->input_indx = input_indx;
815   eht->dynsymcount++;
816
817   /* Whatever binding the symbol had before, it's now local.  */
818   entry->isym.st_info
819     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
820
821   /* The dynindx will be set at the end of size_dynamic_sections.  */
822
823   return 1;
824 }
825
826 /* Return the dynindex of a local dynamic symbol.  */
827
828 long
829 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
830                                     bfd *input_bfd,
831                                     long input_indx)
832 {
833   struct elf_link_local_dynamic_entry *e;
834
835   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
836     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
837       return e->dynindx;
838   return -1;
839 }
840
841 /* This function is used to renumber the dynamic symbols, if some of
842    them are removed because they are marked as local.  This is called
843    via elf_link_hash_traverse.  */
844
845 static bfd_boolean
846 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
847                                       void *data)
848 {
849   size_t *count = (size_t *) data;
850
851   if (h->forced_local)
852     return TRUE;
853
854   if (h->dynindx != -1)
855     h->dynindx = ++(*count);
856
857   return TRUE;
858 }
859
860
861 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
862    STB_LOCAL binding.  */
863
864 static bfd_boolean
865 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
866                                             void *data)
867 {
868   size_t *count = (size_t *) data;
869
870   if (!h->forced_local)
871     return TRUE;
872
873   if (h->dynindx != -1)
874     h->dynindx = ++(*count);
875
876   return TRUE;
877 }
878
879 /* Return true if the dynamic symbol for a given section should be
880    omitted when creating a shared library.  */
881 bfd_boolean
882 _bfd_elf_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED,
883                                    struct bfd_link_info *info,
884                                    asection *p)
885 {
886   struct elf_link_hash_table *htab;
887   asection *ip;
888
889   switch (elf_section_data (p)->this_hdr.sh_type)
890     {
891     case SHT_PROGBITS:
892     case SHT_NOBITS:
893       /* If sh_type is yet undecided, assume it could be
894          SHT_PROGBITS/SHT_NOBITS.  */
895     case SHT_NULL:
896       htab = elf_hash_table (info);
897       if (p == htab->tls_sec)
898         return FALSE;
899
900       if (htab->text_index_section != NULL)
901         return p != htab->text_index_section && p != htab->data_index_section;
902
903       return (htab->dynobj != NULL
904               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
905               && ip->output_section == p);
906
907       /* There shouldn't be section relative relocations
908          against any other section.  */
909     default:
910       return TRUE;
911     }
912 }
913
914 /* Assign dynsym indices.  In a shared library we generate a section
915    symbol for each output section, which come first.  Next come symbols
916    which have been forced to local binding.  Then all of the back-end
917    allocated local dynamic syms, followed by the rest of the global
918    symbols.  */
919
920 static unsigned long
921 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
922                                 struct bfd_link_info *info,
923                                 unsigned long *section_sym_count)
924 {
925   unsigned long dynsymcount = 0;
926
927   if (bfd_link_pic (info)
928       || elf_hash_table (info)->is_relocatable_executable)
929     {
930       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
931       asection *p;
932       for (p = output_bfd->sections; p ; p = p->next)
933         if ((p->flags & SEC_EXCLUDE) == 0
934             && (p->flags & SEC_ALLOC) != 0
935             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
936           elf_section_data (p)->dynindx = ++dynsymcount;
937         else
938           elf_section_data (p)->dynindx = 0;
939     }
940   *section_sym_count = dynsymcount;
941
942   elf_link_hash_traverse (elf_hash_table (info),
943                           elf_link_renumber_local_hash_table_dynsyms,
944                           &dynsymcount);
945
946   if (elf_hash_table (info)->dynlocal)
947     {
948       struct elf_link_local_dynamic_entry *p;
949       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
950         p->dynindx = ++dynsymcount;
951     }
952   elf_hash_table (info)->local_dynsymcount = dynsymcount;
953
954   elf_link_hash_traverse (elf_hash_table (info),
955                           elf_link_renumber_hash_table_dynsyms,
956                           &dynsymcount);
957
958   /* There is an unused NULL entry at the head of the table which we
959      must account for in our count even if the table is empty since it
960      is intended for the mandatory DT_SYMTAB tag (.dynsym section) in
961      .dynamic section.  */
962   dynsymcount++;
963
964   elf_hash_table (info)->dynsymcount = dynsymcount;
965   return dynsymcount;
966 }
967
968 /* Merge st_other field.  */
969
970 static void
971 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
972                     const Elf_Internal_Sym *isym, asection *sec,
973                     bfd_boolean definition, bfd_boolean dynamic)
974 {
975   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
976
977   /* If st_other has a processor-specific meaning, specific
978      code might be needed here.  */
979   if (bed->elf_backend_merge_symbol_attribute)
980     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
981                                                 dynamic);
982
983   if (!dynamic)
984     {
985       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
986       unsigned hvis = ELF_ST_VISIBILITY (h->other);
987
988       /* Keep the most constraining visibility.  Leave the remainder
989          of the st_other field to elf_backend_merge_symbol_attribute.  */
990       if (symvis - 1 < hvis - 1)
991         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
992     }
993   else if (definition
994            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
995            && (sec->flags & SEC_READONLY) == 0)
996     h->protected_def = 1;
997 }
998
999 /* This function is called when we want to merge a new symbol with an
1000    existing symbol.  It handles the various cases which arise when we
1001    find a definition in a dynamic object, or when there is already a
1002    definition in a dynamic object.  The new symbol is described by
1003    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
1004    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
1005    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
1006    of an old common symbol.  We set OVERRIDE if the old symbol is
1007    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
1008    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
1009    to change.  By OK to change, we mean that we shouldn't warn if the
1010    type or size does change.  */
1011
1012 static bfd_boolean
1013 _bfd_elf_merge_symbol (bfd *abfd,
1014                        struct bfd_link_info *info,
1015                        const char *name,
1016                        Elf_Internal_Sym *sym,
1017                        asection **psec,
1018                        bfd_vma *pvalue,
1019                        struct elf_link_hash_entry **sym_hash,
1020                        bfd **poldbfd,
1021                        bfd_boolean *pold_weak,
1022                        unsigned int *pold_alignment,
1023                        bfd_boolean *skip,
1024                        bfd_boolean *override,
1025                        bfd_boolean *type_change_ok,
1026                        bfd_boolean *size_change_ok,
1027                        bfd_boolean *matched)
1028 {
1029   asection *sec, *oldsec;
1030   struct elf_link_hash_entry *h;
1031   struct elf_link_hash_entry *hi;
1032   struct elf_link_hash_entry *flip;
1033   int bind;
1034   bfd *oldbfd;
1035   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
1036   bfd_boolean newweak, oldweak, newfunc, oldfunc;
1037   const struct elf_backend_data *bed;
1038   char *new_version;
1039   bfd_boolean default_sym = *matched;
1040
1041   *skip = FALSE;
1042   *override = FALSE;
1043
1044   sec = *psec;
1045   bind = ELF_ST_BIND (sym->st_info);
1046
1047   if (! bfd_is_und_section (sec))
1048     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
1049   else
1050     h = ((struct elf_link_hash_entry *)
1051          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
1052   if (h == NULL)
1053     return FALSE;
1054   *sym_hash = h;
1055
1056   bed = get_elf_backend_data (abfd);
1057
1058   /* NEW_VERSION is the symbol version of the new symbol.  */
1059   if (h->versioned != unversioned)
1060     {
1061       /* Symbol version is unknown or versioned.  */
1062       new_version = strrchr (name, ELF_VER_CHR);
1063       if (new_version)
1064         {
1065           if (h->versioned == unknown)
1066             {
1067               if (new_version > name && new_version[-1] != ELF_VER_CHR)
1068                 h->versioned = versioned_hidden;
1069               else
1070                 h->versioned = versioned;
1071             }
1072           new_version += 1;
1073           if (new_version[0] == '\0')
1074             new_version = NULL;
1075         }
1076       else
1077         h->versioned = unversioned;
1078     }
1079   else
1080     new_version = NULL;
1081
1082   /* For merging, we only care about real symbols.  But we need to make
1083      sure that indirect symbol dynamic flags are updated.  */
1084   hi = h;
1085   while (h->root.type == bfd_link_hash_indirect
1086          || h->root.type == bfd_link_hash_warning)
1087     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1088
1089   if (!*matched)
1090     {
1091       if (hi == h || h->root.type == bfd_link_hash_new)
1092         *matched = TRUE;
1093       else
1094         {
1095           /* OLD_HIDDEN is true if the existing symbol is only visible
1096              to the symbol with the same symbol version.  NEW_HIDDEN is
1097              true if the new symbol is only visible to the symbol with
1098              the same symbol version.  */
1099           bfd_boolean old_hidden = h->versioned == versioned_hidden;
1100           bfd_boolean new_hidden = hi->versioned == versioned_hidden;
1101           if (!old_hidden && !new_hidden)
1102             /* The new symbol matches the existing symbol if both
1103                aren't hidden.  */
1104             *matched = TRUE;
1105           else
1106             {
1107               /* OLD_VERSION is the symbol version of the existing
1108                  symbol. */
1109               char *old_version;
1110
1111               if (h->versioned >= versioned)
1112                 old_version = strrchr (h->root.root.string,
1113                                        ELF_VER_CHR) + 1;
1114               else
1115                  old_version = NULL;
1116
1117               /* The new symbol matches the existing symbol if they
1118                  have the same symbol version.  */
1119               *matched = (old_version == new_version
1120                           || (old_version != NULL
1121                               && new_version != NULL
1122                               && strcmp (old_version, new_version) == 0));
1123             }
1124         }
1125     }
1126
1127   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
1128      existing symbol.  */
1129
1130   oldbfd = NULL;
1131   oldsec = NULL;
1132   switch (h->root.type)
1133     {
1134     default:
1135       break;
1136
1137     case bfd_link_hash_undefined:
1138     case bfd_link_hash_undefweak:
1139       oldbfd = h->root.u.undef.abfd;
1140       break;
1141
1142     case bfd_link_hash_defined:
1143     case bfd_link_hash_defweak:
1144       oldbfd = h->root.u.def.section->owner;
1145       oldsec = h->root.u.def.section;
1146       break;
1147
1148     case bfd_link_hash_common:
1149       oldbfd = h->root.u.c.p->section->owner;
1150       oldsec = h->root.u.c.p->section;
1151       if (pold_alignment)
1152         *pold_alignment = h->root.u.c.p->alignment_power;
1153       break;
1154     }
1155   if (poldbfd && *poldbfd == NULL)
1156     *poldbfd = oldbfd;
1157
1158   /* Differentiate strong and weak symbols.  */
1159   newweak = bind == STB_WEAK;
1160   oldweak = (h->root.type == bfd_link_hash_defweak
1161              || h->root.type == bfd_link_hash_undefweak);
1162   if (pold_weak)
1163     *pold_weak = oldweak;
1164
1165   /* This code is for coping with dynamic objects, and is only useful
1166      if we are doing an ELF link.  */
1167   if (!(*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
1168     return TRUE;
1169
1170   /* We have to check it for every instance since the first few may be
1171      references and not all compilers emit symbol type for undefined
1172      symbols.  */
1173   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
1174
1175   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1176      respectively, is from a dynamic object.  */
1177
1178   newdyn = (abfd->flags & DYNAMIC) != 0;
1179
1180   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
1181      syms and defined syms in dynamic libraries respectively.
1182      ref_dynamic on the other hand can be set for a symbol defined in
1183      a dynamic library, and def_dynamic may not be set;  When the
1184      definition in a dynamic lib is overridden by a definition in the
1185      executable use of the symbol in the dynamic lib becomes a
1186      reference to the executable symbol.  */
1187   if (newdyn)
1188     {
1189       if (bfd_is_und_section (sec))
1190         {
1191           if (bind != STB_WEAK)
1192             {
1193               h->ref_dynamic_nonweak = 1;
1194               hi->ref_dynamic_nonweak = 1;
1195             }
1196         }
1197       else
1198         {
1199           /* Update the existing symbol only if they match. */
1200           if (*matched)
1201             h->dynamic_def = 1;
1202           hi->dynamic_def = 1;
1203         }
1204     }
1205
1206   /* If we just created the symbol, mark it as being an ELF symbol.
1207      Other than that, there is nothing to do--there is no merge issue
1208      with a newly defined symbol--so we just return.  */
1209
1210   if (h->root.type == bfd_link_hash_new)
1211     {
1212       h->non_elf = 0;
1213       return TRUE;
1214     }
1215
1216   /* In cases involving weak versioned symbols, we may wind up trying
1217      to merge a symbol with itself.  Catch that here, to avoid the
1218      confusion that results if we try to override a symbol with
1219      itself.  The additional tests catch cases like
1220      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1221      dynamic object, which we do want to handle here.  */
1222   if (abfd == oldbfd
1223       && (newweak || oldweak)
1224       && ((abfd->flags & DYNAMIC) == 0
1225           || !h->def_regular))
1226     return TRUE;
1227
1228   olddyn = FALSE;
1229   if (oldbfd != NULL)
1230     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1231   else if (oldsec != NULL)
1232     {
1233       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1234          indices used by MIPS ELF.  */
1235       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1236     }
1237
1238   /* Handle a case where plugin_notice won't be called and thus won't
1239      set the non_ir_ref flags on the first pass over symbols.  */
1240   if (oldbfd != NULL
1241       && (oldbfd->flags & BFD_PLUGIN) != (abfd->flags & BFD_PLUGIN)
1242       && newdyn != olddyn)
1243     {
1244       h->root.non_ir_ref_dynamic = TRUE;
1245       hi->root.non_ir_ref_dynamic = TRUE;
1246     }
1247
1248   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1249      respectively, appear to be a definition rather than reference.  */
1250
1251   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1252
1253   olddef = (h->root.type != bfd_link_hash_undefined
1254             && h->root.type != bfd_link_hash_undefweak
1255             && h->root.type != bfd_link_hash_common);
1256
1257   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1258      respectively, appear to be a function.  */
1259
1260   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1261              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1262
1263   oldfunc = (h->type != STT_NOTYPE
1264              && bed->is_function_type (h->type));
1265
1266   if (!(newfunc && oldfunc)
1267       && ELF_ST_TYPE (sym->st_info) != h->type
1268       && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1269       && h->type != STT_NOTYPE
1270       && (newdef || bfd_is_com_section (sec))
1271       && (olddef || h->root.type == bfd_link_hash_common))
1272     {
1273       /* If creating a default indirect symbol ("foo" or "foo@") from
1274          a dynamic versioned definition ("foo@@") skip doing so if
1275          there is an existing regular definition with a different
1276          type.  We don't want, for example, a "time" variable in the
1277          executable overriding a "time" function in a shared library.  */
1278       if (newdyn
1279           && !olddyn)
1280         {
1281           *skip = TRUE;
1282           return TRUE;
1283         }
1284
1285       /* When adding a symbol from a regular object file after we have
1286          created indirect symbols, undo the indirection and any
1287          dynamic state.  */
1288       if (hi != h
1289           && !newdyn
1290           && olddyn)
1291         {
1292           h = hi;
1293           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1294           h->forced_local = 0;
1295           h->ref_dynamic = 0;
1296           h->def_dynamic = 0;
1297           h->dynamic_def = 0;
1298           if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1299             {
1300               h->root.type = bfd_link_hash_undefined;
1301               h->root.u.undef.abfd = abfd;
1302             }
1303           else
1304             {
1305               h->root.type = bfd_link_hash_new;
1306               h->root.u.undef.abfd = NULL;
1307             }
1308           return TRUE;
1309         }
1310     }
1311
1312   /* Check TLS symbols.  We don't check undefined symbols introduced
1313      by "ld -u" which have no type (and oldbfd NULL), and we don't
1314      check symbols from plugins because they also have no type.  */
1315   if (oldbfd != NULL
1316       && (oldbfd->flags & BFD_PLUGIN) == 0
1317       && (abfd->flags & BFD_PLUGIN) == 0
1318       && ELF_ST_TYPE (sym->st_info) != h->type
1319       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1320     {
1321       bfd *ntbfd, *tbfd;
1322       bfd_boolean ntdef, tdef;
1323       asection *ntsec, *tsec;
1324
1325       if (h->type == STT_TLS)
1326         {
1327           ntbfd = abfd;
1328           ntsec = sec;
1329           ntdef = newdef;
1330           tbfd = oldbfd;
1331           tsec = oldsec;
1332           tdef = olddef;
1333         }
1334       else
1335         {
1336           ntbfd = oldbfd;
1337           ntsec = oldsec;
1338           ntdef = olddef;
1339           tbfd = abfd;
1340           tsec = sec;
1341           tdef = newdef;
1342         }
1343
1344       if (tdef && ntdef)
1345         _bfd_error_handler
1346           /* xgettext:c-format */
1347           (_("%s: TLS definition in %B section %A "
1348              "mismatches non-TLS definition in %B section %A"),
1349            h->root.root.string, tbfd, tsec, ntbfd, ntsec);
1350       else if (!tdef && !ntdef)
1351         _bfd_error_handler
1352           /* xgettext:c-format */
1353           (_("%s: TLS reference in %B "
1354              "mismatches non-TLS reference in %B"),
1355            h->root.root.string, tbfd, ntbfd);
1356       else if (tdef)
1357         _bfd_error_handler
1358           /* xgettext:c-format */
1359           (_("%s: TLS definition in %B section %A "
1360              "mismatches non-TLS reference in %B"),
1361            h->root.root.string, tbfd, tsec, ntbfd);
1362       else
1363         _bfd_error_handler
1364           /* xgettext:c-format */
1365           (_("%s: TLS reference in %B "
1366              "mismatches non-TLS definition in %B section %A"),
1367            h->root.root.string, tbfd, ntbfd, ntsec);
1368
1369       bfd_set_error (bfd_error_bad_value);
1370       return FALSE;
1371     }
1372
1373   /* If the old symbol has non-default visibility, we ignore the new
1374      definition from a dynamic object.  */
1375   if (newdyn
1376       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1377       && !bfd_is_und_section (sec))
1378     {
1379       *skip = TRUE;
1380       /* Make sure this symbol is dynamic.  */
1381       h->ref_dynamic = 1;
1382       hi->ref_dynamic = 1;
1383       /* A protected symbol has external availability. Make sure it is
1384          recorded as dynamic.
1385
1386          FIXME: Should we check type and size for protected symbol?  */
1387       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1388         return bfd_elf_link_record_dynamic_symbol (info, h);
1389       else
1390         return TRUE;
1391     }
1392   else if (!newdyn
1393            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1394            && h->def_dynamic)
1395     {
1396       /* If the new symbol with non-default visibility comes from a
1397          relocatable file and the old definition comes from a dynamic
1398          object, we remove the old definition.  */
1399       if (hi->root.type == bfd_link_hash_indirect)
1400         {
1401           /* Handle the case where the old dynamic definition is
1402              default versioned.  We need to copy the symbol info from
1403              the symbol with default version to the normal one if it
1404              was referenced before.  */
1405           if (h->ref_regular)
1406             {
1407               hi->root.type = h->root.type;
1408               h->root.type = bfd_link_hash_indirect;
1409               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1410
1411               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1412               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1413                 {
1414                   /* If the new symbol is hidden or internal, completely undo
1415                      any dynamic link state.  */
1416                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1417                   h->forced_local = 0;
1418                   h->ref_dynamic = 0;
1419                 }
1420               else
1421                 h->ref_dynamic = 1;
1422
1423               h->def_dynamic = 0;
1424               /* FIXME: Should we check type and size for protected symbol?  */
1425               h->size = 0;
1426               h->type = 0;
1427
1428               h = hi;
1429             }
1430           else
1431             h = hi;
1432         }
1433
1434       /* If the old symbol was undefined before, then it will still be
1435          on the undefs list.  If the new symbol is undefined or
1436          common, we can't make it bfd_link_hash_new here, because new
1437          undefined or common symbols will be added to the undefs list
1438          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1439          added twice to the undefs list.  Also, if the new symbol is
1440          undefweak then we don't want to lose the strong undef.  */
1441       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1442         {
1443           h->root.type = bfd_link_hash_undefined;
1444           h->root.u.undef.abfd = abfd;
1445         }
1446       else
1447         {
1448           h->root.type = bfd_link_hash_new;
1449           h->root.u.undef.abfd = NULL;
1450         }
1451
1452       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1453         {
1454           /* If the new symbol is hidden or internal, completely undo
1455              any dynamic link state.  */
1456           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1457           h->forced_local = 0;
1458           h->ref_dynamic = 0;
1459         }
1460       else
1461         h->ref_dynamic = 1;
1462       h->def_dynamic = 0;
1463       /* FIXME: Should we check type and size for protected symbol?  */
1464       h->size = 0;
1465       h->type = 0;
1466       return TRUE;
1467     }
1468
1469   /* If a new weak symbol definition comes from a regular file and the
1470      old symbol comes from a dynamic library, we treat the new one as
1471      strong.  Similarly, an old weak symbol definition from a regular
1472      file is treated as strong when the new symbol comes from a dynamic
1473      library.  Further, an old weak symbol from a dynamic library is
1474      treated as strong if the new symbol is from a dynamic library.
1475      This reflects the way glibc's ld.so works.
1476
1477      Do this before setting *type_change_ok or *size_change_ok so that
1478      we warn properly when dynamic library symbols are overridden.  */
1479
1480   if (newdef && !newdyn && olddyn)
1481     newweak = FALSE;
1482   if (olddef && newdyn)
1483     oldweak = FALSE;
1484
1485   /* Allow changes between different types of function symbol.  */
1486   if (newfunc && oldfunc)
1487     *type_change_ok = TRUE;
1488
1489   /* It's OK to change the type if either the existing symbol or the
1490      new symbol is weak.  A type change is also OK if the old symbol
1491      is undefined and the new symbol is defined.  */
1492
1493   if (oldweak
1494       || newweak
1495       || (newdef
1496           && h->root.type == bfd_link_hash_undefined))
1497     *type_change_ok = TRUE;
1498
1499   /* It's OK to change the size if either the existing symbol or the
1500      new symbol is weak, or if the old symbol is undefined.  */
1501
1502   if (*type_change_ok
1503       || h->root.type == bfd_link_hash_undefined)
1504     *size_change_ok = TRUE;
1505
1506   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1507      symbol, respectively, appears to be a common symbol in a dynamic
1508      object.  If a symbol appears in an uninitialized section, and is
1509      not weak, and is not a function, then it may be a common symbol
1510      which was resolved when the dynamic object was created.  We want
1511      to treat such symbols specially, because they raise special
1512      considerations when setting the symbol size: if the symbol
1513      appears as a common symbol in a regular object, and the size in
1514      the regular object is larger, we must make sure that we use the
1515      larger size.  This problematic case can always be avoided in C,
1516      but it must be handled correctly when using Fortran shared
1517      libraries.
1518
1519      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1520      likewise for OLDDYNCOMMON and OLDDEF.
1521
1522      Note that this test is just a heuristic, and that it is quite
1523      possible to have an uninitialized symbol in a shared object which
1524      is really a definition, rather than a common symbol.  This could
1525      lead to some minor confusion when the symbol really is a common
1526      symbol in some regular object.  However, I think it will be
1527      harmless.  */
1528
1529   if (newdyn
1530       && newdef
1531       && !newweak
1532       && (sec->flags & SEC_ALLOC) != 0
1533       && (sec->flags & SEC_LOAD) == 0
1534       && sym->st_size > 0
1535       && !newfunc)
1536     newdyncommon = TRUE;
1537   else
1538     newdyncommon = FALSE;
1539
1540   if (olddyn
1541       && olddef
1542       && h->root.type == bfd_link_hash_defined
1543       && h->def_dynamic
1544       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1545       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1546       && h->size > 0
1547       && !oldfunc)
1548     olddyncommon = TRUE;
1549   else
1550     olddyncommon = FALSE;
1551
1552   /* We now know everything about the old and new symbols.  We ask the
1553      backend to check if we can merge them.  */
1554   if (bed->merge_symbol != NULL)
1555     {
1556       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1557         return FALSE;
1558       sec = *psec;
1559     }
1560
1561   /* There are multiple definitions of a normal symbol.
1562      Skip the default symbol as well.  */
1563   if (olddef && !olddyn && !oldweak && newdef && !newdyn && !newweak
1564       && !default_sym && h->def_regular)
1565     {
1566       /* Handle a multiple definition.  */
1567       (*info->callbacks->multiple_definition) (info, &h->root,
1568                                                abfd, sec, *pvalue);
1569       *skip = TRUE;
1570       return TRUE;
1571     }
1572
1573   /* If both the old and the new symbols look like common symbols in a
1574      dynamic object, set the size of the symbol to the larger of the
1575      two.  */
1576
1577   if (olddyncommon
1578       && newdyncommon
1579       && sym->st_size != h->size)
1580     {
1581       /* Since we think we have two common symbols, issue a multiple
1582          common warning if desired.  Note that we only warn if the
1583          size is different.  If the size is the same, we simply let
1584          the old symbol override the new one as normally happens with
1585          symbols defined in dynamic objects.  */
1586
1587       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1588                                            bfd_link_hash_common, sym->st_size);
1589       if (sym->st_size > h->size)
1590         h->size = sym->st_size;
1591
1592       *size_change_ok = TRUE;
1593     }
1594
1595   /* If we are looking at a dynamic object, and we have found a
1596      definition, we need to see if the symbol was already defined by
1597      some other object.  If so, we want to use the existing
1598      definition, and we do not want to report a multiple symbol
1599      definition error; we do this by clobbering *PSEC to be
1600      bfd_und_section_ptr.
1601
1602      We treat a common symbol as a definition if the symbol in the
1603      shared library is a function, since common symbols always
1604      represent variables; this can cause confusion in principle, but
1605      any such confusion would seem to indicate an erroneous program or
1606      shared library.  We also permit a common symbol in a regular
1607      object to override a weak symbol in a shared object.  */
1608
1609   if (newdyn
1610       && newdef
1611       && (olddef
1612           || (h->root.type == bfd_link_hash_common
1613               && (newweak || newfunc))))
1614     {
1615       *override = TRUE;
1616       newdef = FALSE;
1617       newdyncommon = FALSE;
1618
1619       *psec = sec = bfd_und_section_ptr;
1620       *size_change_ok = TRUE;
1621
1622       /* If we get here when the old symbol is a common symbol, then
1623          we are explicitly letting it override a weak symbol or
1624          function in a dynamic object, and we don't want to warn about
1625          a type change.  If the old symbol is a defined symbol, a type
1626          change warning may still be appropriate.  */
1627
1628       if (h->root.type == bfd_link_hash_common)
1629         *type_change_ok = TRUE;
1630     }
1631
1632   /* Handle the special case of an old common symbol merging with a
1633      new symbol which looks like a common symbol in a shared object.
1634      We change *PSEC and *PVALUE to make the new symbol look like a
1635      common symbol, and let _bfd_generic_link_add_one_symbol do the
1636      right thing.  */
1637
1638   if (newdyncommon
1639       && h->root.type == bfd_link_hash_common)
1640     {
1641       *override = TRUE;
1642       newdef = FALSE;
1643       newdyncommon = FALSE;
1644       *pvalue = sym->st_size;
1645       *psec = sec = bed->common_section (oldsec);
1646       *size_change_ok = TRUE;
1647     }
1648
1649   /* Skip weak definitions of symbols that are already defined.  */
1650   if (newdef && olddef && newweak)
1651     {
1652       /* Don't skip new non-IR weak syms.  */
1653       if (!(oldbfd != NULL
1654             && (oldbfd->flags & BFD_PLUGIN) != 0
1655             && (abfd->flags & BFD_PLUGIN) == 0))
1656         {
1657           newdef = FALSE;
1658           *skip = TRUE;
1659         }
1660
1661       /* Merge st_other.  If the symbol already has a dynamic index,
1662          but visibility says it should not be visible, turn it into a
1663          local symbol.  */
1664       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1665       if (h->dynindx != -1)
1666         switch (ELF_ST_VISIBILITY (h->other))
1667           {
1668           case STV_INTERNAL:
1669           case STV_HIDDEN:
1670             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1671             break;
1672           }
1673     }
1674
1675   /* If the old symbol is from a dynamic object, and the new symbol is
1676      a definition which is not from a dynamic object, then the new
1677      symbol overrides the old symbol.  Symbols from regular files
1678      always take precedence over symbols from dynamic objects, even if
1679      they are defined after the dynamic object in the link.
1680
1681      As above, we again permit a common symbol in a regular object to
1682      override a definition in a shared object if the shared object
1683      symbol is a function or is weak.  */
1684
1685   flip = NULL;
1686   if (!newdyn
1687       && (newdef
1688           || (bfd_is_com_section (sec)
1689               && (oldweak || oldfunc)))
1690       && olddyn
1691       && olddef
1692       && h->def_dynamic)
1693     {
1694       /* Change the hash table entry to undefined, and let
1695          _bfd_generic_link_add_one_symbol do the right thing with the
1696          new definition.  */
1697
1698       h->root.type = bfd_link_hash_undefined;
1699       h->root.u.undef.abfd = h->root.u.def.section->owner;
1700       *size_change_ok = TRUE;
1701
1702       olddef = FALSE;
1703       olddyncommon = FALSE;
1704
1705       /* We again permit a type change when a common symbol may be
1706          overriding a function.  */
1707
1708       if (bfd_is_com_section (sec))
1709         {
1710           if (oldfunc)
1711             {
1712               /* If a common symbol overrides a function, make sure
1713                  that it isn't defined dynamically nor has type
1714                  function.  */
1715               h->def_dynamic = 0;
1716               h->type = STT_NOTYPE;
1717             }
1718           *type_change_ok = TRUE;
1719         }
1720
1721       if (hi->root.type == bfd_link_hash_indirect)
1722         flip = hi;
1723       else
1724         /* This union may have been set to be non-NULL when this symbol
1725            was seen in a dynamic object.  We must force the union to be
1726            NULL, so that it is correct for a regular symbol.  */
1727         h->verinfo.vertree = NULL;
1728     }
1729
1730   /* Handle the special case of a new common symbol merging with an
1731      old symbol that looks like it might be a common symbol defined in
1732      a shared object.  Note that we have already handled the case in
1733      which a new common symbol should simply override the definition
1734      in the shared library.  */
1735
1736   if (! newdyn
1737       && bfd_is_com_section (sec)
1738       && olddyncommon)
1739     {
1740       /* It would be best if we could set the hash table entry to a
1741          common symbol, but we don't know what to use for the section
1742          or the alignment.  */
1743       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1744                                            bfd_link_hash_common, sym->st_size);
1745
1746       /* If the presumed common symbol in the dynamic object is
1747          larger, pretend that the new symbol has its size.  */
1748
1749       if (h->size > *pvalue)
1750         *pvalue = h->size;
1751
1752       /* We need to remember the alignment required by the symbol
1753          in the dynamic object.  */
1754       BFD_ASSERT (pold_alignment);
1755       *pold_alignment = h->root.u.def.section->alignment_power;
1756
1757       olddef = FALSE;
1758       olddyncommon = FALSE;
1759
1760       h->root.type = bfd_link_hash_undefined;
1761       h->root.u.undef.abfd = h->root.u.def.section->owner;
1762
1763       *size_change_ok = TRUE;
1764       *type_change_ok = TRUE;
1765
1766       if (hi->root.type == bfd_link_hash_indirect)
1767         flip = hi;
1768       else
1769         h->verinfo.vertree = NULL;
1770     }
1771
1772   if (flip != NULL)
1773     {
1774       /* Handle the case where we had a versioned symbol in a dynamic
1775          library and now find a definition in a normal object.  In this
1776          case, we make the versioned symbol point to the normal one.  */
1777       flip->root.type = h->root.type;
1778       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1779       h->root.type = bfd_link_hash_indirect;
1780       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1781       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1782       if (h->def_dynamic)
1783         {
1784           h->def_dynamic = 0;
1785           flip->ref_dynamic = 1;
1786         }
1787     }
1788
1789   return TRUE;
1790 }
1791
1792 /* This function is called to create an indirect symbol from the
1793    default for the symbol with the default version if needed. The
1794    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1795    set DYNSYM if the new indirect symbol is dynamic.  */
1796
1797 static bfd_boolean
1798 _bfd_elf_add_default_symbol (bfd *abfd,
1799                              struct bfd_link_info *info,
1800                              struct elf_link_hash_entry *h,
1801                              const char *name,
1802                              Elf_Internal_Sym *sym,
1803                              asection *sec,
1804                              bfd_vma value,
1805                              bfd **poldbfd,
1806                              bfd_boolean *dynsym)
1807 {
1808   bfd_boolean type_change_ok;
1809   bfd_boolean size_change_ok;
1810   bfd_boolean skip;
1811   char *shortname;
1812   struct elf_link_hash_entry *hi;
1813   struct bfd_link_hash_entry *bh;
1814   const struct elf_backend_data *bed;
1815   bfd_boolean collect;
1816   bfd_boolean dynamic;
1817   bfd_boolean override;
1818   char *p;
1819   size_t len, shortlen;
1820   asection *tmp_sec;
1821   bfd_boolean matched;
1822
1823   if (h->versioned == unversioned || h->versioned == versioned_hidden)
1824     return TRUE;
1825
1826   /* If this symbol has a version, and it is the default version, we
1827      create an indirect symbol from the default name to the fully
1828      decorated name.  This will cause external references which do not
1829      specify a version to be bound to this version of the symbol.  */
1830   p = strchr (name, ELF_VER_CHR);
1831   if (h->versioned == unknown)
1832     {
1833       if (p == NULL)
1834         {
1835           h->versioned = unversioned;
1836           return TRUE;
1837         }
1838       else
1839         {
1840           if (p[1] != ELF_VER_CHR)
1841             {
1842               h->versioned = versioned_hidden;
1843               return TRUE;
1844             }
1845           else
1846             h->versioned = versioned;
1847         }
1848     }
1849   else
1850     {
1851       /* PR ld/19073: We may see an unversioned definition after the
1852          default version.  */
1853       if (p == NULL)
1854         return TRUE;
1855     }
1856
1857   bed = get_elf_backend_data (abfd);
1858   collect = bed->collect;
1859   dynamic = (abfd->flags & DYNAMIC) != 0;
1860
1861   shortlen = p - name;
1862   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1863   if (shortname == NULL)
1864     return FALSE;
1865   memcpy (shortname, name, shortlen);
1866   shortname[shortlen] = '\0';
1867
1868   /* We are going to create a new symbol.  Merge it with any existing
1869      symbol with this name.  For the purposes of the merge, act as
1870      though we were defining the symbol we just defined, although we
1871      actually going to define an indirect symbol.  */
1872   type_change_ok = FALSE;
1873   size_change_ok = FALSE;
1874   matched = TRUE;
1875   tmp_sec = sec;
1876   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1877                               &hi, poldbfd, NULL, NULL, &skip, &override,
1878                               &type_change_ok, &size_change_ok, &matched))
1879     return FALSE;
1880
1881   if (skip)
1882     goto nondefault;
1883
1884   if (hi->def_regular)
1885     {
1886       /* If the undecorated symbol will have a version added by a
1887          script different to H, then don't indirect to/from the
1888          undecorated symbol.  This isn't ideal because we may not yet
1889          have seen symbol versions, if given by a script on the
1890          command line rather than via --version-script.  */
1891       if (hi->verinfo.vertree == NULL && info->version_info != NULL)
1892         {
1893           bfd_boolean hide;
1894
1895           hi->verinfo.vertree
1896             = bfd_find_version_for_sym (info->version_info,
1897                                         hi->root.root.string, &hide);
1898           if (hi->verinfo.vertree != NULL && hide)
1899             {
1900               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
1901               goto nondefault;
1902             }
1903         }
1904       if (hi->verinfo.vertree != NULL
1905           && strcmp (p + 1 + (p[1] == '@'), hi->verinfo.vertree->name) != 0)
1906         goto nondefault;
1907     }
1908
1909   if (! override)
1910     {
1911       /* Add the default symbol if not performing a relocatable link.  */
1912       if (! bfd_link_relocatable (info))
1913         {
1914           bh = &hi->root;
1915           if (! (_bfd_generic_link_add_one_symbol
1916                  (info, abfd, shortname, BSF_INDIRECT,
1917                   bfd_ind_section_ptr,
1918                   0, name, FALSE, collect, &bh)))
1919             return FALSE;
1920           hi = (struct elf_link_hash_entry *) bh;
1921         }
1922     }
1923   else
1924     {
1925       /* In this case the symbol named SHORTNAME is overriding the
1926          indirect symbol we want to add.  We were planning on making
1927          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1928          is the name without a version.  NAME is the fully versioned
1929          name, and it is the default version.
1930
1931          Overriding means that we already saw a definition for the
1932          symbol SHORTNAME in a regular object, and it is overriding
1933          the symbol defined in the dynamic object.
1934
1935          When this happens, we actually want to change NAME, the
1936          symbol we just added, to refer to SHORTNAME.  This will cause
1937          references to NAME in the shared object to become references
1938          to SHORTNAME in the regular object.  This is what we expect
1939          when we override a function in a shared object: that the
1940          references in the shared object will be mapped to the
1941          definition in the regular object.  */
1942
1943       while (hi->root.type == bfd_link_hash_indirect
1944              || hi->root.type == bfd_link_hash_warning)
1945         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1946
1947       h->root.type = bfd_link_hash_indirect;
1948       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1949       if (h->def_dynamic)
1950         {
1951           h->def_dynamic = 0;
1952           hi->ref_dynamic = 1;
1953           if (hi->ref_regular
1954               || hi->def_regular)
1955             {
1956               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1957                 return FALSE;
1958             }
1959         }
1960
1961       /* Now set HI to H, so that the following code will set the
1962          other fields correctly.  */
1963       hi = h;
1964     }
1965
1966   /* Check if HI is a warning symbol.  */
1967   if (hi->root.type == bfd_link_hash_warning)
1968     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1969
1970   /* If there is a duplicate definition somewhere, then HI may not
1971      point to an indirect symbol.  We will have reported an error to
1972      the user in that case.  */
1973
1974   if (hi->root.type == bfd_link_hash_indirect)
1975     {
1976       struct elf_link_hash_entry *ht;
1977
1978       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1979       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
1980
1981       /* A reference to the SHORTNAME symbol from a dynamic library
1982          will be satisfied by the versioned symbol at runtime.  In
1983          effect, we have a reference to the versioned symbol.  */
1984       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1985       hi->dynamic_def |= ht->dynamic_def;
1986
1987       /* See if the new flags lead us to realize that the symbol must
1988          be dynamic.  */
1989       if (! *dynsym)
1990         {
1991           if (! dynamic)
1992             {
1993               if (! bfd_link_executable (info)
1994                   || hi->def_dynamic
1995                   || hi->ref_dynamic)
1996                 *dynsym = TRUE;
1997             }
1998           else
1999             {
2000               if (hi->ref_regular)
2001                 *dynsym = TRUE;
2002             }
2003         }
2004     }
2005
2006   /* We also need to define an indirection from the nondefault version
2007      of the symbol.  */
2008
2009 nondefault:
2010   len = strlen (name);
2011   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
2012   if (shortname == NULL)
2013     return FALSE;
2014   memcpy (shortname, name, shortlen);
2015   memcpy (shortname + shortlen, p + 1, len - shortlen);
2016
2017   /* Once again, merge with any existing symbol.  */
2018   type_change_ok = FALSE;
2019   size_change_ok = FALSE;
2020   tmp_sec = sec;
2021   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
2022                               &hi, poldbfd, NULL, NULL, &skip, &override,
2023                               &type_change_ok, &size_change_ok, &matched))
2024     return FALSE;
2025
2026   if (skip)
2027     return TRUE;
2028
2029   if (override)
2030     {
2031       /* Here SHORTNAME is a versioned name, so we don't expect to see
2032          the type of override we do in the case above unless it is
2033          overridden by a versioned definition.  */
2034       if (hi->root.type != bfd_link_hash_defined
2035           && hi->root.type != bfd_link_hash_defweak)
2036         _bfd_error_handler
2037           /* xgettext:c-format */
2038           (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
2039            abfd, shortname);
2040     }
2041   else
2042     {
2043       bh = &hi->root;
2044       if (! (_bfd_generic_link_add_one_symbol
2045              (info, abfd, shortname, BSF_INDIRECT,
2046               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
2047         return FALSE;
2048       hi = (struct elf_link_hash_entry *) bh;
2049
2050       /* If there is a duplicate definition somewhere, then HI may not
2051          point to an indirect symbol.  We will have reported an error
2052          to the user in that case.  */
2053
2054       if (hi->root.type == bfd_link_hash_indirect)
2055         {
2056           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
2057           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
2058           hi->dynamic_def |= h->dynamic_def;
2059
2060           /* See if the new flags lead us to realize that the symbol
2061              must be dynamic.  */
2062           if (! *dynsym)
2063             {
2064               if (! dynamic)
2065                 {
2066                   if (! bfd_link_executable (info)
2067                       || hi->ref_dynamic)
2068                     *dynsym = TRUE;
2069                 }
2070               else
2071                 {
2072                   if (hi->ref_regular)
2073                     *dynsym = TRUE;
2074                 }
2075             }
2076         }
2077     }
2078
2079   return TRUE;
2080 }
2081 \f
2082 /* This routine is used to export all defined symbols into the dynamic
2083    symbol table.  It is called via elf_link_hash_traverse.  */
2084
2085 static bfd_boolean
2086 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
2087 {
2088   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2089
2090   /* Ignore indirect symbols.  These are added by the versioning code.  */
2091   if (h->root.type == bfd_link_hash_indirect)
2092     return TRUE;
2093
2094   /* Ignore this if we won't export it.  */
2095   if (!eif->info->export_dynamic && !h->dynamic)
2096     return TRUE;
2097
2098   if (h->dynindx == -1
2099       && (h->def_regular || h->ref_regular)
2100       && ! bfd_hide_sym_by_version (eif->info->version_info,
2101                                     h->root.root.string))
2102     {
2103       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2104         {
2105           eif->failed = TRUE;
2106           return FALSE;
2107         }
2108     }
2109
2110   return TRUE;
2111 }
2112 \f
2113 /* Look through the symbols which are defined in other shared
2114    libraries and referenced here.  Update the list of version
2115    dependencies.  This will be put into the .gnu.version_r section.
2116    This function is called via elf_link_hash_traverse.  */
2117
2118 static bfd_boolean
2119 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
2120                                          void *data)
2121 {
2122   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
2123   Elf_Internal_Verneed *t;
2124   Elf_Internal_Vernaux *a;
2125   bfd_size_type amt;
2126
2127   /* We only care about symbols defined in shared objects with version
2128      information.  */
2129   if (!h->def_dynamic
2130       || h->def_regular
2131       || h->dynindx == -1
2132       || h->verinfo.verdef == NULL
2133       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
2134           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
2135     return TRUE;
2136
2137   /* See if we already know about this version.  */
2138   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
2139        t != NULL;
2140        t = t->vn_nextref)
2141     {
2142       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
2143         continue;
2144
2145       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
2146         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
2147           return TRUE;
2148
2149       break;
2150     }
2151
2152   /* This is a new version.  Add it to tree we are building.  */
2153
2154   if (t == NULL)
2155     {
2156       amt = sizeof *t;
2157       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
2158       if (t == NULL)
2159         {
2160           rinfo->failed = TRUE;
2161           return FALSE;
2162         }
2163
2164       t->vn_bfd = h->verinfo.verdef->vd_bfd;
2165       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
2166       elf_tdata (rinfo->info->output_bfd)->verref = t;
2167     }
2168
2169   amt = sizeof *a;
2170   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
2171   if (a == NULL)
2172     {
2173       rinfo->failed = TRUE;
2174       return FALSE;
2175     }
2176
2177   /* Note that we are copying a string pointer here, and testing it
2178      above.  If bfd_elf_string_from_elf_section is ever changed to
2179      discard the string data when low in memory, this will have to be
2180      fixed.  */
2181   a->vna_nodename = h->verinfo.verdef->vd_nodename;
2182
2183   a->vna_flags = h->verinfo.verdef->vd_flags;
2184   a->vna_nextptr = t->vn_auxptr;
2185
2186   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
2187   ++rinfo->vers;
2188
2189   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
2190
2191   t->vn_auxptr = a;
2192
2193   return TRUE;
2194 }
2195
2196 /* Figure out appropriate versions for all the symbols.  We may not
2197    have the version number script until we have read all of the input
2198    files, so until that point we don't know which symbols should be
2199    local.  This function is called via elf_link_hash_traverse.  */
2200
2201 static bfd_boolean
2202 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2203 {
2204   struct elf_info_failed *sinfo;
2205   struct bfd_link_info *info;
2206   const struct elf_backend_data *bed;
2207   struct elf_info_failed eif;
2208   char *p;
2209
2210   sinfo = (struct elf_info_failed *) data;
2211   info = sinfo->info;
2212
2213   /* Fix the symbol flags.  */
2214   eif.failed = FALSE;
2215   eif.info = info;
2216   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2217     {
2218       if (eif.failed)
2219         sinfo->failed = TRUE;
2220       return FALSE;
2221     }
2222
2223   /* We only need version numbers for symbols defined in regular
2224      objects.  */
2225   if (!h->def_regular)
2226     return TRUE;
2227
2228   bed = get_elf_backend_data (info->output_bfd);
2229   p = strchr (h->root.root.string, ELF_VER_CHR);
2230   if (p != NULL && h->verinfo.vertree == NULL)
2231     {
2232       struct bfd_elf_version_tree *t;
2233
2234       ++p;
2235       if (*p == ELF_VER_CHR)
2236         ++p;
2237
2238       /* If there is no version string, we can just return out.  */
2239       if (*p == '\0')
2240         return TRUE;
2241
2242       /* Look for the version.  If we find it, it is no longer weak.  */
2243       for (t = sinfo->info->version_info; t != NULL; t = t->next)
2244         {
2245           if (strcmp (t->name, p) == 0)
2246             {
2247               size_t len;
2248               char *alc;
2249               struct bfd_elf_version_expr *d;
2250
2251               len = p - h->root.root.string;
2252               alc = (char *) bfd_malloc (len);
2253               if (alc == NULL)
2254                 {
2255                   sinfo->failed = TRUE;
2256                   return FALSE;
2257                 }
2258               memcpy (alc, h->root.root.string, len - 1);
2259               alc[len - 1] = '\0';
2260               if (alc[len - 2] == ELF_VER_CHR)
2261                 alc[len - 2] = '\0';
2262
2263               h->verinfo.vertree = t;
2264               t->used = TRUE;
2265               d = NULL;
2266
2267               if (t->globals.list != NULL)
2268                 d = (*t->match) (&t->globals, NULL, alc);
2269
2270               /* See if there is anything to force this symbol to
2271                  local scope.  */
2272               if (d == NULL && t->locals.list != NULL)
2273                 {
2274                   d = (*t->match) (&t->locals, NULL, alc);
2275                   if (d != NULL
2276                       && h->dynindx != -1
2277                       && ! info->export_dynamic)
2278                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2279                 }
2280
2281               free (alc);
2282               break;
2283             }
2284         }
2285
2286       /* If we are building an application, we need to create a
2287          version node for this version.  */
2288       if (t == NULL && bfd_link_executable (info))
2289         {
2290           struct bfd_elf_version_tree **pp;
2291           int version_index;
2292
2293           /* If we aren't going to export this symbol, we don't need
2294              to worry about it.  */
2295           if (h->dynindx == -1)
2296             return TRUE;
2297
2298           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd,
2299                                                           sizeof *t);
2300           if (t == NULL)
2301             {
2302               sinfo->failed = TRUE;
2303               return FALSE;
2304             }
2305
2306           t->name = p;
2307           t->name_indx = (unsigned int) -1;
2308           t->used = TRUE;
2309
2310           version_index = 1;
2311           /* Don't count anonymous version tag.  */
2312           if (sinfo->info->version_info != NULL
2313               && sinfo->info->version_info->vernum == 0)
2314             version_index = 0;
2315           for (pp = &sinfo->info->version_info;
2316                *pp != NULL;
2317                pp = &(*pp)->next)
2318             ++version_index;
2319           t->vernum = version_index;
2320
2321           *pp = t;
2322
2323           h->verinfo.vertree = t;
2324         }
2325       else if (t == NULL)
2326         {
2327           /* We could not find the version for a symbol when
2328              generating a shared archive.  Return an error.  */
2329           _bfd_error_handler
2330             /* xgettext:c-format */
2331             (_("%B: version node not found for symbol %s"),
2332              info->output_bfd, h->root.root.string);
2333           bfd_set_error (bfd_error_bad_value);
2334           sinfo->failed = TRUE;
2335           return FALSE;
2336         }
2337     }
2338
2339   /* If we don't have a version for this symbol, see if we can find
2340      something.  */
2341   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2342     {
2343       bfd_boolean hide;
2344
2345       h->verinfo.vertree
2346         = bfd_find_version_for_sym (sinfo->info->version_info,
2347                                     h->root.root.string, &hide);
2348       if (h->verinfo.vertree != NULL && hide)
2349         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2350     }
2351
2352   return TRUE;
2353 }
2354 \f
2355 /* Read and swap the relocs from the section indicated by SHDR.  This
2356    may be either a REL or a RELA section.  The relocations are
2357    translated into RELA relocations and stored in INTERNAL_RELOCS,
2358    which should have already been allocated to contain enough space.
2359    The EXTERNAL_RELOCS are a buffer where the external form of the
2360    relocations should be stored.
2361
2362    Returns FALSE if something goes wrong.  */
2363
2364 static bfd_boolean
2365 elf_link_read_relocs_from_section (bfd *abfd,
2366                                    asection *sec,
2367                                    Elf_Internal_Shdr *shdr,
2368                                    void *external_relocs,
2369                                    Elf_Internal_Rela *internal_relocs)
2370 {
2371   const struct elf_backend_data *bed;
2372   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2373   const bfd_byte *erela;
2374   const bfd_byte *erelaend;
2375   Elf_Internal_Rela *irela;
2376   Elf_Internal_Shdr *symtab_hdr;
2377   size_t nsyms;
2378
2379   /* Position ourselves at the start of the section.  */
2380   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2381     return FALSE;
2382
2383   /* Read the relocations.  */
2384   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2385     return FALSE;
2386
2387   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2388   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2389
2390   bed = get_elf_backend_data (abfd);
2391
2392   /* Convert the external relocations to the internal format.  */
2393   if (shdr->sh_entsize == bed->s->sizeof_rel)
2394     swap_in = bed->s->swap_reloc_in;
2395   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2396     swap_in = bed->s->swap_reloca_in;
2397   else
2398     {
2399       bfd_set_error (bfd_error_wrong_format);
2400       return FALSE;
2401     }
2402
2403   erela = (const bfd_byte *) external_relocs;
2404   erelaend = erela + shdr->sh_size;
2405   irela = internal_relocs;
2406   while (erela < erelaend)
2407     {
2408       bfd_vma r_symndx;
2409
2410       (*swap_in) (abfd, erela, irela);
2411       r_symndx = ELF32_R_SYM (irela->r_info);
2412       if (bed->s->arch_size == 64)
2413         r_symndx >>= 24;
2414       if (nsyms > 0)
2415         {
2416           if ((size_t) r_symndx >= nsyms)
2417             {
2418               _bfd_error_handler
2419                 /* xgettext:c-format */
2420                 (_("%B: bad reloc symbol index (%#Lx >= %#lx)"
2421                    " for offset %#Lx in section `%A'"),
2422                  abfd, r_symndx, (unsigned long) nsyms,
2423                  irela->r_offset, sec);
2424               bfd_set_error (bfd_error_bad_value);
2425               return FALSE;
2426             }
2427         }
2428       else if (r_symndx != STN_UNDEF)
2429         {
2430           _bfd_error_handler
2431             /* xgettext:c-format */
2432             (_("%B: non-zero symbol index (%#Lx)"
2433                " for offset %#Lx in section `%A'"
2434                " when the object file has no symbol table"),
2435              abfd, r_symndx,
2436              irela->r_offset, sec);
2437           bfd_set_error (bfd_error_bad_value);
2438           return FALSE;
2439         }
2440       irela += bed->s->int_rels_per_ext_rel;
2441       erela += shdr->sh_entsize;
2442     }
2443
2444   return TRUE;
2445 }
2446
2447 /* Read and swap the relocs for a section O.  They may have been
2448    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2449    not NULL, they are used as buffers to read into.  They are known to
2450    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2451    the return value is allocated using either malloc or bfd_alloc,
2452    according to the KEEP_MEMORY argument.  If O has two relocation
2453    sections (both REL and RELA relocations), then the REL_HDR
2454    relocations will appear first in INTERNAL_RELOCS, followed by the
2455    RELA_HDR relocations.  */
2456
2457 Elf_Internal_Rela *
2458 _bfd_elf_link_read_relocs (bfd *abfd,
2459                            asection *o,
2460                            void *external_relocs,
2461                            Elf_Internal_Rela *internal_relocs,
2462                            bfd_boolean keep_memory)
2463 {
2464   void *alloc1 = NULL;
2465   Elf_Internal_Rela *alloc2 = NULL;
2466   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2467   struct bfd_elf_section_data *esdo = elf_section_data (o);
2468   Elf_Internal_Rela *internal_rela_relocs;
2469
2470   if (esdo->relocs != NULL)
2471     return esdo->relocs;
2472
2473   if (o->reloc_count == 0)
2474     return NULL;
2475
2476   if (internal_relocs == NULL)
2477     {
2478       bfd_size_type size;
2479
2480       size = (bfd_size_type) o->reloc_count * sizeof (Elf_Internal_Rela);
2481       if (keep_memory)
2482         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2483       else
2484         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2485       if (internal_relocs == NULL)
2486         goto error_return;
2487     }
2488
2489   if (external_relocs == NULL)
2490     {
2491       bfd_size_type size = 0;
2492
2493       if (esdo->rel.hdr)
2494         size += esdo->rel.hdr->sh_size;
2495       if (esdo->rela.hdr)
2496         size += esdo->rela.hdr->sh_size;
2497
2498       alloc1 = bfd_malloc (size);
2499       if (alloc1 == NULL)
2500         goto error_return;
2501       external_relocs = alloc1;
2502     }
2503
2504   internal_rela_relocs = internal_relocs;
2505   if (esdo->rel.hdr)
2506     {
2507       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2508                                               external_relocs,
2509                                               internal_relocs))
2510         goto error_return;
2511       external_relocs = (((bfd_byte *) external_relocs)
2512                          + esdo->rel.hdr->sh_size);
2513       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2514                                * bed->s->int_rels_per_ext_rel);
2515     }
2516
2517   if (esdo->rela.hdr
2518       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2519                                               external_relocs,
2520                                               internal_rela_relocs)))
2521     goto error_return;
2522
2523   /* Cache the results for next time, if we can.  */
2524   if (keep_memory)
2525     esdo->relocs = internal_relocs;
2526
2527   if (alloc1 != NULL)
2528     free (alloc1);
2529
2530   /* Don't free alloc2, since if it was allocated we are passing it
2531      back (under the name of internal_relocs).  */
2532
2533   return internal_relocs;
2534
2535  error_return:
2536   if (alloc1 != NULL)
2537     free (alloc1);
2538   if (alloc2 != NULL)
2539     {
2540       if (keep_memory)
2541         bfd_release (abfd, alloc2);
2542       else
2543         free (alloc2);
2544     }
2545   return NULL;
2546 }
2547
2548 /* Compute the size of, and allocate space for, REL_HDR which is the
2549    section header for a section containing relocations for O.  */
2550
2551 static bfd_boolean
2552 _bfd_elf_link_size_reloc_section (bfd *abfd,
2553                                   struct bfd_elf_section_reloc_data *reldata)
2554 {
2555   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2556
2557   /* That allows us to calculate the size of the section.  */
2558   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2559
2560   /* The contents field must last into write_object_contents, so we
2561      allocate it with bfd_alloc rather than malloc.  Also since we
2562      cannot be sure that the contents will actually be filled in,
2563      we zero the allocated space.  */
2564   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2565   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2566     return FALSE;
2567
2568   if (reldata->hashes == NULL && reldata->count)
2569     {
2570       struct elf_link_hash_entry **p;
2571
2572       p = ((struct elf_link_hash_entry **)
2573            bfd_zmalloc (reldata->count * sizeof (*p)));
2574       if (p == NULL)
2575         return FALSE;
2576
2577       reldata->hashes = p;
2578     }
2579
2580   return TRUE;
2581 }
2582
2583 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2584    originated from the section given by INPUT_REL_HDR) to the
2585    OUTPUT_BFD.  */
2586
2587 bfd_boolean
2588 _bfd_elf_link_output_relocs (bfd *output_bfd,
2589                              asection *input_section,
2590                              Elf_Internal_Shdr *input_rel_hdr,
2591                              Elf_Internal_Rela *internal_relocs,
2592                              struct elf_link_hash_entry **rel_hash
2593                                ATTRIBUTE_UNUSED)
2594 {
2595   Elf_Internal_Rela *irela;
2596   Elf_Internal_Rela *irelaend;
2597   bfd_byte *erel;
2598   struct bfd_elf_section_reloc_data *output_reldata;
2599   asection *output_section;
2600   const struct elf_backend_data *bed;
2601   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2602   struct bfd_elf_section_data *esdo;
2603
2604   output_section = input_section->output_section;
2605
2606   bed = get_elf_backend_data (output_bfd);
2607   esdo = elf_section_data (output_section);
2608   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2609     {
2610       output_reldata = &esdo->rel;
2611       swap_out = bed->s->swap_reloc_out;
2612     }
2613   else if (esdo->rela.hdr
2614            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2615     {
2616       output_reldata = &esdo->rela;
2617       swap_out = bed->s->swap_reloca_out;
2618     }
2619   else
2620     {
2621       _bfd_error_handler
2622         /* xgettext:c-format */
2623         (_("%B: relocation size mismatch in %B section %A"),
2624          output_bfd, input_section->owner, input_section);
2625       bfd_set_error (bfd_error_wrong_format);
2626       return FALSE;
2627     }
2628
2629   erel = output_reldata->hdr->contents;
2630   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2631   irela = internal_relocs;
2632   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2633                       * bed->s->int_rels_per_ext_rel);
2634   while (irela < irelaend)
2635     {
2636       (*swap_out) (output_bfd, irela, erel);
2637       irela += bed->s->int_rels_per_ext_rel;
2638       erel += input_rel_hdr->sh_entsize;
2639     }
2640
2641   /* Bump the counter, so that we know where to add the next set of
2642      relocations.  */
2643   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2644
2645   return TRUE;
2646 }
2647 \f
2648 /* Make weak undefined symbols in PIE dynamic.  */
2649
2650 bfd_boolean
2651 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2652                                  struct elf_link_hash_entry *h)
2653 {
2654   if (bfd_link_pie (info)
2655       && h->dynindx == -1
2656       && h->root.type == bfd_link_hash_undefweak)
2657     return bfd_elf_link_record_dynamic_symbol (info, h);
2658
2659   return TRUE;
2660 }
2661
2662 /* Fix up the flags for a symbol.  This handles various cases which
2663    can only be fixed after all the input files are seen.  This is
2664    currently called by both adjust_dynamic_symbol and
2665    assign_sym_version, which is unnecessary but perhaps more robust in
2666    the face of future changes.  */
2667
2668 static bfd_boolean
2669 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2670                            struct elf_info_failed *eif)
2671 {
2672   const struct elf_backend_data *bed;
2673
2674   /* If this symbol was mentioned in a non-ELF file, try to set
2675      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2676      permit a non-ELF file to correctly refer to a symbol defined in
2677      an ELF dynamic object.  */
2678   if (h->non_elf)
2679     {
2680       while (h->root.type == bfd_link_hash_indirect)
2681         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2682
2683       if (h->root.type != bfd_link_hash_defined
2684           && h->root.type != bfd_link_hash_defweak)
2685         {
2686           h->ref_regular = 1;
2687           h->ref_regular_nonweak = 1;
2688         }
2689       else
2690         {
2691           if (h->root.u.def.section->owner != NULL
2692               && (bfd_get_flavour (h->root.u.def.section->owner)
2693                   == bfd_target_elf_flavour))
2694             {
2695               h->ref_regular = 1;
2696               h->ref_regular_nonweak = 1;
2697             }
2698           else
2699             h->def_regular = 1;
2700         }
2701
2702       if (h->dynindx == -1
2703           && (h->def_dynamic
2704               || h->ref_dynamic))
2705         {
2706           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2707             {
2708               eif->failed = TRUE;
2709               return FALSE;
2710             }
2711         }
2712     }
2713   else
2714     {
2715       /* Unfortunately, NON_ELF is only correct if the symbol
2716          was first seen in a non-ELF file.  Fortunately, if the symbol
2717          was first seen in an ELF file, we're probably OK unless the
2718          symbol was defined in a non-ELF file.  Catch that case here.
2719          FIXME: We're still in trouble if the symbol was first seen in
2720          a dynamic object, and then later in a non-ELF regular object.  */
2721       if ((h->root.type == bfd_link_hash_defined
2722            || h->root.type == bfd_link_hash_defweak)
2723           && !h->def_regular
2724           && (h->root.u.def.section->owner != NULL
2725               ? (bfd_get_flavour (h->root.u.def.section->owner)
2726                  != bfd_target_elf_flavour)
2727               : (bfd_is_abs_section (h->root.u.def.section)
2728                  && !h->def_dynamic)))
2729         h->def_regular = 1;
2730     }
2731
2732   /* Backend specific symbol fixup.  */
2733   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2734   if (bed->elf_backend_fixup_symbol
2735       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2736     return FALSE;
2737
2738   /* If this is a final link, and the symbol was defined as a common
2739      symbol in a regular object file, and there was no definition in
2740      any dynamic object, then the linker will have allocated space for
2741      the symbol in a common section but the DEF_REGULAR
2742      flag will not have been set.  */
2743   if (h->root.type == bfd_link_hash_defined
2744       && !h->def_regular
2745       && h->ref_regular
2746       && !h->def_dynamic
2747       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2748     h->def_regular = 1;
2749
2750   /* If a weak undefined symbol has non-default visibility, we also
2751      hide it from the dynamic linker.  */
2752   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2753       && h->root.type == bfd_link_hash_undefweak)
2754     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2755
2756   /* A hidden versioned symbol in executable should be forced local if
2757      it is is locally defined, not referenced by shared library and not
2758      exported.  */
2759   else if (bfd_link_executable (eif->info)
2760            && h->versioned == versioned_hidden
2761            && !eif->info->export_dynamic
2762            && !h->dynamic
2763            && !h->ref_dynamic
2764            && h->def_regular)
2765     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2766
2767   /* If -Bsymbolic was used (which means to bind references to global
2768      symbols to the definition within the shared object), and this
2769      symbol was defined in a regular object, then it actually doesn't
2770      need a PLT entry.  Likewise, if the symbol has non-default
2771      visibility.  If the symbol has hidden or internal visibility, we
2772      will force it local.  */
2773   else if (h->needs_plt
2774            && bfd_link_pic (eif->info)
2775            && is_elf_hash_table (eif->info->hash)
2776            && (SYMBOLIC_BIND (eif->info, h)
2777                || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2778            && h->def_regular)
2779     {
2780       bfd_boolean force_local;
2781
2782       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2783                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2784       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2785     }
2786
2787   /* If this is a weak defined symbol in a dynamic object, and we know
2788      the real definition in the dynamic object, copy interesting flags
2789      over to the real definition.  */
2790   if (h->u.weakdef != NULL)
2791     {
2792       /* If the real definition is defined by a regular object file,
2793          don't do anything special.  See the longer description in
2794          _bfd_elf_adjust_dynamic_symbol, below.  */
2795       if (h->u.weakdef->def_regular)
2796         h->u.weakdef = NULL;
2797       else
2798         {
2799           struct elf_link_hash_entry *weakdef = h->u.weakdef;
2800
2801           while (h->root.type == bfd_link_hash_indirect)
2802             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2803
2804           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2805                       || h->root.type == bfd_link_hash_defweak);
2806           BFD_ASSERT (weakdef->def_dynamic);
2807           BFD_ASSERT (weakdef->root.type == bfd_link_hash_defined
2808                       || weakdef->root.type == bfd_link_hash_defweak);
2809           (*bed->elf_backend_copy_indirect_symbol) (eif->info, weakdef, h);
2810         }
2811     }
2812
2813   return TRUE;
2814 }
2815
2816 /* Make the backend pick a good value for a dynamic symbol.  This is
2817    called via elf_link_hash_traverse, and also calls itself
2818    recursively.  */
2819
2820 static bfd_boolean
2821 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2822 {
2823   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2824   struct elf_link_hash_table *htab;
2825   const struct elf_backend_data *bed;
2826
2827   if (! is_elf_hash_table (eif->info->hash))
2828     return FALSE;
2829
2830   /* Ignore indirect symbols.  These are added by the versioning code.  */
2831   if (h->root.type == bfd_link_hash_indirect)
2832     return TRUE;
2833
2834   /* Fix the symbol flags.  */
2835   if (! _bfd_elf_fix_symbol_flags (h, eif))
2836     return FALSE;
2837
2838   htab = elf_hash_table (eif->info);
2839   bed = get_elf_backend_data (htab->dynobj);
2840
2841   if (h->root.type == bfd_link_hash_undefweak)
2842     {
2843       if (eif->info->dynamic_undefined_weak == 0)
2844         (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2845       else if (eif->info->dynamic_undefined_weak > 0
2846                && h->ref_regular
2847                && ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2848                && !bfd_hide_sym_by_version (eif->info->version_info,
2849                                             h->root.root.string))
2850         {
2851           if (!bfd_elf_link_record_dynamic_symbol (eif->info, h))
2852             {
2853               eif->failed = TRUE;
2854               return FALSE;
2855             }
2856         }
2857     }
2858
2859   /* If this symbol does not require a PLT entry, and it is not
2860      defined by a dynamic object, or is not referenced by a regular
2861      object, ignore it.  We do have to handle a weak defined symbol,
2862      even if no regular object refers to it, if we decided to add it
2863      to the dynamic symbol table.  FIXME: Do we normally need to worry
2864      about symbols which are defined by one dynamic object and
2865      referenced by another one?  */
2866   if (!h->needs_plt
2867       && h->type != STT_GNU_IFUNC
2868       && (h->def_regular
2869           || !h->def_dynamic
2870           || (!h->ref_regular
2871               && (h->u.weakdef == NULL || h->u.weakdef->dynindx == -1))))
2872     {
2873       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2874       return TRUE;
2875     }
2876
2877   /* If we've already adjusted this symbol, don't do it again.  This
2878      can happen via a recursive call.  */
2879   if (h->dynamic_adjusted)
2880     return TRUE;
2881
2882   /* Don't look at this symbol again.  Note that we must set this
2883      after checking the above conditions, because we may look at a
2884      symbol once, decide not to do anything, and then get called
2885      recursively later after REF_REGULAR is set below.  */
2886   h->dynamic_adjusted = 1;
2887
2888   /* If this is a weak definition, and we know a real definition, and
2889      the real symbol is not itself defined by a regular object file,
2890      then get a good value for the real definition.  We handle the
2891      real symbol first, for the convenience of the backend routine.
2892
2893      Note that there is a confusing case here.  If the real definition
2894      is defined by a regular object file, we don't get the real symbol
2895      from the dynamic object, but we do get the weak symbol.  If the
2896      processor backend uses a COPY reloc, then if some routine in the
2897      dynamic object changes the real symbol, we will not see that
2898      change in the corresponding weak symbol.  This is the way other
2899      ELF linkers work as well, and seems to be a result of the shared
2900      library model.
2901
2902      I will clarify this issue.  Most SVR4 shared libraries define the
2903      variable _timezone and define timezone as a weak synonym.  The
2904      tzset call changes _timezone.  If you write
2905        extern int timezone;
2906        int _timezone = 5;
2907        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2908      you might expect that, since timezone is a synonym for _timezone,
2909      the same number will print both times.  However, if the processor
2910      backend uses a COPY reloc, then actually timezone will be copied
2911      into your process image, and, since you define _timezone
2912      yourself, _timezone will not.  Thus timezone and _timezone will
2913      wind up at different memory locations.  The tzset call will set
2914      _timezone, leaving timezone unchanged.  */
2915
2916   if (h->u.weakdef != NULL)
2917     {
2918       /* If we get to this point, there is an implicit reference to
2919          H->U.WEAKDEF by a regular object file via the weak symbol H.  */
2920       h->u.weakdef->ref_regular = 1;
2921
2922       /* Ensure that the backend adjust_dynamic_symbol function sees
2923          H->U.WEAKDEF before H by recursively calling ourselves.  */
2924       if (! _bfd_elf_adjust_dynamic_symbol (h->u.weakdef, eif))
2925         return FALSE;
2926     }
2927
2928   /* If a symbol has no type and no size and does not require a PLT
2929      entry, then we are probably about to do the wrong thing here: we
2930      are probably going to create a COPY reloc for an empty object.
2931      This case can arise when a shared object is built with assembly
2932      code, and the assembly code fails to set the symbol type.  */
2933   if (h->size == 0
2934       && h->type == STT_NOTYPE
2935       && !h->needs_plt)
2936     _bfd_error_handler
2937       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2938        h->root.root.string);
2939
2940   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2941     {
2942       eif->failed = TRUE;
2943       return FALSE;
2944     }
2945
2946   return TRUE;
2947 }
2948
2949 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2950    DYNBSS.  */
2951
2952 bfd_boolean
2953 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
2954                               struct elf_link_hash_entry *h,
2955                               asection *dynbss)
2956 {
2957   unsigned int power_of_two;
2958   bfd_vma mask;
2959   asection *sec = h->root.u.def.section;
2960
2961   /* The section alignment of the definition is the maximum alignment
2962      requirement of symbols defined in the section.  Since we don't
2963      know the symbol alignment requirement, we start with the
2964      maximum alignment and check low bits of the symbol address
2965      for the minimum alignment.  */
2966   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2967   mask = ((bfd_vma) 1 << power_of_two) - 1;
2968   while ((h->root.u.def.value & mask) != 0)
2969     {
2970        mask >>= 1;
2971        --power_of_two;
2972     }
2973
2974   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
2975                                                 dynbss))
2976     {
2977       /* Adjust the section alignment if needed.  */
2978       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
2979                                        power_of_two))
2980         return FALSE;
2981     }
2982
2983   /* We make sure that the symbol will be aligned properly.  */
2984   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
2985
2986   /* Define the symbol as being at this point in DYNBSS.  */
2987   h->root.u.def.section = dynbss;
2988   h->root.u.def.value = dynbss->size;
2989
2990   /* Increment the size of DYNBSS to make room for the symbol.  */
2991   dynbss->size += h->size;
2992
2993   /* No error if extern_protected_data is true.  */
2994   if (h->protected_def
2995       && (!info->extern_protected_data
2996           || (info->extern_protected_data < 0
2997               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
2998     info->callbacks->einfo
2999       (_("%P: copy reloc against protected `%T' is dangerous\n"),
3000        h->root.root.string);
3001
3002   return TRUE;
3003 }
3004
3005 /* Adjust all external symbols pointing into SEC_MERGE sections
3006    to reflect the object merging within the sections.  */
3007
3008 static bfd_boolean
3009 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
3010 {
3011   asection *sec;
3012
3013   if ((h->root.type == bfd_link_hash_defined
3014        || h->root.type == bfd_link_hash_defweak)
3015       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
3016       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
3017     {
3018       bfd *output_bfd = (bfd *) data;
3019
3020       h->root.u.def.value =
3021         _bfd_merged_section_offset (output_bfd,
3022                                     &h->root.u.def.section,
3023                                     elf_section_data (sec)->sec_info,
3024                                     h->root.u.def.value);
3025     }
3026
3027   return TRUE;
3028 }
3029
3030 /* Returns false if the symbol referred to by H should be considered
3031    to resolve local to the current module, and true if it should be
3032    considered to bind dynamically.  */
3033
3034 bfd_boolean
3035 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
3036                            struct bfd_link_info *info,
3037                            bfd_boolean not_local_protected)
3038 {
3039   bfd_boolean binding_stays_local_p;
3040   const struct elf_backend_data *bed;
3041   struct elf_link_hash_table *hash_table;
3042
3043   if (h == NULL)
3044     return FALSE;
3045
3046   while (h->root.type == bfd_link_hash_indirect
3047          || h->root.type == bfd_link_hash_warning)
3048     h = (struct elf_link_hash_entry *) h->root.u.i.link;
3049
3050   /* If it was forced local, then clearly it's not dynamic.  */
3051   if (h->dynindx == -1)
3052     return FALSE;
3053   if (h->forced_local)
3054     return FALSE;
3055
3056   /* Identify the cases where name binding rules say that a
3057      visible symbol resolves locally.  */
3058   binding_stays_local_p = (bfd_link_executable (info)
3059                            || SYMBOLIC_BIND (info, h));
3060
3061   switch (ELF_ST_VISIBILITY (h->other))
3062     {
3063     case STV_INTERNAL:
3064     case STV_HIDDEN:
3065       return FALSE;
3066
3067     case STV_PROTECTED:
3068       hash_table = elf_hash_table (info);
3069       if (!is_elf_hash_table (hash_table))
3070         return FALSE;
3071
3072       bed = get_elf_backend_data (hash_table->dynobj);
3073
3074       /* Proper resolution for function pointer equality may require
3075          that these symbols perhaps be resolved dynamically, even though
3076          we should be resolving them to the current module.  */
3077       if (!not_local_protected || !bed->is_function_type (h->type))
3078         binding_stays_local_p = TRUE;
3079       break;
3080
3081     default:
3082       break;
3083     }
3084
3085   /* If it isn't defined locally, then clearly it's dynamic.  */
3086   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
3087     return TRUE;
3088
3089   /* Otherwise, the symbol is dynamic if binding rules don't tell
3090      us that it remains local.  */
3091   return !binding_stays_local_p;
3092 }
3093
3094 /* Return true if the symbol referred to by H should be considered
3095    to resolve local to the current module, and false otherwise.  Differs
3096    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
3097    undefined symbols.  The two functions are virtually identical except
3098    for the place where dynindx == -1 is tested.  If that test is true,
3099    _bfd_elf_dynamic_symbol_p will say the symbol is local, while
3100    _bfd_elf_symbol_refs_local_p will say the symbol is local only for
3101    defined symbols.
3102    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
3103    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
3104    treatment of undefined weak symbols.  For those that do not make
3105    undefined weak symbols dynamic, both functions may return false.  */
3106
3107 bfd_boolean
3108 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
3109                               struct bfd_link_info *info,
3110                               bfd_boolean local_protected)
3111 {
3112   const struct elf_backend_data *bed;
3113   struct elf_link_hash_table *hash_table;
3114
3115   /* If it's a local sym, of course we resolve locally.  */
3116   if (h == NULL)
3117     return TRUE;
3118
3119   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
3120   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
3121       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
3122     return TRUE;
3123
3124   /* Forced local symbols resolve locally.  */
3125   if (h->forced_local)
3126     return TRUE;
3127
3128   /* Common symbols that become definitions don't get the DEF_REGULAR
3129      flag set, so test it first, and don't bail out.  */
3130   if (ELF_COMMON_DEF_P (h))
3131     /* Do nothing.  */;
3132   /* If we don't have a definition in a regular file, then we can't
3133      resolve locally.  The sym is either undefined or dynamic.  */
3134   else if (!h->def_regular)
3135     return FALSE;
3136
3137   /* Non-dynamic symbols resolve locally.  */
3138   if (h->dynindx == -1)
3139     return TRUE;
3140
3141   /* At this point, we know the symbol is defined and dynamic.  In an
3142      executable it must resolve locally, likewise when building symbolic
3143      shared libraries.  */
3144   if (bfd_link_executable (info) || SYMBOLIC_BIND (info, h))
3145     return TRUE;
3146
3147   /* Now deal with defined dynamic symbols in shared libraries.  Ones
3148      with default visibility might not resolve locally.  */
3149   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
3150     return FALSE;
3151
3152   hash_table = elf_hash_table (info);
3153   if (!is_elf_hash_table (hash_table))
3154     return TRUE;
3155
3156   bed = get_elf_backend_data (hash_table->dynobj);
3157
3158   /* If extern_protected_data is false, STV_PROTECTED non-function
3159      symbols are local.  */
3160   if ((!info->extern_protected_data
3161        || (info->extern_protected_data < 0
3162            && !bed->extern_protected_data))
3163       && !bed->is_function_type (h->type))
3164     return TRUE;
3165
3166   /* Function pointer equality tests may require that STV_PROTECTED
3167      symbols be treated as dynamic symbols.  If the address of a
3168      function not defined in an executable is set to that function's
3169      plt entry in the executable, then the address of the function in
3170      a shared library must also be the plt entry in the executable.  */
3171   return local_protected;
3172 }
3173
3174 /* Caches some TLS segment info, and ensures that the TLS segment vma is
3175    aligned.  Returns the first TLS output section.  */
3176
3177 struct bfd_section *
3178 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
3179 {
3180   struct bfd_section *sec, *tls;
3181   unsigned int align = 0;
3182
3183   for (sec = obfd->sections; sec != NULL; sec = sec->next)
3184     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
3185       break;
3186   tls = sec;
3187
3188   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
3189     if (sec->alignment_power > align)
3190       align = sec->alignment_power;
3191
3192   elf_hash_table (info)->tls_sec = tls;
3193
3194   /* Ensure the alignment of the first section is the largest alignment,
3195      so that the tls segment starts aligned.  */
3196   if (tls != NULL)
3197     tls->alignment_power = align;
3198
3199   return tls;
3200 }
3201
3202 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
3203 static bfd_boolean
3204 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
3205                                   Elf_Internal_Sym *sym)
3206 {
3207   const struct elf_backend_data *bed;
3208
3209   /* Local symbols do not count, but target specific ones might.  */
3210   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
3211       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
3212     return FALSE;
3213
3214   bed = get_elf_backend_data (abfd);
3215   /* Function symbols do not count.  */
3216   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
3217     return FALSE;
3218
3219   /* If the section is undefined, then so is the symbol.  */
3220   if (sym->st_shndx == SHN_UNDEF)
3221     return FALSE;
3222
3223   /* If the symbol is defined in the common section, then
3224      it is a common definition and so does not count.  */
3225   if (bed->common_definition (sym))
3226     return FALSE;
3227
3228   /* If the symbol is in a target specific section then we
3229      must rely upon the backend to tell us what it is.  */
3230   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3231     /* FIXME - this function is not coded yet:
3232
3233        return _bfd_is_global_symbol_definition (abfd, sym);
3234
3235        Instead for now assume that the definition is not global,
3236        Even if this is wrong, at least the linker will behave
3237        in the same way that it used to do.  */
3238     return FALSE;
3239
3240   return TRUE;
3241 }
3242
3243 /* Search the symbol table of the archive element of the archive ABFD
3244    whose archive map contains a mention of SYMDEF, and determine if
3245    the symbol is defined in this element.  */
3246 static bfd_boolean
3247 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3248 {
3249   Elf_Internal_Shdr * hdr;
3250   size_t symcount;
3251   size_t extsymcount;
3252   size_t extsymoff;
3253   Elf_Internal_Sym *isymbuf;
3254   Elf_Internal_Sym *isym;
3255   Elf_Internal_Sym *isymend;
3256   bfd_boolean result;
3257
3258   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3259   if (abfd == NULL)
3260     return FALSE;
3261
3262   if (! bfd_check_format (abfd, bfd_object))
3263     return FALSE;
3264
3265   /* Select the appropriate symbol table.  If we don't know if the
3266      object file is an IR object, give linker LTO plugin a chance to
3267      get the correct symbol table.  */
3268   if (abfd->plugin_format == bfd_plugin_yes
3269 #if BFD_SUPPORTS_PLUGINS
3270       || (abfd->plugin_format == bfd_plugin_unknown
3271           && bfd_link_plugin_object_p (abfd))
3272 #endif
3273       )
3274     {
3275       /* Use the IR symbol table if the object has been claimed by
3276          plugin.  */
3277       abfd = abfd->plugin_dummy_bfd;
3278       hdr = &elf_tdata (abfd)->symtab_hdr;
3279     }
3280   else if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3281     hdr = &elf_tdata (abfd)->symtab_hdr;
3282   else
3283     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3284
3285   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3286
3287   /* The sh_info field of the symtab header tells us where the
3288      external symbols start.  We don't care about the local symbols.  */
3289   if (elf_bad_symtab (abfd))
3290     {
3291       extsymcount = symcount;
3292       extsymoff = 0;
3293     }
3294   else
3295     {
3296       extsymcount = symcount - hdr->sh_info;
3297       extsymoff = hdr->sh_info;
3298     }
3299
3300   if (extsymcount == 0)
3301     return FALSE;
3302
3303   /* Read in the symbol table.  */
3304   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3305                                   NULL, NULL, NULL);
3306   if (isymbuf == NULL)
3307     return FALSE;
3308
3309   /* Scan the symbol table looking for SYMDEF.  */
3310   result = FALSE;
3311   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3312     {
3313       const char *name;
3314
3315       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3316                                               isym->st_name);
3317       if (name == NULL)
3318         break;
3319
3320       if (strcmp (name, symdef->name) == 0)
3321         {
3322           result = is_global_data_symbol_definition (abfd, isym);
3323           break;
3324         }
3325     }
3326
3327   free (isymbuf);
3328
3329   return result;
3330 }
3331 \f
3332 /* Add an entry to the .dynamic table.  */
3333
3334 bfd_boolean
3335 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3336                             bfd_vma tag,
3337                             bfd_vma val)
3338 {
3339   struct elf_link_hash_table *hash_table;
3340   const struct elf_backend_data *bed;
3341   asection *s;
3342   bfd_size_type newsize;
3343   bfd_byte *newcontents;
3344   Elf_Internal_Dyn dyn;
3345
3346   hash_table = elf_hash_table (info);
3347   if (! is_elf_hash_table (hash_table))
3348     return FALSE;
3349
3350   bed = get_elf_backend_data (hash_table->dynobj);
3351   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3352   BFD_ASSERT (s != NULL);
3353
3354   newsize = s->size + bed->s->sizeof_dyn;
3355   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3356   if (newcontents == NULL)
3357     return FALSE;
3358
3359   dyn.d_tag = tag;
3360   dyn.d_un.d_val = val;
3361   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3362
3363   s->size = newsize;
3364   s->contents = newcontents;
3365
3366   return TRUE;
3367 }
3368
3369 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3370    otherwise just check whether one already exists.  Returns -1 on error,
3371    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3372
3373 static int
3374 elf_add_dt_needed_tag (bfd *abfd,
3375                        struct bfd_link_info *info,
3376                        const char *soname,
3377                        bfd_boolean do_it)
3378 {
3379   struct elf_link_hash_table *hash_table;
3380   size_t strindex;
3381
3382   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3383     return -1;
3384
3385   hash_table = elf_hash_table (info);
3386   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3387   if (strindex == (size_t) -1)
3388     return -1;
3389
3390   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3391     {
3392       asection *sdyn;
3393       const struct elf_backend_data *bed;
3394       bfd_byte *extdyn;
3395
3396       bed = get_elf_backend_data (hash_table->dynobj);
3397       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3398       if (sdyn != NULL)
3399         for (extdyn = sdyn->contents;
3400              extdyn < sdyn->contents + sdyn->size;
3401              extdyn += bed->s->sizeof_dyn)
3402           {
3403             Elf_Internal_Dyn dyn;
3404
3405             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3406             if (dyn.d_tag == DT_NEEDED
3407                 && dyn.d_un.d_val == strindex)
3408               {
3409                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3410                 return 1;
3411               }
3412           }
3413     }
3414
3415   if (do_it)
3416     {
3417       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3418         return -1;
3419
3420       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3421         return -1;
3422     }
3423   else
3424     /* We were just checking for existence of the tag.  */
3425     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3426
3427   return 0;
3428 }
3429
3430 /* Return true if SONAME is on the needed list between NEEDED and STOP
3431    (or the end of list if STOP is NULL), and needed by a library that
3432    will be loaded.  */
3433
3434 static bfd_boolean
3435 on_needed_list (const char *soname,
3436                 struct bfd_link_needed_list *needed,
3437                 struct bfd_link_needed_list *stop)
3438 {
3439   struct bfd_link_needed_list *look;
3440   for (look = needed; look != stop; look = look->next)
3441     if (strcmp (soname, look->name) == 0
3442         && ((elf_dyn_lib_class (look->by) & DYN_AS_NEEDED) == 0
3443             /* If needed by a library that itself is not directly
3444                needed, recursively check whether that library is
3445                indirectly needed.  Since we add DT_NEEDED entries to
3446                the end of the list, library dependencies appear after
3447                the library.  Therefore search prior to the current
3448                LOOK, preventing possible infinite recursion.  */
3449             || on_needed_list (elf_dt_name (look->by), needed, look)))
3450       return TRUE;
3451
3452   return FALSE;
3453 }
3454
3455 /* Sort symbol by value, section, and size.  */
3456 static int
3457 elf_sort_symbol (const void *arg1, const void *arg2)
3458 {
3459   const struct elf_link_hash_entry *h1;
3460   const struct elf_link_hash_entry *h2;
3461   bfd_signed_vma vdiff;
3462
3463   h1 = *(const struct elf_link_hash_entry **) arg1;
3464   h2 = *(const struct elf_link_hash_entry **) arg2;
3465   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3466   if (vdiff != 0)
3467     return vdiff > 0 ? 1 : -1;
3468   else
3469     {
3470       int sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3471       if (sdiff != 0)
3472         return sdiff > 0 ? 1 : -1;
3473     }
3474   vdiff = h1->size - h2->size;
3475   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3476 }
3477
3478 /* This function is used to adjust offsets into .dynstr for
3479    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3480
3481 static bfd_boolean
3482 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3483 {
3484   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3485
3486   if (h->dynindx != -1)
3487     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3488   return TRUE;
3489 }
3490
3491 /* Assign string offsets in .dynstr, update all structures referencing
3492    them.  */
3493
3494 static bfd_boolean
3495 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3496 {
3497   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3498   struct elf_link_local_dynamic_entry *entry;
3499   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3500   bfd *dynobj = hash_table->dynobj;
3501   asection *sdyn;
3502   bfd_size_type size;
3503   const struct elf_backend_data *bed;
3504   bfd_byte *extdyn;
3505
3506   _bfd_elf_strtab_finalize (dynstr);
3507   size = _bfd_elf_strtab_size (dynstr);
3508
3509   bed = get_elf_backend_data (dynobj);
3510   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3511   BFD_ASSERT (sdyn != NULL);
3512
3513   /* Update all .dynamic entries referencing .dynstr strings.  */
3514   for (extdyn = sdyn->contents;
3515        extdyn < sdyn->contents + sdyn->size;
3516        extdyn += bed->s->sizeof_dyn)
3517     {
3518       Elf_Internal_Dyn dyn;
3519
3520       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3521       switch (dyn.d_tag)
3522         {
3523         case DT_STRSZ:
3524           dyn.d_un.d_val = size;
3525           break;
3526         case DT_NEEDED:
3527         case DT_SONAME:
3528         case DT_RPATH:
3529         case DT_RUNPATH:
3530         case DT_FILTER:
3531         case DT_AUXILIARY:
3532         case DT_AUDIT:
3533         case DT_DEPAUDIT:
3534           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3535           break;
3536         default:
3537           continue;
3538         }
3539       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3540     }
3541
3542   /* Now update local dynamic symbols.  */
3543   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3544     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3545                                                   entry->isym.st_name);
3546
3547   /* And the rest of dynamic symbols.  */
3548   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3549
3550   /* Adjust version definitions.  */
3551   if (elf_tdata (output_bfd)->cverdefs)
3552     {
3553       asection *s;
3554       bfd_byte *p;
3555       size_t i;
3556       Elf_Internal_Verdef def;
3557       Elf_Internal_Verdaux defaux;
3558
3559       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3560       p = s->contents;
3561       do
3562         {
3563           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3564                                    &def);
3565           p += sizeof (Elf_External_Verdef);
3566           if (def.vd_aux != sizeof (Elf_External_Verdef))
3567             continue;
3568           for (i = 0; i < def.vd_cnt; ++i)
3569             {
3570               _bfd_elf_swap_verdaux_in (output_bfd,
3571                                         (Elf_External_Verdaux *) p, &defaux);
3572               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3573                                                         defaux.vda_name);
3574               _bfd_elf_swap_verdaux_out (output_bfd,
3575                                          &defaux, (Elf_External_Verdaux *) p);
3576               p += sizeof (Elf_External_Verdaux);
3577             }
3578         }
3579       while (def.vd_next);
3580     }
3581
3582   /* Adjust version references.  */
3583   if (elf_tdata (output_bfd)->verref)
3584     {
3585       asection *s;
3586       bfd_byte *p;
3587       size_t i;
3588       Elf_Internal_Verneed need;
3589       Elf_Internal_Vernaux needaux;
3590
3591       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3592       p = s->contents;
3593       do
3594         {
3595           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3596                                     &need);
3597           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3598           _bfd_elf_swap_verneed_out (output_bfd, &need,
3599                                      (Elf_External_Verneed *) p);
3600           p += sizeof (Elf_External_Verneed);
3601           for (i = 0; i < need.vn_cnt; ++i)
3602             {
3603               _bfd_elf_swap_vernaux_in (output_bfd,
3604                                         (Elf_External_Vernaux *) p, &needaux);
3605               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3606                                                          needaux.vna_name);
3607               _bfd_elf_swap_vernaux_out (output_bfd,
3608                                          &needaux,
3609                                          (Elf_External_Vernaux *) p);
3610               p += sizeof (Elf_External_Vernaux);
3611             }
3612         }
3613       while (need.vn_next);
3614     }
3615
3616   return TRUE;
3617 }
3618 \f
3619 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3620    The default is to only match when the INPUT and OUTPUT are exactly
3621    the same target.  */
3622
3623 bfd_boolean
3624 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3625                                     const bfd_target *output)
3626 {
3627   return input == output;
3628 }
3629
3630 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3631    This version is used when different targets for the same architecture
3632    are virtually identical.  */
3633
3634 bfd_boolean
3635 _bfd_elf_relocs_compatible (const bfd_target *input,
3636                             const bfd_target *output)
3637 {
3638   const struct elf_backend_data *obed, *ibed;
3639
3640   if (input == output)
3641     return TRUE;
3642
3643   ibed = xvec_get_elf_backend_data (input);
3644   obed = xvec_get_elf_backend_data (output);
3645
3646   if (ibed->arch != obed->arch)
3647     return FALSE;
3648
3649   /* If both backends are using this function, deem them compatible.  */
3650   return ibed->relocs_compatible == obed->relocs_compatible;
3651 }
3652
3653 /* Make a special call to the linker "notice" function to tell it that
3654    we are about to handle an as-needed lib, or have finished
3655    processing the lib.  */
3656
3657 bfd_boolean
3658 _bfd_elf_notice_as_needed (bfd *ibfd,
3659                            struct bfd_link_info *info,
3660                            enum notice_asneeded_action act)
3661 {
3662   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3663 }
3664
3665 /* Check relocations an ELF object file.  */
3666
3667 bfd_boolean
3668 _bfd_elf_link_check_relocs (bfd *abfd, struct bfd_link_info *info)
3669 {
3670   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3671   struct elf_link_hash_table *htab = elf_hash_table (info);
3672
3673   /* If this object is the same format as the output object, and it is
3674      not a shared library, then let the backend look through the
3675      relocs.
3676
3677      This is required to build global offset table entries and to
3678      arrange for dynamic relocs.  It is not required for the
3679      particular common case of linking non PIC code, even when linking
3680      against shared libraries, but unfortunately there is no way of
3681      knowing whether an object file has been compiled PIC or not.
3682      Looking through the relocs is not particularly time consuming.
3683      The problem is that we must either (1) keep the relocs in memory,
3684      which causes the linker to require additional runtime memory or
3685      (2) read the relocs twice from the input file, which wastes time.
3686      This would be a good case for using mmap.
3687
3688      I have no idea how to handle linking PIC code into a file of a
3689      different format.  It probably can't be done.  */
3690   if ((abfd->flags & DYNAMIC) == 0
3691       && is_elf_hash_table (htab)
3692       && bed->check_relocs != NULL
3693       && elf_object_id (abfd) == elf_hash_table_id (htab)
3694       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
3695     {
3696       asection *o;
3697
3698       for (o = abfd->sections; o != NULL; o = o->next)
3699         {
3700           Elf_Internal_Rela *internal_relocs;
3701           bfd_boolean ok;
3702
3703           /* Don't check relocations in excluded sections.  */
3704           if ((o->flags & SEC_RELOC) == 0
3705               || (o->flags & SEC_EXCLUDE) != 0
3706               || o->reloc_count == 0
3707               || ((info->strip == strip_all || info->strip == strip_debugger)
3708                   && (o->flags & SEC_DEBUGGING) != 0)
3709               || bfd_is_abs_section (o->output_section))
3710             continue;
3711
3712           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
3713                                                        info->keep_memory);
3714           if (internal_relocs == NULL)
3715             return FALSE;
3716
3717           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
3718
3719           if (elf_section_data (o)->relocs != internal_relocs)
3720             free (internal_relocs);
3721
3722           if (! ok)
3723             return FALSE;
3724         }
3725     }
3726
3727   return TRUE;
3728 }
3729
3730 /* Add symbols from an ELF object file to the linker hash table.  */
3731
3732 static bfd_boolean
3733 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3734 {
3735   Elf_Internal_Ehdr *ehdr;
3736   Elf_Internal_Shdr *hdr;
3737   size_t symcount;
3738   size_t extsymcount;
3739   size_t extsymoff;
3740   struct elf_link_hash_entry **sym_hash;
3741   bfd_boolean dynamic;
3742   Elf_External_Versym *extversym = NULL;
3743   Elf_External_Versym *ever;
3744   struct elf_link_hash_entry *weaks;
3745   struct elf_link_hash_entry **nondeflt_vers = NULL;
3746   size_t nondeflt_vers_cnt = 0;
3747   Elf_Internal_Sym *isymbuf = NULL;
3748   Elf_Internal_Sym *isym;
3749   Elf_Internal_Sym *isymend;
3750   const struct elf_backend_data *bed;
3751   bfd_boolean add_needed;
3752   struct elf_link_hash_table *htab;
3753   bfd_size_type amt;
3754   void *alloc_mark = NULL;
3755   struct bfd_hash_entry **old_table = NULL;
3756   unsigned int old_size = 0;
3757   unsigned int old_count = 0;
3758   void *old_tab = NULL;
3759   void *old_ent;
3760   struct bfd_link_hash_entry *old_undefs = NULL;
3761   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3762   void *old_strtab = NULL;
3763   size_t tabsize = 0;
3764   asection *s;
3765   bfd_boolean just_syms;
3766
3767   htab = elf_hash_table (info);
3768   bed = get_elf_backend_data (abfd);
3769
3770   if ((abfd->flags & DYNAMIC) == 0)
3771     dynamic = FALSE;
3772   else
3773     {
3774       dynamic = TRUE;
3775
3776       /* You can't use -r against a dynamic object.  Also, there's no
3777          hope of using a dynamic object which does not exactly match
3778          the format of the output file.  */
3779       if (bfd_link_relocatable (info)
3780           || !is_elf_hash_table (htab)
3781           || info->output_bfd->xvec != abfd->xvec)
3782         {
3783           if (bfd_link_relocatable (info))
3784             bfd_set_error (bfd_error_invalid_operation);
3785           else
3786             bfd_set_error (bfd_error_wrong_format);
3787           goto error_return;
3788         }
3789     }
3790
3791   ehdr = elf_elfheader (abfd);
3792   if (info->warn_alternate_em
3793       && bed->elf_machine_code != ehdr->e_machine
3794       && ((bed->elf_machine_alt1 != 0
3795            && ehdr->e_machine == bed->elf_machine_alt1)
3796           || (bed->elf_machine_alt2 != 0
3797               && ehdr->e_machine == bed->elf_machine_alt2)))
3798     info->callbacks->einfo
3799       /* xgettext:c-format */
3800       (_("%P: alternate ELF machine code found (%d) in %B, expecting %d\n"),
3801        ehdr->e_machine, abfd, bed->elf_machine_code);
3802
3803   /* As a GNU extension, any input sections which are named
3804      .gnu.warning.SYMBOL are treated as warning symbols for the given
3805      symbol.  This differs from .gnu.warning sections, which generate
3806      warnings when they are included in an output file.  */
3807   /* PR 12761: Also generate this warning when building shared libraries.  */
3808   for (s = abfd->sections; s != NULL; s = s->next)
3809     {
3810       const char *name;
3811
3812       name = bfd_get_section_name (abfd, s);
3813       if (CONST_STRNEQ (name, ".gnu.warning."))
3814         {
3815           char *msg;
3816           bfd_size_type sz;
3817
3818           name += sizeof ".gnu.warning." - 1;
3819
3820           /* If this is a shared object, then look up the symbol
3821              in the hash table.  If it is there, and it is already
3822              been defined, then we will not be using the entry
3823              from this shared object, so we don't need to warn.
3824              FIXME: If we see the definition in a regular object
3825              later on, we will warn, but we shouldn't.  The only
3826              fix is to keep track of what warnings we are supposed
3827              to emit, and then handle them all at the end of the
3828              link.  */
3829           if (dynamic)
3830             {
3831               struct elf_link_hash_entry *h;
3832
3833               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3834
3835               /* FIXME: What about bfd_link_hash_common?  */
3836               if (h != NULL
3837                   && (h->root.type == bfd_link_hash_defined
3838                       || h->root.type == bfd_link_hash_defweak))
3839                 continue;
3840             }
3841
3842           sz = s->size;
3843           msg = (char *) bfd_alloc (abfd, sz + 1);
3844           if (msg == NULL)
3845             goto error_return;
3846
3847           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3848             goto error_return;
3849
3850           msg[sz] = '\0';
3851
3852           if (! (_bfd_generic_link_add_one_symbol
3853                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3854                   FALSE, bed->collect, NULL)))
3855             goto error_return;
3856
3857           if (bfd_link_executable (info))
3858             {
3859               /* Clobber the section size so that the warning does
3860                  not get copied into the output file.  */
3861               s->size = 0;
3862
3863               /* Also set SEC_EXCLUDE, so that symbols defined in
3864                  the warning section don't get copied to the output.  */
3865               s->flags |= SEC_EXCLUDE;
3866             }
3867         }
3868     }
3869
3870   just_syms = ((s = abfd->sections) != NULL
3871                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3872
3873   add_needed = TRUE;
3874   if (! dynamic)
3875     {
3876       /* If we are creating a shared library, create all the dynamic
3877          sections immediately.  We need to attach them to something,
3878          so we attach them to this BFD, provided it is the right
3879          format and is not from ld --just-symbols.  Always create the
3880          dynamic sections for -E/--dynamic-list.  FIXME: If there
3881          are no input BFD's of the same format as the output, we can't
3882          make a shared library.  */
3883       if (!just_syms
3884           && (bfd_link_pic (info)
3885               || (!bfd_link_relocatable (info)
3886                   && info->nointerp
3887                   && (info->export_dynamic || info->dynamic)))
3888           && is_elf_hash_table (htab)
3889           && info->output_bfd->xvec == abfd->xvec
3890           && !htab->dynamic_sections_created)
3891         {
3892           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3893             goto error_return;
3894         }
3895     }
3896   else if (!is_elf_hash_table (htab))
3897     goto error_return;
3898   else
3899     {
3900       const char *soname = NULL;
3901       char *audit = NULL;
3902       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3903       const Elf_Internal_Phdr *phdr;
3904       int ret;
3905
3906       /* ld --just-symbols and dynamic objects don't mix very well.
3907          ld shouldn't allow it.  */
3908       if (just_syms)
3909         abort ();
3910
3911       /* If this dynamic lib was specified on the command line with
3912          --as-needed in effect, then we don't want to add a DT_NEEDED
3913          tag unless the lib is actually used.  Similary for libs brought
3914          in by another lib's DT_NEEDED.  When --no-add-needed is used
3915          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3916          any dynamic library in DT_NEEDED tags in the dynamic lib at
3917          all.  */
3918       add_needed = (elf_dyn_lib_class (abfd)
3919                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3920                        | DYN_NO_NEEDED)) == 0;
3921
3922       s = bfd_get_section_by_name (abfd, ".dynamic");
3923       if (s != NULL)
3924         {
3925           bfd_byte *dynbuf;
3926           bfd_byte *extdyn;
3927           unsigned int elfsec;
3928           unsigned long shlink;
3929
3930           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3931             {
3932 error_free_dyn:
3933               free (dynbuf);
3934               goto error_return;
3935             }
3936
3937           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3938           if (elfsec == SHN_BAD)
3939             goto error_free_dyn;
3940           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3941
3942           for (extdyn = dynbuf;
3943                extdyn < dynbuf + s->size;
3944                extdyn += bed->s->sizeof_dyn)
3945             {
3946               Elf_Internal_Dyn dyn;
3947
3948               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3949               if (dyn.d_tag == DT_SONAME)
3950                 {
3951                   unsigned int tagv = dyn.d_un.d_val;
3952                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3953                   if (soname == NULL)
3954                     goto error_free_dyn;
3955                 }
3956               if (dyn.d_tag == DT_NEEDED)
3957                 {
3958                   struct bfd_link_needed_list *n, **pn;
3959                   char *fnm, *anm;
3960                   unsigned int tagv = dyn.d_un.d_val;
3961
3962                   amt = sizeof (struct bfd_link_needed_list);
3963                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3964                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3965                   if (n == NULL || fnm == NULL)
3966                     goto error_free_dyn;
3967                   amt = strlen (fnm) + 1;
3968                   anm = (char *) bfd_alloc (abfd, amt);
3969                   if (anm == NULL)
3970                     goto error_free_dyn;
3971                   memcpy (anm, fnm, amt);
3972                   n->name = anm;
3973                   n->by = abfd;
3974                   n->next = NULL;
3975                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
3976                     ;
3977                   *pn = n;
3978                 }
3979               if (dyn.d_tag == DT_RUNPATH)
3980                 {
3981                   struct bfd_link_needed_list *n, **pn;
3982                   char *fnm, *anm;
3983                   unsigned int tagv = dyn.d_un.d_val;
3984
3985                   amt = sizeof (struct bfd_link_needed_list);
3986                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3987                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3988                   if (n == NULL || fnm == NULL)
3989                     goto error_free_dyn;
3990                   amt = strlen (fnm) + 1;
3991                   anm = (char *) bfd_alloc (abfd, amt);
3992                   if (anm == NULL)
3993                     goto error_free_dyn;
3994                   memcpy (anm, fnm, amt);
3995                   n->name = anm;
3996                   n->by = abfd;
3997                   n->next = NULL;
3998                   for (pn = & runpath;
3999                        *pn != NULL;
4000                        pn = &(*pn)->next)
4001                     ;
4002                   *pn = n;
4003                 }
4004               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
4005               if (!runpath && dyn.d_tag == DT_RPATH)
4006                 {
4007                   struct bfd_link_needed_list *n, **pn;
4008                   char *fnm, *anm;
4009                   unsigned int tagv = dyn.d_un.d_val;
4010
4011                   amt = sizeof (struct bfd_link_needed_list);
4012                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
4013                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4014                   if (n == NULL || fnm == NULL)
4015                     goto error_free_dyn;
4016                   amt = strlen (fnm) + 1;
4017                   anm = (char *) bfd_alloc (abfd, amt);
4018                   if (anm == NULL)
4019                     goto error_free_dyn;
4020                   memcpy (anm, fnm, amt);
4021                   n->name = anm;
4022                   n->by = abfd;
4023                   n->next = NULL;
4024                   for (pn = & rpath;
4025                        *pn != NULL;
4026                        pn = &(*pn)->next)
4027                     ;
4028                   *pn = n;
4029                 }
4030               if (dyn.d_tag == DT_AUDIT)
4031                 {
4032                   unsigned int tagv = dyn.d_un.d_val;
4033                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4034                 }
4035             }
4036
4037           free (dynbuf);
4038         }
4039
4040       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
4041          frees all more recently bfd_alloc'd blocks as well.  */
4042       if (runpath)
4043         rpath = runpath;
4044
4045       if (rpath)
4046         {
4047           struct bfd_link_needed_list **pn;
4048           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
4049             ;
4050           *pn = rpath;
4051         }
4052
4053       /* If we have a PT_GNU_RELRO program header, mark as read-only
4054          all sections contained fully therein.  This makes relro
4055          shared library sections appear as they will at run-time.  */
4056       phdr = elf_tdata (abfd)->phdr + elf_elfheader (abfd)->e_phnum;
4057       while (--phdr >= elf_tdata (abfd)->phdr)
4058         if (phdr->p_type == PT_GNU_RELRO)
4059           {
4060             for (s = abfd->sections; s != NULL; s = s->next)
4061               if ((s->flags & SEC_ALLOC) != 0
4062                   && s->vma >= phdr->p_vaddr
4063                   && s->vma + s->size <= phdr->p_vaddr + phdr->p_memsz)
4064                 s->flags |= SEC_READONLY;
4065             break;
4066           }
4067
4068       /* We do not want to include any of the sections in a dynamic
4069          object in the output file.  We hack by simply clobbering the
4070          list of sections in the BFD.  This could be handled more
4071          cleanly by, say, a new section flag; the existing
4072          SEC_NEVER_LOAD flag is not the one we want, because that one
4073          still implies that the section takes up space in the output
4074          file.  */
4075       bfd_section_list_clear (abfd);
4076
4077       /* Find the name to use in a DT_NEEDED entry that refers to this
4078          object.  If the object has a DT_SONAME entry, we use it.
4079          Otherwise, if the generic linker stuck something in
4080          elf_dt_name, we use that.  Otherwise, we just use the file
4081          name.  */
4082       if (soname == NULL || *soname == '\0')
4083         {
4084           soname = elf_dt_name (abfd);
4085           if (soname == NULL || *soname == '\0')
4086             soname = bfd_get_filename (abfd);
4087         }
4088
4089       /* Save the SONAME because sometimes the linker emulation code
4090          will need to know it.  */
4091       elf_dt_name (abfd) = soname;
4092
4093       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4094       if (ret < 0)
4095         goto error_return;
4096
4097       /* If we have already included this dynamic object in the
4098          link, just ignore it.  There is no reason to include a
4099          particular dynamic object more than once.  */
4100       if (ret > 0)
4101         return TRUE;
4102
4103       /* Save the DT_AUDIT entry for the linker emulation code. */
4104       elf_dt_audit (abfd) = audit;
4105     }
4106
4107   /* If this is a dynamic object, we always link against the .dynsym
4108      symbol table, not the .symtab symbol table.  The dynamic linker
4109      will only see the .dynsym symbol table, so there is no reason to
4110      look at .symtab for a dynamic object.  */
4111
4112   if (! dynamic || elf_dynsymtab (abfd) == 0)
4113     hdr = &elf_tdata (abfd)->symtab_hdr;
4114   else
4115     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
4116
4117   symcount = hdr->sh_size / bed->s->sizeof_sym;
4118
4119   /* The sh_info field of the symtab header tells us where the
4120      external symbols start.  We don't care about the local symbols at
4121      this point.  */
4122   if (elf_bad_symtab (abfd))
4123     {
4124       extsymcount = symcount;
4125       extsymoff = 0;
4126     }
4127   else
4128     {
4129       extsymcount = symcount - hdr->sh_info;
4130       extsymoff = hdr->sh_info;
4131     }
4132
4133   sym_hash = elf_sym_hashes (abfd);
4134   if (extsymcount != 0)
4135     {
4136       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
4137                                       NULL, NULL, NULL);
4138       if (isymbuf == NULL)
4139         goto error_return;
4140
4141       if (sym_hash == NULL)
4142         {
4143           /* We store a pointer to the hash table entry for each
4144              external symbol.  */
4145           amt = extsymcount;
4146           amt *= sizeof (struct elf_link_hash_entry *);
4147           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
4148           if (sym_hash == NULL)
4149             goto error_free_sym;
4150           elf_sym_hashes (abfd) = sym_hash;
4151         }
4152     }
4153
4154   if (dynamic)
4155     {
4156       /* Read in any version definitions.  */
4157       if (!_bfd_elf_slurp_version_tables (abfd,
4158                                           info->default_imported_symver))
4159         goto error_free_sym;
4160
4161       /* Read in the symbol versions, but don't bother to convert them
4162          to internal format.  */
4163       if (elf_dynversym (abfd) != 0)
4164         {
4165           Elf_Internal_Shdr *versymhdr;
4166
4167           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
4168           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
4169           if (extversym == NULL)
4170             goto error_free_sym;
4171           amt = versymhdr->sh_size;
4172           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
4173               || bfd_bread (extversym, amt, abfd) != amt)
4174             goto error_free_vers;
4175         }
4176     }
4177
4178   /* If we are loading an as-needed shared lib, save the symbol table
4179      state before we start adding symbols.  If the lib turns out
4180      to be unneeded, restore the state.  */
4181   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4182     {
4183       unsigned int i;
4184       size_t entsize;
4185
4186       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
4187         {
4188           struct bfd_hash_entry *p;
4189           struct elf_link_hash_entry *h;
4190
4191           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4192             {
4193               h = (struct elf_link_hash_entry *) p;
4194               entsize += htab->root.table.entsize;
4195               if (h->root.type == bfd_link_hash_warning)
4196                 entsize += htab->root.table.entsize;
4197             }
4198         }
4199
4200       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
4201       old_tab = bfd_malloc (tabsize + entsize);
4202       if (old_tab == NULL)
4203         goto error_free_vers;
4204
4205       /* Remember the current objalloc pointer, so that all mem for
4206          symbols added can later be reclaimed.  */
4207       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
4208       if (alloc_mark == NULL)
4209         goto error_free_vers;
4210
4211       /* Make a special call to the linker "notice" function to
4212          tell it that we are about to handle an as-needed lib.  */
4213       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
4214         goto error_free_vers;
4215
4216       /* Clone the symbol table.  Remember some pointers into the
4217          symbol table, and dynamic symbol count.  */
4218       old_ent = (char *) old_tab + tabsize;
4219       memcpy (old_tab, htab->root.table.table, tabsize);
4220       old_undefs = htab->root.undefs;
4221       old_undefs_tail = htab->root.undefs_tail;
4222       old_table = htab->root.table.table;
4223       old_size = htab->root.table.size;
4224       old_count = htab->root.table.count;
4225       old_strtab = _bfd_elf_strtab_save (htab->dynstr);
4226       if (old_strtab == NULL)
4227         goto error_free_vers;
4228
4229       for (i = 0; i < htab->root.table.size; i++)
4230         {
4231           struct bfd_hash_entry *p;
4232           struct elf_link_hash_entry *h;
4233
4234           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4235             {
4236               memcpy (old_ent, p, htab->root.table.entsize);
4237               old_ent = (char *) old_ent + htab->root.table.entsize;
4238               h = (struct elf_link_hash_entry *) p;
4239               if (h->root.type == bfd_link_hash_warning)
4240                 {
4241                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
4242                   old_ent = (char *) old_ent + htab->root.table.entsize;
4243                 }
4244             }
4245         }
4246     }
4247
4248   weaks = NULL;
4249   ever = extversym != NULL ? extversym + extsymoff : NULL;
4250   for (isym = isymbuf, isymend = isymbuf + extsymcount;
4251        isym < isymend;
4252        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
4253     {
4254       int bind;
4255       bfd_vma value;
4256       asection *sec, *new_sec;
4257       flagword flags;
4258       const char *name;
4259       struct elf_link_hash_entry *h;
4260       struct elf_link_hash_entry *hi;
4261       bfd_boolean definition;
4262       bfd_boolean size_change_ok;
4263       bfd_boolean type_change_ok;
4264       bfd_boolean new_weakdef;
4265       bfd_boolean new_weak;
4266       bfd_boolean old_weak;
4267       bfd_boolean override;
4268       bfd_boolean common;
4269       bfd_boolean discarded;
4270       unsigned int old_alignment;
4271       bfd *old_bfd;
4272       bfd_boolean matched;
4273
4274       override = FALSE;
4275
4276       flags = BSF_NO_FLAGS;
4277       sec = NULL;
4278       value = isym->st_value;
4279       common = bed->common_definition (isym);
4280       if (common && info->inhibit_common_definition)
4281         {
4282           /* Treat common symbol as undefined for --no-define-common.  */
4283           isym->st_shndx = SHN_UNDEF;
4284           common = FALSE;
4285         }
4286       discarded = FALSE;
4287
4288       bind = ELF_ST_BIND (isym->st_info);
4289       switch (bind)
4290         {
4291         case STB_LOCAL:
4292           /* This should be impossible, since ELF requires that all
4293              global symbols follow all local symbols, and that sh_info
4294              point to the first global symbol.  Unfortunately, Irix 5
4295              screws this up.  */
4296           continue;
4297
4298         case STB_GLOBAL:
4299           if (isym->st_shndx != SHN_UNDEF && !common)
4300             flags = BSF_GLOBAL;
4301           break;
4302
4303         case STB_WEAK:
4304           flags = BSF_WEAK;
4305           break;
4306
4307         case STB_GNU_UNIQUE:
4308           flags = BSF_GNU_UNIQUE;
4309           break;
4310
4311         default:
4312           /* Leave it up to the processor backend.  */
4313           break;
4314         }
4315
4316       if (isym->st_shndx == SHN_UNDEF)
4317         sec = bfd_und_section_ptr;
4318       else if (isym->st_shndx == SHN_ABS)
4319         sec = bfd_abs_section_ptr;
4320       else if (isym->st_shndx == SHN_COMMON)
4321         {
4322           sec = bfd_com_section_ptr;
4323           /* What ELF calls the size we call the value.  What ELF
4324              calls the value we call the alignment.  */
4325           value = isym->st_size;
4326         }
4327       else
4328         {
4329           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
4330           if (sec == NULL)
4331             sec = bfd_abs_section_ptr;
4332           else if (discarded_section (sec))
4333             {
4334               /* Symbols from discarded section are undefined.  We keep
4335                  its visibility.  */
4336               sec = bfd_und_section_ptr;
4337               discarded = TRUE;
4338               isym->st_shndx = SHN_UNDEF;
4339             }
4340           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
4341             value -= sec->vma;
4342         }
4343
4344       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4345                                               isym->st_name);
4346       if (name == NULL)
4347         goto error_free_vers;
4348
4349       if (isym->st_shndx == SHN_COMMON
4350           && (abfd->flags & BFD_PLUGIN) != 0)
4351         {
4352           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4353
4354           if (xc == NULL)
4355             {
4356               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4357                                  | SEC_EXCLUDE);
4358               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4359               if (xc == NULL)
4360                 goto error_free_vers;
4361             }
4362           sec = xc;
4363         }
4364       else if (isym->st_shndx == SHN_COMMON
4365                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4366                && !bfd_link_relocatable (info))
4367         {
4368           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4369
4370           if (tcomm == NULL)
4371             {
4372               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4373                                  | SEC_LINKER_CREATED);
4374               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4375               if (tcomm == NULL)
4376                 goto error_free_vers;
4377             }
4378           sec = tcomm;
4379         }
4380       else if (bed->elf_add_symbol_hook)
4381         {
4382           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4383                                              &sec, &value))
4384             goto error_free_vers;
4385
4386           /* The hook function sets the name to NULL if this symbol
4387              should be skipped for some reason.  */
4388           if (name == NULL)
4389             continue;
4390         }
4391
4392       /* Sanity check that all possibilities were handled.  */
4393       if (sec == NULL)
4394         {
4395           bfd_set_error (bfd_error_bad_value);
4396           goto error_free_vers;
4397         }
4398
4399       /* Silently discard TLS symbols from --just-syms.  There's
4400          no way to combine a static TLS block with a new TLS block
4401          for this executable.  */
4402       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4403           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4404         continue;
4405
4406       if (bfd_is_und_section (sec)
4407           || bfd_is_com_section (sec))
4408         definition = FALSE;
4409       else
4410         definition = TRUE;
4411
4412       size_change_ok = FALSE;
4413       type_change_ok = bed->type_change_ok;
4414       old_weak = FALSE;
4415       matched = FALSE;
4416       old_alignment = 0;
4417       old_bfd = NULL;
4418       new_sec = sec;
4419
4420       if (is_elf_hash_table (htab))
4421         {
4422           Elf_Internal_Versym iver;
4423           unsigned int vernum = 0;
4424           bfd_boolean skip;
4425
4426           if (ever == NULL)
4427             {
4428               if (info->default_imported_symver)
4429                 /* Use the default symbol version created earlier.  */
4430                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4431               else
4432                 iver.vs_vers = 0;
4433             }
4434           else
4435             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4436
4437           vernum = iver.vs_vers & VERSYM_VERSION;
4438
4439           /* If this is a hidden symbol, or if it is not version
4440              1, we append the version name to the symbol name.
4441              However, we do not modify a non-hidden absolute symbol
4442              if it is not a function, because it might be the version
4443              symbol itself.  FIXME: What if it isn't?  */
4444           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4445               || (vernum > 1
4446                   && (!bfd_is_abs_section (sec)
4447                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4448             {
4449               const char *verstr;
4450               size_t namelen, verlen, newlen;
4451               char *newname, *p;
4452
4453               if (isym->st_shndx != SHN_UNDEF)
4454                 {
4455                   if (vernum > elf_tdata (abfd)->cverdefs)
4456                     verstr = NULL;
4457                   else if (vernum > 1)
4458                     verstr =
4459                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4460                   else
4461                     verstr = "";
4462
4463                   if (verstr == NULL)
4464                     {
4465                       _bfd_error_handler
4466                         /* xgettext:c-format */
4467                         (_("%B: %s: invalid version %u (max %d)"),
4468                          abfd, name, vernum,
4469                          elf_tdata (abfd)->cverdefs);
4470                       bfd_set_error (bfd_error_bad_value);
4471                       goto error_free_vers;
4472                     }
4473                 }
4474               else
4475                 {
4476                   /* We cannot simply test for the number of
4477                      entries in the VERNEED section since the
4478                      numbers for the needed versions do not start
4479                      at 0.  */
4480                   Elf_Internal_Verneed *t;
4481
4482                   verstr = NULL;
4483                   for (t = elf_tdata (abfd)->verref;
4484                        t != NULL;
4485                        t = t->vn_nextref)
4486                     {
4487                       Elf_Internal_Vernaux *a;
4488
4489                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4490                         {
4491                           if (a->vna_other == vernum)
4492                             {
4493                               verstr = a->vna_nodename;
4494                               break;
4495                             }
4496                         }
4497                       if (a != NULL)
4498                         break;
4499                     }
4500                   if (verstr == NULL)
4501                     {
4502                       _bfd_error_handler
4503                         /* xgettext:c-format */
4504                         (_("%B: %s: invalid needed version %d"),
4505                          abfd, name, vernum);
4506                       bfd_set_error (bfd_error_bad_value);
4507                       goto error_free_vers;
4508                     }
4509                 }
4510
4511               namelen = strlen (name);
4512               verlen = strlen (verstr);
4513               newlen = namelen + verlen + 2;
4514               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4515                   && isym->st_shndx != SHN_UNDEF)
4516                 ++newlen;
4517
4518               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4519               if (newname == NULL)
4520                 goto error_free_vers;
4521               memcpy (newname, name, namelen);
4522               p = newname + namelen;
4523               *p++ = ELF_VER_CHR;
4524               /* If this is a defined non-hidden version symbol,
4525                  we add another @ to the name.  This indicates the
4526                  default version of the symbol.  */
4527               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4528                   && isym->st_shndx != SHN_UNDEF)
4529                 *p++ = ELF_VER_CHR;
4530               memcpy (p, verstr, verlen + 1);
4531
4532               name = newname;
4533             }
4534
4535           /* If this symbol has default visibility and the user has
4536              requested we not re-export it, then mark it as hidden.  */
4537           if (!bfd_is_und_section (sec)
4538               && !dynamic
4539               && abfd->no_export
4540               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4541             isym->st_other = (STV_HIDDEN
4542                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4543
4544           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4545                                       sym_hash, &old_bfd, &old_weak,
4546                                       &old_alignment, &skip, &override,
4547                                       &type_change_ok, &size_change_ok,
4548                                       &matched))
4549             goto error_free_vers;
4550
4551           if (skip)
4552             continue;
4553
4554           /* Override a definition only if the new symbol matches the
4555              existing one.  */
4556           if (override && matched)
4557             definition = FALSE;
4558
4559           h = *sym_hash;
4560           while (h->root.type == bfd_link_hash_indirect
4561                  || h->root.type == bfd_link_hash_warning)
4562             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4563
4564           if (elf_tdata (abfd)->verdef != NULL
4565               && vernum > 1
4566               && definition)
4567             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4568         }
4569
4570       if (! (_bfd_generic_link_add_one_symbol
4571              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4572               (struct bfd_link_hash_entry **) sym_hash)))
4573         goto error_free_vers;
4574
4575       if ((flags & BSF_GNU_UNIQUE)
4576           && (abfd->flags & DYNAMIC) == 0
4577           && bfd_get_flavour (info->output_bfd) == bfd_target_elf_flavour)
4578         elf_tdata (info->output_bfd)->has_gnu_symbols |= elf_gnu_symbol_unique;
4579
4580       h = *sym_hash;
4581       /* We need to make sure that indirect symbol dynamic flags are
4582          updated.  */
4583       hi = h;
4584       while (h->root.type == bfd_link_hash_indirect
4585              || h->root.type == bfd_link_hash_warning)
4586         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4587
4588       /* Setting the index to -3 tells elf_link_output_extsym that
4589          this symbol is defined in a discarded section.  */
4590       if (discarded)
4591         h->indx = -3;
4592
4593       *sym_hash = h;
4594
4595       new_weak = (flags & BSF_WEAK) != 0;
4596       new_weakdef = FALSE;
4597       if (dynamic
4598           && definition
4599           && new_weak
4600           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4601           && is_elf_hash_table (htab)
4602           && h->u.weakdef == NULL)
4603         {
4604           /* Keep a list of all weak defined non function symbols from
4605              a dynamic object, using the weakdef field.  Later in this
4606              function we will set the weakdef field to the correct
4607              value.  We only put non-function symbols from dynamic
4608              objects on this list, because that happens to be the only
4609              time we need to know the normal symbol corresponding to a
4610              weak symbol, and the information is time consuming to
4611              figure out.  If the weakdef field is not already NULL,
4612              then this symbol was already defined by some previous
4613              dynamic object, and we will be using that previous
4614              definition anyhow.  */
4615
4616           h->u.weakdef = weaks;
4617           weaks = h;
4618           new_weakdef = TRUE;
4619         }
4620
4621       /* Set the alignment of a common symbol.  */
4622       if ((common || bfd_is_com_section (sec))
4623           && h->root.type == bfd_link_hash_common)
4624         {
4625           unsigned int align;
4626
4627           if (common)
4628             align = bfd_log2 (isym->st_value);
4629           else
4630             {
4631               /* The new symbol is a common symbol in a shared object.
4632                  We need to get the alignment from the section.  */
4633               align = new_sec->alignment_power;
4634             }
4635           if (align > old_alignment)
4636             h->root.u.c.p->alignment_power = align;
4637           else
4638             h->root.u.c.p->alignment_power = old_alignment;
4639         }
4640
4641       if (is_elf_hash_table (htab))
4642         {
4643           /* Set a flag in the hash table entry indicating the type of
4644              reference or definition we just found.  A dynamic symbol
4645              is one which is referenced or defined by both a regular
4646              object and a shared object.  */
4647           bfd_boolean dynsym = FALSE;
4648
4649           /* Plugin symbols aren't normal.  Don't set def_regular or
4650              ref_regular for them, or make them dynamic.  */
4651           if ((abfd->flags & BFD_PLUGIN) != 0)
4652             ;
4653           else if (! dynamic)
4654             {
4655               if (! definition)
4656                 {
4657                   h->ref_regular = 1;
4658                   if (bind != STB_WEAK)
4659                     h->ref_regular_nonweak = 1;
4660                 }
4661               else
4662                 {
4663                   h->def_regular = 1;
4664                   if (h->def_dynamic)
4665                     {
4666                       h->def_dynamic = 0;
4667                       h->ref_dynamic = 1;
4668                     }
4669                 }
4670
4671               /* If the indirect symbol has been forced local, don't
4672                  make the real symbol dynamic.  */
4673               if ((h == hi || !hi->forced_local)
4674                   && (bfd_link_dll (info)
4675                       || h->def_dynamic
4676                       || h->ref_dynamic))
4677                 dynsym = TRUE;
4678             }
4679           else
4680             {
4681               if (! definition)
4682                 {
4683                   h->ref_dynamic = 1;
4684                   hi->ref_dynamic = 1;
4685                 }
4686               else
4687                 {
4688                   h->def_dynamic = 1;
4689                   hi->def_dynamic = 1;
4690                 }
4691
4692               /* If the indirect symbol has been forced local, don't
4693                  make the real symbol dynamic.  */
4694               if ((h == hi || !hi->forced_local)
4695                   && (h->def_regular
4696                       || h->ref_regular
4697                       || (h->u.weakdef != NULL
4698                           && ! new_weakdef
4699                           && h->u.weakdef->dynindx != -1)))
4700                 dynsym = TRUE;
4701             }
4702
4703           /* Check to see if we need to add an indirect symbol for
4704              the default name.  */
4705           if (definition
4706               || (!override && h->root.type == bfd_link_hash_common))
4707             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4708                                               sec, value, &old_bfd, &dynsym))
4709               goto error_free_vers;
4710
4711           /* Check the alignment when a common symbol is involved. This
4712              can change when a common symbol is overridden by a normal
4713              definition or a common symbol is ignored due to the old
4714              normal definition. We need to make sure the maximum
4715              alignment is maintained.  */
4716           if ((old_alignment || common)
4717               && h->root.type != bfd_link_hash_common)
4718             {
4719               unsigned int common_align;
4720               unsigned int normal_align;
4721               unsigned int symbol_align;
4722               bfd *normal_bfd;
4723               bfd *common_bfd;
4724
4725               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4726                           || h->root.type == bfd_link_hash_defweak);
4727
4728               symbol_align = ffs (h->root.u.def.value) - 1;
4729               if (h->root.u.def.section->owner != NULL
4730                   && (h->root.u.def.section->owner->flags
4731                        & (DYNAMIC | BFD_PLUGIN)) == 0)
4732                 {
4733                   normal_align = h->root.u.def.section->alignment_power;
4734                   if (normal_align > symbol_align)
4735                     normal_align = symbol_align;
4736                 }
4737               else
4738                 normal_align = symbol_align;
4739
4740               if (old_alignment)
4741                 {
4742                   common_align = old_alignment;
4743                   common_bfd = old_bfd;
4744                   normal_bfd = abfd;
4745                 }
4746               else
4747                 {
4748                   common_align = bfd_log2 (isym->st_value);
4749                   common_bfd = abfd;
4750                   normal_bfd = old_bfd;
4751                 }
4752
4753               if (normal_align < common_align)
4754                 {
4755                   /* PR binutils/2735 */
4756                   if (normal_bfd == NULL)
4757                     _bfd_error_handler
4758                       /* xgettext:c-format */
4759                       (_("Warning: alignment %u of common symbol `%s' in %B is"
4760                          " greater than the alignment (%u) of its section %A"),
4761                        1 << common_align, name, common_bfd,
4762                        1 << normal_align, h->root.u.def.section);
4763                   else
4764                     _bfd_error_handler
4765                       /* xgettext:c-format */
4766                       (_("Warning: alignment %u of symbol `%s' in %B"
4767                          " is smaller than %u in %B"),
4768                        1 << normal_align, name, normal_bfd,
4769                        1 << common_align, common_bfd);
4770                 }
4771             }
4772
4773           /* Remember the symbol size if it isn't undefined.  */
4774           if (isym->st_size != 0
4775               && isym->st_shndx != SHN_UNDEF
4776               && (definition || h->size == 0))
4777             {
4778               if (h->size != 0
4779                   && h->size != isym->st_size
4780                   && ! size_change_ok)
4781                 _bfd_error_handler
4782                   /* xgettext:c-format */
4783                   (_("Warning: size of symbol `%s' changed"
4784                      " from %Lu in %B to %Lu in %B"),
4785                    name, h->size, old_bfd, isym->st_size, abfd);
4786
4787               h->size = isym->st_size;
4788             }
4789
4790           /* If this is a common symbol, then we always want H->SIZE
4791              to be the size of the common symbol.  The code just above
4792              won't fix the size if a common symbol becomes larger.  We
4793              don't warn about a size change here, because that is
4794              covered by --warn-common.  Allow changes between different
4795              function types.  */
4796           if (h->root.type == bfd_link_hash_common)
4797             h->size = h->root.u.c.size;
4798
4799           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4800               && ((definition && !new_weak)
4801                   || (old_weak && h->root.type == bfd_link_hash_common)
4802                   || h->type == STT_NOTYPE))
4803             {
4804               unsigned int type = ELF_ST_TYPE (isym->st_info);
4805
4806               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4807                  symbol.  */
4808               if (type == STT_GNU_IFUNC
4809                   && (abfd->flags & DYNAMIC) != 0)
4810                 type = STT_FUNC;
4811
4812               if (h->type != type)
4813                 {
4814                   if (h->type != STT_NOTYPE && ! type_change_ok)
4815                     /* xgettext:c-format */
4816                     _bfd_error_handler
4817                       (_("Warning: type of symbol `%s' changed"
4818                          " from %d to %d in %B"),
4819                        name, h->type, type, abfd);
4820
4821                   h->type = type;
4822                 }
4823             }
4824
4825           /* Merge st_other field.  */
4826           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4827
4828           /* We don't want to make debug symbol dynamic.  */
4829           if (definition
4830               && (sec->flags & SEC_DEBUGGING)
4831               && !bfd_link_relocatable (info))
4832             dynsym = FALSE;
4833
4834           /* Nor should we make plugin symbols dynamic.  */
4835           if ((abfd->flags & BFD_PLUGIN) != 0)
4836             dynsym = FALSE;
4837
4838           if (definition)
4839             {
4840               h->target_internal = isym->st_target_internal;
4841               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4842             }
4843
4844           if (definition && !dynamic)
4845             {
4846               char *p = strchr (name, ELF_VER_CHR);
4847               if (p != NULL && p[1] != ELF_VER_CHR)
4848                 {
4849                   /* Queue non-default versions so that .symver x, x@FOO
4850                      aliases can be checked.  */
4851                   if (!nondeflt_vers)
4852                     {
4853                       amt = ((isymend - isym + 1)
4854                              * sizeof (struct elf_link_hash_entry *));
4855                       nondeflt_vers
4856                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
4857                       if (!nondeflt_vers)
4858                         goto error_free_vers;
4859                     }
4860                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4861                 }
4862             }
4863
4864           if (dynsym && h->dynindx == -1)
4865             {
4866               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4867                 goto error_free_vers;
4868               if (h->u.weakdef != NULL
4869                   && ! new_weakdef
4870                   && h->u.weakdef->dynindx == -1)
4871                 {
4872                   if (!bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
4873                     goto error_free_vers;
4874                 }
4875             }
4876           else if (h->dynindx != -1)
4877             /* If the symbol already has a dynamic index, but
4878                visibility says it should not be visible, turn it into
4879                a local symbol.  */
4880             switch (ELF_ST_VISIBILITY (h->other))
4881               {
4882               case STV_INTERNAL:
4883               case STV_HIDDEN:
4884                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4885                 dynsym = FALSE;
4886                 break;
4887               }
4888
4889           /* Don't add DT_NEEDED for references from the dummy bfd nor
4890              for unmatched symbol.  */
4891           if (!add_needed
4892               && matched
4893               && definition
4894               && ((dynsym
4895                    && h->ref_regular_nonweak
4896                    && (old_bfd == NULL
4897                        || (old_bfd->flags & BFD_PLUGIN) == 0))
4898                   || (h->ref_dynamic_nonweak
4899                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4900                       && !on_needed_list (elf_dt_name (abfd),
4901                                           htab->needed, NULL))))
4902             {
4903               int ret;
4904               const char *soname = elf_dt_name (abfd);
4905
4906               info->callbacks->minfo ("%!", soname, old_bfd,
4907                                       h->root.root.string);
4908
4909               /* A symbol from a library loaded via DT_NEEDED of some
4910                  other library is referenced by a regular object.
4911                  Add a DT_NEEDED entry for it.  Issue an error if
4912                  --no-add-needed is used and the reference was not
4913                  a weak one.  */
4914               if (old_bfd != NULL
4915                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4916                 {
4917                   _bfd_error_handler
4918                     /* xgettext:c-format */
4919                     (_("%B: undefined reference to symbol '%s'"),
4920                      old_bfd, name);
4921                   bfd_set_error (bfd_error_missing_dso);
4922                   goto error_free_vers;
4923                 }
4924
4925               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4926                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4927
4928               add_needed = TRUE;
4929               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4930               if (ret < 0)
4931                 goto error_free_vers;
4932
4933               BFD_ASSERT (ret == 0);
4934             }
4935         }
4936     }
4937
4938   if (extversym != NULL)
4939     {
4940       free (extversym);
4941       extversym = NULL;
4942     }
4943
4944   if (isymbuf != NULL)
4945     {
4946       free (isymbuf);
4947       isymbuf = NULL;
4948     }
4949
4950   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4951     {
4952       unsigned int i;
4953
4954       /* Restore the symbol table.  */
4955       old_ent = (char *) old_tab + tabsize;
4956       memset (elf_sym_hashes (abfd), 0,
4957               extsymcount * sizeof (struct elf_link_hash_entry *));
4958       htab->root.table.table = old_table;
4959       htab->root.table.size = old_size;
4960       htab->root.table.count = old_count;
4961       memcpy (htab->root.table.table, old_tab, tabsize);
4962       htab->root.undefs = old_undefs;
4963       htab->root.undefs_tail = old_undefs_tail;
4964       _bfd_elf_strtab_restore (htab->dynstr, old_strtab);
4965       free (old_strtab);
4966       old_strtab = NULL;
4967       for (i = 0; i < htab->root.table.size; i++)
4968         {
4969           struct bfd_hash_entry *p;
4970           struct elf_link_hash_entry *h;
4971           bfd_size_type size;
4972           unsigned int alignment_power;
4973           unsigned int non_ir_ref_dynamic;
4974
4975           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4976             {
4977               h = (struct elf_link_hash_entry *) p;
4978               if (h->root.type == bfd_link_hash_warning)
4979                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
4980
4981               /* Preserve the maximum alignment and size for common
4982                  symbols even if this dynamic lib isn't on DT_NEEDED
4983                  since it can still be loaded at run time by another
4984                  dynamic lib.  */
4985               if (h->root.type == bfd_link_hash_common)
4986                 {
4987                   size = h->root.u.c.size;
4988                   alignment_power = h->root.u.c.p->alignment_power;
4989                 }
4990               else
4991                 {
4992                   size = 0;
4993                   alignment_power = 0;
4994                 }
4995               /* Preserve non_ir_ref_dynamic so that this symbol
4996                  will be exported when the dynamic lib becomes needed
4997                  in the second pass.  */
4998               non_ir_ref_dynamic = h->root.non_ir_ref_dynamic;
4999               memcpy (p, old_ent, htab->root.table.entsize);
5000               old_ent = (char *) old_ent + htab->root.table.entsize;
5001               h = (struct elf_link_hash_entry *) p;
5002               if (h->root.type == bfd_link_hash_warning)
5003                 {
5004                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
5005                   old_ent = (char *) old_ent + htab->root.table.entsize;
5006                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
5007                 }
5008               if (h->root.type == bfd_link_hash_common)
5009                 {
5010                   if (size > h->root.u.c.size)
5011                     h->root.u.c.size = size;
5012                   if (alignment_power > h->root.u.c.p->alignment_power)
5013                     h->root.u.c.p->alignment_power = alignment_power;
5014                 }
5015               h->root.non_ir_ref_dynamic = non_ir_ref_dynamic;
5016             }
5017         }
5018
5019       /* Make a special call to the linker "notice" function to
5020          tell it that symbols added for crefs may need to be removed.  */
5021       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
5022         goto error_free_vers;
5023
5024       free (old_tab);
5025       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
5026                            alloc_mark);
5027       if (nondeflt_vers != NULL)
5028         free (nondeflt_vers);
5029       return TRUE;
5030     }
5031
5032   if (old_tab != NULL)
5033     {
5034       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
5035         goto error_free_vers;
5036       free (old_tab);
5037       old_tab = NULL;
5038     }
5039
5040   /* Now that all the symbols from this input file are created, if
5041      not performing a relocatable link, handle .symver foo, foo@BAR
5042      such that any relocs against foo become foo@BAR.  */
5043   if (!bfd_link_relocatable (info) && nondeflt_vers != NULL)
5044     {
5045       size_t cnt, symidx;
5046
5047       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
5048         {
5049           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
5050           char *shortname, *p;
5051
5052           p = strchr (h->root.root.string, ELF_VER_CHR);
5053           if (p == NULL
5054               || (h->root.type != bfd_link_hash_defined
5055                   && h->root.type != bfd_link_hash_defweak))
5056             continue;
5057
5058           amt = p - h->root.root.string;
5059           shortname = (char *) bfd_malloc (amt + 1);
5060           if (!shortname)
5061             goto error_free_vers;
5062           memcpy (shortname, h->root.root.string, amt);
5063           shortname[amt] = '\0';
5064
5065           hi = (struct elf_link_hash_entry *)
5066                bfd_link_hash_lookup (&htab->root, shortname,
5067                                      FALSE, FALSE, FALSE);
5068           if (hi != NULL
5069               && hi->root.type == h->root.type
5070               && hi->root.u.def.value == h->root.u.def.value
5071               && hi->root.u.def.section == h->root.u.def.section)
5072             {
5073               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
5074               hi->root.type = bfd_link_hash_indirect;
5075               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
5076               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
5077               sym_hash = elf_sym_hashes (abfd);
5078               if (sym_hash)
5079                 for (symidx = 0; symidx < extsymcount; ++symidx)
5080                   if (sym_hash[symidx] == hi)
5081                     {
5082                       sym_hash[symidx] = h;
5083                       break;
5084                     }
5085             }
5086           free (shortname);
5087         }
5088       free (nondeflt_vers);
5089       nondeflt_vers = NULL;
5090     }
5091
5092   /* Now set the weakdefs field correctly for all the weak defined
5093      symbols we found.  The only way to do this is to search all the
5094      symbols.  Since we only need the information for non functions in
5095      dynamic objects, that's the only time we actually put anything on
5096      the list WEAKS.  We need this information so that if a regular
5097      object refers to a symbol defined weakly in a dynamic object, the
5098      real symbol in the dynamic object is also put in the dynamic
5099      symbols; we also must arrange for both symbols to point to the
5100      same memory location.  We could handle the general case of symbol
5101      aliasing, but a general symbol alias can only be generated in
5102      assembler code, handling it correctly would be very time
5103      consuming, and other ELF linkers don't handle general aliasing
5104      either.  */
5105   if (weaks != NULL)
5106     {
5107       struct elf_link_hash_entry **hpp;
5108       struct elf_link_hash_entry **hppend;
5109       struct elf_link_hash_entry **sorted_sym_hash;
5110       struct elf_link_hash_entry *h;
5111       size_t sym_count;
5112
5113       /* Since we have to search the whole symbol list for each weak
5114          defined symbol, search time for N weak defined symbols will be
5115          O(N^2). Binary search will cut it down to O(NlogN).  */
5116       amt = extsymcount;
5117       amt *= sizeof (struct elf_link_hash_entry *);
5118       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
5119       if (sorted_sym_hash == NULL)
5120         goto error_return;
5121       sym_hash = sorted_sym_hash;
5122       hpp = elf_sym_hashes (abfd);
5123       hppend = hpp + extsymcount;
5124       sym_count = 0;
5125       for (; hpp < hppend; hpp++)
5126         {
5127           h = *hpp;
5128           if (h != NULL
5129               && h->root.type == bfd_link_hash_defined
5130               && !bed->is_function_type (h->type))
5131             {
5132               *sym_hash = h;
5133               sym_hash++;
5134               sym_count++;
5135             }
5136         }
5137
5138       qsort (sorted_sym_hash, sym_count,
5139              sizeof (struct elf_link_hash_entry *),
5140              elf_sort_symbol);
5141
5142       while (weaks != NULL)
5143         {
5144           struct elf_link_hash_entry *hlook;
5145           asection *slook;
5146           bfd_vma vlook;
5147           size_t i, j, idx = 0;
5148
5149           hlook = weaks;
5150           weaks = hlook->u.weakdef;
5151           hlook->u.weakdef = NULL;
5152
5153           BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
5154                       || hlook->root.type == bfd_link_hash_defweak
5155                       || hlook->root.type == bfd_link_hash_common
5156                       || hlook->root.type == bfd_link_hash_indirect);
5157           slook = hlook->root.u.def.section;
5158           vlook = hlook->root.u.def.value;
5159
5160           i = 0;
5161           j = sym_count;
5162           while (i != j)
5163             {
5164               bfd_signed_vma vdiff;
5165               idx = (i + j) / 2;
5166               h = sorted_sym_hash[idx];
5167               vdiff = vlook - h->root.u.def.value;
5168               if (vdiff < 0)
5169                 j = idx;
5170               else if (vdiff > 0)
5171                 i = idx + 1;
5172               else
5173                 {
5174                   int sdiff = slook->id - h->root.u.def.section->id;
5175                   if (sdiff < 0)
5176                     j = idx;
5177                   else if (sdiff > 0)
5178                     i = idx + 1;
5179                   else
5180                     break;
5181                 }
5182             }
5183
5184           /* We didn't find a value/section match.  */
5185           if (i == j)
5186             continue;
5187
5188           /* With multiple aliases, or when the weak symbol is already
5189              strongly defined, we have multiple matching symbols and
5190              the binary search above may land on any of them.  Step
5191              one past the matching symbol(s).  */
5192           while (++idx != j)
5193             {
5194               h = sorted_sym_hash[idx];
5195               if (h->root.u.def.section != slook
5196                   || h->root.u.def.value != vlook)
5197                 break;
5198             }
5199
5200           /* Now look back over the aliases.  Since we sorted by size
5201              as well as value and section, we'll choose the one with
5202              the largest size.  */
5203           while (idx-- != i)
5204             {
5205               h = sorted_sym_hash[idx];
5206
5207               /* Stop if value or section doesn't match.  */
5208               if (h->root.u.def.section != slook
5209                   || h->root.u.def.value != vlook)
5210                 break;
5211               else if (h != hlook)
5212                 {
5213                   hlook->u.weakdef = h;
5214
5215                   /* If the weak definition is in the list of dynamic
5216                      symbols, make sure the real definition is put
5217                      there as well.  */
5218                   if (hlook->dynindx != -1 && h->dynindx == -1)
5219                     {
5220                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
5221                         {
5222                         err_free_sym_hash:
5223                           free (sorted_sym_hash);
5224                           goto error_return;
5225                         }
5226                     }
5227
5228                   /* If the real definition is in the list of dynamic
5229                      symbols, make sure the weak definition is put
5230                      there as well.  If we don't do this, then the
5231                      dynamic loader might not merge the entries for the
5232                      real definition and the weak definition.  */
5233                   if (h->dynindx != -1 && hlook->dynindx == -1)
5234                     {
5235                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
5236                         goto err_free_sym_hash;
5237                     }
5238                   break;
5239                 }
5240             }
5241         }
5242
5243       free (sorted_sym_hash);
5244     }
5245
5246   if (bed->check_directives
5247       && !(*bed->check_directives) (abfd, info))
5248     return FALSE;
5249
5250   /* If this is a non-traditional link, try to optimize the handling
5251      of the .stab/.stabstr sections.  */
5252   if (! dynamic
5253       && ! info->traditional_format
5254       && is_elf_hash_table (htab)
5255       && (info->strip != strip_all && info->strip != strip_debugger))
5256     {
5257       asection *stabstr;
5258
5259       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
5260       if (stabstr != NULL)
5261         {
5262           bfd_size_type string_offset = 0;
5263           asection *stab;
5264
5265           for (stab = abfd->sections; stab; stab = stab->next)
5266             if (CONST_STRNEQ (stab->name, ".stab")
5267                 && (!stab->name[5] ||
5268                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
5269                 && (stab->flags & SEC_MERGE) == 0
5270                 && !bfd_is_abs_section (stab->output_section))
5271               {
5272                 struct bfd_elf_section_data *secdata;
5273
5274                 secdata = elf_section_data (stab);
5275                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
5276                                                stabstr, &secdata->sec_info,
5277                                                &string_offset))
5278                   goto error_return;
5279                 if (secdata->sec_info)
5280                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
5281             }
5282         }
5283     }
5284
5285   if (is_elf_hash_table (htab) && add_needed)
5286     {
5287       /* Add this bfd to the loaded list.  */
5288       struct elf_link_loaded_list *n;
5289
5290       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
5291       if (n == NULL)
5292         goto error_return;
5293       n->abfd = abfd;
5294       n->next = htab->loaded;
5295       htab->loaded = n;
5296     }
5297
5298   return TRUE;
5299
5300  error_free_vers:
5301   if (old_tab != NULL)
5302     free (old_tab);
5303   if (old_strtab != NULL)
5304     free (old_strtab);
5305   if (nondeflt_vers != NULL)
5306     free (nondeflt_vers);
5307   if (extversym != NULL)
5308     free (extversym);
5309  error_free_sym:
5310   if (isymbuf != NULL)
5311     free (isymbuf);
5312  error_return:
5313   return FALSE;
5314 }
5315
5316 /* Return the linker hash table entry of a symbol that might be
5317    satisfied by an archive symbol.  Return -1 on error.  */
5318
5319 struct elf_link_hash_entry *
5320 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5321                                 struct bfd_link_info *info,
5322                                 const char *name)
5323 {
5324   struct elf_link_hash_entry *h;
5325   char *p, *copy;
5326   size_t len, first;
5327
5328   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5329   if (h != NULL)
5330     return h;
5331
5332   /* If this is a default version (the name contains @@), look up the
5333      symbol again with only one `@' as well as without the version.
5334      The effect is that references to the symbol with and without the
5335      version will be matched by the default symbol in the archive.  */
5336
5337   p = strchr (name, ELF_VER_CHR);
5338   if (p == NULL || p[1] != ELF_VER_CHR)
5339     return h;
5340
5341   /* First check with only one `@'.  */
5342   len = strlen (name);
5343   copy = (char *) bfd_alloc (abfd, len);
5344   if (copy == NULL)
5345     return (struct elf_link_hash_entry *) 0 - 1;
5346
5347   first = p - name + 1;
5348   memcpy (copy, name, first);
5349   memcpy (copy + first, name + first + 1, len - first);
5350
5351   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5352   if (h == NULL)
5353     {
5354       /* We also need to check references to the symbol without the
5355          version.  */
5356       copy[first - 1] = '\0';
5357       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5358                                 FALSE, FALSE, TRUE);
5359     }
5360
5361   bfd_release (abfd, copy);
5362   return h;
5363 }
5364
5365 /* Add symbols from an ELF archive file to the linker hash table.  We
5366    don't use _bfd_generic_link_add_archive_symbols because we need to
5367    handle versioned symbols.
5368
5369    Fortunately, ELF archive handling is simpler than that done by
5370    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5371    oddities.  In ELF, if we find a symbol in the archive map, and the
5372    symbol is currently undefined, we know that we must pull in that
5373    object file.
5374
5375    Unfortunately, we do have to make multiple passes over the symbol
5376    table until nothing further is resolved.  */
5377
5378 static bfd_boolean
5379 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5380 {
5381   symindex c;
5382   unsigned char *included = NULL;
5383   carsym *symdefs;
5384   bfd_boolean loop;
5385   bfd_size_type amt;
5386   const struct elf_backend_data *bed;
5387   struct elf_link_hash_entry * (*archive_symbol_lookup)
5388     (bfd *, struct bfd_link_info *, const char *);
5389
5390   if (! bfd_has_map (abfd))
5391     {
5392       /* An empty archive is a special case.  */
5393       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5394         return TRUE;
5395       bfd_set_error (bfd_error_no_armap);
5396       return FALSE;
5397     }
5398
5399   /* Keep track of all symbols we know to be already defined, and all
5400      files we know to be already included.  This is to speed up the
5401      second and subsequent passes.  */
5402   c = bfd_ardata (abfd)->symdef_count;
5403   if (c == 0)
5404     return TRUE;
5405   amt = c;
5406   amt *= sizeof (*included);
5407   included = (unsigned char *) bfd_zmalloc (amt);
5408   if (included == NULL)
5409     return FALSE;
5410
5411   symdefs = bfd_ardata (abfd)->symdefs;
5412   bed = get_elf_backend_data (abfd);
5413   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5414
5415   do
5416     {
5417       file_ptr last;
5418       symindex i;
5419       carsym *symdef;
5420       carsym *symdefend;
5421
5422       loop = FALSE;
5423       last = -1;
5424
5425       symdef = symdefs;
5426       symdefend = symdef + c;
5427       for (i = 0; symdef < symdefend; symdef++, i++)
5428         {
5429           struct elf_link_hash_entry *h;
5430           bfd *element;
5431           struct bfd_link_hash_entry *undefs_tail;
5432           symindex mark;
5433
5434           if (included[i])
5435             continue;
5436           if (symdef->file_offset == last)
5437             {
5438               included[i] = TRUE;
5439               continue;
5440             }
5441
5442           h = archive_symbol_lookup (abfd, info, symdef->name);
5443           if (h == (struct elf_link_hash_entry *) 0 - 1)
5444             goto error_return;
5445
5446           if (h == NULL)
5447             continue;
5448
5449           if (h->root.type == bfd_link_hash_common)
5450             {
5451               /* We currently have a common symbol.  The archive map contains
5452                  a reference to this symbol, so we may want to include it.  We
5453                  only want to include it however, if this archive element
5454                  contains a definition of the symbol, not just another common
5455                  declaration of it.
5456
5457                  Unfortunately some archivers (including GNU ar) will put
5458                  declarations of common symbols into their archive maps, as
5459                  well as real definitions, so we cannot just go by the archive
5460                  map alone.  Instead we must read in the element's symbol
5461                  table and check that to see what kind of symbol definition
5462                  this is.  */
5463               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5464                 continue;
5465             }
5466           else if (h->root.type != bfd_link_hash_undefined)
5467             {
5468               if (h->root.type != bfd_link_hash_undefweak)
5469                 /* Symbol must be defined.  Don't check it again.  */
5470                 included[i] = TRUE;
5471               continue;
5472             }
5473
5474           /* We need to include this archive member.  */
5475           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5476           if (element == NULL)
5477             goto error_return;
5478
5479           if (! bfd_check_format (element, bfd_object))
5480             goto error_return;
5481
5482           undefs_tail = info->hash->undefs_tail;
5483
5484           if (!(*info->callbacks
5485                 ->add_archive_element) (info, element, symdef->name, &element))
5486             continue;
5487           if (!bfd_link_add_symbols (element, info))
5488             goto error_return;
5489
5490           /* If there are any new undefined symbols, we need to make
5491              another pass through the archive in order to see whether
5492              they can be defined.  FIXME: This isn't perfect, because
5493              common symbols wind up on undefs_tail and because an
5494              undefined symbol which is defined later on in this pass
5495              does not require another pass.  This isn't a bug, but it
5496              does make the code less efficient than it could be.  */
5497           if (undefs_tail != info->hash->undefs_tail)
5498             loop = TRUE;
5499
5500           /* Look backward to mark all symbols from this object file
5501              which we have already seen in this pass.  */
5502           mark = i;
5503           do
5504             {
5505               included[mark] = TRUE;
5506               if (mark == 0)
5507                 break;
5508               --mark;
5509             }
5510           while (symdefs[mark].file_offset == symdef->file_offset);
5511
5512           /* We mark subsequent symbols from this object file as we go
5513              on through the loop.  */
5514           last = symdef->file_offset;
5515         }
5516     }
5517   while (loop);
5518
5519   free (included);
5520
5521   return TRUE;
5522
5523  error_return:
5524   if (included != NULL)
5525     free (included);
5526   return FALSE;
5527 }
5528
5529 /* Given an ELF BFD, add symbols to the global hash table as
5530    appropriate.  */
5531
5532 bfd_boolean
5533 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5534 {
5535   switch (bfd_get_format (abfd))
5536     {
5537     case bfd_object:
5538       return elf_link_add_object_symbols (abfd, info);
5539     case bfd_archive:
5540       return elf_link_add_archive_symbols (abfd, info);
5541     default:
5542       bfd_set_error (bfd_error_wrong_format);
5543       return FALSE;
5544     }
5545 }
5546 \f
5547 struct hash_codes_info
5548 {
5549   unsigned long *hashcodes;
5550   bfd_boolean error;
5551 };
5552
5553 /* This function will be called though elf_link_hash_traverse to store
5554    all hash value of the exported symbols in an array.  */
5555
5556 static bfd_boolean
5557 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5558 {
5559   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5560   const char *name;
5561   unsigned long ha;
5562   char *alc = NULL;
5563
5564   /* Ignore indirect symbols.  These are added by the versioning code.  */
5565   if (h->dynindx == -1)
5566     return TRUE;
5567
5568   name = h->root.root.string;
5569   if (h->versioned >= versioned)
5570     {
5571       char *p = strchr (name, ELF_VER_CHR);
5572       if (p != NULL)
5573         {
5574           alc = (char *) bfd_malloc (p - name + 1);
5575           if (alc == NULL)
5576             {
5577               inf->error = TRUE;
5578               return FALSE;
5579             }
5580           memcpy (alc, name, p - name);
5581           alc[p - name] = '\0';
5582           name = alc;
5583         }
5584     }
5585
5586   /* Compute the hash value.  */
5587   ha = bfd_elf_hash (name);
5588
5589   /* Store the found hash value in the array given as the argument.  */
5590   *(inf->hashcodes)++ = ha;
5591
5592   /* And store it in the struct so that we can put it in the hash table
5593      later.  */
5594   h->u.elf_hash_value = ha;
5595
5596   if (alc != NULL)
5597     free (alc);
5598
5599   return TRUE;
5600 }
5601
5602 struct collect_gnu_hash_codes
5603 {
5604   bfd *output_bfd;
5605   const struct elf_backend_data *bed;
5606   unsigned long int nsyms;
5607   unsigned long int maskbits;
5608   unsigned long int *hashcodes;
5609   unsigned long int *hashval;
5610   unsigned long int *indx;
5611   unsigned long int *counts;
5612   bfd_vma *bitmask;
5613   bfd_byte *contents;
5614   long int min_dynindx;
5615   unsigned long int bucketcount;
5616   unsigned long int symindx;
5617   long int local_indx;
5618   long int shift1, shift2;
5619   unsigned long int mask;
5620   bfd_boolean error;
5621 };
5622
5623 /* This function will be called though elf_link_hash_traverse to store
5624    all hash value of the exported symbols in an array.  */
5625
5626 static bfd_boolean
5627 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5628 {
5629   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5630   const char *name;
5631   unsigned long ha;
5632   char *alc = NULL;
5633
5634   /* Ignore indirect symbols.  These are added by the versioning code.  */
5635   if (h->dynindx == -1)
5636     return TRUE;
5637
5638   /* Ignore also local symbols and undefined symbols.  */
5639   if (! (*s->bed->elf_hash_symbol) (h))
5640     return TRUE;
5641
5642   name = h->root.root.string;
5643   if (h->versioned >= versioned)
5644     {
5645       char *p = strchr (name, ELF_VER_CHR);
5646       if (p != NULL)
5647         {
5648           alc = (char *) bfd_malloc (p - name + 1);
5649           if (alc == NULL)
5650             {
5651               s->error = TRUE;
5652               return FALSE;
5653             }
5654           memcpy (alc, name, p - name);
5655           alc[p - name] = '\0';
5656           name = alc;
5657         }
5658     }
5659
5660   /* Compute the hash value.  */
5661   ha = bfd_elf_gnu_hash (name);
5662
5663   /* Store the found hash value in the array for compute_bucket_count,
5664      and also for .dynsym reordering purposes.  */
5665   s->hashcodes[s->nsyms] = ha;
5666   s->hashval[h->dynindx] = ha;
5667   ++s->nsyms;
5668   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5669     s->min_dynindx = h->dynindx;
5670
5671   if (alc != NULL)
5672     free (alc);
5673
5674   return TRUE;
5675 }
5676
5677 /* This function will be called though elf_link_hash_traverse to do
5678    final dynaminc symbol renumbering.  */
5679
5680 static bfd_boolean
5681 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5682 {
5683   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5684   unsigned long int bucket;
5685   unsigned long int val;
5686
5687   /* Ignore indirect symbols.  */
5688   if (h->dynindx == -1)
5689     return TRUE;
5690
5691   /* Ignore also local symbols and undefined symbols.  */
5692   if (! (*s->bed->elf_hash_symbol) (h))
5693     {
5694       if (h->dynindx >= s->min_dynindx)
5695         h->dynindx = s->local_indx++;
5696       return TRUE;
5697     }
5698
5699   bucket = s->hashval[h->dynindx] % s->bucketcount;
5700   val = (s->hashval[h->dynindx] >> s->shift1)
5701         & ((s->maskbits >> s->shift1) - 1);
5702   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5703   s->bitmask[val]
5704     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5705   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5706   if (s->counts[bucket] == 1)
5707     /* Last element terminates the chain.  */
5708     val |= 1;
5709   bfd_put_32 (s->output_bfd, val,
5710               s->contents + (s->indx[bucket] - s->symindx) * 4);
5711   --s->counts[bucket];
5712   h->dynindx = s->indx[bucket]++;
5713   return TRUE;
5714 }
5715
5716 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5717
5718 bfd_boolean
5719 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5720 {
5721   return !(h->forced_local
5722            || h->root.type == bfd_link_hash_undefined
5723            || h->root.type == bfd_link_hash_undefweak
5724            || ((h->root.type == bfd_link_hash_defined
5725                 || h->root.type == bfd_link_hash_defweak)
5726                && h->root.u.def.section->output_section == NULL));
5727 }
5728
5729 /* Array used to determine the number of hash table buckets to use
5730    based on the number of symbols there are.  If there are fewer than
5731    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5732    fewer than 37 we use 17 buckets, and so forth.  We never use more
5733    than 32771 buckets.  */
5734
5735 static const size_t elf_buckets[] =
5736 {
5737   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5738   16411, 32771, 0
5739 };
5740
5741 /* Compute bucket count for hashing table.  We do not use a static set
5742    of possible tables sizes anymore.  Instead we determine for all
5743    possible reasonable sizes of the table the outcome (i.e., the
5744    number of collisions etc) and choose the best solution.  The
5745    weighting functions are not too simple to allow the table to grow
5746    without bounds.  Instead one of the weighting factors is the size.
5747    Therefore the result is always a good payoff between few collisions
5748    (= short chain lengths) and table size.  */
5749 static size_t
5750 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5751                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5752                       unsigned long int nsyms,
5753                       int gnu_hash)
5754 {
5755   size_t best_size = 0;
5756   unsigned long int i;
5757
5758   /* We have a problem here.  The following code to optimize the table
5759      size requires an integer type with more the 32 bits.  If
5760      BFD_HOST_U_64_BIT is set we know about such a type.  */
5761 #ifdef BFD_HOST_U_64_BIT
5762   if (info->optimize)
5763     {
5764       size_t minsize;
5765       size_t maxsize;
5766       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5767       bfd *dynobj = elf_hash_table (info)->dynobj;
5768       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5769       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5770       unsigned long int *counts;
5771       bfd_size_type amt;
5772       unsigned int no_improvement_count = 0;
5773
5774       /* Possible optimization parameters: if we have NSYMS symbols we say
5775          that the hashing table must at least have NSYMS/4 and at most
5776          2*NSYMS buckets.  */
5777       minsize = nsyms / 4;
5778       if (minsize == 0)
5779         minsize = 1;
5780       best_size = maxsize = nsyms * 2;
5781       if (gnu_hash)
5782         {
5783           if (minsize < 2)
5784             minsize = 2;
5785           if ((best_size & 31) == 0)
5786             ++best_size;
5787         }
5788
5789       /* Create array where we count the collisions in.  We must use bfd_malloc
5790          since the size could be large.  */
5791       amt = maxsize;
5792       amt *= sizeof (unsigned long int);
5793       counts = (unsigned long int *) bfd_malloc (amt);
5794       if (counts == NULL)
5795         return 0;
5796
5797       /* Compute the "optimal" size for the hash table.  The criteria is a
5798          minimal chain length.  The minor criteria is (of course) the size
5799          of the table.  */
5800       for (i = minsize; i < maxsize; ++i)
5801         {
5802           /* Walk through the array of hashcodes and count the collisions.  */
5803           BFD_HOST_U_64_BIT max;
5804           unsigned long int j;
5805           unsigned long int fact;
5806
5807           if (gnu_hash && (i & 31) == 0)
5808             continue;
5809
5810           memset (counts, '\0', i * sizeof (unsigned long int));
5811
5812           /* Determine how often each hash bucket is used.  */
5813           for (j = 0; j < nsyms; ++j)
5814             ++counts[hashcodes[j] % i];
5815
5816           /* For the weight function we need some information about the
5817              pagesize on the target.  This is information need not be 100%
5818              accurate.  Since this information is not available (so far) we
5819              define it here to a reasonable default value.  If it is crucial
5820              to have a better value some day simply define this value.  */
5821 # ifndef BFD_TARGET_PAGESIZE
5822 #  define BFD_TARGET_PAGESIZE   (4096)
5823 # endif
5824
5825           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5826              and the chains.  */
5827           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5828
5829 # if 1
5830           /* Variant 1: optimize for short chains.  We add the squares
5831              of all the chain lengths (which favors many small chain
5832              over a few long chains).  */
5833           for (j = 0; j < i; ++j)
5834             max += counts[j] * counts[j];
5835
5836           /* This adds penalties for the overall size of the table.  */
5837           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5838           max *= fact * fact;
5839 # else
5840           /* Variant 2: Optimize a lot more for small table.  Here we
5841              also add squares of the size but we also add penalties for
5842              empty slots (the +1 term).  */
5843           for (j = 0; j < i; ++j)
5844             max += (1 + counts[j]) * (1 + counts[j]);
5845
5846           /* The overall size of the table is considered, but not as
5847              strong as in variant 1, where it is squared.  */
5848           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5849           max *= fact;
5850 # endif
5851
5852           /* Compare with current best results.  */
5853           if (max < best_chlen)
5854             {
5855               best_chlen = max;
5856               best_size = i;
5857               no_improvement_count = 0;
5858             }
5859           /* PR 11843: Avoid futile long searches for the best bucket size
5860              when there are a large number of symbols.  */
5861           else if (++no_improvement_count == 100)
5862             break;
5863         }
5864
5865       free (counts);
5866     }
5867   else
5868 #endif /* defined (BFD_HOST_U_64_BIT) */
5869     {
5870       /* This is the fallback solution if no 64bit type is available or if we
5871          are not supposed to spend much time on optimizations.  We select the
5872          bucket count using a fixed set of numbers.  */
5873       for (i = 0; elf_buckets[i] != 0; i++)
5874         {
5875           best_size = elf_buckets[i];
5876           if (nsyms < elf_buckets[i + 1])
5877             break;
5878         }
5879       if (gnu_hash && best_size < 2)
5880         best_size = 2;
5881     }
5882
5883   return best_size;
5884 }
5885
5886 /* Size any SHT_GROUP section for ld -r.  */
5887
5888 bfd_boolean
5889 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5890 {
5891   bfd *ibfd;
5892   asection *s;
5893
5894   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5895     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5896         && (s = ibfd->sections) != NULL
5897         && s->sec_info_type != SEC_INFO_TYPE_JUST_SYMS
5898         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5899       return FALSE;
5900   return TRUE;
5901 }
5902
5903 /* Set a default stack segment size.  The value in INFO wins.  If it
5904    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
5905    undefined it is initialized.  */
5906
5907 bfd_boolean
5908 bfd_elf_stack_segment_size (bfd *output_bfd,
5909                             struct bfd_link_info *info,
5910                             const char *legacy_symbol,
5911                             bfd_vma default_size)
5912 {
5913   struct elf_link_hash_entry *h = NULL;
5914
5915   /* Look for legacy symbol.  */
5916   if (legacy_symbol)
5917     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
5918                               FALSE, FALSE, FALSE);
5919   if (h && (h->root.type == bfd_link_hash_defined
5920             || h->root.type == bfd_link_hash_defweak)
5921       && h->def_regular
5922       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
5923     {
5924       /* The symbol has no type if specified on the command line.  */
5925       h->type = STT_OBJECT;
5926       if (info->stacksize)
5927         /* xgettext:c-format */
5928         _bfd_error_handler (_("%B: stack size specified and %s set"),
5929                             output_bfd, legacy_symbol);
5930       else if (h->root.u.def.section != bfd_abs_section_ptr)
5931         /* xgettext:c-format */
5932         _bfd_error_handler (_("%B: %s not absolute"),
5933                             output_bfd, legacy_symbol);
5934       else
5935         info->stacksize = h->root.u.def.value;
5936     }
5937
5938   if (!info->stacksize)
5939     /* If the user didn't set a size, or explicitly inhibit the
5940        size, set it now.  */
5941     info->stacksize = default_size;
5942
5943   /* Provide the legacy symbol, if it is referenced.  */
5944   if (h && (h->root.type == bfd_link_hash_undefined
5945             || h->root.type == bfd_link_hash_undefweak))
5946     {
5947       struct bfd_link_hash_entry *bh = NULL;
5948
5949       if (!(_bfd_generic_link_add_one_symbol
5950             (info, output_bfd, legacy_symbol,
5951              BSF_GLOBAL, bfd_abs_section_ptr,
5952              info->stacksize >= 0 ? info->stacksize : 0,
5953              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
5954         return FALSE;
5955
5956       h = (struct elf_link_hash_entry *) bh;
5957       h->def_regular = 1;
5958       h->type = STT_OBJECT;
5959     }
5960
5961   return TRUE;
5962 }
5963
5964 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
5965
5966 struct elf_gc_sweep_symbol_info
5967 {
5968   struct bfd_link_info *info;
5969   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
5970                        bfd_boolean);
5971 };
5972
5973 static bfd_boolean
5974 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
5975 {
5976   if (!h->mark
5977       && (((h->root.type == bfd_link_hash_defined
5978             || h->root.type == bfd_link_hash_defweak)
5979            && !((h->def_regular || ELF_COMMON_DEF_P (h))
5980                 && h->root.u.def.section->gc_mark))
5981           || h->root.type == bfd_link_hash_undefined
5982           || h->root.type == bfd_link_hash_undefweak))
5983     {
5984       struct elf_gc_sweep_symbol_info *inf;
5985
5986       inf = (struct elf_gc_sweep_symbol_info *) data;
5987       (*inf->hide_symbol) (inf->info, h, TRUE);
5988       h->def_regular = 0;
5989       h->ref_regular = 0;
5990       h->ref_regular_nonweak = 0;
5991     }
5992
5993   return TRUE;
5994 }
5995
5996 /* Set up the sizes and contents of the ELF dynamic sections.  This is
5997    called by the ELF linker emulation before_allocation routine.  We
5998    must set the sizes of the sections before the linker sets the
5999    addresses of the various sections.  */
6000
6001 bfd_boolean
6002 bfd_elf_size_dynamic_sections (bfd *output_bfd,
6003                                const char *soname,
6004                                const char *rpath,
6005                                const char *filter_shlib,
6006                                const char *audit,
6007                                const char *depaudit,
6008                                const char * const *auxiliary_filters,
6009                                struct bfd_link_info *info,
6010                                asection **sinterpptr)
6011 {
6012   bfd *dynobj;
6013   const struct elf_backend_data *bed;
6014
6015   *sinterpptr = NULL;
6016
6017   if (!is_elf_hash_table (info->hash))
6018     return TRUE;
6019
6020   dynobj = elf_hash_table (info)->dynobj;
6021
6022   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6023     {
6024       struct bfd_elf_version_tree *verdefs;
6025       struct elf_info_failed asvinfo;
6026       struct bfd_elf_version_tree *t;
6027       struct bfd_elf_version_expr *d;
6028       asection *s;
6029       size_t soname_indx;
6030
6031       /* If we are supposed to export all symbols into the dynamic symbol
6032          table (this is not the normal case), then do so.  */
6033       if (info->export_dynamic
6034           || (bfd_link_executable (info) && info->dynamic))
6035         {
6036           struct elf_info_failed eif;
6037
6038           eif.info = info;
6039           eif.failed = FALSE;
6040           elf_link_hash_traverse (elf_hash_table (info),
6041                                   _bfd_elf_export_symbol,
6042                                   &eif);
6043           if (eif.failed)
6044             return FALSE;
6045         }
6046
6047       if (soname != NULL)
6048         {
6049           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6050                                              soname, TRUE);
6051           if (soname_indx == (size_t) -1
6052               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
6053             return FALSE;
6054         }
6055       else
6056         soname_indx = (size_t) -1;
6057
6058       /* Make all global versions with definition.  */
6059       for (t = info->version_info; t != NULL; t = t->next)
6060         for (d = t->globals.list; d != NULL; d = d->next)
6061           if (!d->symver && d->literal)
6062             {
6063               const char *verstr, *name;
6064               size_t namelen, verlen, newlen;
6065               char *newname, *p, leading_char;
6066               struct elf_link_hash_entry *newh;
6067
6068               leading_char = bfd_get_symbol_leading_char (output_bfd);
6069               name = d->pattern;
6070               namelen = strlen (name) + (leading_char != '\0');
6071               verstr = t->name;
6072               verlen = strlen (verstr);
6073               newlen = namelen + verlen + 3;
6074
6075               newname = (char *) bfd_malloc (newlen);
6076               if (newname == NULL)
6077                 return FALSE;
6078               newname[0] = leading_char;
6079               memcpy (newname + (leading_char != '\0'), name, namelen);
6080
6081               /* Check the hidden versioned definition.  */
6082               p = newname + namelen;
6083               *p++ = ELF_VER_CHR;
6084               memcpy (p, verstr, verlen + 1);
6085               newh = elf_link_hash_lookup (elf_hash_table (info),
6086                                            newname, FALSE, FALSE,
6087                                            FALSE);
6088               if (newh == NULL
6089                   || (newh->root.type != bfd_link_hash_defined
6090                       && newh->root.type != bfd_link_hash_defweak))
6091                 {
6092                   /* Check the default versioned definition.  */
6093                   *p++ = ELF_VER_CHR;
6094                   memcpy (p, verstr, verlen + 1);
6095                   newh = elf_link_hash_lookup (elf_hash_table (info),
6096                                                newname, FALSE, FALSE,
6097                                                FALSE);
6098                 }
6099               free (newname);
6100
6101               /* Mark this version if there is a definition and it is
6102                  not defined in a shared object.  */
6103               if (newh != NULL
6104                   && !newh->def_dynamic
6105                   && (newh->root.type == bfd_link_hash_defined
6106                       || newh->root.type == bfd_link_hash_defweak))
6107                 d->symver = 1;
6108             }
6109
6110       /* Attach all the symbols to their version information.  */
6111       asvinfo.info = info;
6112       asvinfo.failed = FALSE;
6113
6114       elf_link_hash_traverse (elf_hash_table (info),
6115                               _bfd_elf_link_assign_sym_version,
6116                               &asvinfo);
6117       if (asvinfo.failed)
6118         return FALSE;
6119
6120       if (!info->allow_undefined_version)
6121         {
6122           /* Check if all global versions have a definition.  */
6123           bfd_boolean all_defined = TRUE;
6124           for (t = info->version_info; t != NULL; t = t->next)
6125             for (d = t->globals.list; d != NULL; d = d->next)
6126               if (d->literal && !d->symver && !d->script)
6127                 {
6128                   _bfd_error_handler
6129                     (_("%s: undefined version: %s"),
6130                      d->pattern, t->name);
6131                   all_defined = FALSE;
6132                 }
6133
6134           if (!all_defined)
6135             {
6136               bfd_set_error (bfd_error_bad_value);
6137               return FALSE;
6138             }
6139         }
6140
6141       /* Set up the version definition section.  */
6142       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6143       BFD_ASSERT (s != NULL);
6144
6145       /* We may have created additional version definitions if we are
6146          just linking a regular application.  */
6147       verdefs = info->version_info;
6148
6149       /* Skip anonymous version tag.  */
6150       if (verdefs != NULL && verdefs->vernum == 0)
6151         verdefs = verdefs->next;
6152
6153       if (verdefs == NULL && !info->create_default_symver)
6154         s->flags |= SEC_EXCLUDE;
6155       else
6156         {
6157           unsigned int cdefs;
6158           bfd_size_type size;
6159           bfd_byte *p;
6160           Elf_Internal_Verdef def;
6161           Elf_Internal_Verdaux defaux;
6162           struct bfd_link_hash_entry *bh;
6163           struct elf_link_hash_entry *h;
6164           const char *name;
6165
6166           cdefs = 0;
6167           size = 0;
6168
6169           /* Make space for the base version.  */
6170           size += sizeof (Elf_External_Verdef);
6171           size += sizeof (Elf_External_Verdaux);
6172           ++cdefs;
6173
6174           /* Make space for the default version.  */
6175           if (info->create_default_symver)
6176             {
6177               size += sizeof (Elf_External_Verdef);
6178               ++cdefs;
6179             }
6180
6181           for (t = verdefs; t != NULL; t = t->next)
6182             {
6183               struct bfd_elf_version_deps *n;
6184
6185               /* Don't emit base version twice.  */
6186               if (t->vernum == 0)
6187                 continue;
6188
6189               size += sizeof (Elf_External_Verdef);
6190               size += sizeof (Elf_External_Verdaux);
6191               ++cdefs;
6192
6193               for (n = t->deps; n != NULL; n = n->next)
6194                 size += sizeof (Elf_External_Verdaux);
6195             }
6196
6197           s->size = size;
6198           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6199           if (s->contents == NULL && s->size != 0)
6200             return FALSE;
6201
6202           /* Fill in the version definition section.  */
6203
6204           p = s->contents;
6205
6206           def.vd_version = VER_DEF_CURRENT;
6207           def.vd_flags = VER_FLG_BASE;
6208           def.vd_ndx = 1;
6209           def.vd_cnt = 1;
6210           if (info->create_default_symver)
6211             {
6212               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6213               def.vd_next = sizeof (Elf_External_Verdef);
6214             }
6215           else
6216             {
6217               def.vd_aux = sizeof (Elf_External_Verdef);
6218               def.vd_next = (sizeof (Elf_External_Verdef)
6219                              + sizeof (Elf_External_Verdaux));
6220             }
6221
6222           if (soname_indx != (size_t) -1)
6223             {
6224               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6225                                       soname_indx);
6226               def.vd_hash = bfd_elf_hash (soname);
6227               defaux.vda_name = soname_indx;
6228               name = soname;
6229             }
6230           else
6231             {
6232               size_t indx;
6233
6234               name = lbasename (output_bfd->filename);
6235               def.vd_hash = bfd_elf_hash (name);
6236               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6237                                           name, FALSE);
6238               if (indx == (size_t) -1)
6239                 return FALSE;
6240               defaux.vda_name = indx;
6241             }
6242           defaux.vda_next = 0;
6243
6244           _bfd_elf_swap_verdef_out (output_bfd, &def,
6245                                     (Elf_External_Verdef *) p);
6246           p += sizeof (Elf_External_Verdef);
6247           if (info->create_default_symver)
6248             {
6249               /* Add a symbol representing this version.  */
6250               bh = NULL;
6251               if (! (_bfd_generic_link_add_one_symbol
6252                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6253                       0, NULL, FALSE,
6254                       get_elf_backend_data (dynobj)->collect, &bh)))
6255                 return FALSE;
6256               h = (struct elf_link_hash_entry *) bh;
6257               h->non_elf = 0;
6258               h->def_regular = 1;
6259               h->type = STT_OBJECT;
6260               h->verinfo.vertree = NULL;
6261
6262               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6263                 return FALSE;
6264
6265               /* Create a duplicate of the base version with the same
6266                  aux block, but different flags.  */
6267               def.vd_flags = 0;
6268               def.vd_ndx = 2;
6269               def.vd_aux = sizeof (Elf_External_Verdef);
6270               if (verdefs)
6271                 def.vd_next = (sizeof (Elf_External_Verdef)
6272                                + sizeof (Elf_External_Verdaux));
6273               else
6274                 def.vd_next = 0;
6275               _bfd_elf_swap_verdef_out (output_bfd, &def,
6276                                         (Elf_External_Verdef *) p);
6277               p += sizeof (Elf_External_Verdef);
6278             }
6279           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6280                                      (Elf_External_Verdaux *) p);
6281           p += sizeof (Elf_External_Verdaux);
6282
6283           for (t = verdefs; t != NULL; t = t->next)
6284             {
6285               unsigned int cdeps;
6286               struct bfd_elf_version_deps *n;
6287
6288               /* Don't emit the base version twice.  */
6289               if (t->vernum == 0)
6290                 continue;
6291
6292               cdeps = 0;
6293               for (n = t->deps; n != NULL; n = n->next)
6294                 ++cdeps;
6295
6296               /* Add a symbol representing this version.  */
6297               bh = NULL;
6298               if (! (_bfd_generic_link_add_one_symbol
6299                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6300                       0, NULL, FALSE,
6301                       get_elf_backend_data (dynobj)->collect, &bh)))
6302                 return FALSE;
6303               h = (struct elf_link_hash_entry *) bh;
6304               h->non_elf = 0;
6305               h->def_regular = 1;
6306               h->type = STT_OBJECT;
6307               h->verinfo.vertree = t;
6308
6309               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6310                 return FALSE;
6311
6312               def.vd_version = VER_DEF_CURRENT;
6313               def.vd_flags = 0;
6314               if (t->globals.list == NULL
6315                   && t->locals.list == NULL
6316                   && ! t->used)
6317                 def.vd_flags |= VER_FLG_WEAK;
6318               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6319               def.vd_cnt = cdeps + 1;
6320               def.vd_hash = bfd_elf_hash (t->name);
6321               def.vd_aux = sizeof (Elf_External_Verdef);
6322               def.vd_next = 0;
6323
6324               /* If a basever node is next, it *must* be the last node in
6325                  the chain, otherwise Verdef construction breaks.  */
6326               if (t->next != NULL && t->next->vernum == 0)
6327                 BFD_ASSERT (t->next->next == NULL);
6328
6329               if (t->next != NULL && t->next->vernum != 0)
6330                 def.vd_next = (sizeof (Elf_External_Verdef)
6331                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6332
6333               _bfd_elf_swap_verdef_out (output_bfd, &def,
6334                                         (Elf_External_Verdef *) p);
6335               p += sizeof (Elf_External_Verdef);
6336
6337               defaux.vda_name = h->dynstr_index;
6338               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6339                                       h->dynstr_index);
6340               defaux.vda_next = 0;
6341               if (t->deps != NULL)
6342                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6343               t->name_indx = defaux.vda_name;
6344
6345               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6346                                          (Elf_External_Verdaux *) p);
6347               p += sizeof (Elf_External_Verdaux);
6348
6349               for (n = t->deps; n != NULL; n = n->next)
6350                 {
6351                   if (n->version_needed == NULL)
6352                     {
6353                       /* This can happen if there was an error in the
6354                          version script.  */
6355                       defaux.vda_name = 0;
6356                     }
6357                   else
6358                     {
6359                       defaux.vda_name = n->version_needed->name_indx;
6360                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6361                                               defaux.vda_name);
6362                     }
6363                   if (n->next == NULL)
6364                     defaux.vda_next = 0;
6365                   else
6366                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6367
6368                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6369                                              (Elf_External_Verdaux *) p);
6370                   p += sizeof (Elf_External_Verdaux);
6371                 }
6372             }
6373
6374           elf_tdata (output_bfd)->cverdefs = cdefs;
6375         }
6376     }
6377
6378   bed = get_elf_backend_data (output_bfd);
6379
6380   if (info->gc_sections && bed->can_gc_sections)
6381     {
6382       struct elf_gc_sweep_symbol_info sweep_info;
6383
6384       /* Remove the symbols that were in the swept sections from the
6385          dynamic symbol table.  */
6386       sweep_info.info = info;
6387       sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
6388       elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
6389                               &sweep_info);
6390     }
6391
6392   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6393     {
6394       asection *s;
6395       struct elf_find_verdep_info sinfo;
6396
6397       /* Work out the size of the version reference section.  */
6398
6399       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6400       BFD_ASSERT (s != NULL);
6401
6402       sinfo.info = info;
6403       sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6404       if (sinfo.vers == 0)
6405         sinfo.vers = 1;
6406       sinfo.failed = FALSE;
6407
6408       elf_link_hash_traverse (elf_hash_table (info),
6409                               _bfd_elf_link_find_version_dependencies,
6410                               &sinfo);
6411       if (sinfo.failed)
6412         return FALSE;
6413
6414       if (elf_tdata (output_bfd)->verref == NULL)
6415         s->flags |= SEC_EXCLUDE;
6416       else
6417         {
6418           Elf_Internal_Verneed *vn;
6419           unsigned int size;
6420           unsigned int crefs;
6421           bfd_byte *p;
6422
6423           /* Build the version dependency section.  */
6424           size = 0;
6425           crefs = 0;
6426           for (vn = elf_tdata (output_bfd)->verref;
6427                vn != NULL;
6428                vn = vn->vn_nextref)
6429             {
6430               Elf_Internal_Vernaux *a;
6431
6432               size += sizeof (Elf_External_Verneed);
6433               ++crefs;
6434               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6435                 size += sizeof (Elf_External_Vernaux);
6436             }
6437
6438           s->size = size;
6439           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6440           if (s->contents == NULL)
6441             return FALSE;
6442
6443           p = s->contents;
6444           for (vn = elf_tdata (output_bfd)->verref;
6445                vn != NULL;
6446                vn = vn->vn_nextref)
6447             {
6448               unsigned int caux;
6449               Elf_Internal_Vernaux *a;
6450               size_t indx;
6451
6452               caux = 0;
6453               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6454                 ++caux;
6455
6456               vn->vn_version = VER_NEED_CURRENT;
6457               vn->vn_cnt = caux;
6458               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6459                                           elf_dt_name (vn->vn_bfd) != NULL
6460                                           ? elf_dt_name (vn->vn_bfd)
6461                                           : lbasename (vn->vn_bfd->filename),
6462                                           FALSE);
6463               if (indx == (size_t) -1)
6464                 return FALSE;
6465               vn->vn_file = indx;
6466               vn->vn_aux = sizeof (Elf_External_Verneed);
6467               if (vn->vn_nextref == NULL)
6468                 vn->vn_next = 0;
6469               else
6470                 vn->vn_next = (sizeof (Elf_External_Verneed)
6471                                + caux * sizeof (Elf_External_Vernaux));
6472
6473               _bfd_elf_swap_verneed_out (output_bfd, vn,
6474                                          (Elf_External_Verneed *) p);
6475               p += sizeof (Elf_External_Verneed);
6476
6477               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6478                 {
6479                   a->vna_hash = bfd_elf_hash (a->vna_nodename);
6480                   indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6481                                               a->vna_nodename, FALSE);
6482                   if (indx == (size_t) -1)
6483                     return FALSE;
6484                   a->vna_name = indx;
6485                   if (a->vna_nextptr == NULL)
6486                     a->vna_next = 0;
6487                   else
6488                     a->vna_next = sizeof (Elf_External_Vernaux);
6489
6490                   _bfd_elf_swap_vernaux_out (output_bfd, a,
6491                                              (Elf_External_Vernaux *) p);
6492                   p += sizeof (Elf_External_Vernaux);
6493                 }
6494             }
6495
6496           elf_tdata (output_bfd)->cverrefs = crefs;
6497         }
6498     }
6499
6500   /* Any syms created from now on start with -1 in
6501      got.refcount/offset and plt.refcount/offset.  */
6502   elf_hash_table (info)->init_got_refcount
6503     = elf_hash_table (info)->init_got_offset;
6504   elf_hash_table (info)->init_plt_refcount
6505     = elf_hash_table (info)->init_plt_offset;
6506
6507   if (bfd_link_relocatable (info)
6508       && !_bfd_elf_size_group_sections (info))
6509     return FALSE;
6510
6511   /* The backend may have to create some sections regardless of whether
6512      we're dynamic or not.  */
6513   if (bed->elf_backend_always_size_sections
6514       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
6515     return FALSE;
6516
6517   /* Determine any GNU_STACK segment requirements, after the backend
6518      has had a chance to set a default segment size.  */
6519   if (info->execstack)
6520     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
6521   else if (info->noexecstack)
6522     elf_stack_flags (output_bfd) = PF_R | PF_W;
6523   else
6524     {
6525       bfd *inputobj;
6526       asection *notesec = NULL;
6527       int exec = 0;
6528
6529       for (inputobj = info->input_bfds;
6530            inputobj;
6531            inputobj = inputobj->link.next)
6532         {
6533           asection *s;
6534
6535           if (inputobj->flags
6536               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
6537             continue;
6538           s = inputobj->sections;
6539           if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
6540             continue;
6541
6542           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
6543           if (s)
6544             {
6545               if (s->flags & SEC_CODE)
6546                 exec = PF_X;
6547               notesec = s;
6548             }
6549           else if (bed->default_execstack)
6550             exec = PF_X;
6551         }
6552       if (notesec || info->stacksize > 0)
6553         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
6554       if (notesec && exec && bfd_link_relocatable (info)
6555           && notesec->output_section != bfd_abs_section_ptr)
6556         notesec->output_section->flags |= SEC_CODE;
6557     }
6558
6559   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6560     {
6561       struct elf_info_failed eif;
6562       struct elf_link_hash_entry *h;
6563       asection *dynstr;
6564       asection *s;
6565
6566       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
6567       BFD_ASSERT (*sinterpptr != NULL || !bfd_link_executable (info) || info->nointerp);
6568
6569       if (info->symbolic)
6570         {
6571           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
6572             return FALSE;
6573           info->flags |= DF_SYMBOLIC;
6574         }
6575
6576       if (rpath != NULL)
6577         {
6578           size_t indx;
6579           bfd_vma tag;
6580
6581           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
6582                                       TRUE);
6583           if (indx == (size_t) -1)
6584             return FALSE;
6585
6586           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
6587           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
6588             return FALSE;
6589         }
6590
6591       if (filter_shlib != NULL)
6592         {
6593           size_t indx;
6594
6595           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6596                                       filter_shlib, TRUE);
6597           if (indx == (size_t) -1
6598               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
6599             return FALSE;
6600         }
6601
6602       if (auxiliary_filters != NULL)
6603         {
6604           const char * const *p;
6605
6606           for (p = auxiliary_filters; *p != NULL; p++)
6607             {
6608               size_t indx;
6609
6610               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6611                                           *p, TRUE);
6612               if (indx == (size_t) -1
6613                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
6614                 return FALSE;
6615             }
6616         }
6617
6618       if (audit != NULL)
6619         {
6620           size_t indx;
6621
6622           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
6623                                       TRUE);
6624           if (indx == (size_t) -1
6625               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
6626             return FALSE;
6627         }
6628
6629       if (depaudit != NULL)
6630         {
6631           size_t indx;
6632
6633           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
6634                                       TRUE);
6635           if (indx == (size_t) -1
6636               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
6637             return FALSE;
6638         }
6639
6640       eif.info = info;
6641       eif.failed = FALSE;
6642
6643       /* Find all symbols which were defined in a dynamic object and make
6644          the backend pick a reasonable value for them.  */
6645       elf_link_hash_traverse (elf_hash_table (info),
6646                               _bfd_elf_adjust_dynamic_symbol,
6647                               &eif);
6648       if (eif.failed)
6649         return FALSE;
6650
6651       /* Add some entries to the .dynamic section.  We fill in some of the
6652          values later, in bfd_elf_final_link, but we must add the entries
6653          now so that we know the final size of the .dynamic section.  */
6654
6655       /* If there are initialization and/or finalization functions to
6656          call then add the corresponding DT_INIT/DT_FINI entries.  */
6657       h = (info->init_function
6658            ? elf_link_hash_lookup (elf_hash_table (info),
6659                                    info->init_function, FALSE,
6660                                    FALSE, FALSE)
6661            : NULL);
6662       if (h != NULL
6663           && (h->ref_regular
6664               || h->def_regular))
6665         {
6666           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
6667             return FALSE;
6668         }
6669       h = (info->fini_function
6670            ? elf_link_hash_lookup (elf_hash_table (info),
6671                                    info->fini_function, FALSE,
6672                                    FALSE, FALSE)
6673            : NULL);
6674       if (h != NULL
6675           && (h->ref_regular
6676               || h->def_regular))
6677         {
6678           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
6679             return FALSE;
6680         }
6681
6682       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
6683       if (s != NULL && s->linker_has_input)
6684         {
6685           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
6686           if (! bfd_link_executable (info))
6687             {
6688               bfd *sub;
6689               asection *o;
6690
6691               for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
6692                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour
6693                     && (o = sub->sections) != NULL
6694                     && o->sec_info_type != SEC_INFO_TYPE_JUST_SYMS)
6695                   for (o = sub->sections; o != NULL; o = o->next)
6696                     if (elf_section_data (o)->this_hdr.sh_type
6697                         == SHT_PREINIT_ARRAY)
6698                       {
6699                         _bfd_error_handler
6700                           (_("%B: .preinit_array section is not allowed in DSO"),
6701                            sub);
6702                         break;
6703                       }
6704
6705               bfd_set_error (bfd_error_nonrepresentable_section);
6706               return FALSE;
6707             }
6708
6709           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6710               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6711             return FALSE;
6712         }
6713       s = bfd_get_section_by_name (output_bfd, ".init_array");
6714       if (s != NULL && s->linker_has_input)
6715         {
6716           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6717               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6718             return FALSE;
6719         }
6720       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6721       if (s != NULL && s->linker_has_input)
6722         {
6723           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6724               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6725             return FALSE;
6726         }
6727
6728       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6729       /* If .dynstr is excluded from the link, we don't want any of
6730          these tags.  Strictly, we should be checking each section
6731          individually;  This quick check covers for the case where
6732          someone does a /DISCARD/ : { *(*) }.  */
6733       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6734         {
6735           bfd_size_type strsize;
6736
6737           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6738           if ((info->emit_hash
6739                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6740               || (info->emit_gnu_hash
6741                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6742               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6743               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6744               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6745               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6746                                               bed->s->sizeof_sym))
6747             return FALSE;
6748         }
6749     }
6750
6751   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6752     return FALSE;
6753
6754   /* The backend must work out the sizes of all the other dynamic
6755      sections.  */
6756   if (dynobj != NULL
6757       && bed->elf_backend_size_dynamic_sections != NULL
6758       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6759     return FALSE;
6760
6761   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6762     {
6763       unsigned long section_sym_count;
6764
6765       if (elf_tdata (output_bfd)->cverdefs)
6766         {
6767           unsigned int crefs = elf_tdata (output_bfd)->cverdefs;
6768
6769           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6770               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, crefs))
6771             return FALSE;
6772         }
6773
6774       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6775         {
6776           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6777             return FALSE;
6778         }
6779       else if (info->flags & DF_BIND_NOW)
6780         {
6781           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6782             return FALSE;
6783         }
6784
6785       if (info->flags_1)
6786         {
6787           if (bfd_link_executable (info))
6788             info->flags_1 &= ~ (DF_1_INITFIRST
6789                                 | DF_1_NODELETE
6790                                 | DF_1_NOOPEN);
6791           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6792             return FALSE;
6793         }
6794
6795       if (elf_tdata (output_bfd)->cverrefs)
6796         {
6797           unsigned int crefs = elf_tdata (output_bfd)->cverrefs;
6798
6799           if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6800               || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6801             return FALSE;
6802         }
6803
6804       if ((elf_tdata (output_bfd)->cverrefs == 0
6805            && elf_tdata (output_bfd)->cverdefs == 0)
6806           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6807                                              &section_sym_count) <= 1)
6808         {
6809           asection *s;
6810
6811           s = bfd_get_linker_section (dynobj, ".gnu.version");
6812           s->flags |= SEC_EXCLUDE;
6813         }
6814     }
6815   return TRUE;
6816 }
6817
6818 /* Find the first non-excluded output section.  We'll use its
6819    section symbol for some emitted relocs.  */
6820 void
6821 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6822 {
6823   asection *s;
6824
6825   for (s = output_bfd->sections; s != NULL; s = s->next)
6826     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6827         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6828       {
6829         elf_hash_table (info)->text_index_section = s;
6830         break;
6831       }
6832 }
6833
6834 /* Find two non-excluded output sections, one for code, one for data.
6835    We'll use their section symbols for some emitted relocs.  */
6836 void
6837 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6838 {
6839   asection *s;
6840
6841   /* Data first, since setting text_index_section changes
6842      _bfd_elf_link_omit_section_dynsym.  */
6843   for (s = output_bfd->sections; s != NULL; s = s->next)
6844     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6845         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6846       {
6847         elf_hash_table (info)->data_index_section = s;
6848         break;
6849       }
6850
6851   for (s = output_bfd->sections; s != NULL; s = s->next)
6852     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6853          == (SEC_ALLOC | SEC_READONLY))
6854         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6855       {
6856         elf_hash_table (info)->text_index_section = s;
6857         break;
6858       }
6859
6860   if (elf_hash_table (info)->text_index_section == NULL)
6861     elf_hash_table (info)->text_index_section
6862       = elf_hash_table (info)->data_index_section;
6863 }
6864
6865 bfd_boolean
6866 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6867 {
6868   const struct elf_backend_data *bed;
6869   unsigned long section_sym_count;
6870   bfd_size_type dynsymcount = 0;
6871
6872   if (!is_elf_hash_table (info->hash))
6873     return TRUE;
6874
6875   bed = get_elf_backend_data (output_bfd);
6876   (*bed->elf_backend_init_index_section) (output_bfd, info);
6877
6878   /* Assign dynsym indices.  In a shared library we generate a section
6879      symbol for each output section, which come first.  Next come all
6880      of the back-end allocated local dynamic syms, followed by the rest
6881      of the global symbols.
6882
6883      This is usually not needed for static binaries, however backends
6884      can request to always do it, e.g. the MIPS backend uses dynamic
6885      symbol counts to lay out GOT, which will be produced in the
6886      presence of GOT relocations even in static binaries (holding fixed
6887      data in that case, to satisfy those relocations).  */
6888
6889   if (elf_hash_table (info)->dynamic_sections_created
6890       || bed->always_renumber_dynsyms)
6891     dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6892                                                   &section_sym_count);
6893
6894   if (elf_hash_table (info)->dynamic_sections_created)
6895     {
6896       bfd *dynobj;
6897       asection *s;
6898       unsigned int dtagcount;
6899
6900       dynobj = elf_hash_table (info)->dynobj;
6901
6902       /* Work out the size of the symbol version section.  */
6903       s = bfd_get_linker_section (dynobj, ".gnu.version");
6904       BFD_ASSERT (s != NULL);
6905       if ((s->flags & SEC_EXCLUDE) == 0)
6906         {
6907           s->size = dynsymcount * sizeof (Elf_External_Versym);
6908           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6909           if (s->contents == NULL)
6910             return FALSE;
6911
6912           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6913             return FALSE;
6914         }
6915
6916       /* Set the size of the .dynsym and .hash sections.  We counted
6917          the number of dynamic symbols in elf_link_add_object_symbols.
6918          We will build the contents of .dynsym and .hash when we build
6919          the final symbol table, because until then we do not know the
6920          correct value to give the symbols.  We built the .dynstr
6921          section as we went along in elf_link_add_object_symbols.  */
6922       s = elf_hash_table (info)->dynsym;
6923       BFD_ASSERT (s != NULL);
6924       s->size = dynsymcount * bed->s->sizeof_sym;
6925
6926       s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6927       if (s->contents == NULL)
6928         return FALSE;
6929
6930       /* The first entry in .dynsym is a dummy symbol.  Clear all the
6931          section syms, in case we don't output them all.  */
6932       ++section_sym_count;
6933       memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6934
6935       elf_hash_table (info)->bucketcount = 0;
6936
6937       /* Compute the size of the hashing table.  As a side effect this
6938          computes the hash values for all the names we export.  */
6939       if (info->emit_hash)
6940         {
6941           unsigned long int *hashcodes;
6942           struct hash_codes_info hashinf;
6943           bfd_size_type amt;
6944           unsigned long int nsyms;
6945           size_t bucketcount;
6946           size_t hash_entry_size;
6947
6948           /* Compute the hash values for all exported symbols.  At the same
6949              time store the values in an array so that we could use them for
6950              optimizations.  */
6951           amt = dynsymcount * sizeof (unsigned long int);
6952           hashcodes = (unsigned long int *) bfd_malloc (amt);
6953           if (hashcodes == NULL)
6954             return FALSE;
6955           hashinf.hashcodes = hashcodes;
6956           hashinf.error = FALSE;
6957
6958           /* Put all hash values in HASHCODES.  */
6959           elf_link_hash_traverse (elf_hash_table (info),
6960                                   elf_collect_hash_codes, &hashinf);
6961           if (hashinf.error)
6962             {
6963               free (hashcodes);
6964               return FALSE;
6965             }
6966
6967           nsyms = hashinf.hashcodes - hashcodes;
6968           bucketcount
6969             = compute_bucket_count (info, hashcodes, nsyms, 0);
6970           free (hashcodes);
6971
6972           if (bucketcount == 0 && nsyms > 0)
6973             return FALSE;
6974
6975           elf_hash_table (info)->bucketcount = bucketcount;
6976
6977           s = bfd_get_linker_section (dynobj, ".hash");
6978           BFD_ASSERT (s != NULL);
6979           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6980           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6981           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6982           if (s->contents == NULL)
6983             return FALSE;
6984
6985           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6986           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6987                    s->contents + hash_entry_size);
6988         }
6989
6990       if (info->emit_gnu_hash)
6991         {
6992           size_t i, cnt;
6993           unsigned char *contents;
6994           struct collect_gnu_hash_codes cinfo;
6995           bfd_size_type amt;
6996           size_t bucketcount;
6997
6998           memset (&cinfo, 0, sizeof (cinfo));
6999
7000           /* Compute the hash values for all exported symbols.  At the same
7001              time store the values in an array so that we could use them for
7002              optimizations.  */
7003           amt = dynsymcount * 2 * sizeof (unsigned long int);
7004           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
7005           if (cinfo.hashcodes == NULL)
7006             return FALSE;
7007
7008           cinfo.hashval = cinfo.hashcodes + dynsymcount;
7009           cinfo.min_dynindx = -1;
7010           cinfo.output_bfd = output_bfd;
7011           cinfo.bed = bed;
7012
7013           /* Put all hash values in HASHCODES.  */
7014           elf_link_hash_traverse (elf_hash_table (info),
7015                                   elf_collect_gnu_hash_codes, &cinfo);
7016           if (cinfo.error)
7017             {
7018               free (cinfo.hashcodes);
7019               return FALSE;
7020             }
7021
7022           bucketcount
7023             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
7024
7025           if (bucketcount == 0)
7026             {
7027               free (cinfo.hashcodes);
7028               return FALSE;
7029             }
7030
7031           s = bfd_get_linker_section (dynobj, ".gnu.hash");
7032           BFD_ASSERT (s != NULL);
7033
7034           if (cinfo.nsyms == 0)
7035             {
7036               /* Empty .gnu.hash section is special.  */
7037               BFD_ASSERT (cinfo.min_dynindx == -1);
7038               free (cinfo.hashcodes);
7039               s->size = 5 * 4 + bed->s->arch_size / 8;
7040               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7041               if (contents == NULL)
7042                 return FALSE;
7043               s->contents = contents;
7044               /* 1 empty bucket.  */
7045               bfd_put_32 (output_bfd, 1, contents);
7046               /* SYMIDX above the special symbol 0.  */
7047               bfd_put_32 (output_bfd, 1, contents + 4);
7048               /* Just one word for bitmask.  */
7049               bfd_put_32 (output_bfd, 1, contents + 8);
7050               /* Only hash fn bloom filter.  */
7051               bfd_put_32 (output_bfd, 0, contents + 12);
7052               /* No hashes are valid - empty bitmask.  */
7053               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
7054               /* No hashes in the only bucket.  */
7055               bfd_put_32 (output_bfd, 0,
7056                           contents + 16 + bed->s->arch_size / 8);
7057             }
7058           else
7059             {
7060               unsigned long int maskwords, maskbitslog2, x;
7061               BFD_ASSERT (cinfo.min_dynindx != -1);
7062
7063               x = cinfo.nsyms;
7064               maskbitslog2 = 1;
7065               while ((x >>= 1) != 0)
7066                 ++maskbitslog2;
7067               if (maskbitslog2 < 3)
7068                 maskbitslog2 = 5;
7069               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
7070                 maskbitslog2 = maskbitslog2 + 3;
7071               else
7072                 maskbitslog2 = maskbitslog2 + 2;
7073               if (bed->s->arch_size == 64)
7074                 {
7075                   if (maskbitslog2 == 5)
7076                     maskbitslog2 = 6;
7077                   cinfo.shift1 = 6;
7078                 }
7079               else
7080                 cinfo.shift1 = 5;
7081               cinfo.mask = (1 << cinfo.shift1) - 1;
7082               cinfo.shift2 = maskbitslog2;
7083               cinfo.maskbits = 1 << maskbitslog2;
7084               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
7085               amt = bucketcount * sizeof (unsigned long int) * 2;
7086               amt += maskwords * sizeof (bfd_vma);
7087               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
7088               if (cinfo.bitmask == NULL)
7089                 {
7090                   free (cinfo.hashcodes);
7091                   return FALSE;
7092                 }
7093
7094               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
7095               cinfo.indx = cinfo.counts + bucketcount;
7096               cinfo.symindx = dynsymcount - cinfo.nsyms;
7097               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
7098
7099               /* Determine how often each hash bucket is used.  */
7100               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
7101               for (i = 0; i < cinfo.nsyms; ++i)
7102                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
7103
7104               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
7105                 if (cinfo.counts[i] != 0)
7106                   {
7107                     cinfo.indx[i] = cnt;
7108                     cnt += cinfo.counts[i];
7109                   }
7110               BFD_ASSERT (cnt == dynsymcount);
7111               cinfo.bucketcount = bucketcount;
7112               cinfo.local_indx = cinfo.min_dynindx;
7113
7114               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
7115               s->size += cinfo.maskbits / 8;
7116               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7117               if (contents == NULL)
7118                 {
7119                   free (cinfo.bitmask);
7120                   free (cinfo.hashcodes);
7121                   return FALSE;
7122                 }
7123
7124               s->contents = contents;
7125               bfd_put_32 (output_bfd, bucketcount, contents);
7126               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
7127               bfd_put_32 (output_bfd, maskwords, contents + 8);
7128               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
7129               contents += 16 + cinfo.maskbits / 8;
7130
7131               for (i = 0; i < bucketcount; ++i)
7132                 {
7133                   if (cinfo.counts[i] == 0)
7134                     bfd_put_32 (output_bfd, 0, contents);
7135                   else
7136                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
7137                   contents += 4;
7138                 }
7139
7140               cinfo.contents = contents;
7141
7142               /* Renumber dynamic symbols, populate .gnu.hash section.  */
7143               elf_link_hash_traverse (elf_hash_table (info),
7144                                       elf_renumber_gnu_hash_syms, &cinfo);
7145
7146               contents = s->contents + 16;
7147               for (i = 0; i < maskwords; ++i)
7148                 {
7149                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
7150                            contents);
7151                   contents += bed->s->arch_size / 8;
7152                 }
7153
7154               free (cinfo.bitmask);
7155               free (cinfo.hashcodes);
7156             }
7157         }
7158
7159       s = bfd_get_linker_section (dynobj, ".dynstr");
7160       BFD_ASSERT (s != NULL);
7161
7162       elf_finalize_dynstr (output_bfd, info);
7163
7164       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
7165
7166       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
7167         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
7168           return FALSE;
7169     }
7170
7171   return TRUE;
7172 }
7173 \f
7174 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
7175
7176 static void
7177 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
7178                             asection *sec)
7179 {
7180   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
7181   sec->sec_info_type = SEC_INFO_TYPE_NONE;
7182 }
7183
7184 /* Finish SHF_MERGE section merging.  */
7185
7186 bfd_boolean
7187 _bfd_elf_merge_sections (bfd *obfd, struct bfd_link_info *info)
7188 {
7189   bfd *ibfd;
7190   asection *sec;
7191
7192   if (!is_elf_hash_table (info->hash))
7193     return FALSE;
7194
7195   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
7196     if ((ibfd->flags & DYNAMIC) == 0
7197         && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
7198         && (elf_elfheader (ibfd)->e_ident[EI_CLASS]
7199             == get_elf_backend_data (obfd)->s->elfclass))
7200       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
7201         if ((sec->flags & SEC_MERGE) != 0
7202             && !bfd_is_abs_section (sec->output_section))
7203           {
7204             struct bfd_elf_section_data *secdata;
7205
7206             secdata = elf_section_data (sec);
7207             if (! _bfd_add_merge_section (obfd,
7208                                           &elf_hash_table (info)->merge_info,
7209                                           sec, &secdata->sec_info))
7210               return FALSE;
7211             else if (secdata->sec_info)
7212               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
7213           }
7214
7215   if (elf_hash_table (info)->merge_info != NULL)
7216     _bfd_merge_sections (obfd, info, elf_hash_table (info)->merge_info,
7217                          merge_sections_remove_hook);
7218   return TRUE;
7219 }
7220
7221 /* Create an entry in an ELF linker hash table.  */
7222
7223 struct bfd_hash_entry *
7224 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
7225                             struct bfd_hash_table *table,
7226                             const char *string)
7227 {
7228   /* Allocate the structure if it has not already been allocated by a
7229      subclass.  */
7230   if (entry == NULL)
7231     {
7232       entry = (struct bfd_hash_entry *)
7233         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
7234       if (entry == NULL)
7235         return entry;
7236     }
7237
7238   /* Call the allocation method of the superclass.  */
7239   entry = _bfd_link_hash_newfunc (entry, table, string);
7240   if (entry != NULL)
7241     {
7242       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
7243       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
7244
7245       /* Set local fields.  */
7246       ret->indx = -1;
7247       ret->dynindx = -1;
7248       ret->got = htab->init_got_refcount;
7249       ret->plt = htab->init_plt_refcount;
7250       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
7251                               - offsetof (struct elf_link_hash_entry, size)));
7252       /* Assume that we have been called by a non-ELF symbol reader.
7253          This flag is then reset by the code which reads an ELF input
7254          file.  This ensures that a symbol created by a non-ELF symbol
7255          reader will have the flag set correctly.  */
7256       ret->non_elf = 1;
7257     }
7258
7259   return entry;
7260 }
7261
7262 /* Copy data from an indirect symbol to its direct symbol, hiding the
7263    old indirect symbol.  Also used for copying flags to a weakdef.  */
7264
7265 void
7266 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
7267                                   struct elf_link_hash_entry *dir,
7268                                   struct elf_link_hash_entry *ind)
7269 {
7270   struct elf_link_hash_table *htab;
7271
7272   /* Copy down any references that we may have already seen to the
7273      symbol which just became indirect.  */
7274
7275   if (dir->versioned != versioned_hidden)
7276     dir->ref_dynamic |= ind->ref_dynamic;
7277   dir->ref_regular |= ind->ref_regular;
7278   dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
7279   dir->non_got_ref |= ind->non_got_ref;
7280   dir->needs_plt |= ind->needs_plt;
7281   dir->pointer_equality_needed |= ind->pointer_equality_needed;
7282
7283   if (ind->root.type != bfd_link_hash_indirect)
7284     return;
7285
7286   /* Copy over the global and procedure linkage table refcount entries.
7287      These may have been already set up by a check_relocs routine.  */
7288   htab = elf_hash_table (info);
7289   if (ind->got.refcount > htab->init_got_refcount.refcount)
7290     {
7291       if (dir->got.refcount < 0)
7292         dir->got.refcount = 0;
7293       dir->got.refcount += ind->got.refcount;
7294       ind->got.refcount = htab->init_got_refcount.refcount;
7295     }
7296
7297   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
7298     {
7299       if (dir->plt.refcount < 0)
7300         dir->plt.refcount = 0;
7301       dir->plt.refcount += ind->plt.refcount;
7302       ind->plt.refcount = htab->init_plt_refcount.refcount;
7303     }
7304
7305   if (ind->dynindx != -1)
7306     {
7307       if (dir->dynindx != -1)
7308         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
7309       dir->dynindx = ind->dynindx;
7310       dir->dynstr_index = ind->dynstr_index;
7311       ind->dynindx = -1;
7312       ind->dynstr_index = 0;
7313     }
7314 }
7315
7316 void
7317 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
7318                                 struct elf_link_hash_entry *h,
7319                                 bfd_boolean force_local)
7320 {
7321   /* STT_GNU_IFUNC symbol must go through PLT.  */
7322   if (h->type != STT_GNU_IFUNC)
7323     {
7324       h->plt = elf_hash_table (info)->init_plt_offset;
7325       h->needs_plt = 0;
7326     }
7327   if (force_local)
7328     {
7329       h->forced_local = 1;
7330       if (h->dynindx != -1)
7331         {
7332           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
7333                                   h->dynstr_index);
7334           h->dynindx = -1;
7335           h->dynstr_index = 0;
7336         }
7337     }
7338 }
7339
7340 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
7341    caller.  */
7342
7343 bfd_boolean
7344 _bfd_elf_link_hash_table_init
7345   (struct elf_link_hash_table *table,
7346    bfd *abfd,
7347    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
7348                                       struct bfd_hash_table *,
7349                                       const char *),
7350    unsigned int entsize,
7351    enum elf_target_id target_id)
7352 {
7353   bfd_boolean ret;
7354   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
7355
7356   table->init_got_refcount.refcount = can_refcount - 1;
7357   table->init_plt_refcount.refcount = can_refcount - 1;
7358   table->init_got_offset.offset = -(bfd_vma) 1;
7359   table->init_plt_offset.offset = -(bfd_vma) 1;
7360   /* The first dynamic symbol is a dummy.  */
7361   table->dynsymcount = 1;
7362
7363   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
7364
7365   table->root.type = bfd_link_elf_hash_table;
7366   table->hash_table_id = target_id;
7367
7368   return ret;
7369 }
7370
7371 /* Create an ELF linker hash table.  */
7372
7373 struct bfd_link_hash_table *
7374 _bfd_elf_link_hash_table_create (bfd *abfd)
7375 {
7376   struct elf_link_hash_table *ret;
7377   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7378
7379   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7380   if (ret == NULL)
7381     return NULL;
7382
7383   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7384                                        sizeof (struct elf_link_hash_entry),
7385                                        GENERIC_ELF_DATA))
7386     {
7387       free (ret);
7388       return NULL;
7389     }
7390   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7391
7392   return &ret->root;
7393 }
7394
7395 /* Destroy an ELF linker hash table.  */
7396
7397 void
7398 _bfd_elf_link_hash_table_free (bfd *obfd)
7399 {
7400   struct elf_link_hash_table *htab;
7401
7402   htab = (struct elf_link_hash_table *) obfd->link.hash;
7403   if (htab->dynstr != NULL)
7404     _bfd_elf_strtab_free (htab->dynstr);
7405   _bfd_merge_sections_free (htab->merge_info);
7406   _bfd_generic_link_hash_table_free (obfd);
7407 }
7408
7409 /* This is a hook for the ELF emulation code in the generic linker to
7410    tell the backend linker what file name to use for the DT_NEEDED
7411    entry for a dynamic object.  */
7412
7413 void
7414 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7415 {
7416   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7417       && bfd_get_format (abfd) == bfd_object)
7418     elf_dt_name (abfd) = name;
7419 }
7420
7421 int
7422 bfd_elf_get_dyn_lib_class (bfd *abfd)
7423 {
7424   int lib_class;
7425   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7426       && bfd_get_format (abfd) == bfd_object)
7427     lib_class = elf_dyn_lib_class (abfd);
7428   else
7429     lib_class = 0;
7430   return lib_class;
7431 }
7432
7433 void
7434 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7435 {
7436   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7437       && bfd_get_format (abfd) == bfd_object)
7438     elf_dyn_lib_class (abfd) = lib_class;
7439 }
7440
7441 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7442    the linker ELF emulation code.  */
7443
7444 struct bfd_link_needed_list *
7445 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7446                          struct bfd_link_info *info)
7447 {
7448   if (! is_elf_hash_table (info->hash))
7449     return NULL;
7450   return elf_hash_table (info)->needed;
7451 }
7452
7453 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7454    hook for the linker ELF emulation code.  */
7455
7456 struct bfd_link_needed_list *
7457 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7458                           struct bfd_link_info *info)
7459 {
7460   if (! is_elf_hash_table (info->hash))
7461     return NULL;
7462   return elf_hash_table (info)->runpath;
7463 }
7464
7465 /* Get the name actually used for a dynamic object for a link.  This
7466    is the SONAME entry if there is one.  Otherwise, it is the string
7467    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7468
7469 const char *
7470 bfd_elf_get_dt_soname (bfd *abfd)
7471 {
7472   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7473       && bfd_get_format (abfd) == bfd_object)
7474     return elf_dt_name (abfd);
7475   return NULL;
7476 }
7477
7478 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7479    the ELF linker emulation code.  */
7480
7481 bfd_boolean
7482 bfd_elf_get_bfd_needed_list (bfd *abfd,
7483                              struct bfd_link_needed_list **pneeded)
7484 {
7485   asection *s;
7486   bfd_byte *dynbuf = NULL;
7487   unsigned int elfsec;
7488   unsigned long shlink;
7489   bfd_byte *extdyn, *extdynend;
7490   size_t extdynsize;
7491   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7492
7493   *pneeded = NULL;
7494
7495   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7496       || bfd_get_format (abfd) != bfd_object)
7497     return TRUE;
7498
7499   s = bfd_get_section_by_name (abfd, ".dynamic");
7500   if (s == NULL || s->size == 0)
7501     return TRUE;
7502
7503   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7504     goto error_return;
7505
7506   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7507   if (elfsec == SHN_BAD)
7508     goto error_return;
7509
7510   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7511
7512   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7513   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7514
7515   extdyn = dynbuf;
7516   extdynend = extdyn + s->size;
7517   for (; extdyn < extdynend; extdyn += extdynsize)
7518     {
7519       Elf_Internal_Dyn dyn;
7520
7521       (*swap_dyn_in) (abfd, extdyn, &dyn);
7522
7523       if (dyn.d_tag == DT_NULL)
7524         break;
7525
7526       if (dyn.d_tag == DT_NEEDED)
7527         {
7528           const char *string;
7529           struct bfd_link_needed_list *l;
7530           unsigned int tagv = dyn.d_un.d_val;
7531           bfd_size_type amt;
7532
7533           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7534           if (string == NULL)
7535             goto error_return;
7536
7537           amt = sizeof *l;
7538           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7539           if (l == NULL)
7540             goto error_return;
7541
7542           l->by = abfd;
7543           l->name = string;
7544           l->next = *pneeded;
7545           *pneeded = l;
7546         }
7547     }
7548
7549   free (dynbuf);
7550
7551   return TRUE;
7552
7553  error_return:
7554   if (dynbuf != NULL)
7555     free (dynbuf);
7556   return FALSE;
7557 }
7558
7559 struct elf_symbuf_symbol
7560 {
7561   unsigned long st_name;        /* Symbol name, index in string tbl */
7562   unsigned char st_info;        /* Type and binding attributes */
7563   unsigned char st_other;       /* Visibilty, and target specific */
7564 };
7565
7566 struct elf_symbuf_head
7567 {
7568   struct elf_symbuf_symbol *ssym;
7569   size_t count;
7570   unsigned int st_shndx;
7571 };
7572
7573 struct elf_symbol
7574 {
7575   union
7576     {
7577       Elf_Internal_Sym *isym;
7578       struct elf_symbuf_symbol *ssym;
7579     } u;
7580   const char *name;
7581 };
7582
7583 /* Sort references to symbols by ascending section number.  */
7584
7585 static int
7586 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7587 {
7588   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7589   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7590
7591   return s1->st_shndx - s2->st_shndx;
7592 }
7593
7594 static int
7595 elf_sym_name_compare (const void *arg1, const void *arg2)
7596 {
7597   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7598   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7599   return strcmp (s1->name, s2->name);
7600 }
7601
7602 static struct elf_symbuf_head *
7603 elf_create_symbuf (size_t symcount, Elf_Internal_Sym *isymbuf)
7604 {
7605   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7606   struct elf_symbuf_symbol *ssym;
7607   struct elf_symbuf_head *ssymbuf, *ssymhead;
7608   size_t i, shndx_count, total_size;
7609
7610   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7611   if (indbuf == NULL)
7612     return NULL;
7613
7614   for (ind = indbuf, i = 0; i < symcount; i++)
7615     if (isymbuf[i].st_shndx != SHN_UNDEF)
7616       *ind++ = &isymbuf[i];
7617   indbufend = ind;
7618
7619   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7620          elf_sort_elf_symbol);
7621
7622   shndx_count = 0;
7623   if (indbufend > indbuf)
7624     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7625       if (ind[0]->st_shndx != ind[1]->st_shndx)
7626         shndx_count++;
7627
7628   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7629                 + (indbufend - indbuf) * sizeof (*ssym));
7630   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7631   if (ssymbuf == NULL)
7632     {
7633       free (indbuf);
7634       return NULL;
7635     }
7636
7637   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7638   ssymbuf->ssym = NULL;
7639   ssymbuf->count = shndx_count;
7640   ssymbuf->st_shndx = 0;
7641   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7642     {
7643       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7644         {
7645           ssymhead++;
7646           ssymhead->ssym = ssym;
7647           ssymhead->count = 0;
7648           ssymhead->st_shndx = (*ind)->st_shndx;
7649         }
7650       ssym->st_name = (*ind)->st_name;
7651       ssym->st_info = (*ind)->st_info;
7652       ssym->st_other = (*ind)->st_other;
7653       ssymhead->count++;
7654     }
7655   BFD_ASSERT ((size_t) (ssymhead - ssymbuf) == shndx_count
7656               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7657                   == total_size));
7658
7659   free (indbuf);
7660   return ssymbuf;
7661 }
7662
7663 /* Check if 2 sections define the same set of local and global
7664    symbols.  */
7665
7666 static bfd_boolean
7667 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7668                                    struct bfd_link_info *info)
7669 {
7670   bfd *bfd1, *bfd2;
7671   const struct elf_backend_data *bed1, *bed2;
7672   Elf_Internal_Shdr *hdr1, *hdr2;
7673   size_t symcount1, symcount2;
7674   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7675   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7676   Elf_Internal_Sym *isym, *isymend;
7677   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7678   size_t count1, count2, i;
7679   unsigned int shndx1, shndx2;
7680   bfd_boolean result;
7681
7682   bfd1 = sec1->owner;
7683   bfd2 = sec2->owner;
7684
7685   /* Both sections have to be in ELF.  */
7686   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7687       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7688     return FALSE;
7689
7690   if (elf_section_type (sec1) != elf_section_type (sec2))
7691     return FALSE;
7692
7693   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7694   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7695   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7696     return FALSE;
7697
7698   bed1 = get_elf_backend_data (bfd1);
7699   bed2 = get_elf_backend_data (bfd2);
7700   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7701   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7702   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7703   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7704
7705   if (symcount1 == 0 || symcount2 == 0)
7706     return FALSE;
7707
7708   result = FALSE;
7709   isymbuf1 = NULL;
7710   isymbuf2 = NULL;
7711   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7712   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7713
7714   if (ssymbuf1 == NULL)
7715     {
7716       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7717                                        NULL, NULL, NULL);
7718       if (isymbuf1 == NULL)
7719         goto done;
7720
7721       if (!info->reduce_memory_overheads)
7722         elf_tdata (bfd1)->symbuf = ssymbuf1
7723           = elf_create_symbuf (symcount1, isymbuf1);
7724     }
7725
7726   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7727     {
7728       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7729                                        NULL, NULL, NULL);
7730       if (isymbuf2 == NULL)
7731         goto done;
7732
7733       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7734         elf_tdata (bfd2)->symbuf = ssymbuf2
7735           = elf_create_symbuf (symcount2, isymbuf2);
7736     }
7737
7738   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7739     {
7740       /* Optimized faster version.  */
7741       size_t lo, hi, mid;
7742       struct elf_symbol *symp;
7743       struct elf_symbuf_symbol *ssym, *ssymend;
7744
7745       lo = 0;
7746       hi = ssymbuf1->count;
7747       ssymbuf1++;
7748       count1 = 0;
7749       while (lo < hi)
7750         {
7751           mid = (lo + hi) / 2;
7752           if (shndx1 < ssymbuf1[mid].st_shndx)
7753             hi = mid;
7754           else if (shndx1 > ssymbuf1[mid].st_shndx)
7755             lo = mid + 1;
7756           else
7757             {
7758               count1 = ssymbuf1[mid].count;
7759               ssymbuf1 += mid;
7760               break;
7761             }
7762         }
7763
7764       lo = 0;
7765       hi = ssymbuf2->count;
7766       ssymbuf2++;
7767       count2 = 0;
7768       while (lo < hi)
7769         {
7770           mid = (lo + hi) / 2;
7771           if (shndx2 < ssymbuf2[mid].st_shndx)
7772             hi = mid;
7773           else if (shndx2 > ssymbuf2[mid].st_shndx)
7774             lo = mid + 1;
7775           else
7776             {
7777               count2 = ssymbuf2[mid].count;
7778               ssymbuf2 += mid;
7779               break;
7780             }
7781         }
7782
7783       if (count1 == 0 || count2 == 0 || count1 != count2)
7784         goto done;
7785
7786       symtable1
7787         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
7788       symtable2
7789         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
7790       if (symtable1 == NULL || symtable2 == NULL)
7791         goto done;
7792
7793       symp = symtable1;
7794       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7795            ssym < ssymend; ssym++, symp++)
7796         {
7797           symp->u.ssym = ssym;
7798           symp->name = bfd_elf_string_from_elf_section (bfd1,
7799                                                         hdr1->sh_link,
7800                                                         ssym->st_name);
7801         }
7802
7803       symp = symtable2;
7804       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7805            ssym < ssymend; ssym++, symp++)
7806         {
7807           symp->u.ssym = ssym;
7808           symp->name = bfd_elf_string_from_elf_section (bfd2,
7809                                                         hdr2->sh_link,
7810                                                         ssym->st_name);
7811         }
7812
7813       /* Sort symbol by name.  */
7814       qsort (symtable1, count1, sizeof (struct elf_symbol),
7815              elf_sym_name_compare);
7816       qsort (symtable2, count1, sizeof (struct elf_symbol),
7817              elf_sym_name_compare);
7818
7819       for (i = 0; i < count1; i++)
7820         /* Two symbols must have the same binding, type and name.  */
7821         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7822             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7823             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7824           goto done;
7825
7826       result = TRUE;
7827       goto done;
7828     }
7829
7830   symtable1 = (struct elf_symbol *)
7831       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7832   symtable2 = (struct elf_symbol *)
7833       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7834   if (symtable1 == NULL || symtable2 == NULL)
7835     goto done;
7836
7837   /* Count definitions in the section.  */
7838   count1 = 0;
7839   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7840     if (isym->st_shndx == shndx1)
7841       symtable1[count1++].u.isym = isym;
7842
7843   count2 = 0;
7844   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7845     if (isym->st_shndx == shndx2)
7846       symtable2[count2++].u.isym = isym;
7847
7848   if (count1 == 0 || count2 == 0 || count1 != count2)
7849     goto done;
7850
7851   for (i = 0; i < count1; i++)
7852     symtable1[i].name
7853       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7854                                          symtable1[i].u.isym->st_name);
7855
7856   for (i = 0; i < count2; i++)
7857     symtable2[i].name
7858       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7859                                          symtable2[i].u.isym->st_name);
7860
7861   /* Sort symbol by name.  */
7862   qsort (symtable1, count1, sizeof (struct elf_symbol),
7863          elf_sym_name_compare);
7864   qsort (symtable2, count1, sizeof (struct elf_symbol),
7865          elf_sym_name_compare);
7866
7867   for (i = 0; i < count1; i++)
7868     /* Two symbols must have the same binding, type and name.  */
7869     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7870         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7871         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7872       goto done;
7873
7874   result = TRUE;
7875
7876 done:
7877   if (symtable1)
7878     free (symtable1);
7879   if (symtable2)
7880     free (symtable2);
7881   if (isymbuf1)
7882     free (isymbuf1);
7883   if (isymbuf2)
7884     free (isymbuf2);
7885
7886   return result;
7887 }
7888
7889 /* Return TRUE if 2 section types are compatible.  */
7890
7891 bfd_boolean
7892 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7893                                  bfd *bbfd, const asection *bsec)
7894 {
7895   if (asec == NULL
7896       || bsec == NULL
7897       || abfd->xvec->flavour != bfd_target_elf_flavour
7898       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7899     return TRUE;
7900
7901   return elf_section_type (asec) == elf_section_type (bsec);
7902 }
7903 \f
7904 /* Final phase of ELF linker.  */
7905
7906 /* A structure we use to avoid passing large numbers of arguments.  */
7907
7908 struct elf_final_link_info
7909 {
7910   /* General link information.  */
7911   struct bfd_link_info *info;
7912   /* Output BFD.  */
7913   bfd *output_bfd;
7914   /* Symbol string table.  */
7915   struct elf_strtab_hash *symstrtab;
7916   /* .hash section.  */
7917   asection *hash_sec;
7918   /* symbol version section (.gnu.version).  */
7919   asection *symver_sec;
7920   /* Buffer large enough to hold contents of any section.  */
7921   bfd_byte *contents;
7922   /* Buffer large enough to hold external relocs of any section.  */
7923   void *external_relocs;
7924   /* Buffer large enough to hold internal relocs of any section.  */
7925   Elf_Internal_Rela *internal_relocs;
7926   /* Buffer large enough to hold external local symbols of any input
7927      BFD.  */
7928   bfd_byte *external_syms;
7929   /* And a buffer for symbol section indices.  */
7930   Elf_External_Sym_Shndx *locsym_shndx;
7931   /* Buffer large enough to hold internal local symbols of any input
7932      BFD.  */
7933   Elf_Internal_Sym *internal_syms;
7934   /* Array large enough to hold a symbol index for each local symbol
7935      of any input BFD.  */
7936   long *indices;
7937   /* Array large enough to hold a section pointer for each local
7938      symbol of any input BFD.  */
7939   asection **sections;
7940   /* Buffer for SHT_SYMTAB_SHNDX section.  */
7941   Elf_External_Sym_Shndx *symshndxbuf;
7942   /* Number of STT_FILE syms seen.  */
7943   size_t filesym_count;
7944 };
7945
7946 /* This struct is used to pass information to elf_link_output_extsym.  */
7947
7948 struct elf_outext_info
7949 {
7950   bfd_boolean failed;
7951   bfd_boolean localsyms;
7952   bfd_boolean file_sym_done;
7953   struct elf_final_link_info *flinfo;
7954 };
7955
7956
7957 /* Support for evaluating a complex relocation.
7958
7959    Complex relocations are generalized, self-describing relocations.  The
7960    implementation of them consists of two parts: complex symbols, and the
7961    relocations themselves.
7962
7963    The relocations are use a reserved elf-wide relocation type code (R_RELC
7964    external / BFD_RELOC_RELC internal) and an encoding of relocation field
7965    information (start bit, end bit, word width, etc) into the addend.  This
7966    information is extracted from CGEN-generated operand tables within gas.
7967
7968    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
7969    internal) representing prefix-notation expressions, including but not
7970    limited to those sorts of expressions normally encoded as addends in the
7971    addend field.  The symbol mangling format is:
7972
7973    <node> := <literal>
7974           |  <unary-operator> ':' <node>
7975           |  <binary-operator> ':' <node> ':' <node>
7976           ;
7977
7978    <literal> := 's' <digits=N> ':' <N character symbol name>
7979              |  'S' <digits=N> ':' <N character section name>
7980              |  '#' <hexdigits>
7981              ;
7982
7983    <binary-operator> := as in C
7984    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
7985
7986 static void
7987 set_symbol_value (bfd *bfd_with_globals,
7988                   Elf_Internal_Sym *isymbuf,
7989                   size_t locsymcount,
7990                   size_t symidx,
7991                   bfd_vma val)
7992 {
7993   struct elf_link_hash_entry **sym_hashes;
7994   struct elf_link_hash_entry *h;
7995   size_t extsymoff = locsymcount;
7996
7997   if (symidx < locsymcount)
7998     {
7999       Elf_Internal_Sym *sym;
8000
8001       sym = isymbuf + symidx;
8002       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
8003         {
8004           /* It is a local symbol: move it to the
8005              "absolute" section and give it a value.  */
8006           sym->st_shndx = SHN_ABS;
8007           sym->st_value = val;
8008           return;
8009         }
8010       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
8011       extsymoff = 0;
8012     }
8013
8014   /* It is a global symbol: set its link type
8015      to "defined" and give it a value.  */
8016
8017   sym_hashes = elf_sym_hashes (bfd_with_globals);
8018   h = sym_hashes [symidx - extsymoff];
8019   while (h->root.type == bfd_link_hash_indirect
8020          || h->root.type == bfd_link_hash_warning)
8021     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8022   h->root.type = bfd_link_hash_defined;
8023   h->root.u.def.value = val;
8024   h->root.u.def.section = bfd_abs_section_ptr;
8025 }
8026
8027 static bfd_boolean
8028 resolve_symbol (const char *name,
8029                 bfd *input_bfd,
8030                 struct elf_final_link_info *flinfo,
8031                 bfd_vma *result,
8032                 Elf_Internal_Sym *isymbuf,
8033                 size_t locsymcount)
8034 {
8035   Elf_Internal_Sym *sym;
8036   struct bfd_link_hash_entry *global_entry;
8037   const char *candidate = NULL;
8038   Elf_Internal_Shdr *symtab_hdr;
8039   size_t i;
8040
8041   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
8042
8043   for (i = 0; i < locsymcount; ++ i)
8044     {
8045       sym = isymbuf + i;
8046
8047       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
8048         continue;
8049
8050       candidate = bfd_elf_string_from_elf_section (input_bfd,
8051                                                    symtab_hdr->sh_link,
8052                                                    sym->st_name);
8053 #ifdef DEBUG
8054       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
8055               name, candidate, (unsigned long) sym->st_value);
8056 #endif
8057       if (candidate && strcmp (candidate, name) == 0)
8058         {
8059           asection *sec = flinfo->sections [i];
8060
8061           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
8062           *result += sec->output_offset + sec->output_section->vma;
8063 #ifdef DEBUG
8064           printf ("Found symbol with value %8.8lx\n",
8065                   (unsigned long) *result);
8066 #endif
8067           return TRUE;
8068         }
8069     }
8070
8071   /* Hmm, haven't found it yet. perhaps it is a global.  */
8072   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
8073                                        FALSE, FALSE, TRUE);
8074   if (!global_entry)
8075     return FALSE;
8076
8077   if (global_entry->type == bfd_link_hash_defined
8078       || global_entry->type == bfd_link_hash_defweak)
8079     {
8080       *result = (global_entry->u.def.value
8081                  + global_entry->u.def.section->output_section->vma
8082                  + global_entry->u.def.section->output_offset);
8083 #ifdef DEBUG
8084       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
8085               global_entry->root.string, (unsigned long) *result);
8086 #endif
8087       return TRUE;
8088     }
8089
8090   return FALSE;
8091 }
8092
8093 /* Looks up NAME in SECTIONS.  If found sets RESULT to NAME's address (in
8094    bytes) and returns TRUE, otherwise returns FALSE.  Accepts pseudo-section
8095    names like "foo.end" which is the end address of section "foo".  */
8096    
8097 static bfd_boolean
8098 resolve_section (const char *name,
8099                  asection *sections,
8100                  bfd_vma *result,
8101                  bfd * abfd)
8102 {
8103   asection *curr;
8104   unsigned int len;
8105
8106   for (curr = sections; curr; curr = curr->next)
8107     if (strcmp (curr->name, name) == 0)
8108       {
8109         *result = curr->vma;
8110         return TRUE;
8111       }
8112
8113   /* Hmm. still haven't found it. try pseudo-section names.  */
8114   /* FIXME: This could be coded more efficiently...  */
8115   for (curr = sections; curr; curr = curr->next)
8116     {
8117       len = strlen (curr->name);
8118       if (len > strlen (name))
8119         continue;
8120
8121       if (strncmp (curr->name, name, len) == 0)
8122         {
8123           if (strncmp (".end", name + len, 4) == 0)
8124             {
8125               *result = curr->vma + curr->size / bfd_octets_per_byte (abfd);
8126               return TRUE;
8127             }
8128
8129           /* Insert more pseudo-section names here, if you like.  */
8130         }
8131     }
8132
8133   return FALSE;
8134 }
8135
8136 static void
8137 undefined_reference (const char *reftype, const char *name)
8138 {
8139   /* xgettext:c-format */
8140   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
8141                       reftype, name);
8142 }
8143
8144 static bfd_boolean
8145 eval_symbol (bfd_vma *result,
8146              const char **symp,
8147              bfd *input_bfd,
8148              struct elf_final_link_info *flinfo,
8149              bfd_vma dot,
8150              Elf_Internal_Sym *isymbuf,
8151              size_t locsymcount,
8152              int signed_p)
8153 {
8154   size_t len;
8155   size_t symlen;
8156   bfd_vma a;
8157   bfd_vma b;
8158   char symbuf[4096];
8159   const char *sym = *symp;
8160   const char *symend;
8161   bfd_boolean symbol_is_section = FALSE;
8162
8163   len = strlen (sym);
8164   symend = sym + len;
8165
8166   if (len < 1 || len > sizeof (symbuf))
8167     {
8168       bfd_set_error (bfd_error_invalid_operation);
8169       return FALSE;
8170     }
8171
8172   switch (* sym)
8173     {
8174     case '.':
8175       *result = dot;
8176       *symp = sym + 1;
8177       return TRUE;
8178
8179     case '#':
8180       ++sym;
8181       *result = strtoul (sym, (char **) symp, 16);
8182       return TRUE;
8183
8184     case 'S':
8185       symbol_is_section = TRUE;
8186       /* Fall through.  */
8187     case 's':
8188       ++sym;
8189       symlen = strtol (sym, (char **) symp, 10);
8190       sym = *symp + 1; /* Skip the trailing ':'.  */
8191
8192       if (symend < sym || symlen + 1 > sizeof (symbuf))
8193         {
8194           bfd_set_error (bfd_error_invalid_operation);
8195           return FALSE;
8196         }
8197
8198       memcpy (symbuf, sym, symlen);
8199       symbuf[symlen] = '\0';
8200       *symp = sym + symlen;
8201
8202       /* Is it always possible, with complex symbols, that gas "mis-guessed"
8203          the symbol as a section, or vice-versa. so we're pretty liberal in our
8204          interpretation here; section means "try section first", not "must be a
8205          section", and likewise with symbol.  */
8206
8207       if (symbol_is_section)
8208         {
8209           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result, input_bfd)
8210               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
8211                                   isymbuf, locsymcount))
8212             {
8213               undefined_reference ("section", symbuf);
8214               return FALSE;
8215             }
8216         }
8217       else
8218         {
8219           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
8220                                isymbuf, locsymcount)
8221               && !resolve_section (symbuf, flinfo->output_bfd->sections,
8222                                    result, input_bfd))
8223             {
8224               undefined_reference ("symbol", symbuf);
8225               return FALSE;
8226             }
8227         }
8228
8229       return TRUE;
8230
8231       /* All that remains are operators.  */
8232
8233 #define UNARY_OP(op)                                            \
8234   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8235     {                                                           \
8236       sym += strlen (#op);                                      \
8237       if (*sym == ':')                                          \
8238         ++sym;                                                  \
8239       *symp = sym;                                              \
8240       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8241                         isymbuf, locsymcount, signed_p))        \
8242         return FALSE;                                           \
8243       if (signed_p)                                             \
8244         *result = op ((bfd_signed_vma) a);                      \
8245       else                                                      \
8246         *result = op a;                                         \
8247       return TRUE;                                              \
8248     }
8249
8250 #define BINARY_OP(op)                                           \
8251   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8252     {                                                           \
8253       sym += strlen (#op);                                      \
8254       if (*sym == ':')                                          \
8255         ++sym;                                                  \
8256       *symp = sym;                                              \
8257       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8258                         isymbuf, locsymcount, signed_p))        \
8259         return FALSE;                                           \
8260       ++*symp;                                                  \
8261       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
8262                         isymbuf, locsymcount, signed_p))        \
8263         return FALSE;                                           \
8264       if (signed_p)                                             \
8265         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
8266       else                                                      \
8267         *result = a op b;                                       \
8268       return TRUE;                                              \
8269     }
8270
8271     default:
8272       UNARY_OP  (0-);
8273       BINARY_OP (<<);
8274       BINARY_OP (>>);
8275       BINARY_OP (==);
8276       BINARY_OP (!=);
8277       BINARY_OP (<=);
8278       BINARY_OP (>=);
8279       BINARY_OP (&&);
8280       BINARY_OP (||);
8281       UNARY_OP  (~);
8282       UNARY_OP  (!);
8283       BINARY_OP (*);
8284       BINARY_OP (/);
8285       BINARY_OP (%);
8286       BINARY_OP (^);
8287       BINARY_OP (|);
8288       BINARY_OP (&);
8289       BINARY_OP (+);
8290       BINARY_OP (-);
8291       BINARY_OP (<);
8292       BINARY_OP (>);
8293 #undef UNARY_OP
8294 #undef BINARY_OP
8295       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
8296       bfd_set_error (bfd_error_invalid_operation);
8297       return FALSE;
8298     }
8299 }
8300
8301 static void
8302 put_value (bfd_vma size,
8303            unsigned long chunksz,
8304            bfd *input_bfd,
8305            bfd_vma x,
8306            bfd_byte *location)
8307 {
8308   location += (size - chunksz);
8309
8310   for (; size; size -= chunksz, location -= chunksz)
8311     {
8312       switch (chunksz)
8313         {
8314         case 1:
8315           bfd_put_8 (input_bfd, x, location);
8316           x >>= 8;
8317           break;
8318         case 2:
8319           bfd_put_16 (input_bfd, x, location);
8320           x >>= 16;
8321           break;
8322         case 4:
8323           bfd_put_32 (input_bfd, x, location);
8324           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
8325           x >>= 16;
8326           x >>= 16;
8327           break;
8328 #ifdef BFD64
8329         case 8:
8330           bfd_put_64 (input_bfd, x, location);
8331           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
8332           x >>= 32;
8333           x >>= 32;
8334           break;
8335 #endif
8336         default:
8337           abort ();
8338           break;
8339         }
8340     }
8341 }
8342
8343 static bfd_vma
8344 get_value (bfd_vma size,
8345            unsigned long chunksz,
8346            bfd *input_bfd,
8347            bfd_byte *location)
8348 {
8349   int shift;
8350   bfd_vma x = 0;
8351
8352   /* Sanity checks.  */
8353   BFD_ASSERT (chunksz <= sizeof (x)
8354               && size >= chunksz
8355               && chunksz != 0
8356               && (size % chunksz) == 0
8357               && input_bfd != NULL
8358               && location != NULL);
8359
8360   if (chunksz == sizeof (x))
8361     {
8362       BFD_ASSERT (size == chunksz);
8363
8364       /* Make sure that we do not perform an undefined shift operation.
8365          We know that size == chunksz so there will only be one iteration
8366          of the loop below.  */
8367       shift = 0;
8368     }
8369   else
8370     shift = 8 * chunksz;
8371
8372   for (; size; size -= chunksz, location += chunksz)
8373     {
8374       switch (chunksz)
8375         {
8376         case 1:
8377           x = (x << shift) | bfd_get_8 (input_bfd, location);
8378           break;
8379         case 2:
8380           x = (x << shift) | bfd_get_16 (input_bfd, location);
8381           break;
8382         case 4:
8383           x = (x << shift) | bfd_get_32 (input_bfd, location);
8384           break;
8385 #ifdef BFD64
8386         case 8:
8387           x = (x << shift) | bfd_get_64 (input_bfd, location);
8388           break;
8389 #endif
8390         default:
8391           abort ();
8392         }
8393     }
8394   return x;
8395 }
8396
8397 static void
8398 decode_complex_addend (unsigned long *start,   /* in bits */
8399                        unsigned long *oplen,   /* in bits */
8400                        unsigned long *len,     /* in bits */
8401                        unsigned long *wordsz,  /* in bytes */
8402                        unsigned long *chunksz, /* in bytes */
8403                        unsigned long *lsb0_p,
8404                        unsigned long *signed_p,
8405                        unsigned long *trunc_p,
8406                        unsigned long encoded)
8407 {
8408   * start     =  encoded        & 0x3F;
8409   * len       = (encoded >>  6) & 0x3F;
8410   * oplen     = (encoded >> 12) & 0x3F;
8411   * wordsz    = (encoded >> 18) & 0xF;
8412   * chunksz   = (encoded >> 22) & 0xF;
8413   * lsb0_p    = (encoded >> 27) & 1;
8414   * signed_p  = (encoded >> 28) & 1;
8415   * trunc_p   = (encoded >> 29) & 1;
8416 }
8417
8418 bfd_reloc_status_type
8419 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8420                                     asection *input_section ATTRIBUTE_UNUSED,
8421                                     bfd_byte *contents,
8422                                     Elf_Internal_Rela *rel,
8423                                     bfd_vma relocation)
8424 {
8425   bfd_vma shift, x, mask;
8426   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8427   bfd_reloc_status_type r;
8428
8429   /*  Perform this reloc, since it is complex.
8430       (this is not to say that it necessarily refers to a complex
8431       symbol; merely that it is a self-describing CGEN based reloc.
8432       i.e. the addend has the complete reloc information (bit start, end,
8433       word size, etc) encoded within it.).  */
8434
8435   decode_complex_addend (&start, &oplen, &len, &wordsz,
8436                          &chunksz, &lsb0_p, &signed_p,
8437                          &trunc_p, rel->r_addend);
8438
8439   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8440
8441   if (lsb0_p)
8442     shift = (start + 1) - len;
8443   else
8444     shift = (8 * wordsz) - (start + len);
8445
8446   x = get_value (wordsz, chunksz, input_bfd,
8447                  contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8448
8449 #ifdef DEBUG
8450   printf ("Doing complex reloc: "
8451           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8452           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8453           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8454           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8455           oplen, (unsigned long) x, (unsigned long) mask,
8456           (unsigned long) relocation);
8457 #endif
8458
8459   r = bfd_reloc_ok;
8460   if (! trunc_p)
8461     /* Now do an overflow check.  */
8462     r = bfd_check_overflow ((signed_p
8463                              ? complain_overflow_signed
8464                              : complain_overflow_unsigned),
8465                             len, 0, (8 * wordsz),
8466                             relocation);
8467
8468   /* Do the deed.  */
8469   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8470
8471 #ifdef DEBUG
8472   printf ("           relocation: %8.8lx\n"
8473           "         shifted mask: %8.8lx\n"
8474           " shifted/masked reloc: %8.8lx\n"
8475           "               result: %8.8lx\n",
8476           (unsigned long) relocation, (unsigned long) (mask << shift),
8477           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8478 #endif
8479   put_value (wordsz, chunksz, input_bfd, x,
8480              contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8481   return r;
8482 }
8483
8484 /* Functions to read r_offset from external (target order) reloc
8485    entry.  Faster than bfd_getl32 et al, because we let the compiler
8486    know the value is aligned.  */
8487
8488 static bfd_vma
8489 ext32l_r_offset (const void *p)
8490 {
8491   union aligned32
8492   {
8493     uint32_t v;
8494     unsigned char c[4];
8495   };
8496   const union aligned32 *a
8497     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8498
8499   uint32_t aval = (  (uint32_t) a->c[0]
8500                    | (uint32_t) a->c[1] << 8
8501                    | (uint32_t) a->c[2] << 16
8502                    | (uint32_t) a->c[3] << 24);
8503   return aval;
8504 }
8505
8506 static bfd_vma
8507 ext32b_r_offset (const void *p)
8508 {
8509   union aligned32
8510   {
8511     uint32_t v;
8512     unsigned char c[4];
8513   };
8514   const union aligned32 *a
8515     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8516
8517   uint32_t aval = (  (uint32_t) a->c[0] << 24
8518                    | (uint32_t) a->c[1] << 16
8519                    | (uint32_t) a->c[2] << 8
8520                    | (uint32_t) a->c[3]);
8521   return aval;
8522 }
8523
8524 #ifdef BFD_HOST_64_BIT
8525 static bfd_vma
8526 ext64l_r_offset (const void *p)
8527 {
8528   union aligned64
8529   {
8530     uint64_t v;
8531     unsigned char c[8];
8532   };
8533   const union aligned64 *a
8534     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8535
8536   uint64_t aval = (  (uint64_t) a->c[0]
8537                    | (uint64_t) a->c[1] << 8
8538                    | (uint64_t) a->c[2] << 16
8539                    | (uint64_t) a->c[3] << 24
8540                    | (uint64_t) a->c[4] << 32
8541                    | (uint64_t) a->c[5] << 40
8542                    | (uint64_t) a->c[6] << 48
8543                    | (uint64_t) a->c[7] << 56);
8544   return aval;
8545 }
8546
8547 static bfd_vma
8548 ext64b_r_offset (const void *p)
8549 {
8550   union aligned64
8551   {
8552     uint64_t v;
8553     unsigned char c[8];
8554   };
8555   const union aligned64 *a
8556     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8557
8558   uint64_t aval = (  (uint64_t) a->c[0] << 56
8559                    | (uint64_t) a->c[1] << 48
8560                    | (uint64_t) a->c[2] << 40
8561                    | (uint64_t) a->c[3] << 32
8562                    | (uint64_t) a->c[4] << 24
8563                    | (uint64_t) a->c[5] << 16
8564                    | (uint64_t) a->c[6] << 8
8565                    | (uint64_t) a->c[7]);
8566   return aval;
8567 }
8568 #endif
8569
8570 /* When performing a relocatable link, the input relocations are
8571    preserved.  But, if they reference global symbols, the indices
8572    referenced must be updated.  Update all the relocations found in
8573    RELDATA.  */
8574
8575 static bfd_boolean
8576 elf_link_adjust_relocs (bfd *abfd,
8577                         asection *sec,
8578                         struct bfd_elf_section_reloc_data *reldata,
8579                         bfd_boolean sort,
8580                         struct bfd_link_info *info)
8581 {
8582   unsigned int i;
8583   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8584   bfd_byte *erela;
8585   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8586   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8587   bfd_vma r_type_mask;
8588   int r_sym_shift;
8589   unsigned int count = reldata->count;
8590   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8591
8592   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8593     {
8594       swap_in = bed->s->swap_reloc_in;
8595       swap_out = bed->s->swap_reloc_out;
8596     }
8597   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8598     {
8599       swap_in = bed->s->swap_reloca_in;
8600       swap_out = bed->s->swap_reloca_out;
8601     }
8602   else
8603     abort ();
8604
8605   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8606     abort ();
8607
8608   if (bed->s->arch_size == 32)
8609     {
8610       r_type_mask = 0xff;
8611       r_sym_shift = 8;
8612     }
8613   else
8614     {
8615       r_type_mask = 0xffffffff;
8616       r_sym_shift = 32;
8617     }
8618
8619   erela = reldata->hdr->contents;
8620   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8621     {
8622       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8623       unsigned int j;
8624
8625       if (*rel_hash == NULL)
8626         continue;
8627
8628       if ((*rel_hash)->indx == -2
8629           && info->gc_sections
8630           && ! info->gc_keep_exported)
8631         {
8632           /* PR 21524: Let the user know if a symbol was removed by garbage collection.  */
8633           _bfd_error_handler (_("%B:%A: error: relocation references symbol %s which was removed by garbage collection."),
8634                               abfd, sec,
8635                               (*rel_hash)->root.root.string);
8636           _bfd_error_handler (_("%B:%A: error: try relinking with --gc-keep-exported enabled."),
8637                               abfd, sec);
8638           bfd_set_error (bfd_error_invalid_operation);
8639           return FALSE;
8640         }
8641       BFD_ASSERT ((*rel_hash)->indx >= 0);
8642
8643       (*swap_in) (abfd, erela, irela);
8644       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8645         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8646                            | (irela[j].r_info & r_type_mask));
8647       (*swap_out) (abfd, irela, erela);
8648     }
8649
8650   if (bed->elf_backend_update_relocs)
8651     (*bed->elf_backend_update_relocs) (sec, reldata);
8652
8653   if (sort && count != 0)
8654     {
8655       bfd_vma (*ext_r_off) (const void *);
8656       bfd_vma r_off;
8657       size_t elt_size;
8658       bfd_byte *base, *end, *p, *loc;
8659       bfd_byte *buf = NULL;
8660
8661       if (bed->s->arch_size == 32)
8662         {
8663           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8664             ext_r_off = ext32l_r_offset;
8665           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8666             ext_r_off = ext32b_r_offset;
8667           else
8668             abort ();
8669         }
8670       else
8671         {
8672 #ifdef BFD_HOST_64_BIT
8673           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8674             ext_r_off = ext64l_r_offset;
8675           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8676             ext_r_off = ext64b_r_offset;
8677           else
8678 #endif
8679             abort ();
8680         }
8681
8682       /*  Must use a stable sort here.  A modified insertion sort,
8683           since the relocs are mostly sorted already.  */
8684       elt_size = reldata->hdr->sh_entsize;
8685       base = reldata->hdr->contents;
8686       end = base + count * elt_size;
8687       if (elt_size > sizeof (Elf64_External_Rela))
8688         abort ();
8689
8690       /* Ensure the first element is lowest.  This acts as a sentinel,
8691          speeding the main loop below.  */
8692       r_off = (*ext_r_off) (base);
8693       for (p = loc = base; (p += elt_size) < end; )
8694         {
8695           bfd_vma r_off2 = (*ext_r_off) (p);
8696           if (r_off > r_off2)
8697             {
8698               r_off = r_off2;
8699               loc = p;
8700             }
8701         }
8702       if (loc != base)
8703         {
8704           /* Don't just swap *base and *loc as that changes the order
8705              of the original base[0] and base[1] if they happen to
8706              have the same r_offset.  */
8707           bfd_byte onebuf[sizeof (Elf64_External_Rela)];
8708           memcpy (onebuf, loc, elt_size);
8709           memmove (base + elt_size, base, loc - base);
8710           memcpy (base, onebuf, elt_size);
8711         }
8712
8713       for (p = base + elt_size; (p += elt_size) < end; )
8714         {
8715           /* base to p is sorted, *p is next to insert.  */
8716           r_off = (*ext_r_off) (p);
8717           /* Search the sorted region for location to insert.  */
8718           loc = p - elt_size;
8719           while (r_off < (*ext_r_off) (loc))
8720             loc -= elt_size;
8721           loc += elt_size;
8722           if (loc != p)
8723             {
8724               /* Chances are there is a run of relocs to insert here,
8725                  from one of more input files.  Files are not always
8726                  linked in order due to the way elf_link_input_bfd is
8727                  called.  See pr17666.  */
8728               size_t sortlen = p - loc;
8729               bfd_vma r_off2 = (*ext_r_off) (loc);
8730               size_t runlen = elt_size;
8731               size_t buf_size = 96 * 1024;
8732               while (p + runlen < end
8733                      && (sortlen <= buf_size
8734                          || runlen + elt_size <= buf_size)
8735                      && r_off2 > (*ext_r_off) (p + runlen))
8736                 runlen += elt_size;
8737               if (buf == NULL)
8738                 {
8739                   buf = bfd_malloc (buf_size);
8740                   if (buf == NULL)
8741                     return FALSE;
8742                 }
8743               if (runlen < sortlen)
8744                 {
8745                   memcpy (buf, p, runlen);
8746                   memmove (loc + runlen, loc, sortlen);
8747                   memcpy (loc, buf, runlen);
8748                 }
8749               else
8750                 {
8751                   memcpy (buf, loc, sortlen);
8752                   memmove (loc, p, runlen);
8753                   memcpy (loc + runlen, buf, sortlen);
8754                 }
8755               p += runlen - elt_size;
8756             }
8757         }
8758       /* Hashes are no longer valid.  */
8759       free (reldata->hashes);
8760       reldata->hashes = NULL;
8761       free (buf);
8762     }
8763   return TRUE;
8764 }
8765
8766 struct elf_link_sort_rela
8767 {
8768   union {
8769     bfd_vma offset;
8770     bfd_vma sym_mask;
8771   } u;
8772   enum elf_reloc_type_class type;
8773   /* We use this as an array of size int_rels_per_ext_rel.  */
8774   Elf_Internal_Rela rela[1];
8775 };
8776
8777 static int
8778 elf_link_sort_cmp1 (const void *A, const void *B)
8779 {
8780   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8781   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8782   int relativea, relativeb;
8783
8784   relativea = a->type == reloc_class_relative;
8785   relativeb = b->type == reloc_class_relative;
8786
8787   if (relativea < relativeb)
8788     return 1;
8789   if (relativea > relativeb)
8790     return -1;
8791   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8792     return -1;
8793   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8794     return 1;
8795   if (a->rela->r_offset < b->rela->r_offset)
8796     return -1;
8797   if (a->rela->r_offset > b->rela->r_offset)
8798     return 1;
8799   return 0;
8800 }
8801
8802 static int
8803 elf_link_sort_cmp2 (const void *A, const void *B)
8804 {
8805   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8806   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8807
8808   if (a->type < b->type)
8809     return -1;
8810   if (a->type > b->type)
8811     return 1;
8812   if (a->u.offset < b->u.offset)
8813     return -1;
8814   if (a->u.offset > b->u.offset)
8815     return 1;
8816   if (a->rela->r_offset < b->rela->r_offset)
8817     return -1;
8818   if (a->rela->r_offset > b->rela->r_offset)
8819     return 1;
8820   return 0;
8821 }
8822
8823 static size_t
8824 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8825 {
8826   asection *dynamic_relocs;
8827   asection *rela_dyn;
8828   asection *rel_dyn;
8829   bfd_size_type count, size;
8830   size_t i, ret, sort_elt, ext_size;
8831   bfd_byte *sort, *s_non_relative, *p;
8832   struct elf_link_sort_rela *sq;
8833   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8834   int i2e = bed->s->int_rels_per_ext_rel;
8835   unsigned int opb = bfd_octets_per_byte (abfd);
8836   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8837   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8838   struct bfd_link_order *lo;
8839   bfd_vma r_sym_mask;
8840   bfd_boolean use_rela;
8841
8842   /* Find a dynamic reloc section.  */
8843   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8844   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8845   if (rela_dyn != NULL && rela_dyn->size > 0
8846       && rel_dyn != NULL && rel_dyn->size > 0)
8847     {
8848       bfd_boolean use_rela_initialised = FALSE;
8849
8850       /* This is just here to stop gcc from complaining.
8851          Its initialization checking code is not perfect.  */
8852       use_rela = TRUE;
8853
8854       /* Both sections are present.  Examine the sizes
8855          of the indirect sections to help us choose.  */
8856       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8857         if (lo->type == bfd_indirect_link_order)
8858           {
8859             asection *o = lo->u.indirect.section;
8860
8861             if ((o->size % bed->s->sizeof_rela) == 0)
8862               {
8863                 if ((o->size % bed->s->sizeof_rel) == 0)
8864                   /* Section size is divisible by both rel and rela sizes.
8865                      It is of no help to us.  */
8866                   ;
8867                 else
8868                   {
8869                     /* Section size is only divisible by rela.  */
8870                     if (use_rela_initialised && !use_rela)
8871                       {
8872                         _bfd_error_handler (_("%B: Unable to sort relocs - "
8873                                               "they are in more than one size"),
8874                                             abfd);
8875                         bfd_set_error (bfd_error_invalid_operation);
8876                         return 0;
8877                       }
8878                     else
8879                       {
8880                         use_rela = TRUE;
8881                         use_rela_initialised = TRUE;
8882                       }
8883                   }
8884               }
8885             else if ((o->size % bed->s->sizeof_rel) == 0)
8886               {
8887                 /* Section size is only divisible by rel.  */
8888                 if (use_rela_initialised && use_rela)
8889                   {
8890                     _bfd_error_handler (_("%B: Unable to sort relocs - "
8891                                           "they are in more than one size"),
8892                                         abfd);
8893                     bfd_set_error (bfd_error_invalid_operation);
8894                     return 0;
8895                   }
8896                 else
8897                   {
8898                     use_rela = FALSE;
8899                     use_rela_initialised = TRUE;
8900                   }
8901               }
8902             else
8903               {
8904                 /* The section size is not divisible by either -
8905                    something is wrong.  */
8906                 _bfd_error_handler (_("%B: Unable to sort relocs - "
8907                                       "they are of an unknown size"), abfd);
8908                 bfd_set_error (bfd_error_invalid_operation);
8909                 return 0;
8910               }
8911           }
8912
8913       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8914         if (lo->type == bfd_indirect_link_order)
8915           {
8916             asection *o = lo->u.indirect.section;
8917
8918             if ((o->size % bed->s->sizeof_rela) == 0)
8919               {
8920                 if ((o->size % bed->s->sizeof_rel) == 0)
8921                   /* Section size is divisible by both rel and rela sizes.
8922                      It is of no help to us.  */
8923                   ;
8924                 else
8925                   {
8926                     /* Section size is only divisible by rela.  */
8927                     if (use_rela_initialised && !use_rela)
8928                       {
8929                         _bfd_error_handler (_("%B: Unable to sort relocs - "
8930                                               "they are in more than one size"),
8931                                             abfd);
8932                         bfd_set_error (bfd_error_invalid_operation);
8933                         return 0;
8934                       }
8935                     else
8936                       {
8937                         use_rela = TRUE;
8938                         use_rela_initialised = TRUE;
8939                       }
8940                   }
8941               }
8942             else if ((o->size % bed->s->sizeof_rel) == 0)
8943               {
8944                 /* Section size is only divisible by rel.  */
8945                 if (use_rela_initialised && use_rela)
8946                   {
8947                     _bfd_error_handler (_("%B: Unable to sort relocs - "
8948                                           "they are in more than one size"),
8949                                         abfd);
8950                     bfd_set_error (bfd_error_invalid_operation);
8951                     return 0;
8952                   }
8953                 else
8954                   {
8955                     use_rela = FALSE;
8956                     use_rela_initialised = TRUE;
8957                   }
8958               }
8959             else
8960               {
8961                 /* The section size is not divisible by either -
8962                    something is wrong.  */
8963                 _bfd_error_handler (_("%B: Unable to sort relocs - "
8964                                       "they are of an unknown size"), abfd);
8965                 bfd_set_error (bfd_error_invalid_operation);
8966                 return 0;
8967               }
8968           }
8969
8970       if (! use_rela_initialised)
8971         /* Make a guess.  */
8972         use_rela = TRUE;
8973     }
8974   else if (rela_dyn != NULL && rela_dyn->size > 0)
8975     use_rela = TRUE;
8976   else if (rel_dyn != NULL && rel_dyn->size > 0)
8977     use_rela = FALSE;
8978   else
8979     return 0;
8980
8981   if (use_rela)
8982     {
8983       dynamic_relocs = rela_dyn;
8984       ext_size = bed->s->sizeof_rela;
8985       swap_in = bed->s->swap_reloca_in;
8986       swap_out = bed->s->swap_reloca_out;
8987     }
8988   else
8989     {
8990       dynamic_relocs = rel_dyn;
8991       ext_size = bed->s->sizeof_rel;
8992       swap_in = bed->s->swap_reloc_in;
8993       swap_out = bed->s->swap_reloc_out;
8994     }
8995
8996   size = 0;
8997   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8998     if (lo->type == bfd_indirect_link_order)
8999       size += lo->u.indirect.section->size;
9000
9001   if (size != dynamic_relocs->size)
9002     return 0;
9003
9004   sort_elt = (sizeof (struct elf_link_sort_rela)
9005               + (i2e - 1) * sizeof (Elf_Internal_Rela));
9006
9007   count = dynamic_relocs->size / ext_size;
9008   if (count == 0)
9009     return 0;
9010   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
9011
9012   if (sort == NULL)
9013     {
9014       (*info->callbacks->warning)
9015         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
9016       return 0;
9017     }
9018
9019   if (bed->s->arch_size == 32)
9020     r_sym_mask = ~(bfd_vma) 0xff;
9021   else
9022     r_sym_mask = ~(bfd_vma) 0xffffffff;
9023
9024   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9025     if (lo->type == bfd_indirect_link_order)
9026       {
9027         bfd_byte *erel, *erelend;
9028         asection *o = lo->u.indirect.section;
9029
9030         if (o->contents == NULL && o->size != 0)
9031           {
9032             /* This is a reloc section that is being handled as a normal
9033                section.  See bfd_section_from_shdr.  We can't combine
9034                relocs in this case.  */
9035             free (sort);
9036             return 0;
9037           }
9038         erel = o->contents;
9039         erelend = o->contents + o->size;
9040         p = sort + o->output_offset * opb / ext_size * sort_elt;
9041
9042         while (erel < erelend)
9043           {
9044             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9045
9046             (*swap_in) (abfd, erel, s->rela);
9047             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
9048             s->u.sym_mask = r_sym_mask;
9049             p += sort_elt;
9050             erel += ext_size;
9051           }
9052       }
9053
9054   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
9055
9056   for (i = 0, p = sort; i < count; i++, p += sort_elt)
9057     {
9058       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9059       if (s->type != reloc_class_relative)
9060         break;
9061     }
9062   ret = i;
9063   s_non_relative = p;
9064
9065   sq = (struct elf_link_sort_rela *) s_non_relative;
9066   for (; i < count; i++, p += sort_elt)
9067     {
9068       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
9069       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
9070         sq = sp;
9071       sp->u.offset = sq->rela->r_offset;
9072     }
9073
9074   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
9075
9076   struct elf_link_hash_table *htab = elf_hash_table (info);
9077   if (htab->srelplt && htab->srelplt->output_section == dynamic_relocs)
9078     {
9079       /* We have plt relocs in .rela.dyn.  */
9080       sq = (struct elf_link_sort_rela *) sort;
9081       for (i = 0; i < count; i++)
9082         if (sq[count - i - 1].type != reloc_class_plt)
9083           break;
9084       if (i != 0 && htab->srelplt->size == i * ext_size)
9085         {
9086           struct bfd_link_order **plo;
9087           /* Put srelplt link_order last.  This is so the output_offset
9088              set in the next loop is correct for DT_JMPREL.  */
9089           for (plo = &dynamic_relocs->map_head.link_order; *plo != NULL; )
9090             if ((*plo)->type == bfd_indirect_link_order
9091                 && (*plo)->u.indirect.section == htab->srelplt)
9092               {
9093                 lo = *plo;
9094                 *plo = lo->next;
9095               }
9096             else
9097               plo = &(*plo)->next;
9098           *plo = lo;
9099           lo->next = NULL;
9100           dynamic_relocs->map_tail.link_order = lo;
9101         }
9102     }
9103
9104   p = sort;
9105   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9106     if (lo->type == bfd_indirect_link_order)
9107       {
9108         bfd_byte *erel, *erelend;
9109         asection *o = lo->u.indirect.section;
9110
9111         erel = o->contents;
9112         erelend = o->contents + o->size;
9113         o->output_offset = (p - sort) / sort_elt * ext_size / opb;
9114         while (erel < erelend)
9115           {
9116             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9117             (*swap_out) (abfd, s->rela, erel);
9118             p += sort_elt;
9119             erel += ext_size;
9120           }
9121       }
9122
9123   free (sort);
9124   *psec = dynamic_relocs;
9125   return ret;
9126 }
9127
9128 /* Add a symbol to the output symbol string table.  */
9129
9130 static int
9131 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
9132                            const char *name,
9133                            Elf_Internal_Sym *elfsym,
9134                            asection *input_sec,
9135                            struct elf_link_hash_entry *h)
9136 {
9137   int (*output_symbol_hook)
9138     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
9139      struct elf_link_hash_entry *);
9140   struct elf_link_hash_table *hash_table;
9141   const struct elf_backend_data *bed;
9142   bfd_size_type strtabsize;
9143
9144   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9145
9146   bed = get_elf_backend_data (flinfo->output_bfd);
9147   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
9148   if (output_symbol_hook != NULL)
9149     {
9150       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
9151       if (ret != 1)
9152         return ret;
9153     }
9154
9155   if (name == NULL
9156       || *name == '\0'
9157       || (input_sec->flags & SEC_EXCLUDE))
9158     elfsym->st_name = (unsigned long) -1;
9159   else
9160     {
9161       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
9162          to get the final offset for st_name.  */
9163       elfsym->st_name
9164         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
9165                                                name, FALSE);
9166       if (elfsym->st_name == (unsigned long) -1)
9167         return 0;
9168     }
9169
9170   hash_table = elf_hash_table (flinfo->info);
9171   strtabsize = hash_table->strtabsize;
9172   if (strtabsize <= hash_table->strtabcount)
9173     {
9174       strtabsize += strtabsize;
9175       hash_table->strtabsize = strtabsize;
9176       strtabsize *= sizeof (*hash_table->strtab);
9177       hash_table->strtab
9178         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
9179                                                  strtabsize);
9180       if (hash_table->strtab == NULL)
9181         return 0;
9182     }
9183   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
9184   hash_table->strtab[hash_table->strtabcount].dest_index
9185     = hash_table->strtabcount;
9186   hash_table->strtab[hash_table->strtabcount].destshndx_index
9187     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
9188
9189   bfd_get_symcount (flinfo->output_bfd) += 1;
9190   hash_table->strtabcount += 1;
9191
9192   return 1;
9193 }
9194
9195 /* Swap symbols out to the symbol table and flush the output symbols to
9196    the file.  */
9197
9198 static bfd_boolean
9199 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
9200 {
9201   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
9202   bfd_size_type amt;
9203   size_t i;
9204   const struct elf_backend_data *bed;
9205   bfd_byte *symbuf;
9206   Elf_Internal_Shdr *hdr;
9207   file_ptr pos;
9208   bfd_boolean ret;
9209
9210   if (!hash_table->strtabcount)
9211     return TRUE;
9212
9213   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9214
9215   bed = get_elf_backend_data (flinfo->output_bfd);
9216
9217   amt = bed->s->sizeof_sym * hash_table->strtabcount;
9218   symbuf = (bfd_byte *) bfd_malloc (amt);
9219   if (symbuf == NULL)
9220     return FALSE;
9221
9222   if (flinfo->symshndxbuf)
9223     {
9224       amt = sizeof (Elf_External_Sym_Shndx);
9225       amt *= bfd_get_symcount (flinfo->output_bfd);
9226       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
9227       if (flinfo->symshndxbuf == NULL)
9228         {
9229           free (symbuf);
9230           return FALSE;
9231         }
9232     }
9233
9234   for (i = 0; i < hash_table->strtabcount; i++)
9235     {
9236       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
9237       if (elfsym->sym.st_name == (unsigned long) -1)
9238         elfsym->sym.st_name = 0;
9239       else
9240         elfsym->sym.st_name
9241           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
9242                                                     elfsym->sym.st_name);
9243       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
9244                                ((bfd_byte *) symbuf
9245                                 + (elfsym->dest_index
9246                                    * bed->s->sizeof_sym)),
9247                                (flinfo->symshndxbuf
9248                                 + elfsym->destshndx_index));
9249     }
9250
9251   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
9252   pos = hdr->sh_offset + hdr->sh_size;
9253   amt = hash_table->strtabcount * bed->s->sizeof_sym;
9254   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
9255       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
9256     {
9257       hdr->sh_size += amt;
9258       ret = TRUE;
9259     }
9260   else
9261     ret = FALSE;
9262
9263   free (symbuf);
9264
9265   free (hash_table->strtab);
9266   hash_table->strtab = NULL;
9267
9268   return ret;
9269 }
9270
9271 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
9272
9273 static bfd_boolean
9274 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
9275 {
9276   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
9277       && sym->st_shndx < SHN_LORESERVE)
9278     {
9279       /* The gABI doesn't support dynamic symbols in output sections
9280          beyond 64k.  */
9281       _bfd_error_handler
9282         /* xgettext:c-format */
9283         (_("%B: Too many sections: %d (>= %d)"),
9284          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
9285       bfd_set_error (bfd_error_nonrepresentable_section);
9286       return FALSE;
9287     }
9288   return TRUE;
9289 }
9290
9291 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
9292    allowing an unsatisfied unversioned symbol in the DSO to match a
9293    versioned symbol that would normally require an explicit version.
9294    We also handle the case that a DSO references a hidden symbol
9295    which may be satisfied by a versioned symbol in another DSO.  */
9296
9297 static bfd_boolean
9298 elf_link_check_versioned_symbol (struct bfd_link_info *info,
9299                                  const struct elf_backend_data *bed,
9300                                  struct elf_link_hash_entry *h)
9301 {
9302   bfd *abfd;
9303   struct elf_link_loaded_list *loaded;
9304
9305   if (!is_elf_hash_table (info->hash))
9306     return FALSE;
9307
9308   /* Check indirect symbol.  */
9309   while (h->root.type == bfd_link_hash_indirect)
9310     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9311
9312   switch (h->root.type)
9313     {
9314     default:
9315       abfd = NULL;
9316       break;
9317
9318     case bfd_link_hash_undefined:
9319     case bfd_link_hash_undefweak:
9320       abfd = h->root.u.undef.abfd;
9321       if (abfd == NULL
9322           || (abfd->flags & DYNAMIC) == 0
9323           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
9324         return FALSE;
9325       break;
9326
9327     case bfd_link_hash_defined:
9328     case bfd_link_hash_defweak:
9329       abfd = h->root.u.def.section->owner;
9330       break;
9331
9332     case bfd_link_hash_common:
9333       abfd = h->root.u.c.p->section->owner;
9334       break;
9335     }
9336   BFD_ASSERT (abfd != NULL);
9337
9338   for (loaded = elf_hash_table (info)->loaded;
9339        loaded != NULL;
9340        loaded = loaded->next)
9341     {
9342       bfd *input;
9343       Elf_Internal_Shdr *hdr;
9344       size_t symcount;
9345       size_t extsymcount;
9346       size_t extsymoff;
9347       Elf_Internal_Shdr *versymhdr;
9348       Elf_Internal_Sym *isym;
9349       Elf_Internal_Sym *isymend;
9350       Elf_Internal_Sym *isymbuf;
9351       Elf_External_Versym *ever;
9352       Elf_External_Versym *extversym;
9353
9354       input = loaded->abfd;
9355
9356       /* We check each DSO for a possible hidden versioned definition.  */
9357       if (input == abfd
9358           || (input->flags & DYNAMIC) == 0
9359           || elf_dynversym (input) == 0)
9360         continue;
9361
9362       hdr = &elf_tdata (input)->dynsymtab_hdr;
9363
9364       symcount = hdr->sh_size / bed->s->sizeof_sym;
9365       if (elf_bad_symtab (input))
9366         {
9367           extsymcount = symcount;
9368           extsymoff = 0;
9369         }
9370       else
9371         {
9372           extsymcount = symcount - hdr->sh_info;
9373           extsymoff = hdr->sh_info;
9374         }
9375
9376       if (extsymcount == 0)
9377         continue;
9378
9379       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
9380                                       NULL, NULL, NULL);
9381       if (isymbuf == NULL)
9382         return FALSE;
9383
9384       /* Read in any version definitions.  */
9385       versymhdr = &elf_tdata (input)->dynversym_hdr;
9386       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
9387       if (extversym == NULL)
9388         goto error_ret;
9389
9390       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
9391           || (bfd_bread (extversym, versymhdr->sh_size, input)
9392               != versymhdr->sh_size))
9393         {
9394           free (extversym);
9395         error_ret:
9396           free (isymbuf);
9397           return FALSE;
9398         }
9399
9400       ever = extversym + extsymoff;
9401       isymend = isymbuf + extsymcount;
9402       for (isym = isymbuf; isym < isymend; isym++, ever++)
9403         {
9404           const char *name;
9405           Elf_Internal_Versym iver;
9406           unsigned short version_index;
9407
9408           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
9409               || isym->st_shndx == SHN_UNDEF)
9410             continue;
9411
9412           name = bfd_elf_string_from_elf_section (input,
9413                                                   hdr->sh_link,
9414                                                   isym->st_name);
9415           if (strcmp (name, h->root.root.string) != 0)
9416             continue;
9417
9418           _bfd_elf_swap_versym_in (input, ever, &iver);
9419
9420           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
9421               && !(h->def_regular
9422                    && h->forced_local))
9423             {
9424               /* If we have a non-hidden versioned sym, then it should
9425                  have provided a definition for the undefined sym unless
9426                  it is defined in a non-shared object and forced local.
9427                */
9428               abort ();
9429             }
9430
9431           version_index = iver.vs_vers & VERSYM_VERSION;
9432           if (version_index == 1 || version_index == 2)
9433             {
9434               /* This is the base or first version.  We can use it.  */
9435               free (extversym);
9436               free (isymbuf);
9437               return TRUE;
9438             }
9439         }
9440
9441       free (extversym);
9442       free (isymbuf);
9443     }
9444
9445   return FALSE;
9446 }
9447
9448 /* Convert ELF common symbol TYPE.  */
9449
9450 static int
9451 elf_link_convert_common_type (struct bfd_link_info *info, int type)
9452 {
9453   /* Commom symbol can only appear in relocatable link.  */
9454   if (!bfd_link_relocatable (info))
9455     abort ();
9456   switch (info->elf_stt_common)
9457     {
9458     case unchanged:
9459       break;
9460     case elf_stt_common:
9461       type = STT_COMMON;
9462       break;
9463     case no_elf_stt_common:
9464       type = STT_OBJECT;
9465       break;
9466     }
9467   return type;
9468 }
9469
9470 /* Add an external symbol to the symbol table.  This is called from
9471    the hash table traversal routine.  When generating a shared object,
9472    we go through the symbol table twice.  The first time we output
9473    anything that might have been forced to local scope in a version
9474    script.  The second time we output the symbols that are still
9475    global symbols.  */
9476
9477 static bfd_boolean
9478 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
9479 {
9480   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
9481   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
9482   struct elf_final_link_info *flinfo = eoinfo->flinfo;
9483   bfd_boolean strip;
9484   Elf_Internal_Sym sym;
9485   asection *input_sec;
9486   const struct elf_backend_data *bed;
9487   long indx;
9488   int ret;
9489   unsigned int type;
9490
9491   if (h->root.type == bfd_link_hash_warning)
9492     {
9493       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9494       if (h->root.type == bfd_link_hash_new)
9495         return TRUE;
9496     }
9497
9498   /* Decide whether to output this symbol in this pass.  */
9499   if (eoinfo->localsyms)
9500     {
9501       if (!h->forced_local)
9502         return TRUE;
9503     }
9504   else
9505     {
9506       if (h->forced_local)
9507         return TRUE;
9508     }
9509
9510   bed = get_elf_backend_data (flinfo->output_bfd);
9511
9512   if (h->root.type == bfd_link_hash_undefined)
9513     {
9514       /* If we have an undefined symbol reference here then it must have
9515          come from a shared library that is being linked in.  (Undefined
9516          references in regular files have already been handled unless
9517          they are in unreferenced sections which are removed by garbage
9518          collection).  */
9519       bfd_boolean ignore_undef = FALSE;
9520
9521       /* Some symbols may be special in that the fact that they're
9522          undefined can be safely ignored - let backend determine that.  */
9523       if (bed->elf_backend_ignore_undef_symbol)
9524         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9525
9526       /* If we are reporting errors for this situation then do so now.  */
9527       if (!ignore_undef
9528           && h->ref_dynamic
9529           && (!h->ref_regular || flinfo->info->gc_sections)
9530           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9531           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9532         (*flinfo->info->callbacks->undefined_symbol)
9533           (flinfo->info, h->root.root.string,
9534            h->ref_regular ? NULL : h->root.u.undef.abfd,
9535            NULL, 0,
9536            flinfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR);
9537
9538       /* Strip a global symbol defined in a discarded section.  */
9539       if (h->indx == -3)
9540         return TRUE;
9541     }
9542
9543   /* We should also warn if a forced local symbol is referenced from
9544      shared libraries.  */
9545   if (bfd_link_executable (flinfo->info)
9546       && h->forced_local
9547       && h->ref_dynamic
9548       && h->def_regular
9549       && !h->dynamic_def
9550       && h->ref_dynamic_nonweak
9551       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9552     {
9553       bfd *def_bfd;
9554       const char *msg;
9555       struct elf_link_hash_entry *hi = h;
9556
9557       /* Check indirect symbol.  */
9558       while (hi->root.type == bfd_link_hash_indirect)
9559         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9560
9561       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9562         /* xgettext:c-format */
9563         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
9564       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9565         /* xgettext:c-format */
9566         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
9567       else
9568         /* xgettext:c-format */
9569         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
9570       def_bfd = flinfo->output_bfd;
9571       if (hi->root.u.def.section != bfd_abs_section_ptr)
9572         def_bfd = hi->root.u.def.section->owner;
9573       _bfd_error_handler (msg, flinfo->output_bfd,
9574                           h->root.root.string, def_bfd);
9575       bfd_set_error (bfd_error_bad_value);
9576       eoinfo->failed = TRUE;
9577       return FALSE;
9578     }
9579
9580   /* We don't want to output symbols that have never been mentioned by
9581      a regular file, or that we have been told to strip.  However, if
9582      h->indx is set to -2, the symbol is used by a reloc and we must
9583      output it.  */
9584   strip = FALSE;
9585   if (h->indx == -2)
9586     ;
9587   else if ((h->def_dynamic
9588             || h->ref_dynamic
9589             || h->root.type == bfd_link_hash_new)
9590            && !h->def_regular
9591            && !h->ref_regular)
9592     strip = TRUE;
9593   else if (flinfo->info->strip == strip_all)
9594     strip = TRUE;
9595   else if (flinfo->info->strip == strip_some
9596            && bfd_hash_lookup (flinfo->info->keep_hash,
9597                                h->root.root.string, FALSE, FALSE) == NULL)
9598     strip = TRUE;
9599   else if ((h->root.type == bfd_link_hash_defined
9600             || h->root.type == bfd_link_hash_defweak)
9601            && ((flinfo->info->strip_discarded
9602                 && discarded_section (h->root.u.def.section))
9603                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9604                    && h->root.u.def.section->owner != NULL
9605                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9606     strip = TRUE;
9607   else if ((h->root.type == bfd_link_hash_undefined
9608             || h->root.type == bfd_link_hash_undefweak)
9609            && h->root.u.undef.abfd != NULL
9610            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9611     strip = TRUE;
9612
9613   type = h->type;
9614
9615   /* If we're stripping it, and it's not a dynamic symbol, there's
9616      nothing else to do.   However, if it is a forced local symbol or
9617      an ifunc symbol we need to give the backend finish_dynamic_symbol
9618      function a chance to make it dynamic.  */
9619   if (strip
9620       && h->dynindx == -1
9621       && type != STT_GNU_IFUNC
9622       && !h->forced_local)
9623     return TRUE;
9624
9625   sym.st_value = 0;
9626   sym.st_size = h->size;
9627   sym.st_other = h->other;
9628   switch (h->root.type)
9629     {
9630     default:
9631     case bfd_link_hash_new:
9632     case bfd_link_hash_warning:
9633       abort ();
9634       return FALSE;
9635
9636     case bfd_link_hash_undefined:
9637     case bfd_link_hash_undefweak:
9638       input_sec = bfd_und_section_ptr;
9639       sym.st_shndx = SHN_UNDEF;
9640       break;
9641
9642     case bfd_link_hash_defined:
9643     case bfd_link_hash_defweak:
9644       {
9645         input_sec = h->root.u.def.section;
9646         if (input_sec->output_section != NULL)
9647           {
9648             sym.st_shndx =
9649               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9650                                                  input_sec->output_section);
9651             if (sym.st_shndx == SHN_BAD)
9652               {
9653                 _bfd_error_handler
9654                   /* xgettext:c-format */
9655                   (_("%B: could not find output section %A for input section %A"),
9656                    flinfo->output_bfd, input_sec->output_section, input_sec);
9657                 bfd_set_error (bfd_error_nonrepresentable_section);
9658                 eoinfo->failed = TRUE;
9659                 return FALSE;
9660               }
9661
9662             /* ELF symbols in relocatable files are section relative,
9663                but in nonrelocatable files they are virtual
9664                addresses.  */
9665             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9666             if (!bfd_link_relocatable (flinfo->info))
9667               {
9668                 sym.st_value += input_sec->output_section->vma;
9669                 if (h->type == STT_TLS)
9670                   {
9671                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9672                     if (tls_sec != NULL)
9673                       sym.st_value -= tls_sec->vma;
9674                   }
9675               }
9676           }
9677         else
9678           {
9679             BFD_ASSERT (input_sec->owner == NULL
9680                         || (input_sec->owner->flags & DYNAMIC) != 0);
9681             sym.st_shndx = SHN_UNDEF;
9682             input_sec = bfd_und_section_ptr;
9683           }
9684       }
9685       break;
9686
9687     case bfd_link_hash_common:
9688       input_sec = h->root.u.c.p->section;
9689       sym.st_shndx = bed->common_section_index (input_sec);
9690       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9691       break;
9692
9693     case bfd_link_hash_indirect:
9694       /* These symbols are created by symbol versioning.  They point
9695          to the decorated version of the name.  For example, if the
9696          symbol foo@@GNU_1.2 is the default, which should be used when
9697          foo is used with no version, then we add an indirect symbol
9698          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9699          since the indirected symbol is already in the hash table.  */
9700       return TRUE;
9701     }
9702
9703   if (type == STT_COMMON || type == STT_OBJECT)
9704     switch (h->root.type)
9705       {
9706       case bfd_link_hash_common:
9707         type = elf_link_convert_common_type (flinfo->info, type);
9708         break;
9709       case bfd_link_hash_defined:
9710       case bfd_link_hash_defweak:
9711         if (bed->common_definition (&sym))
9712           type = elf_link_convert_common_type (flinfo->info, type);
9713         else
9714           type = STT_OBJECT;
9715         break;
9716       case bfd_link_hash_undefined:
9717       case bfd_link_hash_undefweak:
9718         break;
9719       default:
9720         abort ();
9721       }
9722
9723   if (h->forced_local)
9724     {
9725       sym.st_info = ELF_ST_INFO (STB_LOCAL, type);
9726       /* Turn off visibility on local symbol.  */
9727       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9728     }
9729   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9730   else if (h->unique_global && h->def_regular)
9731     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, type);
9732   else if (h->root.type == bfd_link_hash_undefweak
9733            || h->root.type == bfd_link_hash_defweak)
9734     sym.st_info = ELF_ST_INFO (STB_WEAK, type);
9735   else
9736     sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9737   sym.st_target_internal = h->target_internal;
9738
9739   /* Give the processor backend a chance to tweak the symbol value,
9740      and also to finish up anything that needs to be done for this
9741      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9742      forced local syms when non-shared is due to a historical quirk.
9743      STT_GNU_IFUNC symbol must go through PLT.  */
9744   if ((h->type == STT_GNU_IFUNC
9745        && h->def_regular
9746        && !bfd_link_relocatable (flinfo->info))
9747       || ((h->dynindx != -1
9748            || h->forced_local)
9749           && ((bfd_link_pic (flinfo->info)
9750                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9751                    || h->root.type != bfd_link_hash_undefweak))
9752               || !h->forced_local)
9753           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9754     {
9755       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9756              (flinfo->output_bfd, flinfo->info, h, &sym)))
9757         {
9758           eoinfo->failed = TRUE;
9759           return FALSE;
9760         }
9761     }
9762
9763   /* If we are marking the symbol as undefined, and there are no
9764      non-weak references to this symbol from a regular object, then
9765      mark the symbol as weak undefined; if there are non-weak
9766      references, mark the symbol as strong.  We can't do this earlier,
9767      because it might not be marked as undefined until the
9768      finish_dynamic_symbol routine gets through with it.  */
9769   if (sym.st_shndx == SHN_UNDEF
9770       && h->ref_regular
9771       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9772           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9773     {
9774       int bindtype;
9775       type = ELF_ST_TYPE (sym.st_info);
9776
9777       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9778       if (type == STT_GNU_IFUNC)
9779         type = STT_FUNC;
9780
9781       if (h->ref_regular_nonweak)
9782         bindtype = STB_GLOBAL;
9783       else
9784         bindtype = STB_WEAK;
9785       sym.st_info = ELF_ST_INFO (bindtype, type);
9786     }
9787
9788   /* If this is a symbol defined in a dynamic library, don't use the
9789      symbol size from the dynamic library.  Relinking an executable
9790      against a new library may introduce gratuitous changes in the
9791      executable's symbols if we keep the size.  */
9792   if (sym.st_shndx == SHN_UNDEF
9793       && !h->def_regular
9794       && h->def_dynamic)
9795     sym.st_size = 0;
9796
9797   /* If a non-weak symbol with non-default visibility is not defined
9798      locally, it is a fatal error.  */
9799   if (!bfd_link_relocatable (flinfo->info)
9800       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9801       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9802       && h->root.type == bfd_link_hash_undefined
9803       && !h->def_regular)
9804     {
9805       const char *msg;
9806
9807       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9808         /* xgettext:c-format */
9809         msg = _("%B: protected symbol `%s' isn't defined");
9810       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9811         /* xgettext:c-format */
9812         msg = _("%B: internal symbol `%s' isn't defined");
9813       else
9814         /* xgettext:c-format */
9815         msg = _("%B: hidden symbol `%s' isn't defined");
9816       _bfd_error_handler (msg, flinfo->output_bfd, h->root.root.string);
9817       bfd_set_error (bfd_error_bad_value);
9818       eoinfo->failed = TRUE;
9819       return FALSE;
9820     }
9821
9822   /* If this symbol should be put in the .dynsym section, then put it
9823      there now.  We already know the symbol index.  We also fill in
9824      the entry in the .hash section.  */
9825   if (elf_hash_table (flinfo->info)->dynsym != NULL
9826       && h->dynindx != -1
9827       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9828     {
9829       bfd_byte *esym;
9830
9831       /* Since there is no version information in the dynamic string,
9832          if there is no version info in symbol version section, we will
9833          have a run-time problem if not linking executable, referenced
9834          by shared library, or not bound locally.  */
9835       if (h->verinfo.verdef == NULL
9836           && (!bfd_link_executable (flinfo->info)
9837               || h->ref_dynamic
9838               || !h->def_regular))
9839         {
9840           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9841
9842           if (p && p [1] != '\0')
9843             {
9844               _bfd_error_handler
9845                 /* xgettext:c-format */
9846                 (_("%B: No symbol version section for versioned symbol `%s'"),
9847                  flinfo->output_bfd, h->root.root.string);
9848               eoinfo->failed = TRUE;
9849               return FALSE;
9850             }
9851         }
9852
9853       sym.st_name = h->dynstr_index;
9854       esym = (elf_hash_table (flinfo->info)->dynsym->contents
9855               + h->dynindx * bed->s->sizeof_sym);
9856       if (!check_dynsym (flinfo->output_bfd, &sym))
9857         {
9858           eoinfo->failed = TRUE;
9859           return FALSE;
9860         }
9861       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9862
9863       if (flinfo->hash_sec != NULL)
9864         {
9865           size_t hash_entry_size;
9866           bfd_byte *bucketpos;
9867           bfd_vma chain;
9868           size_t bucketcount;
9869           size_t bucket;
9870
9871           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9872           bucket = h->u.elf_hash_value % bucketcount;
9873
9874           hash_entry_size
9875             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9876           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9877                        + (bucket + 2) * hash_entry_size);
9878           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9879           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9880                    bucketpos);
9881           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9882                    ((bfd_byte *) flinfo->hash_sec->contents
9883                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9884         }
9885
9886       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9887         {
9888           Elf_Internal_Versym iversym;
9889           Elf_External_Versym *eversym;
9890
9891           if (!h->def_regular)
9892             {
9893               if (h->verinfo.verdef == NULL
9894                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9895                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9896                 iversym.vs_vers = 0;
9897               else
9898                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9899             }
9900           else
9901             {
9902               if (h->verinfo.vertree == NULL)
9903                 iversym.vs_vers = 1;
9904               else
9905                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9906               if (flinfo->info->create_default_symver)
9907                 iversym.vs_vers++;
9908             }
9909
9910           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
9911              defined locally.  */
9912           if (h->versioned == versioned_hidden && h->def_regular)
9913             iversym.vs_vers |= VERSYM_HIDDEN;
9914
9915           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
9916           eversym += h->dynindx;
9917           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
9918         }
9919     }
9920
9921   /* If the symbol is undefined, and we didn't output it to .dynsym,
9922      strip it from .symtab too.  Obviously we can't do this for
9923      relocatable output or when needed for --emit-relocs.  */
9924   else if (input_sec == bfd_und_section_ptr
9925            && h->indx != -2
9926            /* PR 22319 Do not strip global undefined symbols marked as being needed.  */
9927            && (h->mark != 1 || ELF_ST_BIND (sym.st_info) != STB_GLOBAL)
9928            && !bfd_link_relocatable (flinfo->info))
9929     return TRUE;
9930
9931   /* Also strip others that we couldn't earlier due to dynamic symbol
9932      processing.  */
9933   if (strip)
9934     return TRUE;
9935   if ((input_sec->flags & SEC_EXCLUDE) != 0)
9936     return TRUE;
9937
9938   /* Output a FILE symbol so that following locals are not associated
9939      with the wrong input file.  We need one for forced local symbols
9940      if we've seen more than one FILE symbol or when we have exactly
9941      one FILE symbol but global symbols are present in a file other
9942      than the one with the FILE symbol.  We also need one if linker
9943      defined symbols are present.  In practice these conditions are
9944      always met, so just emit the FILE symbol unconditionally.  */
9945   if (eoinfo->localsyms
9946       && !eoinfo->file_sym_done
9947       && eoinfo->flinfo->filesym_count != 0)
9948     {
9949       Elf_Internal_Sym fsym;
9950
9951       memset (&fsym, 0, sizeof (fsym));
9952       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9953       fsym.st_shndx = SHN_ABS;
9954       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
9955                                       bfd_und_section_ptr, NULL))
9956         return FALSE;
9957
9958       eoinfo->file_sym_done = TRUE;
9959     }
9960
9961   indx = bfd_get_symcount (flinfo->output_bfd);
9962   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
9963                                    input_sec, h);
9964   if (ret == 0)
9965     {
9966       eoinfo->failed = TRUE;
9967       return FALSE;
9968     }
9969   else if (ret == 1)
9970     h->indx = indx;
9971   else if (h->indx == -2)
9972     abort();
9973
9974   return TRUE;
9975 }
9976
9977 /* Return TRUE if special handling is done for relocs in SEC against
9978    symbols defined in discarded sections.  */
9979
9980 static bfd_boolean
9981 elf_section_ignore_discarded_relocs (asection *sec)
9982 {
9983   const struct elf_backend_data *bed;
9984
9985   switch (sec->sec_info_type)
9986     {
9987     case SEC_INFO_TYPE_STABS:
9988     case SEC_INFO_TYPE_EH_FRAME:
9989     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
9990       return TRUE;
9991     default:
9992       break;
9993     }
9994
9995   bed = get_elf_backend_data (sec->owner);
9996   if (bed->elf_backend_ignore_discarded_relocs != NULL
9997       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
9998     return TRUE;
9999
10000   return FALSE;
10001 }
10002
10003 /* Return a mask saying how ld should treat relocations in SEC against
10004    symbols defined in discarded sections.  If this function returns
10005    COMPLAIN set, ld will issue a warning message.  If this function
10006    returns PRETEND set, and the discarded section was link-once and the
10007    same size as the kept link-once section, ld will pretend that the
10008    symbol was actually defined in the kept section.  Otherwise ld will
10009    zero the reloc (at least that is the intent, but some cooperation by
10010    the target dependent code is needed, particularly for REL targets).  */
10011
10012 unsigned int
10013 _bfd_elf_default_action_discarded (asection *sec)
10014 {
10015   if (sec->flags & SEC_DEBUGGING)
10016     return PRETEND;
10017
10018   if (strcmp (".eh_frame", sec->name) == 0)
10019     return 0;
10020
10021   if (strcmp (".gcc_except_table", sec->name) == 0)
10022     return 0;
10023
10024   return COMPLAIN | PRETEND;
10025 }
10026
10027 /* Find a match between a section and a member of a section group.  */
10028
10029 static asection *
10030 match_group_member (asection *sec, asection *group,
10031                     struct bfd_link_info *info)
10032 {
10033   asection *first = elf_next_in_group (group);
10034   asection *s = first;
10035
10036   while (s != NULL)
10037     {
10038       if (bfd_elf_match_symbols_in_sections (s, sec, info))
10039         return s;
10040
10041       s = elf_next_in_group (s);
10042       if (s == first)
10043         break;
10044     }
10045
10046   return NULL;
10047 }
10048
10049 /* Check if the kept section of a discarded section SEC can be used
10050    to replace it.  Return the replacement if it is OK.  Otherwise return
10051    NULL.  */
10052
10053 asection *
10054 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
10055 {
10056   asection *kept;
10057
10058   kept = sec->kept_section;
10059   if (kept != NULL)
10060     {
10061       if ((kept->flags & SEC_GROUP) != 0)
10062         kept = match_group_member (sec, kept, info);
10063       if (kept != NULL
10064           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
10065               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
10066         kept = NULL;
10067       sec->kept_section = kept;
10068     }
10069   return kept;
10070 }
10071
10072 /* Link an input file into the linker output file.  This function
10073    handles all the sections and relocations of the input file at once.
10074    This is so that we only have to read the local symbols once, and
10075    don't have to keep them in memory.  */
10076
10077 static bfd_boolean
10078 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
10079 {
10080   int (*relocate_section)
10081     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
10082      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
10083   bfd *output_bfd;
10084   Elf_Internal_Shdr *symtab_hdr;
10085   size_t locsymcount;
10086   size_t extsymoff;
10087   Elf_Internal_Sym *isymbuf;
10088   Elf_Internal_Sym *isym;
10089   Elf_Internal_Sym *isymend;
10090   long *pindex;
10091   asection **ppsection;
10092   asection *o;
10093   const struct elf_backend_data *bed;
10094   struct elf_link_hash_entry **sym_hashes;
10095   bfd_size_type address_size;
10096   bfd_vma r_type_mask;
10097   int r_sym_shift;
10098   bfd_boolean have_file_sym = FALSE;
10099
10100   output_bfd = flinfo->output_bfd;
10101   bed = get_elf_backend_data (output_bfd);
10102   relocate_section = bed->elf_backend_relocate_section;
10103
10104   /* If this is a dynamic object, we don't want to do anything here:
10105      we don't want the local symbols, and we don't want the section
10106      contents.  */
10107   if ((input_bfd->flags & DYNAMIC) != 0)
10108     return TRUE;
10109
10110   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
10111   if (elf_bad_symtab (input_bfd))
10112     {
10113       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
10114       extsymoff = 0;
10115     }
10116   else
10117     {
10118       locsymcount = symtab_hdr->sh_info;
10119       extsymoff = symtab_hdr->sh_info;
10120     }
10121
10122   /* Read the local symbols.  */
10123   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
10124   if (isymbuf == NULL && locsymcount != 0)
10125     {
10126       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
10127                                       flinfo->internal_syms,
10128                                       flinfo->external_syms,
10129                                       flinfo->locsym_shndx);
10130       if (isymbuf == NULL)
10131         return FALSE;
10132     }
10133
10134   /* Find local symbol sections and adjust values of symbols in
10135      SEC_MERGE sections.  Write out those local symbols we know are
10136      going into the output file.  */
10137   isymend = isymbuf + locsymcount;
10138   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
10139        isym < isymend;
10140        isym++, pindex++, ppsection++)
10141     {
10142       asection *isec;
10143       const char *name;
10144       Elf_Internal_Sym osym;
10145       long indx;
10146       int ret;
10147
10148       *pindex = -1;
10149
10150       if (elf_bad_symtab (input_bfd))
10151         {
10152           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
10153             {
10154               *ppsection = NULL;
10155               continue;
10156             }
10157         }
10158
10159       if (isym->st_shndx == SHN_UNDEF)
10160         isec = bfd_und_section_ptr;
10161       else if (isym->st_shndx == SHN_ABS)
10162         isec = bfd_abs_section_ptr;
10163       else if (isym->st_shndx == SHN_COMMON)
10164         isec = bfd_com_section_ptr;
10165       else
10166         {
10167           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
10168           if (isec == NULL)
10169             {
10170               /* Don't attempt to output symbols with st_shnx in the
10171                  reserved range other than SHN_ABS and SHN_COMMON.  */
10172               *ppsection = NULL;
10173               continue;
10174             }
10175           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
10176                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
10177             isym->st_value =
10178               _bfd_merged_section_offset (output_bfd, &isec,
10179                                           elf_section_data (isec)->sec_info,
10180                                           isym->st_value);
10181         }
10182
10183       *ppsection = isec;
10184
10185       /* Don't output the first, undefined, symbol.  In fact, don't
10186          output any undefined local symbol.  */
10187       if (isec == bfd_und_section_ptr)
10188         continue;
10189
10190       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
10191         {
10192           /* We never output section symbols.  Instead, we use the
10193              section symbol of the corresponding section in the output
10194              file.  */
10195           continue;
10196         }
10197
10198       /* If we are stripping all symbols, we don't want to output this
10199          one.  */
10200       if (flinfo->info->strip == strip_all)
10201         continue;
10202
10203       /* If we are discarding all local symbols, we don't want to
10204          output this one.  If we are generating a relocatable output
10205          file, then some of the local symbols may be required by
10206          relocs; we output them below as we discover that they are
10207          needed.  */
10208       if (flinfo->info->discard == discard_all)
10209         continue;
10210
10211       /* If this symbol is defined in a section which we are
10212          discarding, we don't need to keep it.  */
10213       if (isym->st_shndx != SHN_UNDEF
10214           && isym->st_shndx < SHN_LORESERVE
10215           && bfd_section_removed_from_list (output_bfd,
10216                                             isec->output_section))
10217         continue;
10218
10219       /* Get the name of the symbol.  */
10220       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
10221                                               isym->st_name);
10222       if (name == NULL)
10223         return FALSE;
10224
10225       /* See if we are discarding symbols with this name.  */
10226       if ((flinfo->info->strip == strip_some
10227            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
10228                == NULL))
10229           || (((flinfo->info->discard == discard_sec_merge
10230                 && (isec->flags & SEC_MERGE)
10231                 && !bfd_link_relocatable (flinfo->info))
10232                || flinfo->info->discard == discard_l)
10233               && bfd_is_local_label_name (input_bfd, name)))
10234         continue;
10235
10236       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
10237         {
10238           if (input_bfd->lto_output)
10239             /* -flto puts a temp file name here.  This means builds
10240                are not reproducible.  Discard the symbol.  */
10241             continue;
10242           have_file_sym = TRUE;
10243           flinfo->filesym_count += 1;
10244         }
10245       if (!have_file_sym)
10246         {
10247           /* In the absence of debug info, bfd_find_nearest_line uses
10248              FILE symbols to determine the source file for local
10249              function symbols.  Provide a FILE symbol here if input
10250              files lack such, so that their symbols won't be
10251              associated with a previous input file.  It's not the
10252              source file, but the best we can do.  */
10253           have_file_sym = TRUE;
10254           flinfo->filesym_count += 1;
10255           memset (&osym, 0, sizeof (osym));
10256           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10257           osym.st_shndx = SHN_ABS;
10258           if (!elf_link_output_symstrtab (flinfo,
10259                                           (input_bfd->lto_output ? NULL
10260                                            : input_bfd->filename),
10261                                           &osym, bfd_abs_section_ptr,
10262                                           NULL))
10263             return FALSE;
10264         }
10265
10266       osym = *isym;
10267
10268       /* Adjust the section index for the output file.  */
10269       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10270                                                          isec->output_section);
10271       if (osym.st_shndx == SHN_BAD)
10272         return FALSE;
10273
10274       /* ELF symbols in relocatable files are section relative, but
10275          in executable files they are virtual addresses.  Note that
10276          this code assumes that all ELF sections have an associated
10277          BFD section with a reasonable value for output_offset; below
10278          we assume that they also have a reasonable value for
10279          output_section.  Any special sections must be set up to meet
10280          these requirements.  */
10281       osym.st_value += isec->output_offset;
10282       if (!bfd_link_relocatable (flinfo->info))
10283         {
10284           osym.st_value += isec->output_section->vma;
10285           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
10286             {
10287               /* STT_TLS symbols are relative to PT_TLS segment base.  */
10288               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
10289               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
10290             }
10291         }
10292
10293       indx = bfd_get_symcount (output_bfd);
10294       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
10295       if (ret == 0)
10296         return FALSE;
10297       else if (ret == 1)
10298         *pindex = indx;
10299     }
10300
10301   if (bed->s->arch_size == 32)
10302     {
10303       r_type_mask = 0xff;
10304       r_sym_shift = 8;
10305       address_size = 4;
10306     }
10307   else
10308     {
10309       r_type_mask = 0xffffffff;
10310       r_sym_shift = 32;
10311       address_size = 8;
10312     }
10313
10314   /* Relocate the contents of each section.  */
10315   sym_hashes = elf_sym_hashes (input_bfd);
10316   for (o = input_bfd->sections; o != NULL; o = o->next)
10317     {
10318       bfd_byte *contents;
10319
10320       if (! o->linker_mark)
10321         {
10322           /* This section was omitted from the link.  */
10323           continue;
10324         }
10325
10326       if (!flinfo->info->resolve_section_groups
10327           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
10328         {
10329           /* Deal with the group signature symbol.  */
10330           struct bfd_elf_section_data *sec_data = elf_section_data (o);
10331           unsigned long symndx = sec_data->this_hdr.sh_info;
10332           asection *osec = o->output_section;
10333
10334           BFD_ASSERT (bfd_link_relocatable (flinfo->info));
10335           if (symndx >= locsymcount
10336               || (elf_bad_symtab (input_bfd)
10337                   && flinfo->sections[symndx] == NULL))
10338             {
10339               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
10340               while (h->root.type == bfd_link_hash_indirect
10341                      || h->root.type == bfd_link_hash_warning)
10342                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
10343               /* Arrange for symbol to be output.  */
10344               h->indx = -2;
10345               elf_section_data (osec)->this_hdr.sh_info = -2;
10346             }
10347           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
10348             {
10349               /* We'll use the output section target_index.  */
10350               asection *sec = flinfo->sections[symndx]->output_section;
10351               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
10352             }
10353           else
10354             {
10355               if (flinfo->indices[symndx] == -1)
10356                 {
10357                   /* Otherwise output the local symbol now.  */
10358                   Elf_Internal_Sym sym = isymbuf[symndx];
10359                   asection *sec = flinfo->sections[symndx]->output_section;
10360                   const char *name;
10361                   long indx;
10362                   int ret;
10363
10364                   name = bfd_elf_string_from_elf_section (input_bfd,
10365                                                           symtab_hdr->sh_link,
10366                                                           sym.st_name);
10367                   if (name == NULL)
10368                     return FALSE;
10369
10370                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10371                                                                     sec);
10372                   if (sym.st_shndx == SHN_BAD)
10373                     return FALSE;
10374
10375                   sym.st_value += o->output_offset;
10376
10377                   indx = bfd_get_symcount (output_bfd);
10378                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
10379                                                    NULL);
10380                   if (ret == 0)
10381                     return FALSE;
10382                   else if (ret == 1)
10383                     flinfo->indices[symndx] = indx;
10384                   else
10385                     abort ();
10386                 }
10387               elf_section_data (osec)->this_hdr.sh_info
10388                 = flinfo->indices[symndx];
10389             }
10390         }
10391
10392       if ((o->flags & SEC_HAS_CONTENTS) == 0
10393           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
10394         continue;
10395
10396       if ((o->flags & SEC_LINKER_CREATED) != 0)
10397         {
10398           /* Section was created by _bfd_elf_link_create_dynamic_sections
10399              or somesuch.  */
10400           continue;
10401         }
10402
10403       /* Get the contents of the section.  They have been cached by a
10404          relaxation routine.  Note that o is a section in an input
10405          file, so the contents field will not have been set by any of
10406          the routines which work on output files.  */
10407       if (elf_section_data (o)->this_hdr.contents != NULL)
10408         {
10409           contents = elf_section_data (o)->this_hdr.contents;
10410           if (bed->caches_rawsize
10411               && o->rawsize != 0
10412               && o->rawsize < o->size)
10413             {
10414               memcpy (flinfo->contents, contents, o->rawsize);
10415               contents = flinfo->contents;
10416             }
10417         }
10418       else
10419         {
10420           contents = flinfo->contents;
10421           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
10422             return FALSE;
10423         }
10424
10425       if ((o->flags & SEC_RELOC) != 0)
10426         {
10427           Elf_Internal_Rela *internal_relocs;
10428           Elf_Internal_Rela *rel, *relend;
10429           int action_discarded;
10430           int ret;
10431
10432           /* Get the swapped relocs.  */
10433           internal_relocs
10434             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
10435                                          flinfo->internal_relocs, FALSE);
10436           if (internal_relocs == NULL
10437               && o->reloc_count > 0)
10438             return FALSE;
10439
10440           /* We need to reverse-copy input .ctors/.dtors sections if
10441              they are placed in .init_array/.finit_array for output.  */
10442           if (o->size > address_size
10443               && ((strncmp (o->name, ".ctors", 6) == 0
10444                    && strcmp (o->output_section->name,
10445                               ".init_array") == 0)
10446                   || (strncmp (o->name, ".dtors", 6) == 0
10447                       && strcmp (o->output_section->name,
10448                                  ".fini_array") == 0))
10449               && (o->name[6] == 0 || o->name[6] == '.'))
10450             {
10451               if (o->size * bed->s->int_rels_per_ext_rel
10452                   != o->reloc_count * address_size)
10453                 {
10454                   _bfd_error_handler
10455                     /* xgettext:c-format */
10456                     (_("error: %B: size of section %A is not "
10457                        "multiple of address size"),
10458                      input_bfd, o);
10459                   bfd_set_error (bfd_error_bad_value);
10460                   return FALSE;
10461                 }
10462               o->flags |= SEC_ELF_REVERSE_COPY;
10463             }
10464
10465           action_discarded = -1;
10466           if (!elf_section_ignore_discarded_relocs (o))
10467             action_discarded = (*bed->action_discarded) (o);
10468
10469           /* Run through the relocs evaluating complex reloc symbols and
10470              looking for relocs against symbols from discarded sections
10471              or section symbols from removed link-once sections.
10472              Complain about relocs against discarded sections.  Zero
10473              relocs against removed link-once sections.  */
10474
10475           rel = internal_relocs;
10476           relend = rel + o->reloc_count;
10477           for ( ; rel < relend; rel++)
10478             {
10479               unsigned long r_symndx = rel->r_info >> r_sym_shift;
10480               unsigned int s_type;
10481               asection **ps, *sec;
10482               struct elf_link_hash_entry *h = NULL;
10483               const char *sym_name;
10484
10485               if (r_symndx == STN_UNDEF)
10486                 continue;
10487
10488               if (r_symndx >= locsymcount
10489                   || (elf_bad_symtab (input_bfd)
10490                       && flinfo->sections[r_symndx] == NULL))
10491                 {
10492                   h = sym_hashes[r_symndx - extsymoff];
10493
10494                   /* Badly formatted input files can contain relocs that
10495                      reference non-existant symbols.  Check here so that
10496                      we do not seg fault.  */
10497                   if (h == NULL)
10498                     {
10499                       _bfd_error_handler
10500                         /* xgettext:c-format */
10501                         (_("error: %B contains a reloc (%#Lx) for section %A "
10502                            "that references a non-existent global symbol"),
10503                          input_bfd, rel->r_info, o);
10504                       bfd_set_error (bfd_error_bad_value);
10505                       return FALSE;
10506                     }
10507
10508                   while (h->root.type == bfd_link_hash_indirect
10509                          || h->root.type == bfd_link_hash_warning)
10510                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10511
10512                   s_type = h->type;
10513
10514                   /* If a plugin symbol is referenced from a non-IR file,
10515                      mark the symbol as undefined.  Note that the
10516                      linker may attach linker created dynamic sections
10517                      to the plugin bfd.  Symbols defined in linker
10518                      created sections are not plugin symbols.  */
10519                   if ((h->root.non_ir_ref_regular
10520                        || h->root.non_ir_ref_dynamic)
10521                       && (h->root.type == bfd_link_hash_defined
10522                           || h->root.type == bfd_link_hash_defweak)
10523                       && (h->root.u.def.section->flags
10524                           & SEC_LINKER_CREATED) == 0
10525                       && h->root.u.def.section->owner != NULL
10526                       && (h->root.u.def.section->owner->flags
10527                           & BFD_PLUGIN) != 0)
10528                     {
10529                       h->root.type = bfd_link_hash_undefined;
10530                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10531                     }
10532
10533                   ps = NULL;
10534                   if (h->root.type == bfd_link_hash_defined
10535                       || h->root.type == bfd_link_hash_defweak)
10536                     ps = &h->root.u.def.section;
10537
10538                   sym_name = h->root.root.string;
10539                 }
10540               else
10541                 {
10542                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10543
10544                   s_type = ELF_ST_TYPE (sym->st_info);
10545                   ps = &flinfo->sections[r_symndx];
10546                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10547                                                sym, *ps);
10548                 }
10549
10550               if ((s_type == STT_RELC || s_type == STT_SRELC)
10551                   && !bfd_link_relocatable (flinfo->info))
10552                 {
10553                   bfd_vma val;
10554                   bfd_vma dot = (rel->r_offset
10555                                  + o->output_offset + o->output_section->vma);
10556 #ifdef DEBUG
10557                   printf ("Encountered a complex symbol!");
10558                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10559                           input_bfd->filename, o->name,
10560                           (long) (rel - internal_relocs));
10561                   printf (" symbol: idx  %8.8lx, name %s\n",
10562                           r_symndx, sym_name);
10563                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10564                           (unsigned long) rel->r_info,
10565                           (unsigned long) rel->r_offset);
10566 #endif
10567                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10568                                     isymbuf, locsymcount, s_type == STT_SRELC))
10569                     return FALSE;
10570
10571                   /* Symbol evaluated OK.  Update to absolute value.  */
10572                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10573                                     r_symndx, val);
10574                   continue;
10575                 }
10576
10577               if (action_discarded != -1 && ps != NULL)
10578                 {
10579                   /* Complain if the definition comes from a
10580                      discarded section.  */
10581                   if ((sec = *ps) != NULL && discarded_section (sec))
10582                     {
10583                       BFD_ASSERT (r_symndx != STN_UNDEF);
10584                       if (action_discarded & COMPLAIN)
10585                         (*flinfo->info->callbacks->einfo)
10586                           /* xgettext:c-format */
10587                           (_("%X`%s' referenced in section `%A' of %B: "
10588                              "defined in discarded section `%A' of %B\n"),
10589                            sym_name, o, input_bfd, sec, sec->owner);
10590
10591                       /* Try to do the best we can to support buggy old
10592                          versions of gcc.  Pretend that the symbol is
10593                          really defined in the kept linkonce section.
10594                          FIXME: This is quite broken.  Modifying the
10595                          symbol here means we will be changing all later
10596                          uses of the symbol, not just in this section.  */
10597                       if (action_discarded & PRETEND)
10598                         {
10599                           asection *kept;
10600
10601                           kept = _bfd_elf_check_kept_section (sec,
10602                                                               flinfo->info);
10603                           if (kept != NULL)
10604                             {
10605                               *ps = kept;
10606                               continue;
10607                             }
10608                         }
10609                     }
10610                 }
10611             }
10612
10613           /* Relocate the section by invoking a back end routine.
10614
10615              The back end routine is responsible for adjusting the
10616              section contents as necessary, and (if using Rela relocs
10617              and generating a relocatable output file) adjusting the
10618              reloc addend as necessary.
10619
10620              The back end routine does not have to worry about setting
10621              the reloc address or the reloc symbol index.
10622
10623              The back end routine is given a pointer to the swapped in
10624              internal symbols, and can access the hash table entries
10625              for the external symbols via elf_sym_hashes (input_bfd).
10626
10627              When generating relocatable output, the back end routine
10628              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10629              output symbol is going to be a section symbol
10630              corresponding to the output section, which will require
10631              the addend to be adjusted.  */
10632
10633           ret = (*relocate_section) (output_bfd, flinfo->info,
10634                                      input_bfd, o, contents,
10635                                      internal_relocs,
10636                                      isymbuf,
10637                                      flinfo->sections);
10638           if (!ret)
10639             return FALSE;
10640
10641           if (ret == 2
10642               || bfd_link_relocatable (flinfo->info)
10643               || flinfo->info->emitrelocations)
10644             {
10645               Elf_Internal_Rela *irela;
10646               Elf_Internal_Rela *irelaend, *irelamid;
10647               bfd_vma last_offset;
10648               struct elf_link_hash_entry **rel_hash;
10649               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10650               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10651               unsigned int next_erel;
10652               bfd_boolean rela_normal;
10653               struct bfd_elf_section_data *esdi, *esdo;
10654
10655               esdi = elf_section_data (o);
10656               esdo = elf_section_data (o->output_section);
10657               rela_normal = FALSE;
10658
10659               /* Adjust the reloc addresses and symbol indices.  */
10660
10661               irela = internal_relocs;
10662               irelaend = irela + o->reloc_count;
10663               rel_hash = esdo->rel.hashes + esdo->rel.count;
10664               /* We start processing the REL relocs, if any.  When we reach
10665                  IRELAMID in the loop, we switch to the RELA relocs.  */
10666               irelamid = irela;
10667               if (esdi->rel.hdr != NULL)
10668                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10669                              * bed->s->int_rels_per_ext_rel);
10670               rel_hash_list = rel_hash;
10671               rela_hash_list = NULL;
10672               last_offset = o->output_offset;
10673               if (!bfd_link_relocatable (flinfo->info))
10674                 last_offset += o->output_section->vma;
10675               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10676                 {
10677                   unsigned long r_symndx;
10678                   asection *sec;
10679                   Elf_Internal_Sym sym;
10680
10681                   if (next_erel == bed->s->int_rels_per_ext_rel)
10682                     {
10683                       rel_hash++;
10684                       next_erel = 0;
10685                     }
10686
10687                   if (irela == irelamid)
10688                     {
10689                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10690                       rela_hash_list = rel_hash;
10691                       rela_normal = bed->rela_normal;
10692                     }
10693
10694                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10695                                                              flinfo->info, o,
10696                                                              irela->r_offset);
10697                   if (irela->r_offset >= (bfd_vma) -2)
10698                     {
10699                       /* This is a reloc for a deleted entry or somesuch.
10700                          Turn it into an R_*_NONE reloc, at the same
10701                          offset as the last reloc.  elf_eh_frame.c and
10702                          bfd_elf_discard_info rely on reloc offsets
10703                          being ordered.  */
10704                       irela->r_offset = last_offset;
10705                       irela->r_info = 0;
10706                       irela->r_addend = 0;
10707                       continue;
10708                     }
10709
10710                   irela->r_offset += o->output_offset;
10711
10712                   /* Relocs in an executable have to be virtual addresses.  */
10713                   if (!bfd_link_relocatable (flinfo->info))
10714                     irela->r_offset += o->output_section->vma;
10715
10716                   last_offset = irela->r_offset;
10717
10718                   r_symndx = irela->r_info >> r_sym_shift;
10719                   if (r_symndx == STN_UNDEF)
10720                     continue;
10721
10722                   if (r_symndx >= locsymcount
10723                       || (elf_bad_symtab (input_bfd)
10724                           && flinfo->sections[r_symndx] == NULL))
10725                     {
10726                       struct elf_link_hash_entry *rh;
10727                       unsigned long indx;
10728
10729                       /* This is a reloc against a global symbol.  We
10730                          have not yet output all the local symbols, so
10731                          we do not know the symbol index of any global
10732                          symbol.  We set the rel_hash entry for this
10733                          reloc to point to the global hash table entry
10734                          for this symbol.  The symbol index is then
10735                          set at the end of bfd_elf_final_link.  */
10736                       indx = r_symndx - extsymoff;
10737                       rh = elf_sym_hashes (input_bfd)[indx];
10738                       while (rh->root.type == bfd_link_hash_indirect
10739                              || rh->root.type == bfd_link_hash_warning)
10740                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10741
10742                       /* Setting the index to -2 tells
10743                          elf_link_output_extsym that this symbol is
10744                          used by a reloc.  */
10745                       BFD_ASSERT (rh->indx < 0);
10746                       rh->indx = -2;
10747                       *rel_hash = rh;
10748
10749                       continue;
10750                     }
10751
10752                   /* This is a reloc against a local symbol.  */
10753
10754                   *rel_hash = NULL;
10755                   sym = isymbuf[r_symndx];
10756                   sec = flinfo->sections[r_symndx];
10757                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10758                     {
10759                       /* I suppose the backend ought to fill in the
10760                          section of any STT_SECTION symbol against a
10761                          processor specific section.  */
10762                       r_symndx = STN_UNDEF;
10763                       if (bfd_is_abs_section (sec))
10764                         ;
10765                       else if (sec == NULL || sec->owner == NULL)
10766                         {
10767                           bfd_set_error (bfd_error_bad_value);
10768                           return FALSE;
10769                         }
10770                       else
10771                         {
10772                           asection *osec = sec->output_section;
10773
10774                           /* If we have discarded a section, the output
10775                              section will be the absolute section.  In
10776                              case of discarded SEC_MERGE sections, use
10777                              the kept section.  relocate_section should
10778                              have already handled discarded linkonce
10779                              sections.  */
10780                           if (bfd_is_abs_section (osec)
10781                               && sec->kept_section != NULL
10782                               && sec->kept_section->output_section != NULL)
10783                             {
10784                               osec = sec->kept_section->output_section;
10785                               irela->r_addend -= osec->vma;
10786                             }
10787
10788                           if (!bfd_is_abs_section (osec))
10789                             {
10790                               r_symndx = osec->target_index;
10791                               if (r_symndx == STN_UNDEF)
10792                                 {
10793                                   irela->r_addend += osec->vma;
10794                                   osec = _bfd_nearby_section (output_bfd, osec,
10795                                                               osec->vma);
10796                                   irela->r_addend -= osec->vma;
10797                                   r_symndx = osec->target_index;
10798                                 }
10799                             }
10800                         }
10801
10802                       /* Adjust the addend according to where the
10803                          section winds up in the output section.  */
10804                       if (rela_normal)
10805                         irela->r_addend += sec->output_offset;
10806                     }
10807                   else
10808                     {
10809                       if (flinfo->indices[r_symndx] == -1)
10810                         {
10811                           unsigned long shlink;
10812                           const char *name;
10813                           asection *osec;
10814                           long indx;
10815
10816                           if (flinfo->info->strip == strip_all)
10817                             {
10818                               /* You can't do ld -r -s.  */
10819                               bfd_set_error (bfd_error_invalid_operation);
10820                               return FALSE;
10821                             }
10822
10823                           /* This symbol was skipped earlier, but
10824                              since it is needed by a reloc, we
10825                              must output it now.  */
10826                           shlink = symtab_hdr->sh_link;
10827                           name = (bfd_elf_string_from_elf_section
10828                                   (input_bfd, shlink, sym.st_name));
10829                           if (name == NULL)
10830                             return FALSE;
10831
10832                           osec = sec->output_section;
10833                           sym.st_shndx =
10834                             _bfd_elf_section_from_bfd_section (output_bfd,
10835                                                                osec);
10836                           if (sym.st_shndx == SHN_BAD)
10837                             return FALSE;
10838
10839                           sym.st_value += sec->output_offset;
10840                           if (!bfd_link_relocatable (flinfo->info))
10841                             {
10842                               sym.st_value += osec->vma;
10843                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10844                                 {
10845                                   /* STT_TLS symbols are relative to PT_TLS
10846                                      segment base.  */
10847                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10848                                               ->tls_sec != NULL);
10849                                   sym.st_value -= (elf_hash_table (flinfo->info)
10850                                                    ->tls_sec->vma);
10851                                 }
10852                             }
10853
10854                           indx = bfd_get_symcount (output_bfd);
10855                           ret = elf_link_output_symstrtab (flinfo, name,
10856                                                            &sym, sec,
10857                                                            NULL);
10858                           if (ret == 0)
10859                             return FALSE;
10860                           else if (ret == 1)
10861                             flinfo->indices[r_symndx] = indx;
10862                           else
10863                             abort ();
10864                         }
10865
10866                       r_symndx = flinfo->indices[r_symndx];
10867                     }
10868
10869                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10870                                    | (irela->r_info & r_type_mask));
10871                 }
10872
10873               /* Swap out the relocs.  */
10874               input_rel_hdr = esdi->rel.hdr;
10875               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10876                 {
10877                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10878                                                      input_rel_hdr,
10879                                                      internal_relocs,
10880                                                      rel_hash_list))
10881                     return FALSE;
10882                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10883                                       * bed->s->int_rels_per_ext_rel);
10884                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10885                 }
10886
10887               input_rela_hdr = esdi->rela.hdr;
10888               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10889                 {
10890                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10891                                                      input_rela_hdr,
10892                                                      internal_relocs,
10893                                                      rela_hash_list))
10894                     return FALSE;
10895                 }
10896             }
10897         }
10898
10899       /* Write out the modified section contents.  */
10900       if (bed->elf_backend_write_section
10901           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10902                                                 contents))
10903         {
10904           /* Section written out.  */
10905         }
10906       else switch (o->sec_info_type)
10907         {
10908         case SEC_INFO_TYPE_STABS:
10909           if (! (_bfd_write_section_stabs
10910                  (output_bfd,
10911                   &elf_hash_table (flinfo->info)->stab_info,
10912                   o, &elf_section_data (o)->sec_info, contents)))
10913             return FALSE;
10914           break;
10915         case SEC_INFO_TYPE_MERGE:
10916           if (! _bfd_write_merged_section (output_bfd, o,
10917                                            elf_section_data (o)->sec_info))
10918             return FALSE;
10919           break;
10920         case SEC_INFO_TYPE_EH_FRAME:
10921           {
10922             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
10923                                                    o, contents))
10924               return FALSE;
10925           }
10926           break;
10927         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10928           {
10929             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
10930                                                          flinfo->info,
10931                                                          o, contents))
10932               return FALSE;
10933           }
10934           break;
10935         default:
10936           {
10937             if (! (o->flags & SEC_EXCLUDE))
10938               {
10939                 file_ptr offset = (file_ptr) o->output_offset;
10940                 bfd_size_type todo = o->size;
10941
10942                 offset *= bfd_octets_per_byte (output_bfd);
10943
10944                 if ((o->flags & SEC_ELF_REVERSE_COPY))
10945                   {
10946                     /* Reverse-copy input section to output.  */
10947                     do
10948                       {
10949                         todo -= address_size;
10950                         if (! bfd_set_section_contents (output_bfd,
10951                                                         o->output_section,
10952                                                         contents + todo,
10953                                                         offset,
10954                                                         address_size))
10955                           return FALSE;
10956                         if (todo == 0)
10957                           break;
10958                         offset += address_size;
10959                       }
10960                     while (1);
10961                   }
10962                 else if (! bfd_set_section_contents (output_bfd,
10963                                                      o->output_section,
10964                                                      contents,
10965                                                      offset, todo))
10966                   return FALSE;
10967               }
10968           }
10969           break;
10970         }
10971     }
10972
10973   return TRUE;
10974 }
10975
10976 /* Generate a reloc when linking an ELF file.  This is a reloc
10977    requested by the linker, and does not come from any input file.  This
10978    is used to build constructor and destructor tables when linking
10979    with -Ur.  */
10980
10981 static bfd_boolean
10982 elf_reloc_link_order (bfd *output_bfd,
10983                       struct bfd_link_info *info,
10984                       asection *output_section,
10985                       struct bfd_link_order *link_order)
10986 {
10987   reloc_howto_type *howto;
10988   long indx;
10989   bfd_vma offset;
10990   bfd_vma addend;
10991   struct bfd_elf_section_reloc_data *reldata;
10992   struct elf_link_hash_entry **rel_hash_ptr;
10993   Elf_Internal_Shdr *rel_hdr;
10994   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
10995   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
10996   bfd_byte *erel;
10997   unsigned int i;
10998   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
10999
11000   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
11001   if (howto == NULL)
11002     {
11003       bfd_set_error (bfd_error_bad_value);
11004       return FALSE;
11005     }
11006
11007   addend = link_order->u.reloc.p->addend;
11008
11009   if (esdo->rel.hdr)
11010     reldata = &esdo->rel;
11011   else if (esdo->rela.hdr)
11012     reldata = &esdo->rela;
11013   else
11014     {
11015       reldata = NULL;
11016       BFD_ASSERT (0);
11017     }
11018
11019   /* Figure out the symbol index.  */
11020   rel_hash_ptr = reldata->hashes + reldata->count;
11021   if (link_order->type == bfd_section_reloc_link_order)
11022     {
11023       indx = link_order->u.reloc.p->u.section->target_index;
11024       BFD_ASSERT (indx != 0);
11025       *rel_hash_ptr = NULL;
11026     }
11027   else
11028     {
11029       struct elf_link_hash_entry *h;
11030
11031       /* Treat a reloc against a defined symbol as though it were
11032          actually against the section.  */
11033       h = ((struct elf_link_hash_entry *)
11034            bfd_wrapped_link_hash_lookup (output_bfd, info,
11035                                          link_order->u.reloc.p->u.name,
11036                                          FALSE, FALSE, TRUE));
11037       if (h != NULL
11038           && (h->root.type == bfd_link_hash_defined
11039               || h->root.type == bfd_link_hash_defweak))
11040         {
11041           asection *section;
11042
11043           section = h->root.u.def.section;
11044           indx = section->output_section->target_index;
11045           *rel_hash_ptr = NULL;
11046           /* It seems that we ought to add the symbol value to the
11047              addend here, but in practice it has already been added
11048              because it was passed to constructor_callback.  */
11049           addend += section->output_section->vma + section->output_offset;
11050         }
11051       else if (h != NULL)
11052         {
11053           /* Setting the index to -2 tells elf_link_output_extsym that
11054              this symbol is used by a reloc.  */
11055           h->indx = -2;
11056           *rel_hash_ptr = h;
11057           indx = 0;
11058         }
11059       else
11060         {
11061           (*info->callbacks->unattached_reloc)
11062             (info, link_order->u.reloc.p->u.name, NULL, NULL, 0);
11063           indx = 0;
11064         }
11065     }
11066
11067   /* If this is an inplace reloc, we must write the addend into the
11068      object file.  */
11069   if (howto->partial_inplace && addend != 0)
11070     {
11071       bfd_size_type size;
11072       bfd_reloc_status_type rstat;
11073       bfd_byte *buf;
11074       bfd_boolean ok;
11075       const char *sym_name;
11076
11077       size = (bfd_size_type) bfd_get_reloc_size (howto);
11078       buf = (bfd_byte *) bfd_zmalloc (size);
11079       if (buf == NULL && size != 0)
11080         return FALSE;
11081       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
11082       switch (rstat)
11083         {
11084         case bfd_reloc_ok:
11085           break;
11086
11087         default:
11088         case bfd_reloc_outofrange:
11089           abort ();
11090
11091         case bfd_reloc_overflow:
11092           if (link_order->type == bfd_section_reloc_link_order)
11093             sym_name = bfd_section_name (output_bfd,
11094                                          link_order->u.reloc.p->u.section);
11095           else
11096             sym_name = link_order->u.reloc.p->u.name;
11097           (*info->callbacks->reloc_overflow) (info, NULL, sym_name,
11098                                               howto->name, addend, NULL, NULL,
11099                                               (bfd_vma) 0);
11100           break;
11101         }
11102
11103       ok = bfd_set_section_contents (output_bfd, output_section, buf,
11104                                      link_order->offset
11105                                      * bfd_octets_per_byte (output_bfd),
11106                                      size);
11107       free (buf);
11108       if (! ok)
11109         return FALSE;
11110     }
11111
11112   /* The address of a reloc is relative to the section in a
11113      relocatable file, and is a virtual address in an executable
11114      file.  */
11115   offset = link_order->offset;
11116   if (! bfd_link_relocatable (info))
11117     offset += output_section->vma;
11118
11119   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
11120     {
11121       irel[i].r_offset = offset;
11122       irel[i].r_info = 0;
11123       irel[i].r_addend = 0;
11124     }
11125   if (bed->s->arch_size == 32)
11126     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
11127   else
11128     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
11129
11130   rel_hdr = reldata->hdr;
11131   erel = rel_hdr->contents;
11132   if (rel_hdr->sh_type == SHT_REL)
11133     {
11134       erel += reldata->count * bed->s->sizeof_rel;
11135       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
11136     }
11137   else
11138     {
11139       irel[0].r_addend = addend;
11140       erel += reldata->count * bed->s->sizeof_rela;
11141       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
11142     }
11143
11144   ++reldata->count;
11145
11146   return TRUE;
11147 }
11148
11149
11150 /* Get the output vma of the section pointed to by the sh_link field.  */
11151
11152 static bfd_vma
11153 elf_get_linked_section_vma (struct bfd_link_order *p)
11154 {
11155   Elf_Internal_Shdr **elf_shdrp;
11156   asection *s;
11157   int elfsec;
11158
11159   s = p->u.indirect.section;
11160   elf_shdrp = elf_elfsections (s->owner);
11161   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
11162   elfsec = elf_shdrp[elfsec]->sh_link;
11163   /* PR 290:
11164      The Intel C compiler generates SHT_IA_64_UNWIND with
11165      SHF_LINK_ORDER.  But it doesn't set the sh_link or
11166      sh_info fields.  Hence we could get the situation
11167      where elfsec is 0.  */
11168   if (elfsec == 0)
11169     {
11170       const struct elf_backend_data *bed
11171         = get_elf_backend_data (s->owner);
11172       if (bed->link_order_error_handler)
11173         bed->link_order_error_handler
11174           /* xgettext:c-format */
11175           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
11176       return 0;
11177     }
11178   else
11179     {
11180       s = elf_shdrp[elfsec]->bfd_section;
11181       return s->output_section->vma + s->output_offset;
11182     }
11183 }
11184
11185
11186 /* Compare two sections based on the locations of the sections they are
11187    linked to.  Used by elf_fixup_link_order.  */
11188
11189 static int
11190 compare_link_order (const void * a, const void * b)
11191 {
11192   bfd_vma apos;
11193   bfd_vma bpos;
11194
11195   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
11196   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
11197   if (apos < bpos)
11198     return -1;
11199   return apos > bpos;
11200 }
11201
11202
11203 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
11204    order as their linked sections.  Returns false if this could not be done
11205    because an output section includes both ordered and unordered
11206    sections.  Ideally we'd do this in the linker proper.  */
11207
11208 static bfd_boolean
11209 elf_fixup_link_order (bfd *abfd, asection *o)
11210 {
11211   int seen_linkorder;
11212   int seen_other;
11213   int n;
11214   struct bfd_link_order *p;
11215   bfd *sub;
11216   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11217   unsigned elfsec;
11218   struct bfd_link_order **sections;
11219   asection *s, *other_sec, *linkorder_sec;
11220   bfd_vma offset;
11221
11222   other_sec = NULL;
11223   linkorder_sec = NULL;
11224   seen_other = 0;
11225   seen_linkorder = 0;
11226   for (p = o->map_head.link_order; p != NULL; p = p->next)
11227     {
11228       if (p->type == bfd_indirect_link_order)
11229         {
11230           s = p->u.indirect.section;
11231           sub = s->owner;
11232           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11233               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
11234               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
11235               && elfsec < elf_numsections (sub)
11236               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
11237               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
11238             {
11239               seen_linkorder++;
11240               linkorder_sec = s;
11241             }
11242           else
11243             {
11244               seen_other++;
11245               other_sec = s;
11246             }
11247         }
11248       else
11249         seen_other++;
11250
11251       if (seen_other && seen_linkorder)
11252         {
11253           if (other_sec && linkorder_sec)
11254             _bfd_error_handler
11255               /* xgettext:c-format */
11256               (_("%A has both ordered [`%A' in %B] "
11257                  "and unordered [`%A' in %B] sections"),
11258                o, linkorder_sec, linkorder_sec->owner,
11259                other_sec, other_sec->owner);
11260           else
11261             _bfd_error_handler
11262               (_("%A has both ordered and unordered sections"), o);
11263           bfd_set_error (bfd_error_bad_value);
11264           return FALSE;
11265         }
11266     }
11267
11268   if (!seen_linkorder)
11269     return TRUE;
11270
11271   sections = (struct bfd_link_order **)
11272     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
11273   if (sections == NULL)
11274     return FALSE;
11275   seen_linkorder = 0;
11276
11277   for (p = o->map_head.link_order; p != NULL; p = p->next)
11278     {
11279       sections[seen_linkorder++] = p;
11280     }
11281   /* Sort the input sections in the order of their linked section.  */
11282   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
11283          compare_link_order);
11284
11285   /* Change the offsets of the sections.  */
11286   offset = 0;
11287   for (n = 0; n < seen_linkorder; n++)
11288     {
11289       s = sections[n]->u.indirect.section;
11290       offset &= ~(bfd_vma) 0 << s->alignment_power;
11291       s->output_offset = offset / bfd_octets_per_byte (abfd);
11292       sections[n]->offset = offset;
11293       offset += sections[n]->size;
11294     }
11295
11296   free (sections);
11297   return TRUE;
11298 }
11299
11300 /* Generate an import library in INFO->implib_bfd from symbols in ABFD.
11301    Returns TRUE upon success, FALSE otherwise.  */
11302
11303 static bfd_boolean
11304 elf_output_implib (bfd *abfd, struct bfd_link_info *info)
11305 {
11306   bfd_boolean ret = FALSE;
11307   bfd *implib_bfd;
11308   const struct elf_backend_data *bed;
11309   flagword flags;
11310   enum bfd_architecture arch;
11311   unsigned int mach;
11312   asymbol **sympp = NULL;
11313   long symsize;
11314   long symcount;
11315   long src_count;
11316   elf_symbol_type *osymbuf;
11317
11318   implib_bfd = info->out_implib_bfd;
11319   bed = get_elf_backend_data (abfd);
11320
11321   if (!bfd_set_format (implib_bfd, bfd_object))
11322     return FALSE;
11323
11324   /* Use flag from executable but make it a relocatable object.  */
11325   flags = bfd_get_file_flags (abfd);
11326   flags &= ~HAS_RELOC;
11327   if (!bfd_set_start_address (implib_bfd, 0)
11328       || !bfd_set_file_flags (implib_bfd, flags & ~EXEC_P))
11329     return FALSE;
11330
11331   /* Copy architecture of output file to import library file.  */
11332   arch = bfd_get_arch (abfd);
11333   mach = bfd_get_mach (abfd);
11334   if (!bfd_set_arch_mach (implib_bfd, arch, mach)
11335       && (abfd->target_defaulted
11336           || bfd_get_arch (abfd) != bfd_get_arch (implib_bfd)))
11337     return FALSE;
11338
11339   /* Get symbol table size.  */
11340   symsize = bfd_get_symtab_upper_bound (abfd);
11341   if (symsize < 0)
11342     return FALSE;
11343
11344   /* Read in the symbol table.  */
11345   sympp = (asymbol **) xmalloc (symsize);
11346   symcount = bfd_canonicalize_symtab (abfd, sympp);
11347   if (symcount < 0)
11348     goto free_sym_buf;
11349
11350   /* Allow the BFD backend to copy any private header data it
11351      understands from the output BFD to the import library BFD.  */
11352   if (! bfd_copy_private_header_data (abfd, implib_bfd))
11353     goto free_sym_buf;
11354
11355   /* Filter symbols to appear in the import library.  */
11356   if (bed->elf_backend_filter_implib_symbols)
11357     symcount = bed->elf_backend_filter_implib_symbols (abfd, info, sympp,
11358                                                        symcount);
11359   else
11360     symcount = _bfd_elf_filter_global_symbols (abfd, info, sympp, symcount);
11361   if (symcount == 0)
11362     {
11363       bfd_set_error (bfd_error_no_symbols);
11364       _bfd_error_handler (_("%B: no symbol found for import library"),
11365                           implib_bfd);
11366       goto free_sym_buf;
11367     }
11368
11369
11370   /* Make symbols absolute.  */
11371   osymbuf = (elf_symbol_type *) bfd_alloc2 (implib_bfd, symcount,
11372                                             sizeof (*osymbuf));
11373   for (src_count = 0; src_count < symcount; src_count++)
11374     {
11375       memcpy (&osymbuf[src_count], (elf_symbol_type *) sympp[src_count],
11376               sizeof (*osymbuf));
11377       osymbuf[src_count].symbol.section = bfd_abs_section_ptr;
11378       osymbuf[src_count].internal_elf_sym.st_shndx = SHN_ABS;
11379       osymbuf[src_count].symbol.value += sympp[src_count]->section->vma;
11380       osymbuf[src_count].internal_elf_sym.st_value =
11381         osymbuf[src_count].symbol.value;
11382       sympp[src_count] = &osymbuf[src_count].symbol;
11383     }
11384
11385   bfd_set_symtab (implib_bfd, sympp, symcount);
11386
11387   /* Allow the BFD backend to copy any private data it understands
11388      from the output BFD to the import library BFD.  This is done last
11389      to permit the routine to look at the filtered symbol table.  */
11390   if (! bfd_copy_private_bfd_data (abfd, implib_bfd))
11391     goto free_sym_buf;
11392
11393   if (!bfd_close (implib_bfd))
11394     goto free_sym_buf;
11395
11396   ret = TRUE;
11397
11398 free_sym_buf:
11399   free (sympp);
11400   return ret;
11401 }
11402
11403 static void
11404 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
11405 {
11406   asection *o;
11407
11408   if (flinfo->symstrtab != NULL)
11409     _bfd_elf_strtab_free (flinfo->symstrtab);
11410   if (flinfo->contents != NULL)
11411     free (flinfo->contents);
11412   if (flinfo->external_relocs != NULL)
11413     free (flinfo->external_relocs);
11414   if (flinfo->internal_relocs != NULL)
11415     free (flinfo->internal_relocs);
11416   if (flinfo->external_syms != NULL)
11417     free (flinfo->external_syms);
11418   if (flinfo->locsym_shndx != NULL)
11419     free (flinfo->locsym_shndx);
11420   if (flinfo->internal_syms != NULL)
11421     free (flinfo->internal_syms);
11422   if (flinfo->indices != NULL)
11423     free (flinfo->indices);
11424   if (flinfo->sections != NULL)
11425     free (flinfo->sections);
11426   if (flinfo->symshndxbuf != NULL)
11427     free (flinfo->symshndxbuf);
11428   for (o = obfd->sections; o != NULL; o = o->next)
11429     {
11430       struct bfd_elf_section_data *esdo = elf_section_data (o);
11431       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11432         free (esdo->rel.hashes);
11433       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11434         free (esdo->rela.hashes);
11435     }
11436 }
11437
11438 /* Do the final step of an ELF link.  */
11439
11440 bfd_boolean
11441 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
11442 {
11443   bfd_boolean dynamic;
11444   bfd_boolean emit_relocs;
11445   bfd *dynobj;
11446   struct elf_final_link_info flinfo;
11447   asection *o;
11448   struct bfd_link_order *p;
11449   bfd *sub;
11450   bfd_size_type max_contents_size;
11451   bfd_size_type max_external_reloc_size;
11452   bfd_size_type max_internal_reloc_count;
11453   bfd_size_type max_sym_count;
11454   bfd_size_type max_sym_shndx_count;
11455   Elf_Internal_Sym elfsym;
11456   unsigned int i;
11457   Elf_Internal_Shdr *symtab_hdr;
11458   Elf_Internal_Shdr *symtab_shndx_hdr;
11459   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11460   struct elf_outext_info eoinfo;
11461   bfd_boolean merged;
11462   size_t relativecount = 0;
11463   asection *reldyn = 0;
11464   bfd_size_type amt;
11465   asection *attr_section = NULL;
11466   bfd_vma attr_size = 0;
11467   const char *std_attrs_section;
11468   struct elf_link_hash_table *htab = elf_hash_table (info);
11469
11470   if (!is_elf_hash_table (htab))
11471     return FALSE;
11472
11473   if (bfd_link_pic (info))
11474     abfd->flags |= DYNAMIC;
11475
11476   dynamic = htab->dynamic_sections_created;
11477   dynobj = htab->dynobj;
11478
11479   emit_relocs = (bfd_link_relocatable (info)
11480                  || info->emitrelocations);
11481
11482   flinfo.info = info;
11483   flinfo.output_bfd = abfd;
11484   flinfo.symstrtab = _bfd_elf_strtab_init ();
11485   if (flinfo.symstrtab == NULL)
11486     return FALSE;
11487
11488   if (! dynamic)
11489     {
11490       flinfo.hash_sec = NULL;
11491       flinfo.symver_sec = NULL;
11492     }
11493   else
11494     {
11495       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
11496       /* Note that dynsym_sec can be NULL (on VMS).  */
11497       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
11498       /* Note that it is OK if symver_sec is NULL.  */
11499     }
11500
11501   flinfo.contents = NULL;
11502   flinfo.external_relocs = NULL;
11503   flinfo.internal_relocs = NULL;
11504   flinfo.external_syms = NULL;
11505   flinfo.locsym_shndx = NULL;
11506   flinfo.internal_syms = NULL;
11507   flinfo.indices = NULL;
11508   flinfo.sections = NULL;
11509   flinfo.symshndxbuf = NULL;
11510   flinfo.filesym_count = 0;
11511
11512   /* The object attributes have been merged.  Remove the input
11513      sections from the link, and set the contents of the output
11514      secton.  */
11515   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
11516   for (o = abfd->sections; o != NULL; o = o->next)
11517     {
11518       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
11519           || strcmp (o->name, ".gnu.attributes") == 0)
11520         {
11521           for (p = o->map_head.link_order; p != NULL; p = p->next)
11522             {
11523               asection *input_section;
11524
11525               if (p->type != bfd_indirect_link_order)
11526                 continue;
11527               input_section = p->u.indirect.section;
11528               /* Hack: reset the SEC_HAS_CONTENTS flag so that
11529                  elf_link_input_bfd ignores this section.  */
11530               input_section->flags &= ~SEC_HAS_CONTENTS;
11531             }
11532
11533           attr_size = bfd_elf_obj_attr_size (abfd);
11534           if (attr_size)
11535             {
11536               bfd_set_section_size (abfd, o, attr_size);
11537               attr_section = o;
11538               /* Skip this section later on.  */
11539               o->map_head.link_order = NULL;
11540             }
11541           else
11542             o->flags |= SEC_EXCLUDE;
11543         }
11544     }
11545
11546   /* Count up the number of relocations we will output for each output
11547      section, so that we know the sizes of the reloc sections.  We
11548      also figure out some maximum sizes.  */
11549   max_contents_size = 0;
11550   max_external_reloc_size = 0;
11551   max_internal_reloc_count = 0;
11552   max_sym_count = 0;
11553   max_sym_shndx_count = 0;
11554   merged = FALSE;
11555   for (o = abfd->sections; o != NULL; o = o->next)
11556     {
11557       struct bfd_elf_section_data *esdo = elf_section_data (o);
11558       o->reloc_count = 0;
11559
11560       for (p = o->map_head.link_order; p != NULL; p = p->next)
11561         {
11562           unsigned int reloc_count = 0;
11563           unsigned int additional_reloc_count = 0;
11564           struct bfd_elf_section_data *esdi = NULL;
11565
11566           if (p->type == bfd_section_reloc_link_order
11567               || p->type == bfd_symbol_reloc_link_order)
11568             reloc_count = 1;
11569           else if (p->type == bfd_indirect_link_order)
11570             {
11571               asection *sec;
11572
11573               sec = p->u.indirect.section;
11574
11575               /* Mark all sections which are to be included in the
11576                  link.  This will normally be every section.  We need
11577                  to do this so that we can identify any sections which
11578                  the linker has decided to not include.  */
11579               sec->linker_mark = TRUE;
11580
11581               if (sec->flags & SEC_MERGE)
11582                 merged = TRUE;
11583
11584               if (sec->rawsize > max_contents_size)
11585                 max_contents_size = sec->rawsize;
11586               if (sec->size > max_contents_size)
11587                 max_contents_size = sec->size;
11588
11589               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
11590                   && (sec->owner->flags & DYNAMIC) == 0)
11591                 {
11592                   size_t sym_count;
11593
11594                   /* We are interested in just local symbols, not all
11595                      symbols.  */
11596                   if (elf_bad_symtab (sec->owner))
11597                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
11598                                  / bed->s->sizeof_sym);
11599                   else
11600                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
11601
11602                   if (sym_count > max_sym_count)
11603                     max_sym_count = sym_count;
11604
11605                   if (sym_count > max_sym_shndx_count
11606                       && elf_symtab_shndx_list (sec->owner) != NULL)
11607                     max_sym_shndx_count = sym_count;
11608
11609                   if (esdo->this_hdr.sh_type == SHT_REL
11610                       || esdo->this_hdr.sh_type == SHT_RELA)
11611                     /* Some backends use reloc_count in relocation sections
11612                        to count particular types of relocs.  Of course,
11613                        reloc sections themselves can't have relocations.  */
11614                     ;
11615                   else if (emit_relocs)
11616                     {
11617                       reloc_count = sec->reloc_count;
11618                       if (bed->elf_backend_count_additional_relocs)
11619                         {
11620                           int c;
11621                           c = (*bed->elf_backend_count_additional_relocs) (sec);
11622                           additional_reloc_count += c;
11623                         }
11624                     }
11625                   else if (bed->elf_backend_count_relocs)
11626                     reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
11627
11628                   esdi = elf_section_data (sec);
11629
11630                   if ((sec->flags & SEC_RELOC) != 0)
11631                     {
11632                       size_t ext_size = 0;
11633
11634                       if (esdi->rel.hdr != NULL)
11635                         ext_size = esdi->rel.hdr->sh_size;
11636                       if (esdi->rela.hdr != NULL)
11637                         ext_size += esdi->rela.hdr->sh_size;
11638
11639                       if (ext_size > max_external_reloc_size)
11640                         max_external_reloc_size = ext_size;
11641                       if (sec->reloc_count > max_internal_reloc_count)
11642                         max_internal_reloc_count = sec->reloc_count;
11643                     }
11644                 }
11645             }
11646
11647           if (reloc_count == 0)
11648             continue;
11649
11650           reloc_count += additional_reloc_count;
11651           o->reloc_count += reloc_count;
11652
11653           if (p->type == bfd_indirect_link_order && emit_relocs)
11654             {
11655               if (esdi->rel.hdr)
11656                 {
11657                   esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11658                   esdo->rel.count += additional_reloc_count;
11659                 }
11660               if (esdi->rela.hdr)
11661                 {
11662                   esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11663                   esdo->rela.count += additional_reloc_count;
11664                 }
11665             }
11666           else
11667             {
11668               if (o->use_rela_p)
11669                 esdo->rela.count += reloc_count;
11670               else
11671                 esdo->rel.count += reloc_count;
11672             }
11673         }
11674
11675       if (o->reloc_count > 0)
11676         o->flags |= SEC_RELOC;
11677       else
11678         {
11679           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11680              set it (this is probably a bug) and if it is set
11681              assign_section_numbers will create a reloc section.  */
11682           o->flags &=~ SEC_RELOC;
11683         }
11684
11685       /* If the SEC_ALLOC flag is not set, force the section VMA to
11686          zero.  This is done in elf_fake_sections as well, but forcing
11687          the VMA to 0 here will ensure that relocs against these
11688          sections are handled correctly.  */
11689       if ((o->flags & SEC_ALLOC) == 0
11690           && ! o->user_set_vma)
11691         o->vma = 0;
11692     }
11693
11694   if (! bfd_link_relocatable (info) && merged)
11695     elf_link_hash_traverse (htab, _bfd_elf_link_sec_merge_syms, abfd);
11696
11697   /* Figure out the file positions for everything but the symbol table
11698      and the relocs.  We set symcount to force assign_section_numbers
11699      to create a symbol table.  */
11700   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11701   BFD_ASSERT (! abfd->output_has_begun);
11702   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11703     goto error_return;
11704
11705   /* Set sizes, and assign file positions for reloc sections.  */
11706   for (o = abfd->sections; o != NULL; o = o->next)
11707     {
11708       struct bfd_elf_section_data *esdo = elf_section_data (o);
11709       if ((o->flags & SEC_RELOC) != 0)
11710         {
11711           if (esdo->rel.hdr
11712               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11713             goto error_return;
11714
11715           if (esdo->rela.hdr
11716               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11717             goto error_return;
11718         }
11719
11720       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
11721          to count upwards while actually outputting the relocations.  */
11722       esdo->rel.count = 0;
11723       esdo->rela.count = 0;
11724
11725       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
11726         {
11727           /* Cache the section contents so that they can be compressed
11728              later.  Use bfd_malloc since it will be freed by
11729              bfd_compress_section_contents.  */
11730           unsigned char *contents = esdo->this_hdr.contents;
11731           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
11732             abort ();
11733           contents
11734             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
11735           if (contents == NULL)
11736             goto error_return;
11737           esdo->this_hdr.contents = contents;
11738         }
11739     }
11740
11741   /* We have now assigned file positions for all the sections except
11742      .symtab, .strtab, and non-loaded reloc sections.  We start the
11743      .symtab section at the current file position, and write directly
11744      to it.  We build the .strtab section in memory.  */
11745   bfd_get_symcount (abfd) = 0;
11746   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11747   /* sh_name is set in prep_headers.  */
11748   symtab_hdr->sh_type = SHT_SYMTAB;
11749   /* sh_flags, sh_addr and sh_size all start off zero.  */
11750   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
11751   /* sh_link is set in assign_section_numbers.  */
11752   /* sh_info is set below.  */
11753   /* sh_offset is set just below.  */
11754   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
11755
11756   if (max_sym_count < 20)
11757     max_sym_count = 20;
11758   htab->strtabsize = max_sym_count;
11759   amt = max_sym_count * sizeof (struct elf_sym_strtab);
11760   htab->strtab = (struct elf_sym_strtab *) bfd_malloc (amt);
11761   if (htab->strtab == NULL)
11762     goto error_return;
11763   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
11764   flinfo.symshndxbuf
11765     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
11766        ? (Elf_External_Sym_Shndx *) -1 : NULL);
11767
11768   if (info->strip != strip_all || emit_relocs)
11769     {
11770       file_ptr off = elf_next_file_pos (abfd);
11771
11772       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
11773
11774       /* Note that at this point elf_next_file_pos (abfd) is
11775          incorrect.  We do not yet know the size of the .symtab section.
11776          We correct next_file_pos below, after we do know the size.  */
11777
11778       /* Start writing out the symbol table.  The first symbol is always a
11779          dummy symbol.  */
11780       elfsym.st_value = 0;
11781       elfsym.st_size = 0;
11782       elfsym.st_info = 0;
11783       elfsym.st_other = 0;
11784       elfsym.st_shndx = SHN_UNDEF;
11785       elfsym.st_target_internal = 0;
11786       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
11787                                      bfd_und_section_ptr, NULL) != 1)
11788         goto error_return;
11789
11790       /* Output a symbol for each section.  We output these even if we are
11791          discarding local symbols, since they are used for relocs.  These
11792          symbols have no names.  We store the index of each one in the
11793          index field of the section, so that we can find it again when
11794          outputting relocs.  */
11795
11796       elfsym.st_size = 0;
11797       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11798       elfsym.st_other = 0;
11799       elfsym.st_value = 0;
11800       elfsym.st_target_internal = 0;
11801       for (i = 1; i < elf_numsections (abfd); i++)
11802         {
11803           o = bfd_section_from_elf_index (abfd, i);
11804           if (o != NULL)
11805             {
11806               o->target_index = bfd_get_symcount (abfd);
11807               elfsym.st_shndx = i;
11808               if (!bfd_link_relocatable (info))
11809                 elfsym.st_value = o->vma;
11810               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
11811                                              NULL) != 1)
11812                 goto error_return;
11813             }
11814         }
11815     }
11816
11817   /* Allocate some memory to hold information read in from the input
11818      files.  */
11819   if (max_contents_size != 0)
11820     {
11821       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
11822       if (flinfo.contents == NULL)
11823         goto error_return;
11824     }
11825
11826   if (max_external_reloc_size != 0)
11827     {
11828       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
11829       if (flinfo.external_relocs == NULL)
11830         goto error_return;
11831     }
11832
11833   if (max_internal_reloc_count != 0)
11834     {
11835       amt = max_internal_reloc_count * sizeof (Elf_Internal_Rela);
11836       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
11837       if (flinfo.internal_relocs == NULL)
11838         goto error_return;
11839     }
11840
11841   if (max_sym_count != 0)
11842     {
11843       amt = max_sym_count * bed->s->sizeof_sym;
11844       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
11845       if (flinfo.external_syms == NULL)
11846         goto error_return;
11847
11848       amt = max_sym_count * sizeof (Elf_Internal_Sym);
11849       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
11850       if (flinfo.internal_syms == NULL)
11851         goto error_return;
11852
11853       amt = max_sym_count * sizeof (long);
11854       flinfo.indices = (long int *) bfd_malloc (amt);
11855       if (flinfo.indices == NULL)
11856         goto error_return;
11857
11858       amt = max_sym_count * sizeof (asection *);
11859       flinfo.sections = (asection **) bfd_malloc (amt);
11860       if (flinfo.sections == NULL)
11861         goto error_return;
11862     }
11863
11864   if (max_sym_shndx_count != 0)
11865     {
11866       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
11867       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
11868       if (flinfo.locsym_shndx == NULL)
11869         goto error_return;
11870     }
11871
11872   if (htab->tls_sec)
11873     {
11874       bfd_vma base, end = 0;
11875       asection *sec;
11876
11877       for (sec = htab->tls_sec;
11878            sec && (sec->flags & SEC_THREAD_LOCAL);
11879            sec = sec->next)
11880         {
11881           bfd_size_type size = sec->size;
11882
11883           if (size == 0
11884               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11885             {
11886               struct bfd_link_order *ord = sec->map_tail.link_order;
11887
11888               if (ord != NULL)
11889                 size = ord->offset + ord->size;
11890             }
11891           end = sec->vma + size;
11892         }
11893       base = htab->tls_sec->vma;
11894       /* Only align end of TLS section if static TLS doesn't have special
11895          alignment requirements.  */
11896       if (bed->static_tls_alignment == 1)
11897         end = align_power (end, htab->tls_sec->alignment_power);
11898       htab->tls_size = end - base;
11899     }
11900
11901   /* Reorder SHF_LINK_ORDER sections.  */
11902   for (o = abfd->sections; o != NULL; o = o->next)
11903     {
11904       if (!elf_fixup_link_order (abfd, o))
11905         return FALSE;
11906     }
11907
11908   if (!_bfd_elf_fixup_eh_frame_hdr (info))
11909     return FALSE;
11910
11911   /* Since ELF permits relocations to be against local symbols, we
11912      must have the local symbols available when we do the relocations.
11913      Since we would rather only read the local symbols once, and we
11914      would rather not keep them in memory, we handle all the
11915      relocations for a single input file at the same time.
11916
11917      Unfortunately, there is no way to know the total number of local
11918      symbols until we have seen all of them, and the local symbol
11919      indices precede the global symbol indices.  This means that when
11920      we are generating relocatable output, and we see a reloc against
11921      a global symbol, we can not know the symbol index until we have
11922      finished examining all the local symbols to see which ones we are
11923      going to output.  To deal with this, we keep the relocations in
11924      memory, and don't output them until the end of the link.  This is
11925      an unfortunate waste of memory, but I don't see a good way around
11926      it.  Fortunately, it only happens when performing a relocatable
11927      link, which is not the common case.  FIXME: If keep_memory is set
11928      we could write the relocs out and then read them again; I don't
11929      know how bad the memory loss will be.  */
11930
11931   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11932     sub->output_has_begun = FALSE;
11933   for (o = abfd->sections; o != NULL; o = o->next)
11934     {
11935       for (p = o->map_head.link_order; p != NULL; p = p->next)
11936         {
11937           if (p->type == bfd_indirect_link_order
11938               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
11939                   == bfd_target_elf_flavour)
11940               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
11941             {
11942               if (! sub->output_has_begun)
11943                 {
11944                   if (! elf_link_input_bfd (&flinfo, sub))
11945                     goto error_return;
11946                   sub->output_has_begun = TRUE;
11947                 }
11948             }
11949           else if (p->type == bfd_section_reloc_link_order
11950                    || p->type == bfd_symbol_reloc_link_order)
11951             {
11952               if (! elf_reloc_link_order (abfd, info, o, p))
11953                 goto error_return;
11954             }
11955           else
11956             {
11957               if (! _bfd_default_link_order (abfd, info, o, p))
11958                 {
11959                   if (p->type == bfd_indirect_link_order
11960                       && (bfd_get_flavour (sub)
11961                           == bfd_target_elf_flavour)
11962                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
11963                           != bed->s->elfclass))
11964                     {
11965                       const char *iclass, *oclass;
11966
11967                       switch (bed->s->elfclass)
11968                         {
11969                         case ELFCLASS64: oclass = "ELFCLASS64"; break;
11970                         case ELFCLASS32: oclass = "ELFCLASS32"; break;
11971                         case ELFCLASSNONE: oclass = "ELFCLASSNONE"; break;
11972                         default: abort ();
11973                         }
11974
11975                       switch (elf_elfheader (sub)->e_ident[EI_CLASS])
11976                         {
11977                         case ELFCLASS64: iclass = "ELFCLASS64"; break;
11978                         case ELFCLASS32: iclass = "ELFCLASS32"; break;
11979                         case ELFCLASSNONE: iclass = "ELFCLASSNONE"; break;
11980                         default: abort ();
11981                         }
11982
11983                       bfd_set_error (bfd_error_wrong_format);
11984                       _bfd_error_handler
11985                         /* xgettext:c-format */
11986                         (_("%B: file class %s incompatible with %s"),
11987                          sub, iclass, oclass);
11988                     }
11989
11990                   goto error_return;
11991                 }
11992             }
11993         }
11994     }
11995
11996   /* Free symbol buffer if needed.  */
11997   if (!info->reduce_memory_overheads)
11998     {
11999       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12000         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
12001             && elf_tdata (sub)->symbuf)
12002           {
12003             free (elf_tdata (sub)->symbuf);
12004             elf_tdata (sub)->symbuf = NULL;
12005           }
12006     }
12007
12008   /* Output any global symbols that got converted to local in a
12009      version script or due to symbol visibility.  We do this in a
12010      separate step since ELF requires all local symbols to appear
12011      prior to any global symbols.  FIXME: We should only do this if
12012      some global symbols were, in fact, converted to become local.
12013      FIXME: Will this work correctly with the Irix 5 linker?  */
12014   eoinfo.failed = FALSE;
12015   eoinfo.flinfo = &flinfo;
12016   eoinfo.localsyms = TRUE;
12017   eoinfo.file_sym_done = FALSE;
12018   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12019   if (eoinfo.failed)
12020     return FALSE;
12021
12022   /* If backend needs to output some local symbols not present in the hash
12023      table, do it now.  */
12024   if (bed->elf_backend_output_arch_local_syms
12025       && (info->strip != strip_all || emit_relocs))
12026     {
12027       typedef int (*out_sym_func)
12028         (void *, const char *, Elf_Internal_Sym *, asection *,
12029          struct elf_link_hash_entry *);
12030
12031       if (! ((*bed->elf_backend_output_arch_local_syms)
12032              (abfd, info, &flinfo,
12033               (out_sym_func) elf_link_output_symstrtab)))
12034         return FALSE;
12035     }
12036
12037   /* That wrote out all the local symbols.  Finish up the symbol table
12038      with the global symbols. Even if we want to strip everything we
12039      can, we still need to deal with those global symbols that got
12040      converted to local in a version script.  */
12041
12042   /* The sh_info field records the index of the first non local symbol.  */
12043   symtab_hdr->sh_info = bfd_get_symcount (abfd);
12044
12045   if (dynamic
12046       && htab->dynsym != NULL
12047       && htab->dynsym->output_section != bfd_abs_section_ptr)
12048     {
12049       Elf_Internal_Sym sym;
12050       bfd_byte *dynsym = htab->dynsym->contents;
12051
12052       o = htab->dynsym->output_section;
12053       elf_section_data (o)->this_hdr.sh_info = htab->local_dynsymcount + 1;
12054
12055       /* Write out the section symbols for the output sections.  */
12056       if (bfd_link_pic (info)
12057           || htab->is_relocatable_executable)
12058         {
12059           asection *s;
12060
12061           sym.st_size = 0;
12062           sym.st_name = 0;
12063           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
12064           sym.st_other = 0;
12065           sym.st_target_internal = 0;
12066
12067           for (s = abfd->sections; s != NULL; s = s->next)
12068             {
12069               int indx;
12070               bfd_byte *dest;
12071               long dynindx;
12072
12073               dynindx = elf_section_data (s)->dynindx;
12074               if (dynindx <= 0)
12075                 continue;
12076               indx = elf_section_data (s)->this_idx;
12077               BFD_ASSERT (indx > 0);
12078               sym.st_shndx = indx;
12079               if (! check_dynsym (abfd, &sym))
12080                 return FALSE;
12081               sym.st_value = s->vma;
12082               dest = dynsym + dynindx * bed->s->sizeof_sym;
12083               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12084             }
12085         }
12086
12087       /* Write out the local dynsyms.  */
12088       if (htab->dynlocal)
12089         {
12090           struct elf_link_local_dynamic_entry *e;
12091           for (e = htab->dynlocal; e ; e = e->next)
12092             {
12093               asection *s;
12094               bfd_byte *dest;
12095
12096               /* Copy the internal symbol and turn off visibility.
12097                  Note that we saved a word of storage and overwrote
12098                  the original st_name with the dynstr_index.  */
12099               sym = e->isym;
12100               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
12101
12102               s = bfd_section_from_elf_index (e->input_bfd,
12103                                               e->isym.st_shndx);
12104               if (s != NULL)
12105                 {
12106                   sym.st_shndx =
12107                     elf_section_data (s->output_section)->this_idx;
12108                   if (! check_dynsym (abfd, &sym))
12109                     return FALSE;
12110                   sym.st_value = (s->output_section->vma
12111                                   + s->output_offset
12112                                   + e->isym.st_value);
12113                 }
12114
12115               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
12116               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12117             }
12118         }
12119     }
12120
12121   /* We get the global symbols from the hash table.  */
12122   eoinfo.failed = FALSE;
12123   eoinfo.localsyms = FALSE;
12124   eoinfo.flinfo = &flinfo;
12125   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12126   if (eoinfo.failed)
12127     return FALSE;
12128
12129   /* If backend needs to output some symbols not present in the hash
12130      table, do it now.  */
12131   if (bed->elf_backend_output_arch_syms
12132       && (info->strip != strip_all || emit_relocs))
12133     {
12134       typedef int (*out_sym_func)
12135         (void *, const char *, Elf_Internal_Sym *, asection *,
12136          struct elf_link_hash_entry *);
12137
12138       if (! ((*bed->elf_backend_output_arch_syms)
12139              (abfd, info, &flinfo,
12140               (out_sym_func) elf_link_output_symstrtab)))
12141         return FALSE;
12142     }
12143
12144   /* Finalize the .strtab section.  */
12145   _bfd_elf_strtab_finalize (flinfo.symstrtab);
12146
12147   /* Swap out the .strtab section. */
12148   if (!elf_link_swap_symbols_out (&flinfo))
12149     return FALSE;
12150
12151   /* Now we know the size of the symtab section.  */
12152   if (bfd_get_symcount (abfd) > 0)
12153     {
12154       /* Finish up and write out the symbol string table (.strtab)
12155          section.  */
12156       Elf_Internal_Shdr *symstrtab_hdr = NULL;
12157       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
12158
12159       if (elf_symtab_shndx_list (abfd))
12160         {
12161           symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
12162
12163           if (symtab_shndx_hdr != NULL && symtab_shndx_hdr->sh_name != 0)
12164             {
12165               symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
12166               symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
12167               symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
12168               amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
12169               symtab_shndx_hdr->sh_size = amt;
12170
12171               off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
12172                                                                off, TRUE);
12173
12174               if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
12175                   || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
12176                 return FALSE;
12177             }
12178         }
12179
12180       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
12181       /* sh_name was set in prep_headers.  */
12182       symstrtab_hdr->sh_type = SHT_STRTAB;
12183       symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
12184       symstrtab_hdr->sh_addr = 0;
12185       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
12186       symstrtab_hdr->sh_entsize = 0;
12187       symstrtab_hdr->sh_link = 0;
12188       symstrtab_hdr->sh_info = 0;
12189       /* sh_offset is set just below.  */
12190       symstrtab_hdr->sh_addralign = 1;
12191
12192       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
12193                                                        off, TRUE);
12194       elf_next_file_pos (abfd) = off;
12195
12196       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
12197           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
12198         return FALSE;
12199     }
12200
12201   if (info->out_implib_bfd && !elf_output_implib (abfd, info))
12202     {
12203       _bfd_error_handler (_("%B: failed to generate import library"),
12204                           info->out_implib_bfd);
12205       return FALSE;
12206     }
12207
12208   /* Adjust the relocs to have the correct symbol indices.  */
12209   for (o = abfd->sections; o != NULL; o = o->next)
12210     {
12211       struct bfd_elf_section_data *esdo = elf_section_data (o);
12212       bfd_boolean sort;
12213
12214       if ((o->flags & SEC_RELOC) == 0)
12215         continue;
12216
12217       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
12218       if (esdo->rel.hdr != NULL
12219           && !elf_link_adjust_relocs (abfd, o, &esdo->rel, sort, info))
12220         return FALSE;
12221       if (esdo->rela.hdr != NULL
12222           && !elf_link_adjust_relocs (abfd, o, &esdo->rela, sort, info))
12223         return FALSE;
12224
12225       /* Set the reloc_count field to 0 to prevent write_relocs from
12226          trying to swap the relocs out itself.  */
12227       o->reloc_count = 0;
12228     }
12229
12230   if (dynamic && info->combreloc && dynobj != NULL)
12231     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
12232
12233   /* If we are linking against a dynamic object, or generating a
12234      shared library, finish up the dynamic linking information.  */
12235   if (dynamic)
12236     {
12237       bfd_byte *dyncon, *dynconend;
12238
12239       /* Fix up .dynamic entries.  */
12240       o = bfd_get_linker_section (dynobj, ".dynamic");
12241       BFD_ASSERT (o != NULL);
12242
12243       dyncon = o->contents;
12244       dynconend = o->contents + o->size;
12245       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12246         {
12247           Elf_Internal_Dyn dyn;
12248           const char *name;
12249           unsigned int type;
12250           bfd_size_type sh_size;
12251           bfd_vma sh_addr;
12252
12253           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12254
12255           switch (dyn.d_tag)
12256             {
12257             default:
12258               continue;
12259             case DT_NULL:
12260               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
12261                 {
12262                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
12263                     {
12264                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
12265                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
12266                     default: continue;
12267                     }
12268                   dyn.d_un.d_val = relativecount;
12269                   relativecount = 0;
12270                   break;
12271                 }
12272               continue;
12273
12274             case DT_INIT:
12275               name = info->init_function;
12276               goto get_sym;
12277             case DT_FINI:
12278               name = info->fini_function;
12279             get_sym:
12280               {
12281                 struct elf_link_hash_entry *h;
12282
12283                 h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
12284                 if (h != NULL
12285                     && (h->root.type == bfd_link_hash_defined
12286                         || h->root.type == bfd_link_hash_defweak))
12287                   {
12288                     dyn.d_un.d_ptr = h->root.u.def.value;
12289                     o = h->root.u.def.section;
12290                     if (o->output_section != NULL)
12291                       dyn.d_un.d_ptr += (o->output_section->vma
12292                                          + o->output_offset);
12293                     else
12294                       {
12295                         /* The symbol is imported from another shared
12296                            library and does not apply to this one.  */
12297                         dyn.d_un.d_ptr = 0;
12298                       }
12299                     break;
12300                   }
12301               }
12302               continue;
12303
12304             case DT_PREINIT_ARRAYSZ:
12305               name = ".preinit_array";
12306               goto get_out_size;
12307             case DT_INIT_ARRAYSZ:
12308               name = ".init_array";
12309               goto get_out_size;
12310             case DT_FINI_ARRAYSZ:
12311               name = ".fini_array";
12312             get_out_size:
12313               o = bfd_get_section_by_name (abfd, name);
12314               if (o == NULL)
12315                 {
12316                   _bfd_error_handler
12317                     (_("could not find section %s"), name);
12318                   goto error_return;
12319                 }
12320               if (o->size == 0)
12321                 _bfd_error_handler
12322                   (_("warning: %s section has zero size"), name);
12323               dyn.d_un.d_val = o->size;
12324               break;
12325
12326             case DT_PREINIT_ARRAY:
12327               name = ".preinit_array";
12328               goto get_out_vma;
12329             case DT_INIT_ARRAY:
12330               name = ".init_array";
12331               goto get_out_vma;
12332             case DT_FINI_ARRAY:
12333               name = ".fini_array";
12334             get_out_vma:
12335               o = bfd_get_section_by_name (abfd, name);
12336               goto do_vma;
12337
12338             case DT_HASH:
12339               name = ".hash";
12340               goto get_vma;
12341             case DT_GNU_HASH:
12342               name = ".gnu.hash";
12343               goto get_vma;
12344             case DT_STRTAB:
12345               name = ".dynstr";
12346               goto get_vma;
12347             case DT_SYMTAB:
12348               name = ".dynsym";
12349               goto get_vma;
12350             case DT_VERDEF:
12351               name = ".gnu.version_d";
12352               goto get_vma;
12353             case DT_VERNEED:
12354               name = ".gnu.version_r";
12355               goto get_vma;
12356             case DT_VERSYM:
12357               name = ".gnu.version";
12358             get_vma:
12359               o = bfd_get_linker_section (dynobj, name);
12360             do_vma:
12361               if (o == NULL || bfd_is_abs_section (o->output_section))
12362                 {
12363                   _bfd_error_handler
12364                     (_("could not find section %s"), name);
12365                   goto error_return;
12366                 }
12367               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
12368                 {
12369                   _bfd_error_handler
12370                     (_("warning: section '%s' is being made into a note"), name);
12371                   bfd_set_error (bfd_error_nonrepresentable_section);
12372                   goto error_return;
12373                 }
12374               dyn.d_un.d_ptr = o->output_section->vma + o->output_offset;
12375               break;
12376
12377             case DT_REL:
12378             case DT_RELA:
12379             case DT_RELSZ:
12380             case DT_RELASZ:
12381               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
12382                 type = SHT_REL;
12383               else
12384                 type = SHT_RELA;
12385               sh_size = 0;
12386               sh_addr = 0;
12387               for (i = 1; i < elf_numsections (abfd); i++)
12388                 {
12389                   Elf_Internal_Shdr *hdr;
12390
12391                   hdr = elf_elfsections (abfd)[i];
12392                   if (hdr->sh_type == type
12393                       && (hdr->sh_flags & SHF_ALLOC) != 0)
12394                     {
12395                       sh_size += hdr->sh_size;
12396                       if (sh_addr == 0
12397                           || sh_addr > hdr->sh_addr)
12398                         sh_addr = hdr->sh_addr;
12399                     }
12400                 }
12401
12402               if (bed->dtrel_excludes_plt && htab->srelplt != NULL)
12403                 {
12404                   /* Don't count procedure linkage table relocs in the
12405                      overall reloc count.  */
12406                   sh_size -= htab->srelplt->size;
12407                   if (sh_size == 0)
12408                     /* If the size is zero, make the address zero too.
12409                        This is to avoid a glibc bug.  If the backend
12410                        emits DT_RELA/DT_RELASZ even when DT_RELASZ is
12411                        zero, then we'll put DT_RELA at the end of
12412                        DT_JMPREL.  glibc will interpret the end of
12413                        DT_RELA matching the end of DT_JMPREL as the
12414                        case where DT_RELA includes DT_JMPREL, and for
12415                        LD_BIND_NOW will decide that processing DT_RELA
12416                        will process the PLT relocs too.  Net result:
12417                        No PLT relocs applied.  */
12418                     sh_addr = 0;
12419
12420                   /* If .rela.plt is the first .rela section, exclude
12421                      it from DT_RELA.  */
12422                   else if (sh_addr == (htab->srelplt->output_section->vma
12423                                        + htab->srelplt->output_offset))
12424                     sh_addr += htab->srelplt->size;
12425                 }
12426
12427               if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
12428                 dyn.d_un.d_val = sh_size;
12429               else
12430                 dyn.d_un.d_ptr = sh_addr;
12431               break;
12432             }
12433           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
12434         }
12435     }
12436
12437   /* If we have created any dynamic sections, then output them.  */
12438   if (dynobj != NULL)
12439     {
12440       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
12441         goto error_return;
12442
12443       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
12444       if (((info->warn_shared_textrel && bfd_link_pic (info))
12445            || info->error_textrel)
12446           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
12447         {
12448           bfd_byte *dyncon, *dynconend;
12449
12450           dyncon = o->contents;
12451           dynconend = o->contents + o->size;
12452           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12453             {
12454               Elf_Internal_Dyn dyn;
12455
12456               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12457
12458               if (dyn.d_tag == DT_TEXTREL)
12459                 {
12460                   if (info->error_textrel)
12461                     info->callbacks->einfo
12462                       (_("%P%X: read-only segment has dynamic relocations.\n"));
12463                   else
12464                     info->callbacks->einfo
12465                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
12466                   break;
12467                 }
12468             }
12469         }
12470
12471       for (o = dynobj->sections; o != NULL; o = o->next)
12472         {
12473           if ((o->flags & SEC_HAS_CONTENTS) == 0
12474               || o->size == 0
12475               || o->output_section == bfd_abs_section_ptr)
12476             continue;
12477           if ((o->flags & SEC_LINKER_CREATED) == 0)
12478             {
12479               /* At this point, we are only interested in sections
12480                  created by _bfd_elf_link_create_dynamic_sections.  */
12481               continue;
12482             }
12483           if (htab->stab_info.stabstr == o)
12484             continue;
12485           if (htab->eh_info.hdr_sec == o)
12486             continue;
12487           if (strcmp (o->name, ".dynstr") != 0)
12488             {
12489               if (! bfd_set_section_contents (abfd, o->output_section,
12490                                               o->contents,
12491                                               (file_ptr) o->output_offset
12492                                               * bfd_octets_per_byte (abfd),
12493                                               o->size))
12494                 goto error_return;
12495             }
12496           else
12497             {
12498               /* The contents of the .dynstr section are actually in a
12499                  stringtab.  */
12500               file_ptr off;
12501
12502               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
12503               if (bfd_seek (abfd, off, SEEK_SET) != 0
12504                   || !_bfd_elf_strtab_emit (abfd, htab->dynstr))
12505                 goto error_return;
12506             }
12507         }
12508     }
12509
12510   if (!info->resolve_section_groups)
12511     {
12512       bfd_boolean failed = FALSE;
12513
12514       BFD_ASSERT (bfd_link_relocatable (info));
12515       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
12516       if (failed)
12517         goto error_return;
12518     }
12519
12520   /* If we have optimized stabs strings, output them.  */
12521   if (htab->stab_info.stabstr != NULL)
12522     {
12523       if (!_bfd_write_stab_strings (abfd, &htab->stab_info))
12524         goto error_return;
12525     }
12526
12527   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
12528     goto error_return;
12529
12530   elf_final_link_free (abfd, &flinfo);
12531
12532   elf_linker (abfd) = TRUE;
12533
12534   if (attr_section)
12535     {
12536       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
12537       if (contents == NULL)
12538         return FALSE;   /* Bail out and fail.  */
12539       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
12540       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
12541       free (contents);
12542     }
12543
12544   return TRUE;
12545
12546  error_return:
12547   elf_final_link_free (abfd, &flinfo);
12548   return FALSE;
12549 }
12550 \f
12551 /* Initialize COOKIE for input bfd ABFD.  */
12552
12553 static bfd_boolean
12554 init_reloc_cookie (struct elf_reloc_cookie *cookie,
12555                    struct bfd_link_info *info, bfd *abfd)
12556 {
12557   Elf_Internal_Shdr *symtab_hdr;
12558   const struct elf_backend_data *bed;
12559
12560   bed = get_elf_backend_data (abfd);
12561   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12562
12563   cookie->abfd = abfd;
12564   cookie->sym_hashes = elf_sym_hashes (abfd);
12565   cookie->bad_symtab = elf_bad_symtab (abfd);
12566   if (cookie->bad_symtab)
12567     {
12568       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12569       cookie->extsymoff = 0;
12570     }
12571   else
12572     {
12573       cookie->locsymcount = symtab_hdr->sh_info;
12574       cookie->extsymoff = symtab_hdr->sh_info;
12575     }
12576
12577   if (bed->s->arch_size == 32)
12578     cookie->r_sym_shift = 8;
12579   else
12580     cookie->r_sym_shift = 32;
12581
12582   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
12583   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
12584     {
12585       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12586                                               cookie->locsymcount, 0,
12587                                               NULL, NULL, NULL);
12588       if (cookie->locsyms == NULL)
12589         {
12590           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
12591           return FALSE;
12592         }
12593       if (info->keep_memory)
12594         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
12595     }
12596   return TRUE;
12597 }
12598
12599 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
12600
12601 static void
12602 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
12603 {
12604   Elf_Internal_Shdr *symtab_hdr;
12605
12606   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12607   if (cookie->locsyms != NULL
12608       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
12609     free (cookie->locsyms);
12610 }
12611
12612 /* Initialize the relocation information in COOKIE for input section SEC
12613    of input bfd ABFD.  */
12614
12615 static bfd_boolean
12616 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12617                         struct bfd_link_info *info, bfd *abfd,
12618                         asection *sec)
12619 {
12620   if (sec->reloc_count == 0)
12621     {
12622       cookie->rels = NULL;
12623       cookie->relend = NULL;
12624     }
12625   else
12626     {
12627       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
12628                                                 info->keep_memory);
12629       if (cookie->rels == NULL)
12630         return FALSE;
12631       cookie->rel = cookie->rels;
12632       cookie->relend = cookie->rels + sec->reloc_count;
12633     }
12634   cookie->rel = cookie->rels;
12635   return TRUE;
12636 }
12637
12638 /* Free the memory allocated by init_reloc_cookie_rels,
12639    if appropriate.  */
12640
12641 static void
12642 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12643                         asection *sec)
12644 {
12645   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
12646     free (cookie->rels);
12647 }
12648
12649 /* Initialize the whole of COOKIE for input section SEC.  */
12650
12651 static bfd_boolean
12652 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12653                                struct bfd_link_info *info,
12654                                asection *sec)
12655 {
12656   if (!init_reloc_cookie (cookie, info, sec->owner))
12657     goto error1;
12658   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
12659     goto error2;
12660   return TRUE;
12661
12662  error2:
12663   fini_reloc_cookie (cookie, sec->owner);
12664  error1:
12665   return FALSE;
12666 }
12667
12668 /* Free the memory allocated by init_reloc_cookie_for_section,
12669    if appropriate.  */
12670
12671 static void
12672 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12673                                asection *sec)
12674 {
12675   fini_reloc_cookie_rels (cookie, sec);
12676   fini_reloc_cookie (cookie, sec->owner);
12677 }
12678 \f
12679 /* Garbage collect unused sections.  */
12680
12681 /* Default gc_mark_hook.  */
12682
12683 asection *
12684 _bfd_elf_gc_mark_hook (asection *sec,
12685                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12686                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12687                        struct elf_link_hash_entry *h,
12688                        Elf_Internal_Sym *sym)
12689 {
12690   if (h != NULL)
12691     {
12692       switch (h->root.type)
12693         {
12694         case bfd_link_hash_defined:
12695         case bfd_link_hash_defweak:
12696           return h->root.u.def.section;
12697
12698         case bfd_link_hash_common:
12699           return h->root.u.c.p->section;
12700
12701         default:
12702           break;
12703         }
12704     }
12705   else
12706     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12707
12708   return NULL;
12709 }
12710
12711 /* Return the global debug definition section.  */
12712
12713 static asection *
12714 elf_gc_mark_debug_section (asection *sec ATTRIBUTE_UNUSED,
12715                            struct bfd_link_info *info ATTRIBUTE_UNUSED,
12716                            Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12717                            struct elf_link_hash_entry *h,
12718                            Elf_Internal_Sym *sym ATTRIBUTE_UNUSED)
12719 {
12720   if (h != NULL
12721       && (h->root.type == bfd_link_hash_defined
12722           || h->root.type == bfd_link_hash_defweak)
12723       && (h->root.u.def.section->flags & SEC_DEBUGGING) != 0)
12724     return h->root.u.def.section;
12725
12726   return NULL;
12727 }
12728
12729 /* COOKIE->rel describes a relocation against section SEC, which is
12730    a section we've decided to keep.  Return the section that contains
12731    the relocation symbol, or NULL if no section contains it.  */
12732
12733 asection *
12734 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
12735                        elf_gc_mark_hook_fn gc_mark_hook,
12736                        struct elf_reloc_cookie *cookie,
12737                        bfd_boolean *start_stop)
12738 {
12739   unsigned long r_symndx;
12740   struct elf_link_hash_entry *h;
12741
12742   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
12743   if (r_symndx == STN_UNDEF)
12744     return NULL;
12745
12746   if (r_symndx >= cookie->locsymcount
12747       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12748     {
12749       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
12750       if (h == NULL)
12751         {
12752           info->callbacks->einfo (_("%F%P: corrupt input: %B\n"),
12753                                   sec->owner);
12754           return NULL;
12755         }
12756       while (h->root.type == bfd_link_hash_indirect
12757              || h->root.type == bfd_link_hash_warning)
12758         h = (struct elf_link_hash_entry *) h->root.u.i.link;
12759       h->mark = 1;
12760       /* If this symbol is weak and there is a non-weak definition, we
12761          keep the non-weak definition because many backends put
12762          dynamic reloc info on the non-weak definition for code
12763          handling copy relocs.  */
12764       if (h->u.weakdef != NULL)
12765         h->u.weakdef->mark = 1;
12766
12767       if (start_stop != NULL)
12768         {
12769           /* To work around a glibc bug, mark XXX input sections
12770              when there is a reference to __start_XXX or __stop_XXX
12771              symbols.  */
12772           if (h->start_stop)
12773             {
12774               asection *s = h->u2.start_stop_section;
12775               *start_stop = !s->gc_mark;
12776               return s;
12777             }
12778         }
12779
12780       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
12781     }
12782
12783   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
12784                           &cookie->locsyms[r_symndx]);
12785 }
12786
12787 /* COOKIE->rel describes a relocation against section SEC, which is
12788    a section we've decided to keep.  Mark the section that contains
12789    the relocation symbol.  */
12790
12791 bfd_boolean
12792 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
12793                         asection *sec,
12794                         elf_gc_mark_hook_fn gc_mark_hook,
12795                         struct elf_reloc_cookie *cookie)
12796 {
12797   asection *rsec;
12798   bfd_boolean start_stop = FALSE;
12799
12800   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie, &start_stop);
12801   while (rsec != NULL)
12802     {
12803       if (!rsec->gc_mark)
12804         {
12805           if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
12806               || (rsec->owner->flags & DYNAMIC) != 0)
12807             rsec->gc_mark = 1;
12808           else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
12809             return FALSE;
12810         }
12811       if (!start_stop)
12812         break;
12813       rsec = bfd_get_next_section_by_name (rsec->owner, rsec);
12814     }
12815   return TRUE;
12816 }
12817
12818 /* The mark phase of garbage collection.  For a given section, mark
12819    it and any sections in this section's group, and all the sections
12820    which define symbols to which it refers.  */
12821
12822 bfd_boolean
12823 _bfd_elf_gc_mark (struct bfd_link_info *info,
12824                   asection *sec,
12825                   elf_gc_mark_hook_fn gc_mark_hook)
12826 {
12827   bfd_boolean ret;
12828   asection *group_sec, *eh_frame;
12829
12830   sec->gc_mark = 1;
12831
12832   /* Mark all the sections in the group.  */
12833   group_sec = elf_section_data (sec)->next_in_group;
12834   if (group_sec && !group_sec->gc_mark)
12835     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
12836       return FALSE;
12837
12838   /* Look through the section relocs.  */
12839   ret = TRUE;
12840   eh_frame = elf_eh_frame_section (sec->owner);
12841   if ((sec->flags & SEC_RELOC) != 0
12842       && sec->reloc_count > 0
12843       && sec != eh_frame)
12844     {
12845       struct elf_reloc_cookie cookie;
12846
12847       if (!init_reloc_cookie_for_section (&cookie, info, sec))
12848         ret = FALSE;
12849       else
12850         {
12851           for (; cookie.rel < cookie.relend; cookie.rel++)
12852             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
12853               {
12854                 ret = FALSE;
12855                 break;
12856               }
12857           fini_reloc_cookie_for_section (&cookie, sec);
12858         }
12859     }
12860
12861   if (ret && eh_frame && elf_fde_list (sec))
12862     {
12863       struct elf_reloc_cookie cookie;
12864
12865       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
12866         ret = FALSE;
12867       else
12868         {
12869           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
12870                                       gc_mark_hook, &cookie))
12871             ret = FALSE;
12872           fini_reloc_cookie_for_section (&cookie, eh_frame);
12873         }
12874     }
12875
12876   eh_frame = elf_section_eh_frame_entry (sec);
12877   if (ret && eh_frame && !eh_frame->gc_mark)
12878     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
12879       ret = FALSE;
12880
12881   return ret;
12882 }
12883
12884 /* Scan and mark sections in a special or debug section group.  */
12885
12886 static void
12887 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
12888 {
12889   /* Point to first section of section group.  */
12890   asection *ssec;
12891   /* Used to iterate the section group.  */
12892   asection *msec;
12893
12894   bfd_boolean is_special_grp = TRUE;
12895   bfd_boolean is_debug_grp = TRUE;
12896
12897   /* First scan to see if group contains any section other than debug
12898      and special section.  */
12899   ssec = msec = elf_next_in_group (grp);
12900   do
12901     {
12902       if ((msec->flags & SEC_DEBUGGING) == 0)
12903         is_debug_grp = FALSE;
12904
12905       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
12906         is_special_grp = FALSE;
12907
12908       msec = elf_next_in_group (msec);
12909     }
12910   while (msec != ssec);
12911
12912   /* If this is a pure debug section group or pure special section group,
12913      keep all sections in this group.  */
12914   if (is_debug_grp || is_special_grp)
12915     {
12916       do
12917         {
12918           msec->gc_mark = 1;
12919           msec = elf_next_in_group (msec);
12920         }
12921       while (msec != ssec);
12922     }
12923 }
12924
12925 /* Keep debug and special sections.  */
12926
12927 bfd_boolean
12928 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
12929                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
12930 {
12931   bfd *ibfd;
12932
12933   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
12934     {
12935       asection *isec;
12936       bfd_boolean some_kept;
12937       bfd_boolean debug_frag_seen;
12938       bfd_boolean has_kept_debug_info;
12939
12940       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
12941         continue;
12942       isec = ibfd->sections;
12943       if (isec == NULL || isec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
12944         continue;
12945
12946       /* Ensure all linker created sections are kept,
12947          see if any other section is already marked,
12948          and note if we have any fragmented debug sections.  */
12949       debug_frag_seen = some_kept = has_kept_debug_info = FALSE;
12950       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12951         {
12952           if ((isec->flags & SEC_LINKER_CREATED) != 0)
12953             isec->gc_mark = 1;
12954           else if (isec->gc_mark
12955                    && (isec->flags & SEC_ALLOC) != 0
12956                    && elf_section_type (isec) != SHT_NOTE)
12957             some_kept = TRUE;
12958
12959           if (!debug_frag_seen
12960               && (isec->flags & SEC_DEBUGGING)
12961               && CONST_STRNEQ (isec->name, ".debug_line."))
12962             debug_frag_seen = TRUE;
12963         }
12964
12965       /* If no non-note alloc section in this file will be kept, then
12966          we can toss out the debug and special sections.  */
12967       if (!some_kept)
12968         continue;
12969
12970       /* Keep debug and special sections like .comment when they are
12971          not part of a group.  Also keep section groups that contain
12972          just debug sections or special sections.  */
12973       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12974         {
12975           if ((isec->flags & SEC_GROUP) != 0)
12976             _bfd_elf_gc_mark_debug_special_section_group (isec);
12977           else if (((isec->flags & SEC_DEBUGGING) != 0
12978                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
12979                    && elf_next_in_group (isec) == NULL)
12980             isec->gc_mark = 1;
12981           if (isec->gc_mark && (isec->flags & SEC_DEBUGGING) != 0)
12982             has_kept_debug_info = TRUE;
12983         }
12984
12985       /* Look for CODE sections which are going to be discarded,
12986          and find and discard any fragmented debug sections which
12987          are associated with that code section.  */
12988       if (debug_frag_seen)
12989         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12990           if ((isec->flags & SEC_CODE) != 0
12991               && isec->gc_mark == 0)
12992             {
12993               unsigned int ilen;
12994               asection *dsec;
12995
12996               ilen = strlen (isec->name);
12997
12998               /* Association is determined by the name of the debug
12999                  section containing the name of the code section as
13000                  a suffix.  For example .debug_line.text.foo is a
13001                  debug section associated with .text.foo.  */
13002               for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
13003                 {
13004                   unsigned int dlen;
13005
13006                   if (dsec->gc_mark == 0
13007                       || (dsec->flags & SEC_DEBUGGING) == 0)
13008                     continue;
13009
13010                   dlen = strlen (dsec->name);
13011
13012                   if (dlen > ilen
13013                       && strncmp (dsec->name + (dlen - ilen),
13014                                   isec->name, ilen) == 0)
13015                     dsec->gc_mark = 0;
13016                 }
13017           }
13018
13019       /* Mark debug sections referenced by kept debug sections.  */
13020       if (has_kept_debug_info)
13021         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13022           if (isec->gc_mark
13023               && (isec->flags & SEC_DEBUGGING) != 0)
13024             if (!_bfd_elf_gc_mark (info, isec,
13025                                    elf_gc_mark_debug_section))
13026               return FALSE;
13027     }
13028   return TRUE;
13029 }
13030
13031 static bfd_boolean
13032 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
13033 {
13034   bfd *sub;
13035   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13036
13037   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13038     {
13039       asection *o;
13040
13041       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13042           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13043         continue;
13044       o = sub->sections;
13045       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13046         continue;
13047
13048       for (o = sub->sections; o != NULL; o = o->next)
13049         {
13050           /* When any section in a section group is kept, we keep all
13051              sections in the section group.  If the first member of
13052              the section group is excluded, we will also exclude the
13053              group section.  */
13054           if (o->flags & SEC_GROUP)
13055             {
13056               asection *first = elf_next_in_group (o);
13057               o->gc_mark = first->gc_mark;
13058             }
13059
13060           if (o->gc_mark)
13061             continue;
13062
13063           /* Skip sweeping sections already excluded.  */
13064           if (o->flags & SEC_EXCLUDE)
13065             continue;
13066
13067           /* Since this is early in the link process, it is simple
13068              to remove a section from the output.  */
13069           o->flags |= SEC_EXCLUDE;
13070
13071           if (info->print_gc_sections && o->size != 0)
13072             /* xgettext:c-format */
13073             _bfd_error_handler (_("Removing unused section '%A' in file '%B'"),
13074                                 o, sub);
13075         }
13076     }
13077
13078   return TRUE;
13079 }
13080
13081 /* Propagate collected vtable information.  This is called through
13082    elf_link_hash_traverse.  */
13083
13084 static bfd_boolean
13085 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
13086 {
13087   /* Those that are not vtables.  */
13088   if (h->start_stop
13089       || h->u2.vtable == NULL
13090       || h->u2.vtable->parent == NULL)
13091     return TRUE;
13092
13093   /* Those vtables that do not have parents, we cannot merge.  */
13094   if (h->u2.vtable->parent == (struct elf_link_hash_entry *) -1)
13095     return TRUE;
13096
13097   /* If we've already been done, exit.  */
13098   if (h->u2.vtable->used && h->u2.vtable->used[-1])
13099     return TRUE;
13100
13101   /* Make sure the parent's table is up to date.  */
13102   elf_gc_propagate_vtable_entries_used (h->u2.vtable->parent, okp);
13103
13104   if (h->u2.vtable->used == NULL)
13105     {
13106       /* None of this table's entries were referenced.  Re-use the
13107          parent's table.  */
13108       h->u2.vtable->used = h->u2.vtable->parent->u2.vtable->used;
13109       h->u2.vtable->size = h->u2.vtable->parent->u2.vtable->size;
13110     }
13111   else
13112     {
13113       size_t n;
13114       bfd_boolean *cu, *pu;
13115
13116       /* Or the parent's entries into ours.  */
13117       cu = h->u2.vtable->used;
13118       cu[-1] = TRUE;
13119       pu = h->u2.vtable->parent->u2.vtable->used;
13120       if (pu != NULL)
13121         {
13122           const struct elf_backend_data *bed;
13123           unsigned int log_file_align;
13124
13125           bed = get_elf_backend_data (h->root.u.def.section->owner);
13126           log_file_align = bed->s->log_file_align;
13127           n = h->u2.vtable->parent->u2.vtable->size >> log_file_align;
13128           while (n--)
13129             {
13130               if (*pu)
13131                 *cu = TRUE;
13132               pu++;
13133               cu++;
13134             }
13135         }
13136     }
13137
13138   return TRUE;
13139 }
13140
13141 static bfd_boolean
13142 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
13143 {
13144   asection *sec;
13145   bfd_vma hstart, hend;
13146   Elf_Internal_Rela *relstart, *relend, *rel;
13147   const struct elf_backend_data *bed;
13148   unsigned int log_file_align;
13149
13150   /* Take care of both those symbols that do not describe vtables as
13151      well as those that are not loaded.  */
13152   if (h->start_stop
13153       || h->u2.vtable == NULL
13154       || h->u2.vtable->parent == NULL)
13155     return TRUE;
13156
13157   BFD_ASSERT (h->root.type == bfd_link_hash_defined
13158               || h->root.type == bfd_link_hash_defweak);
13159
13160   sec = h->root.u.def.section;
13161   hstart = h->root.u.def.value;
13162   hend = hstart + h->size;
13163
13164   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
13165   if (!relstart)
13166     return *(bfd_boolean *) okp = FALSE;
13167   bed = get_elf_backend_data (sec->owner);
13168   log_file_align = bed->s->log_file_align;
13169
13170   relend = relstart + sec->reloc_count;
13171
13172   for (rel = relstart; rel < relend; ++rel)
13173     if (rel->r_offset >= hstart && rel->r_offset < hend)
13174       {
13175         /* If the entry is in use, do nothing.  */
13176         if (h->u2.vtable->used
13177             && (rel->r_offset - hstart) < h->u2.vtable->size)
13178           {
13179             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
13180             if (h->u2.vtable->used[entry])
13181               continue;
13182           }
13183         /* Otherwise, kill it.  */
13184         rel->r_offset = rel->r_info = rel->r_addend = 0;
13185       }
13186
13187   return TRUE;
13188 }
13189
13190 /* Mark sections containing dynamically referenced symbols.  When
13191    building shared libraries, we must assume that any visible symbol is
13192    referenced.  */
13193
13194 bfd_boolean
13195 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
13196 {
13197   struct bfd_link_info *info = (struct bfd_link_info *) inf;
13198   struct bfd_elf_dynamic_list *d = info->dynamic_list;
13199
13200   if ((h->root.type == bfd_link_hash_defined
13201        || h->root.type == bfd_link_hash_defweak)
13202       && (h->ref_dynamic
13203           || ((h->def_regular || ELF_COMMON_DEF_P (h))
13204               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
13205               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
13206               && (!bfd_link_executable (info)
13207                   || info->gc_keep_exported
13208                   || info->export_dynamic
13209                   || (h->dynamic
13210                       && d != NULL
13211                       && (*d->match) (&d->head, NULL, h->root.root.string)))
13212               && (h->versioned >= versioned
13213                   || !bfd_hide_sym_by_version (info->version_info,
13214                                                h->root.root.string)))))
13215     h->root.u.def.section->flags |= SEC_KEEP;
13216
13217   return TRUE;
13218 }
13219
13220 /* Keep all sections containing symbols undefined on the command-line,
13221    and the section containing the entry symbol.  */
13222
13223 void
13224 _bfd_elf_gc_keep (struct bfd_link_info *info)
13225 {
13226   struct bfd_sym_chain *sym;
13227
13228   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
13229     {
13230       struct elf_link_hash_entry *h;
13231
13232       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
13233                                 FALSE, FALSE, FALSE);
13234
13235       if (h != NULL
13236           && (h->root.type == bfd_link_hash_defined
13237               || h->root.type == bfd_link_hash_defweak)
13238           && !bfd_is_abs_section (h->root.u.def.section)
13239           && !bfd_is_und_section (h->root.u.def.section))
13240         h->root.u.def.section->flags |= SEC_KEEP;
13241     }
13242 }
13243
13244 bfd_boolean
13245 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
13246                                 struct bfd_link_info *info)
13247 {
13248   bfd *ibfd = info->input_bfds;
13249
13250   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13251     {
13252       asection *sec;
13253       struct elf_reloc_cookie cookie;
13254
13255       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13256         continue;
13257       sec = ibfd->sections;
13258       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13259         continue;
13260
13261       if (!init_reloc_cookie (&cookie, info, ibfd))
13262         return FALSE;
13263
13264       for (sec = ibfd->sections; sec; sec = sec->next)
13265         {
13266           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
13267               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
13268             {
13269               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
13270               fini_reloc_cookie_rels (&cookie, sec);
13271             }
13272         }
13273     }
13274   return TRUE;
13275 }
13276
13277 /* Do mark and sweep of unused sections.  */
13278
13279 bfd_boolean
13280 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
13281 {
13282   bfd_boolean ok = TRUE;
13283   bfd *sub;
13284   elf_gc_mark_hook_fn gc_mark_hook;
13285   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13286   struct elf_link_hash_table *htab;
13287
13288   if (!bed->can_gc_sections
13289       || !is_elf_hash_table (info->hash))
13290     {
13291       _bfd_error_handler(_("Warning: gc-sections option ignored"));
13292       return TRUE;
13293     }
13294
13295   bed->gc_keep (info);
13296   htab = elf_hash_table (info);
13297
13298   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
13299      at the .eh_frame section if we can mark the FDEs individually.  */
13300   for (sub = info->input_bfds;
13301        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
13302        sub = sub->link.next)
13303     {
13304       asection *sec;
13305       struct elf_reloc_cookie cookie;
13306
13307       sec = sub->sections;
13308       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13309         continue;
13310       sec = bfd_get_section_by_name (sub, ".eh_frame");
13311       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
13312         {
13313           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
13314           if (elf_section_data (sec)->sec_info
13315               && (sec->flags & SEC_LINKER_CREATED) == 0)
13316             elf_eh_frame_section (sub) = sec;
13317           fini_reloc_cookie_for_section (&cookie, sec);
13318           sec = bfd_get_next_section_by_name (NULL, sec);
13319         }
13320     }
13321
13322   /* Apply transitive closure to the vtable entry usage info.  */
13323   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
13324   if (!ok)
13325     return FALSE;
13326
13327   /* Kill the vtable relocations that were not used.  */
13328   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
13329   if (!ok)
13330     return FALSE;
13331
13332   /* Mark dynamically referenced symbols.  */
13333   if (htab->dynamic_sections_created || info->gc_keep_exported)
13334     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
13335
13336   /* Grovel through relocs to find out who stays ...  */
13337   gc_mark_hook = bed->gc_mark_hook;
13338   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13339     {
13340       asection *o;
13341
13342       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13343           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13344         continue;
13345
13346       o = sub->sections;
13347       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13348         continue;
13349
13350       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
13351          Also treat note sections as a root, if the section is not part
13352          of a group.  */
13353       for (o = sub->sections; o != NULL; o = o->next)
13354         if (!o->gc_mark
13355             && (o->flags & SEC_EXCLUDE) == 0
13356             && ((o->flags & SEC_KEEP) != 0
13357                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
13358                     && elf_next_in_group (o) == NULL )))
13359           {
13360             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
13361               return FALSE;
13362           }
13363     }
13364
13365   /* Allow the backend to mark additional target specific sections.  */
13366   bed->gc_mark_extra_sections (info, gc_mark_hook);
13367
13368   /* ... and mark SEC_EXCLUDE for those that go.  */
13369   return elf_gc_sweep (abfd, info);
13370 }
13371 \f
13372 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
13373
13374 bfd_boolean
13375 bfd_elf_gc_record_vtinherit (bfd *abfd,
13376                              asection *sec,
13377                              struct elf_link_hash_entry *h,
13378                              bfd_vma offset)
13379 {
13380   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
13381   struct elf_link_hash_entry **search, *child;
13382   size_t extsymcount;
13383   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13384
13385   /* The sh_info field of the symtab header tells us where the
13386      external symbols start.  We don't care about the local symbols at
13387      this point.  */
13388   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
13389   if (!elf_bad_symtab (abfd))
13390     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
13391
13392   sym_hashes = elf_sym_hashes (abfd);
13393   sym_hashes_end = sym_hashes + extsymcount;
13394
13395   /* Hunt down the child symbol, which is in this section at the same
13396      offset as the relocation.  */
13397   for (search = sym_hashes; search != sym_hashes_end; ++search)
13398     {
13399       if ((child = *search) != NULL
13400           && (child->root.type == bfd_link_hash_defined
13401               || child->root.type == bfd_link_hash_defweak)
13402           && child->root.u.def.section == sec
13403           && child->root.u.def.value == offset)
13404         goto win;
13405     }
13406
13407   /* xgettext:c-format */
13408   _bfd_error_handler (_("%B: %A+%#Lx: No symbol found for INHERIT"),
13409                       abfd, sec, offset);
13410   bfd_set_error (bfd_error_invalid_operation);
13411   return FALSE;
13412
13413  win:
13414   if (!child->u2.vtable)
13415     {
13416       child->u2.vtable = ((struct elf_link_virtual_table_entry *)
13417                           bfd_zalloc (abfd, sizeof (*child->u2.vtable)));
13418       if (!child->u2.vtable)
13419         return FALSE;
13420     }
13421   if (!h)
13422     {
13423       /* This *should* only be the absolute section.  It could potentially
13424          be that someone has defined a non-global vtable though, which
13425          would be bad.  It isn't worth paging in the local symbols to be
13426          sure though; that case should simply be handled by the assembler.  */
13427
13428       child->u2.vtable->parent = (struct elf_link_hash_entry *) -1;
13429     }
13430   else
13431     child->u2.vtable->parent = h;
13432
13433   return TRUE;
13434 }
13435
13436 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
13437
13438 bfd_boolean
13439 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
13440                            asection *sec ATTRIBUTE_UNUSED,
13441                            struct elf_link_hash_entry *h,
13442                            bfd_vma addend)
13443 {
13444   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13445   unsigned int log_file_align = bed->s->log_file_align;
13446
13447   if (!h->u2.vtable)
13448     {
13449       h->u2.vtable = ((struct elf_link_virtual_table_entry *)
13450                       bfd_zalloc (abfd, sizeof (*h->u2.vtable)));
13451       if (!h->u2.vtable)
13452         return FALSE;
13453     }
13454
13455   if (addend >= h->u2.vtable->size)
13456     {
13457       size_t size, bytes, file_align;
13458       bfd_boolean *ptr = h->u2.vtable->used;
13459
13460       /* While the symbol is undefined, we have to be prepared to handle
13461          a zero size.  */
13462       file_align = 1 << log_file_align;
13463       if (h->root.type == bfd_link_hash_undefined)
13464         size = addend + file_align;
13465       else
13466         {
13467           size = h->size;
13468           if (addend >= size)
13469             {
13470               /* Oops!  We've got a reference past the defined end of
13471                  the table.  This is probably a bug -- shall we warn?  */
13472               size = addend + file_align;
13473             }
13474         }
13475       size = (size + file_align - 1) & -file_align;
13476
13477       /* Allocate one extra entry for use as a "done" flag for the
13478          consolidation pass.  */
13479       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
13480
13481       if (ptr)
13482         {
13483           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
13484
13485           if (ptr != NULL)
13486             {
13487               size_t oldbytes;
13488
13489               oldbytes = (((h->u2.vtable->size >> log_file_align) + 1)
13490                           * sizeof (bfd_boolean));
13491               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
13492             }
13493         }
13494       else
13495         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
13496
13497       if (ptr == NULL)
13498         return FALSE;
13499
13500       /* And arrange for that done flag to be at index -1.  */
13501       h->u2.vtable->used = ptr + 1;
13502       h->u2.vtable->size = size;
13503     }
13504
13505   h->u2.vtable->used[addend >> log_file_align] = TRUE;
13506
13507   return TRUE;
13508 }
13509
13510 /* Map an ELF section header flag to its corresponding string.  */
13511 typedef struct
13512 {
13513   char *flag_name;
13514   flagword flag_value;
13515 } elf_flags_to_name_table;
13516
13517 static elf_flags_to_name_table elf_flags_to_names [] =
13518 {
13519   { "SHF_WRITE", SHF_WRITE },
13520   { "SHF_ALLOC", SHF_ALLOC },
13521   { "SHF_EXECINSTR", SHF_EXECINSTR },
13522   { "SHF_MERGE", SHF_MERGE },
13523   { "SHF_STRINGS", SHF_STRINGS },
13524   { "SHF_INFO_LINK", SHF_INFO_LINK},
13525   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
13526   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
13527   { "SHF_GROUP", SHF_GROUP },
13528   { "SHF_TLS", SHF_TLS },
13529   { "SHF_MASKOS", SHF_MASKOS },
13530   { "SHF_EXCLUDE", SHF_EXCLUDE },
13531 };
13532
13533 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
13534 bfd_boolean
13535 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
13536                               struct flag_info *flaginfo,
13537                               asection *section)
13538 {
13539   const bfd_vma sh_flags = elf_section_flags (section);
13540
13541   if (!flaginfo->flags_initialized)
13542     {
13543       bfd *obfd = info->output_bfd;
13544       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13545       struct flag_info_list *tf = flaginfo->flag_list;
13546       int with_hex = 0;
13547       int without_hex = 0;
13548
13549       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
13550         {
13551           unsigned i;
13552           flagword (*lookup) (char *);
13553
13554           lookup = bed->elf_backend_lookup_section_flags_hook;
13555           if (lookup != NULL)
13556             {
13557               flagword hexval = (*lookup) ((char *) tf->name);
13558
13559               if (hexval != 0)
13560                 {
13561                   if (tf->with == with_flags)
13562                     with_hex |= hexval;
13563                   else if (tf->with == without_flags)
13564                     without_hex |= hexval;
13565                   tf->valid = TRUE;
13566                   continue;
13567                 }
13568             }
13569           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
13570             {
13571               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
13572                 {
13573                   if (tf->with == with_flags)
13574                     with_hex |= elf_flags_to_names[i].flag_value;
13575                   else if (tf->with == without_flags)
13576                     without_hex |= elf_flags_to_names[i].flag_value;
13577                   tf->valid = TRUE;
13578                   break;
13579                 }
13580             }
13581           if (!tf->valid)
13582             {
13583               info->callbacks->einfo
13584                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
13585               return FALSE;
13586             }
13587         }
13588       flaginfo->flags_initialized = TRUE;
13589       flaginfo->only_with_flags |= with_hex;
13590       flaginfo->not_with_flags |= without_hex;
13591     }
13592
13593   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
13594     return FALSE;
13595
13596   if ((flaginfo->not_with_flags & sh_flags) != 0)
13597     return FALSE;
13598
13599   return TRUE;
13600 }
13601
13602 struct alloc_got_off_arg {
13603   bfd_vma gotoff;
13604   struct bfd_link_info *info;
13605 };
13606
13607 /* We need a special top-level link routine to convert got reference counts
13608    to real got offsets.  */
13609
13610 static bfd_boolean
13611 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
13612 {
13613   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
13614   bfd *obfd = gofarg->info->output_bfd;
13615   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13616
13617   if (h->got.refcount > 0)
13618     {
13619       h->got.offset = gofarg->gotoff;
13620       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
13621     }
13622   else
13623     h->got.offset = (bfd_vma) -1;
13624
13625   return TRUE;
13626 }
13627
13628 /* And an accompanying bit to work out final got entry offsets once
13629    we're done.  Should be called from final_link.  */
13630
13631 bfd_boolean
13632 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
13633                                         struct bfd_link_info *info)
13634 {
13635   bfd *i;
13636   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13637   bfd_vma gotoff;
13638   struct alloc_got_off_arg gofarg;
13639
13640   BFD_ASSERT (abfd == info->output_bfd);
13641
13642   if (! is_elf_hash_table (info->hash))
13643     return FALSE;
13644
13645   /* The GOT offset is relative to the .got section, but the GOT header is
13646      put into the .got.plt section, if the backend uses it.  */
13647   if (bed->want_got_plt)
13648     gotoff = 0;
13649   else
13650     gotoff = bed->got_header_size;
13651
13652   /* Do the local .got entries first.  */
13653   for (i = info->input_bfds; i; i = i->link.next)
13654     {
13655       bfd_signed_vma *local_got;
13656       size_t j, locsymcount;
13657       Elf_Internal_Shdr *symtab_hdr;
13658
13659       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13660         continue;
13661
13662       local_got = elf_local_got_refcounts (i);
13663       if (!local_got)
13664         continue;
13665
13666       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13667       if (elf_bad_symtab (i))
13668         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13669       else
13670         locsymcount = symtab_hdr->sh_info;
13671
13672       for (j = 0; j < locsymcount; ++j)
13673         {
13674           if (local_got[j] > 0)
13675             {
13676               local_got[j] = gotoff;
13677               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13678             }
13679           else
13680             local_got[j] = (bfd_vma) -1;
13681         }
13682     }
13683
13684   /* Then the global .got entries.  .plt refcounts are handled by
13685      adjust_dynamic_symbol  */
13686   gofarg.gotoff = gotoff;
13687   gofarg.info = info;
13688   elf_link_hash_traverse (elf_hash_table (info),
13689                           elf_gc_allocate_got_offsets,
13690                           &gofarg);
13691   return TRUE;
13692 }
13693
13694 /* Many folk need no more in the way of final link than this, once
13695    got entry reference counting is enabled.  */
13696
13697 bfd_boolean
13698 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
13699 {
13700   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
13701     return FALSE;
13702
13703   /* Invoke the regular ELF backend linker to do all the work.  */
13704   return bfd_elf_final_link (abfd, info);
13705 }
13706
13707 bfd_boolean
13708 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
13709 {
13710   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
13711
13712   if (rcookie->bad_symtab)
13713     rcookie->rel = rcookie->rels;
13714
13715   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
13716     {
13717       unsigned long r_symndx;
13718
13719       if (! rcookie->bad_symtab)
13720         if (rcookie->rel->r_offset > offset)
13721           return FALSE;
13722       if (rcookie->rel->r_offset != offset)
13723         continue;
13724
13725       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
13726       if (r_symndx == STN_UNDEF)
13727         return TRUE;
13728
13729       if (r_symndx >= rcookie->locsymcount
13730           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13731         {
13732           struct elf_link_hash_entry *h;
13733
13734           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
13735
13736           while (h->root.type == bfd_link_hash_indirect
13737                  || h->root.type == bfd_link_hash_warning)
13738             h = (struct elf_link_hash_entry *) h->root.u.i.link;
13739
13740           if ((h->root.type == bfd_link_hash_defined
13741                || h->root.type == bfd_link_hash_defweak)
13742               && (h->root.u.def.section->owner != rcookie->abfd
13743                   || h->root.u.def.section->kept_section != NULL
13744                   || discarded_section (h->root.u.def.section)))
13745             return TRUE;
13746         }
13747       else
13748         {
13749           /* It's not a relocation against a global symbol,
13750              but it could be a relocation against a local
13751              symbol for a discarded section.  */
13752           asection *isec;
13753           Elf_Internal_Sym *isym;
13754
13755           /* Need to: get the symbol; get the section.  */
13756           isym = &rcookie->locsyms[r_symndx];
13757           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
13758           if (isec != NULL
13759               && (isec->kept_section != NULL
13760                   || discarded_section (isec)))
13761             return TRUE;
13762         }
13763       return FALSE;
13764     }
13765   return FALSE;
13766 }
13767
13768 /* Discard unneeded references to discarded sections.
13769    Returns -1 on error, 1 if any section's size was changed, 0 if
13770    nothing changed.  This function assumes that the relocations are in
13771    sorted order, which is true for all known assemblers.  */
13772
13773 int
13774 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
13775 {
13776   struct elf_reloc_cookie cookie;
13777   asection *o;
13778   bfd *abfd;
13779   int changed = 0;
13780
13781   if (info->traditional_format
13782       || !is_elf_hash_table (info->hash))
13783     return 0;
13784
13785   o = bfd_get_section_by_name (output_bfd, ".stab");
13786   if (o != NULL)
13787     {
13788       asection *i;
13789
13790       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13791         {
13792           if (i->size == 0
13793               || i->reloc_count == 0
13794               || i->sec_info_type != SEC_INFO_TYPE_STABS)
13795             continue;
13796
13797           abfd = i->owner;
13798           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13799             continue;
13800
13801           if (!init_reloc_cookie_for_section (&cookie, info, i))
13802             return -1;
13803
13804           if (_bfd_discard_section_stabs (abfd, i,
13805                                           elf_section_data (i)->sec_info,
13806                                           bfd_elf_reloc_symbol_deleted_p,
13807                                           &cookie))
13808             changed = 1;
13809
13810           fini_reloc_cookie_for_section (&cookie, i);
13811         }
13812     }
13813
13814   o = NULL;
13815   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
13816     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
13817   if (o != NULL)
13818     {
13819       asection *i;
13820       int eh_changed = 0;
13821       unsigned int eh_alignment;
13822
13823       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13824         {
13825           if (i->size == 0)
13826             continue;
13827
13828           abfd = i->owner;
13829           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13830             continue;
13831
13832           if (!init_reloc_cookie_for_section (&cookie, info, i))
13833             return -1;
13834
13835           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
13836           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
13837                                                  bfd_elf_reloc_symbol_deleted_p,
13838                                                  &cookie))
13839             {
13840               eh_changed = 1;
13841               if (i->size != i->rawsize)
13842                 changed = 1;
13843             }
13844
13845           fini_reloc_cookie_for_section (&cookie, i);
13846         }
13847
13848       eh_alignment = 1 << o->alignment_power;
13849       /* Skip over zero terminator, and prevent empty sections from
13850          adding alignment padding at the end.  */
13851       for (i = o->map_tail.s; i != NULL; i = i->map_tail.s)
13852         if (i->size == 0)
13853           i->flags |= SEC_EXCLUDE;
13854         else if (i->size > 4)
13855           break;
13856       /* The last non-empty eh_frame section doesn't need padding.  */
13857       if (i != NULL)
13858         i = i->map_tail.s;
13859       /* Any prior sections must pad the last FDE out to the output
13860          section alignment.  Otherwise we might have zero padding
13861          between sections, which would be seen as a terminator.  */
13862       for (; i != NULL; i = i->map_tail.s)
13863         if (i->size == 4)
13864           /* All but the last zero terminator should have been removed.  */
13865           BFD_FAIL ();
13866         else
13867           {
13868             bfd_size_type size
13869               = (i->size + eh_alignment - 1) & -eh_alignment;
13870             if (i->size != size)
13871               {
13872                 i->size = size;
13873                 changed = 1;
13874                 eh_changed = 1;
13875               }
13876           }
13877       if (eh_changed)
13878         elf_link_hash_traverse (elf_hash_table (info),
13879                                 _bfd_elf_adjust_eh_frame_global_symbol, NULL);
13880     }
13881
13882   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
13883     {
13884       const struct elf_backend_data *bed;
13885       asection *s;
13886
13887       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13888         continue;
13889       s = abfd->sections;
13890       if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13891         continue;
13892
13893       bed = get_elf_backend_data (abfd);
13894
13895       if (bed->elf_backend_discard_info != NULL)
13896         {
13897           if (!init_reloc_cookie (&cookie, info, abfd))
13898             return -1;
13899
13900           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
13901             changed = 1;
13902
13903           fini_reloc_cookie (&cookie, abfd);
13904         }
13905     }
13906
13907   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
13908     _bfd_elf_end_eh_frame_parsing (info);
13909
13910   if (info->eh_frame_hdr_type
13911       && !bfd_link_relocatable (info)
13912       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
13913     changed = 1;
13914
13915   return changed;
13916 }
13917
13918 bfd_boolean
13919 _bfd_elf_section_already_linked (bfd *abfd,
13920                                  asection *sec,
13921                                  struct bfd_link_info *info)
13922 {
13923   flagword flags;
13924   const char *name, *key;
13925   struct bfd_section_already_linked *l;
13926   struct bfd_section_already_linked_hash_entry *already_linked_list;
13927
13928   if (sec->output_section == bfd_abs_section_ptr)
13929     return FALSE;
13930
13931   flags = sec->flags;
13932
13933   /* Return if it isn't a linkonce section.  A comdat group section
13934      also has SEC_LINK_ONCE set.  */
13935   if ((flags & SEC_LINK_ONCE) == 0)
13936     return FALSE;
13937
13938   /* Don't put group member sections on our list of already linked
13939      sections.  They are handled as a group via their group section.  */
13940   if (elf_sec_group (sec) != NULL)
13941     return FALSE;
13942
13943   /* For a SHT_GROUP section, use the group signature as the key.  */
13944   name = sec->name;
13945   if ((flags & SEC_GROUP) != 0
13946       && elf_next_in_group (sec) != NULL
13947       && elf_group_name (elf_next_in_group (sec)) != NULL)
13948     key = elf_group_name (elf_next_in_group (sec));
13949   else
13950     {
13951       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
13952       if (CONST_STRNEQ (name, ".gnu.linkonce.")
13953           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
13954         key++;
13955       else
13956         /* Must be a user linkonce section that doesn't follow gcc's
13957            naming convention.  In this case we won't be matching
13958            single member groups.  */
13959         key = name;
13960     }
13961
13962   already_linked_list = bfd_section_already_linked_table_lookup (key);
13963
13964   for (l = already_linked_list->entry; l != NULL; l = l->next)
13965     {
13966       /* We may have 2 different types of sections on the list: group
13967          sections with a signature of <key> (<key> is some string),
13968          and linkonce sections named .gnu.linkonce.<type>.<key>.
13969          Match like sections.  LTO plugin sections are an exception.
13970          They are always named .gnu.linkonce.t.<key> and match either
13971          type of section.  */
13972       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
13973            && ((flags & SEC_GROUP) != 0
13974                || strcmp (name, l->sec->name) == 0))
13975           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
13976         {
13977           /* The section has already been linked.  See if we should
13978              issue a warning.  */
13979           if (!_bfd_handle_already_linked (sec, l, info))
13980             return FALSE;
13981
13982           if (flags & SEC_GROUP)
13983             {
13984               asection *first = elf_next_in_group (sec);
13985               asection *s = first;
13986
13987               while (s != NULL)
13988                 {
13989                   s->output_section = bfd_abs_section_ptr;
13990                   /* Record which group discards it.  */
13991                   s->kept_section = l->sec;
13992                   s = elf_next_in_group (s);
13993                   /* These lists are circular.  */
13994                   if (s == first)
13995                     break;
13996                 }
13997             }
13998
13999           return TRUE;
14000         }
14001     }
14002
14003   /* A single member comdat group section may be discarded by a
14004      linkonce section and vice versa.  */
14005   if ((flags & SEC_GROUP) != 0)
14006     {
14007       asection *first = elf_next_in_group (sec);
14008
14009       if (first != NULL && elf_next_in_group (first) == first)
14010         /* Check this single member group against linkonce sections.  */
14011         for (l = already_linked_list->entry; l != NULL; l = l->next)
14012           if ((l->sec->flags & SEC_GROUP) == 0
14013               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
14014             {
14015               first->output_section = bfd_abs_section_ptr;
14016               first->kept_section = l->sec;
14017               sec->output_section = bfd_abs_section_ptr;
14018               break;
14019             }
14020     }
14021   else
14022     /* Check this linkonce section against single member groups.  */
14023     for (l = already_linked_list->entry; l != NULL; l = l->next)
14024       if (l->sec->flags & SEC_GROUP)
14025         {
14026           asection *first = elf_next_in_group (l->sec);
14027
14028           if (first != NULL
14029               && elf_next_in_group (first) == first
14030               && bfd_elf_match_symbols_in_sections (first, sec, info))
14031             {
14032               sec->output_section = bfd_abs_section_ptr;
14033               sec->kept_section = first;
14034               break;
14035             }
14036         }
14037
14038   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
14039      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
14040      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
14041      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
14042      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
14043      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
14044      `.gnu.linkonce.t.F' section from a different bfd not requiring any
14045      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
14046      The reverse order cannot happen as there is never a bfd with only the
14047      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
14048      matter as here were are looking only for cross-bfd sections.  */
14049
14050   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
14051     for (l = already_linked_list->entry; l != NULL; l = l->next)
14052       if ((l->sec->flags & SEC_GROUP) == 0
14053           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
14054         {
14055           if (abfd != l->sec->owner)
14056             sec->output_section = bfd_abs_section_ptr;
14057           break;
14058         }
14059
14060   /* This is the first section with this name.  Record it.  */
14061   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
14062     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
14063   return sec->output_section == bfd_abs_section_ptr;
14064 }
14065
14066 bfd_boolean
14067 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
14068 {
14069   return sym->st_shndx == SHN_COMMON;
14070 }
14071
14072 unsigned int
14073 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
14074 {
14075   return SHN_COMMON;
14076 }
14077
14078 asection *
14079 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
14080 {
14081   return bfd_com_section_ptr;
14082 }
14083
14084 bfd_vma
14085 _bfd_elf_default_got_elt_size (bfd *abfd,
14086                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
14087                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
14088                                bfd *ibfd ATTRIBUTE_UNUSED,
14089                                unsigned long symndx ATTRIBUTE_UNUSED)
14090 {
14091   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14092   return bed->s->arch_size / 8;
14093 }
14094
14095 /* Routines to support the creation of dynamic relocs.  */
14096
14097 /* Returns the name of the dynamic reloc section associated with SEC.  */
14098
14099 static const char *
14100 get_dynamic_reloc_section_name (bfd *       abfd,
14101                                 asection *  sec,
14102                                 bfd_boolean is_rela)
14103 {
14104   char *name;
14105   const char *old_name = bfd_get_section_name (NULL, sec);
14106   const char *prefix = is_rela ? ".rela" : ".rel";
14107
14108   if (old_name == NULL)
14109     return NULL;
14110
14111   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
14112   sprintf (name, "%s%s", prefix, old_name);
14113
14114   return name;
14115 }
14116
14117 /* Returns the dynamic reloc section associated with SEC.
14118    If necessary compute the name of the dynamic reloc section based
14119    on SEC's name (looked up in ABFD's string table) and the setting
14120    of IS_RELA.  */
14121
14122 asection *
14123 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
14124                                     asection *  sec,
14125                                     bfd_boolean is_rela)
14126 {
14127   asection * reloc_sec = elf_section_data (sec)->sreloc;
14128
14129   if (reloc_sec == NULL)
14130     {
14131       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14132
14133       if (name != NULL)
14134         {
14135           reloc_sec = bfd_get_linker_section (abfd, name);
14136
14137           if (reloc_sec != NULL)
14138             elf_section_data (sec)->sreloc = reloc_sec;
14139         }
14140     }
14141
14142   return reloc_sec;
14143 }
14144
14145 /* Returns the dynamic reloc section associated with SEC.  If the
14146    section does not exist it is created and attached to the DYNOBJ
14147    bfd and stored in the SRELOC field of SEC's elf_section_data
14148    structure.
14149
14150    ALIGNMENT is the alignment for the newly created section and
14151    IS_RELA defines whether the name should be .rela.<SEC's name>
14152    or .rel.<SEC's name>.  The section name is looked up in the
14153    string table associated with ABFD.  */
14154
14155 asection *
14156 _bfd_elf_make_dynamic_reloc_section (asection *sec,
14157                                      bfd *dynobj,
14158                                      unsigned int alignment,
14159                                      bfd *abfd,
14160                                      bfd_boolean is_rela)
14161 {
14162   asection * reloc_sec = elf_section_data (sec)->sreloc;
14163
14164   if (reloc_sec == NULL)
14165     {
14166       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14167
14168       if (name == NULL)
14169         return NULL;
14170
14171       reloc_sec = bfd_get_linker_section (dynobj, name);
14172
14173       if (reloc_sec == NULL)
14174         {
14175           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
14176                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
14177           if ((sec->flags & SEC_ALLOC) != 0)
14178             flags |= SEC_ALLOC | SEC_LOAD;
14179
14180           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
14181           if (reloc_sec != NULL)
14182             {
14183               /* _bfd_elf_get_sec_type_attr chooses a section type by
14184                  name.  Override as it may be wrong, eg. for a user
14185                  section named "auto" we'll get ".relauto" which is
14186                  seen to be a .rela section.  */
14187               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
14188               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
14189                 reloc_sec = NULL;
14190             }
14191         }
14192
14193       elf_section_data (sec)->sreloc = reloc_sec;
14194     }
14195
14196   return reloc_sec;
14197 }
14198
14199 /* Copy the ELF symbol type and other attributes for a linker script
14200    assignment from HSRC to HDEST.  Generally this should be treated as
14201    if we found a strong non-dynamic definition for HDEST (except that
14202    ld ignores multiple definition errors).  */
14203 void
14204 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
14205                                      struct bfd_link_hash_entry *hdest,
14206                                      struct bfd_link_hash_entry *hsrc)
14207 {
14208   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
14209   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
14210   Elf_Internal_Sym isym;
14211
14212   ehdest->type = ehsrc->type;
14213   ehdest->target_internal = ehsrc->target_internal;
14214
14215   isym.st_other = ehsrc->other;
14216   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
14217 }
14218
14219 /* Append a RELA relocation REL to section S in BFD.  */
14220
14221 void
14222 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14223 {
14224   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14225   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
14226   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
14227   bed->s->swap_reloca_out (abfd, rel, loc);
14228 }
14229
14230 /* Append a REL relocation REL to section S in BFD.  */
14231
14232 void
14233 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14234 {
14235   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14236   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
14237   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
14238   bed->s->swap_reloc_out (abfd, rel, loc);
14239 }
14240
14241 /* Define __start, __stop, .startof. or .sizeof. symbol.  */
14242
14243 struct bfd_link_hash_entry *
14244 bfd_elf_define_start_stop (struct bfd_link_info *info,
14245                            const char *symbol, asection *sec)
14246 {
14247   struct elf_link_hash_entry *h;
14248
14249   h = elf_link_hash_lookup (elf_hash_table (info), symbol,
14250                             FALSE, FALSE, TRUE);
14251   if (h != NULL
14252       && (h->root.type == bfd_link_hash_undefined
14253           || h->root.type == bfd_link_hash_undefweak
14254           || (h->ref_regular && !h->def_regular)))
14255     {
14256       h->root.type = bfd_link_hash_defined;
14257       h->root.u.def.section = sec;
14258       h->root.u.def.value = 0;
14259       h->def_regular = 1;
14260       h->def_dynamic = 0;
14261       h->start_stop = 1;
14262       h->u2.start_stop_section = sec;
14263       if (symbol[0] == '.')
14264         {
14265           /* .startof. and .sizeof. symbols are local.  */
14266           const struct elf_backend_data *bed;
14267           bed = get_elf_backend_data (info->output_bfd);
14268           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
14269         }
14270       else if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
14271         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_PROTECTED;
14272       return &h->root;
14273     }
14274   return NULL;
14275 }