PR22471, undefined reference to linker-defined symbols
[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->is_weakalias)
727         {
728           struct elf_link_hash_entry *def = weakdef (h);
729
730           if (def->dynindx == -1
731               && !bfd_elf_link_record_dynamic_symbol (info, def))
732             return FALSE;
733         }
734     }
735
736   return TRUE;
737 }
738
739 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
740    success, and 2 on a failure caused by attempting to record a symbol
741    in a discarded section, eg. a discarded link-once section symbol.  */
742
743 int
744 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
745                                           bfd *input_bfd,
746                                           long input_indx)
747 {
748   bfd_size_type amt;
749   struct elf_link_local_dynamic_entry *entry;
750   struct elf_link_hash_table *eht;
751   struct elf_strtab_hash *dynstr;
752   size_t dynstr_index;
753   char *name;
754   Elf_External_Sym_Shndx eshndx;
755   char esym[sizeof (Elf64_External_Sym)];
756
757   if (! is_elf_hash_table (info->hash))
758     return 0;
759
760   /* See if the entry exists already.  */
761   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
762     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
763       return 1;
764
765   amt = sizeof (*entry);
766   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
767   if (entry == NULL)
768     return 0;
769
770   /* Go find the symbol, so that we can find it's name.  */
771   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
772                              1, input_indx, &entry->isym, esym, &eshndx))
773     {
774       bfd_release (input_bfd, entry);
775       return 0;
776     }
777
778   if (entry->isym.st_shndx != SHN_UNDEF
779       && entry->isym.st_shndx < SHN_LORESERVE)
780     {
781       asection *s;
782
783       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
784       if (s == NULL || bfd_is_abs_section (s->output_section))
785         {
786           /* We can still bfd_release here as nothing has done another
787              bfd_alloc.  We can't do this later in this function.  */
788           bfd_release (input_bfd, entry);
789           return 2;
790         }
791     }
792
793   name = (bfd_elf_string_from_elf_section
794           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
795            entry->isym.st_name));
796
797   dynstr = elf_hash_table (info)->dynstr;
798   if (dynstr == NULL)
799     {
800       /* Create a strtab to hold the dynamic symbol names.  */
801       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
802       if (dynstr == NULL)
803         return 0;
804     }
805
806   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
807   if (dynstr_index == (size_t) -1)
808     return 0;
809   entry->isym.st_name = dynstr_index;
810
811   eht = elf_hash_table (info);
812
813   entry->next = eht->dynlocal;
814   eht->dynlocal = entry;
815   entry->input_bfd = input_bfd;
816   entry->input_indx = input_indx;
817   eht->dynsymcount++;
818
819   /* Whatever binding the symbol had before, it's now local.  */
820   entry->isym.st_info
821     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
822
823   /* The dynindx will be set at the end of size_dynamic_sections.  */
824
825   return 1;
826 }
827
828 /* Return the dynindex of a local dynamic symbol.  */
829
830 long
831 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
832                                     bfd *input_bfd,
833                                     long input_indx)
834 {
835   struct elf_link_local_dynamic_entry *e;
836
837   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
838     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
839       return e->dynindx;
840   return -1;
841 }
842
843 /* This function is used to renumber the dynamic symbols, if some of
844    them are removed because they are marked as local.  This is called
845    via elf_link_hash_traverse.  */
846
847 static bfd_boolean
848 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
849                                       void *data)
850 {
851   size_t *count = (size_t *) data;
852
853   if (h->forced_local)
854     return TRUE;
855
856   if (h->dynindx != -1)
857     h->dynindx = ++(*count);
858
859   return TRUE;
860 }
861
862
863 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
864    STB_LOCAL binding.  */
865
866 static bfd_boolean
867 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
868                                             void *data)
869 {
870   size_t *count = (size_t *) data;
871
872   if (!h->forced_local)
873     return TRUE;
874
875   if (h->dynindx != -1)
876     h->dynindx = ++(*count);
877
878   return TRUE;
879 }
880
881 /* Return true if the dynamic symbol for a given section should be
882    omitted when creating a shared library.  */
883 bfd_boolean
884 _bfd_elf_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED,
885                                    struct bfd_link_info *info,
886                                    asection *p)
887 {
888   struct elf_link_hash_table *htab;
889   asection *ip;
890
891   switch (elf_section_data (p)->this_hdr.sh_type)
892     {
893     case SHT_PROGBITS:
894     case SHT_NOBITS:
895       /* If sh_type is yet undecided, assume it could be
896          SHT_PROGBITS/SHT_NOBITS.  */
897     case SHT_NULL:
898       htab = elf_hash_table (info);
899       if (p == htab->tls_sec)
900         return FALSE;
901
902       if (htab->text_index_section != NULL)
903         return p != htab->text_index_section && p != htab->data_index_section;
904
905       return (htab->dynobj != NULL
906               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
907               && ip->output_section == p);
908
909       /* There shouldn't be section relative relocations
910          against any other section.  */
911     default:
912       return TRUE;
913     }
914 }
915
916 /* Assign dynsym indices.  In a shared library we generate a section
917    symbol for each output section, which come first.  Next come symbols
918    which have been forced to local binding.  Then all of the back-end
919    allocated local dynamic syms, followed by the rest of the global
920    symbols.  */
921
922 static unsigned long
923 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
924                                 struct bfd_link_info *info,
925                                 unsigned long *section_sym_count)
926 {
927   unsigned long dynsymcount = 0;
928
929   if (bfd_link_pic (info)
930       || elf_hash_table (info)->is_relocatable_executable)
931     {
932       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
933       asection *p;
934       for (p = output_bfd->sections; p ; p = p->next)
935         if ((p->flags & SEC_EXCLUDE) == 0
936             && (p->flags & SEC_ALLOC) != 0
937             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
938           elf_section_data (p)->dynindx = ++dynsymcount;
939         else
940           elf_section_data (p)->dynindx = 0;
941     }
942   *section_sym_count = dynsymcount;
943
944   elf_link_hash_traverse (elf_hash_table (info),
945                           elf_link_renumber_local_hash_table_dynsyms,
946                           &dynsymcount);
947
948   if (elf_hash_table (info)->dynlocal)
949     {
950       struct elf_link_local_dynamic_entry *p;
951       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
952         p->dynindx = ++dynsymcount;
953     }
954   elf_hash_table (info)->local_dynsymcount = dynsymcount;
955
956   elf_link_hash_traverse (elf_hash_table (info),
957                           elf_link_renumber_hash_table_dynsyms,
958                           &dynsymcount);
959
960   /* There is an unused NULL entry at the head of the table which we
961      must account for in our count even if the table is empty since it
962      is intended for the mandatory DT_SYMTAB tag (.dynsym section) in
963      .dynamic section.  */
964   dynsymcount++;
965
966   elf_hash_table (info)->dynsymcount = dynsymcount;
967   return dynsymcount;
968 }
969
970 /* Merge st_other field.  */
971
972 static void
973 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
974                     const Elf_Internal_Sym *isym, asection *sec,
975                     bfd_boolean definition, bfd_boolean dynamic)
976 {
977   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
978
979   /* If st_other has a processor-specific meaning, specific
980      code might be needed here.  */
981   if (bed->elf_backend_merge_symbol_attribute)
982     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
983                                                 dynamic);
984
985   if (!dynamic)
986     {
987       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
988       unsigned hvis = ELF_ST_VISIBILITY (h->other);
989
990       /* Keep the most constraining visibility.  Leave the remainder
991          of the st_other field to elf_backend_merge_symbol_attribute.  */
992       if (symvis - 1 < hvis - 1)
993         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
994     }
995   else if (definition
996            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
997            && (sec->flags & SEC_READONLY) == 0)
998     h->protected_def = 1;
999 }
1000
1001 /* This function is called when we want to merge a new symbol with an
1002    existing symbol.  It handles the various cases which arise when we
1003    find a definition in a dynamic object, or when there is already a
1004    definition in a dynamic object.  The new symbol is described by
1005    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
1006    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
1007    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
1008    of an old common symbol.  We set OVERRIDE if the old symbol is
1009    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
1010    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
1011    to change.  By OK to change, we mean that we shouldn't warn if the
1012    type or size does change.  */
1013
1014 static bfd_boolean
1015 _bfd_elf_merge_symbol (bfd *abfd,
1016                        struct bfd_link_info *info,
1017                        const char *name,
1018                        Elf_Internal_Sym *sym,
1019                        asection **psec,
1020                        bfd_vma *pvalue,
1021                        struct elf_link_hash_entry **sym_hash,
1022                        bfd **poldbfd,
1023                        bfd_boolean *pold_weak,
1024                        unsigned int *pold_alignment,
1025                        bfd_boolean *skip,
1026                        bfd_boolean *override,
1027                        bfd_boolean *type_change_ok,
1028                        bfd_boolean *size_change_ok,
1029                        bfd_boolean *matched)
1030 {
1031   asection *sec, *oldsec;
1032   struct elf_link_hash_entry *h;
1033   struct elf_link_hash_entry *hi;
1034   struct elf_link_hash_entry *flip;
1035   int bind;
1036   bfd *oldbfd;
1037   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
1038   bfd_boolean newweak, oldweak, newfunc, oldfunc;
1039   const struct elf_backend_data *bed;
1040   char *new_version;
1041   bfd_boolean default_sym = *matched;
1042
1043   *skip = FALSE;
1044   *override = FALSE;
1045
1046   sec = *psec;
1047   bind = ELF_ST_BIND (sym->st_info);
1048
1049   if (! bfd_is_und_section (sec))
1050     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
1051   else
1052     h = ((struct elf_link_hash_entry *)
1053          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
1054   if (h == NULL)
1055     return FALSE;
1056   *sym_hash = h;
1057
1058   bed = get_elf_backend_data (abfd);
1059
1060   /* NEW_VERSION is the symbol version of the new symbol.  */
1061   if (h->versioned != unversioned)
1062     {
1063       /* Symbol version is unknown or versioned.  */
1064       new_version = strrchr (name, ELF_VER_CHR);
1065       if (new_version)
1066         {
1067           if (h->versioned == unknown)
1068             {
1069               if (new_version > name && new_version[-1] != ELF_VER_CHR)
1070                 h->versioned = versioned_hidden;
1071               else
1072                 h->versioned = versioned;
1073             }
1074           new_version += 1;
1075           if (new_version[0] == '\0')
1076             new_version = NULL;
1077         }
1078       else
1079         h->versioned = unversioned;
1080     }
1081   else
1082     new_version = NULL;
1083
1084   /* For merging, we only care about real symbols.  But we need to make
1085      sure that indirect symbol dynamic flags are updated.  */
1086   hi = h;
1087   while (h->root.type == bfd_link_hash_indirect
1088          || h->root.type == bfd_link_hash_warning)
1089     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1090
1091   if (!*matched)
1092     {
1093       if (hi == h || h->root.type == bfd_link_hash_new)
1094         *matched = TRUE;
1095       else
1096         {
1097           /* OLD_HIDDEN is true if the existing symbol is only visible
1098              to the symbol with the same symbol version.  NEW_HIDDEN is
1099              true if the new symbol is only visible to the symbol with
1100              the same symbol version.  */
1101           bfd_boolean old_hidden = h->versioned == versioned_hidden;
1102           bfd_boolean new_hidden = hi->versioned == versioned_hidden;
1103           if (!old_hidden && !new_hidden)
1104             /* The new symbol matches the existing symbol if both
1105                aren't hidden.  */
1106             *matched = TRUE;
1107           else
1108             {
1109               /* OLD_VERSION is the symbol version of the existing
1110                  symbol. */
1111               char *old_version;
1112
1113               if (h->versioned >= versioned)
1114                 old_version = strrchr (h->root.root.string,
1115                                        ELF_VER_CHR) + 1;
1116               else
1117                  old_version = NULL;
1118
1119               /* The new symbol matches the existing symbol if they
1120                  have the same symbol version.  */
1121               *matched = (old_version == new_version
1122                           || (old_version != NULL
1123                               && new_version != NULL
1124                               && strcmp (old_version, new_version) == 0));
1125             }
1126         }
1127     }
1128
1129   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
1130      existing symbol.  */
1131
1132   oldbfd = NULL;
1133   oldsec = NULL;
1134   switch (h->root.type)
1135     {
1136     default:
1137       break;
1138
1139     case bfd_link_hash_undefined:
1140     case bfd_link_hash_undefweak:
1141       oldbfd = h->root.u.undef.abfd;
1142       break;
1143
1144     case bfd_link_hash_defined:
1145     case bfd_link_hash_defweak:
1146       oldbfd = h->root.u.def.section->owner;
1147       oldsec = h->root.u.def.section;
1148       break;
1149
1150     case bfd_link_hash_common:
1151       oldbfd = h->root.u.c.p->section->owner;
1152       oldsec = h->root.u.c.p->section;
1153       if (pold_alignment)
1154         *pold_alignment = h->root.u.c.p->alignment_power;
1155       break;
1156     }
1157   if (poldbfd && *poldbfd == NULL)
1158     *poldbfd = oldbfd;
1159
1160   /* Differentiate strong and weak symbols.  */
1161   newweak = bind == STB_WEAK;
1162   oldweak = (h->root.type == bfd_link_hash_defweak
1163              || h->root.type == bfd_link_hash_undefweak);
1164   if (pold_weak)
1165     *pold_weak = oldweak;
1166
1167   /* We have to check it for every instance since the first few may be
1168      references and not all compilers emit symbol type for undefined
1169      symbols.  */
1170   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
1171
1172   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1173      respectively, is from a dynamic object.  */
1174
1175   newdyn = (abfd->flags & DYNAMIC) != 0;
1176
1177   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
1178      syms and defined syms in dynamic libraries respectively.
1179      ref_dynamic on the other hand can be set for a symbol defined in
1180      a dynamic library, and def_dynamic may not be set;  When the
1181      definition in a dynamic lib is overridden by a definition in the
1182      executable use of the symbol in the dynamic lib becomes a
1183      reference to the executable symbol.  */
1184   if (newdyn)
1185     {
1186       if (bfd_is_und_section (sec))
1187         {
1188           if (bind != STB_WEAK)
1189             {
1190               h->ref_dynamic_nonweak = 1;
1191               hi->ref_dynamic_nonweak = 1;
1192             }
1193         }
1194       else
1195         {
1196           /* Update the existing symbol only if they match. */
1197           if (*matched)
1198             h->dynamic_def = 1;
1199           hi->dynamic_def = 1;
1200         }
1201     }
1202
1203   /* If we just created the symbol, mark it as being an ELF symbol.
1204      Other than that, there is nothing to do--there is no merge issue
1205      with a newly defined symbol--so we just return.  */
1206
1207   if (h->root.type == bfd_link_hash_new)
1208     {
1209       h->non_elf = 0;
1210       return TRUE;
1211     }
1212
1213   /* In cases involving weak versioned symbols, we may wind up trying
1214      to merge a symbol with itself.  Catch that here, to avoid the
1215      confusion that results if we try to override a symbol with
1216      itself.  The additional tests catch cases like
1217      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1218      dynamic object, which we do want to handle here.  */
1219   if (abfd == oldbfd
1220       && (newweak || oldweak)
1221       && ((abfd->flags & DYNAMIC) == 0
1222           || !h->def_regular))
1223     return TRUE;
1224
1225   olddyn = FALSE;
1226   if (oldbfd != NULL)
1227     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1228   else if (oldsec != NULL)
1229     {
1230       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1231          indices used by MIPS ELF.  */
1232       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1233     }
1234
1235   /* Handle a case where plugin_notice won't be called and thus won't
1236      set the non_ir_ref flags on the first pass over symbols.  */
1237   if (oldbfd != NULL
1238       && (oldbfd->flags & BFD_PLUGIN) != (abfd->flags & BFD_PLUGIN)
1239       && newdyn != olddyn)
1240     {
1241       h->root.non_ir_ref_dynamic = TRUE;
1242       hi->root.non_ir_ref_dynamic = TRUE;
1243     }
1244
1245   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1246      respectively, appear to be a definition rather than reference.  */
1247
1248   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1249
1250   olddef = (h->root.type != bfd_link_hash_undefined
1251             && h->root.type != bfd_link_hash_undefweak
1252             && h->root.type != bfd_link_hash_common);
1253
1254   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1255      respectively, appear to be a function.  */
1256
1257   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1258              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1259
1260   oldfunc = (h->type != STT_NOTYPE
1261              && bed->is_function_type (h->type));
1262
1263   if (!(newfunc && oldfunc)
1264       && ELF_ST_TYPE (sym->st_info) != h->type
1265       && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1266       && h->type != STT_NOTYPE
1267       && (newdef || bfd_is_com_section (sec))
1268       && (olddef || h->root.type == bfd_link_hash_common))
1269     {
1270       /* If creating a default indirect symbol ("foo" or "foo@") from
1271          a dynamic versioned definition ("foo@@") skip doing so if
1272          there is an existing regular definition with a different
1273          type.  We don't want, for example, a "time" variable in the
1274          executable overriding a "time" function in a shared library.  */
1275       if (newdyn
1276           && !olddyn)
1277         {
1278           *skip = TRUE;
1279           return TRUE;
1280         }
1281
1282       /* When adding a symbol from a regular object file after we have
1283          created indirect symbols, undo the indirection and any
1284          dynamic state.  */
1285       if (hi != h
1286           && !newdyn
1287           && olddyn)
1288         {
1289           h = hi;
1290           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1291           h->forced_local = 0;
1292           h->ref_dynamic = 0;
1293           h->def_dynamic = 0;
1294           h->dynamic_def = 0;
1295           if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1296             {
1297               h->root.type = bfd_link_hash_undefined;
1298               h->root.u.undef.abfd = abfd;
1299             }
1300           else
1301             {
1302               h->root.type = bfd_link_hash_new;
1303               h->root.u.undef.abfd = NULL;
1304             }
1305           return TRUE;
1306         }
1307     }
1308
1309   /* Check TLS symbols.  We don't check undefined symbols introduced
1310      by "ld -u" which have no type (and oldbfd NULL), and we don't
1311      check symbols from plugins because they also have no type.  */
1312   if (oldbfd != NULL
1313       && (oldbfd->flags & BFD_PLUGIN) == 0
1314       && (abfd->flags & BFD_PLUGIN) == 0
1315       && ELF_ST_TYPE (sym->st_info) != h->type
1316       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1317     {
1318       bfd *ntbfd, *tbfd;
1319       bfd_boolean ntdef, tdef;
1320       asection *ntsec, *tsec;
1321
1322       if (h->type == STT_TLS)
1323         {
1324           ntbfd = abfd;
1325           ntsec = sec;
1326           ntdef = newdef;
1327           tbfd = oldbfd;
1328           tsec = oldsec;
1329           tdef = olddef;
1330         }
1331       else
1332         {
1333           ntbfd = oldbfd;
1334           ntsec = oldsec;
1335           ntdef = olddef;
1336           tbfd = abfd;
1337           tsec = sec;
1338           tdef = newdef;
1339         }
1340
1341       if (tdef && ntdef)
1342         _bfd_error_handler
1343           /* xgettext:c-format */
1344           (_("%s: TLS definition in %B section %A "
1345              "mismatches non-TLS definition in %B section %A"),
1346            h->root.root.string, tbfd, tsec, ntbfd, ntsec);
1347       else if (!tdef && !ntdef)
1348         _bfd_error_handler
1349           /* xgettext:c-format */
1350           (_("%s: TLS reference in %B "
1351              "mismatches non-TLS reference in %B"),
1352            h->root.root.string, tbfd, ntbfd);
1353       else if (tdef)
1354         _bfd_error_handler
1355           /* xgettext:c-format */
1356           (_("%s: TLS definition in %B section %A "
1357              "mismatches non-TLS reference in %B"),
1358            h->root.root.string, tbfd, tsec, ntbfd);
1359       else
1360         _bfd_error_handler
1361           /* xgettext:c-format */
1362           (_("%s: TLS reference in %B "
1363              "mismatches non-TLS definition in %B section %A"),
1364            h->root.root.string, tbfd, ntbfd, ntsec);
1365
1366       bfd_set_error (bfd_error_bad_value);
1367       return FALSE;
1368     }
1369
1370   /* If the old symbol has non-default visibility, we ignore the new
1371      definition from a dynamic object.  */
1372   if (newdyn
1373       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1374       && !bfd_is_und_section (sec))
1375     {
1376       *skip = TRUE;
1377       /* Make sure this symbol is dynamic.  */
1378       h->ref_dynamic = 1;
1379       hi->ref_dynamic = 1;
1380       /* A protected symbol has external availability. Make sure it is
1381          recorded as dynamic.
1382
1383          FIXME: Should we check type and size for protected symbol?  */
1384       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1385         return bfd_elf_link_record_dynamic_symbol (info, h);
1386       else
1387         return TRUE;
1388     }
1389   else if (!newdyn
1390            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1391            && h->def_dynamic)
1392     {
1393       /* If the new symbol with non-default visibility comes from a
1394          relocatable file and the old definition comes from a dynamic
1395          object, we remove the old definition.  */
1396       if (hi->root.type == bfd_link_hash_indirect)
1397         {
1398           /* Handle the case where the old dynamic definition is
1399              default versioned.  We need to copy the symbol info from
1400              the symbol with default version to the normal one if it
1401              was referenced before.  */
1402           if (h->ref_regular)
1403             {
1404               hi->root.type = h->root.type;
1405               h->root.type = bfd_link_hash_indirect;
1406               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1407
1408               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1409               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1410                 {
1411                   /* If the new symbol is hidden or internal, completely undo
1412                      any dynamic link state.  */
1413                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1414                   h->forced_local = 0;
1415                   h->ref_dynamic = 0;
1416                 }
1417               else
1418                 h->ref_dynamic = 1;
1419
1420               h->def_dynamic = 0;
1421               /* FIXME: Should we check type and size for protected symbol?  */
1422               h->size = 0;
1423               h->type = 0;
1424
1425               h = hi;
1426             }
1427           else
1428             h = hi;
1429         }
1430
1431       /* If the old symbol was undefined before, then it will still be
1432          on the undefs list.  If the new symbol is undefined or
1433          common, we can't make it bfd_link_hash_new here, because new
1434          undefined or common symbols will be added to the undefs list
1435          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1436          added twice to the undefs list.  Also, if the new symbol is
1437          undefweak then we don't want to lose the strong undef.  */
1438       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1439         {
1440           h->root.type = bfd_link_hash_undefined;
1441           h->root.u.undef.abfd = abfd;
1442         }
1443       else
1444         {
1445           h->root.type = bfd_link_hash_new;
1446           h->root.u.undef.abfd = NULL;
1447         }
1448
1449       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1450         {
1451           /* If the new symbol is hidden or internal, completely undo
1452              any dynamic link state.  */
1453           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1454           h->forced_local = 0;
1455           h->ref_dynamic = 0;
1456         }
1457       else
1458         h->ref_dynamic = 1;
1459       h->def_dynamic = 0;
1460       /* FIXME: Should we check type and size for protected symbol?  */
1461       h->size = 0;
1462       h->type = 0;
1463       return TRUE;
1464     }
1465
1466   /* If a new weak symbol definition comes from a regular file and the
1467      old symbol comes from a dynamic library, we treat the new one as
1468      strong.  Similarly, an old weak symbol definition from a regular
1469      file is treated as strong when the new symbol comes from a dynamic
1470      library.  Further, an old weak symbol from a dynamic library is
1471      treated as strong if the new symbol is from a dynamic library.
1472      This reflects the way glibc's ld.so works.
1473
1474      Also allow a weak symbol to override a linker script symbol
1475      defined by an early pass over the script.  This is done so the
1476      linker knows the symbol is defined in an object file, for the
1477      DEFINED script function.
1478
1479      Do this before setting *type_change_ok or *size_change_ok so that
1480      we warn properly when dynamic library symbols are overridden.  */
1481
1482   if (newdef && !newdyn && (olddyn || h->root.ldscript_def))
1483     newweak = FALSE;
1484   if (olddef && newdyn)
1485     oldweak = FALSE;
1486
1487   /* Allow changes between different types of function symbol.  */
1488   if (newfunc && oldfunc)
1489     *type_change_ok = TRUE;
1490
1491   /* It's OK to change the type if either the existing symbol or the
1492      new symbol is weak.  A type change is also OK if the old symbol
1493      is undefined and the new symbol is defined.  */
1494
1495   if (oldweak
1496       || newweak
1497       || (newdef
1498           && h->root.type == bfd_link_hash_undefined))
1499     *type_change_ok = TRUE;
1500
1501   /* It's OK to change the size if either the existing symbol or the
1502      new symbol is weak, or if the old symbol is undefined.  */
1503
1504   if (*type_change_ok
1505       || h->root.type == bfd_link_hash_undefined)
1506     *size_change_ok = TRUE;
1507
1508   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1509      symbol, respectively, appears to be a common symbol in a dynamic
1510      object.  If a symbol appears in an uninitialized section, and is
1511      not weak, and is not a function, then it may be a common symbol
1512      which was resolved when the dynamic object was created.  We want
1513      to treat such symbols specially, because they raise special
1514      considerations when setting the symbol size: if the symbol
1515      appears as a common symbol in a regular object, and the size in
1516      the regular object is larger, we must make sure that we use the
1517      larger size.  This problematic case can always be avoided in C,
1518      but it must be handled correctly when using Fortran shared
1519      libraries.
1520
1521      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1522      likewise for OLDDYNCOMMON and OLDDEF.
1523
1524      Note that this test is just a heuristic, and that it is quite
1525      possible to have an uninitialized symbol in a shared object which
1526      is really a definition, rather than a common symbol.  This could
1527      lead to some minor confusion when the symbol really is a common
1528      symbol in some regular object.  However, I think it will be
1529      harmless.  */
1530
1531   if (newdyn
1532       && newdef
1533       && !newweak
1534       && (sec->flags & SEC_ALLOC) != 0
1535       && (sec->flags & SEC_LOAD) == 0
1536       && sym->st_size > 0
1537       && !newfunc)
1538     newdyncommon = TRUE;
1539   else
1540     newdyncommon = FALSE;
1541
1542   if (olddyn
1543       && olddef
1544       && h->root.type == bfd_link_hash_defined
1545       && h->def_dynamic
1546       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1547       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1548       && h->size > 0
1549       && !oldfunc)
1550     olddyncommon = TRUE;
1551   else
1552     olddyncommon = FALSE;
1553
1554   /* We now know everything about the old and new symbols.  We ask the
1555      backend to check if we can merge them.  */
1556   if (bed->merge_symbol != NULL)
1557     {
1558       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1559         return FALSE;
1560       sec = *psec;
1561     }
1562
1563   /* There are multiple definitions of a normal symbol.  Skip the
1564      default symbol as well as definition from an IR object.  */
1565   if (olddef && !olddyn && !oldweak && newdef && !newdyn && !newweak
1566       && !default_sym && h->def_regular
1567       && !(oldbfd != NULL
1568            && (oldbfd->flags & BFD_PLUGIN) != 0
1569            && (abfd->flags & BFD_PLUGIN) == 0))
1570     {
1571       /* Handle a multiple definition.  */
1572       (*info->callbacks->multiple_definition) (info, &h->root,
1573                                                abfd, sec, *pvalue);
1574       *skip = TRUE;
1575       return TRUE;
1576     }
1577
1578   /* If both the old and the new symbols look like common symbols in a
1579      dynamic object, set the size of the symbol to the larger of the
1580      two.  */
1581
1582   if (olddyncommon
1583       && newdyncommon
1584       && sym->st_size != h->size)
1585     {
1586       /* Since we think we have two common symbols, issue a multiple
1587          common warning if desired.  Note that we only warn if the
1588          size is different.  If the size is the same, we simply let
1589          the old symbol override the new one as normally happens with
1590          symbols defined in dynamic objects.  */
1591
1592       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1593                                            bfd_link_hash_common, sym->st_size);
1594       if (sym->st_size > h->size)
1595         h->size = sym->st_size;
1596
1597       *size_change_ok = TRUE;
1598     }
1599
1600   /* If we are looking at a dynamic object, and we have found a
1601      definition, we need to see if the symbol was already defined by
1602      some other object.  If so, we want to use the existing
1603      definition, and we do not want to report a multiple symbol
1604      definition error; we do this by clobbering *PSEC to be
1605      bfd_und_section_ptr.
1606
1607      We treat a common symbol as a definition if the symbol in the
1608      shared library is a function, since common symbols always
1609      represent variables; this can cause confusion in principle, but
1610      any such confusion would seem to indicate an erroneous program or
1611      shared library.  We also permit a common symbol in a regular
1612      object to override a weak symbol in a shared object.  */
1613
1614   if (newdyn
1615       && newdef
1616       && (olddef
1617           || (h->root.type == bfd_link_hash_common
1618               && (newweak || newfunc))))
1619     {
1620       *override = TRUE;
1621       newdef = FALSE;
1622       newdyncommon = FALSE;
1623
1624       *psec = sec = bfd_und_section_ptr;
1625       *size_change_ok = TRUE;
1626
1627       /* If we get here when the old symbol is a common symbol, then
1628          we are explicitly letting it override a weak symbol or
1629          function in a dynamic object, and we don't want to warn about
1630          a type change.  If the old symbol is a defined symbol, a type
1631          change warning may still be appropriate.  */
1632
1633       if (h->root.type == bfd_link_hash_common)
1634         *type_change_ok = TRUE;
1635     }
1636
1637   /* Handle the special case of an old common symbol merging with a
1638      new symbol which looks like a common symbol in a shared object.
1639      We change *PSEC and *PVALUE to make the new symbol look like a
1640      common symbol, and let _bfd_generic_link_add_one_symbol do the
1641      right thing.  */
1642
1643   if (newdyncommon
1644       && h->root.type == bfd_link_hash_common)
1645     {
1646       *override = TRUE;
1647       newdef = FALSE;
1648       newdyncommon = FALSE;
1649       *pvalue = sym->st_size;
1650       *psec = sec = bed->common_section (oldsec);
1651       *size_change_ok = TRUE;
1652     }
1653
1654   /* Skip weak definitions of symbols that are already defined.  */
1655   if (newdef && olddef && newweak)
1656     {
1657       /* Don't skip new non-IR weak syms.  */
1658       if (!(oldbfd != NULL
1659             && (oldbfd->flags & BFD_PLUGIN) != 0
1660             && (abfd->flags & BFD_PLUGIN) == 0))
1661         {
1662           newdef = FALSE;
1663           *skip = TRUE;
1664         }
1665
1666       /* Merge st_other.  If the symbol already has a dynamic index,
1667          but visibility says it should not be visible, turn it into a
1668          local symbol.  */
1669       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1670       if (h->dynindx != -1)
1671         switch (ELF_ST_VISIBILITY (h->other))
1672           {
1673           case STV_INTERNAL:
1674           case STV_HIDDEN:
1675             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1676             break;
1677           }
1678     }
1679
1680   /* If the old symbol is from a dynamic object, and the new symbol is
1681      a definition which is not from a dynamic object, then the new
1682      symbol overrides the old symbol.  Symbols from regular files
1683      always take precedence over symbols from dynamic objects, even if
1684      they are defined after the dynamic object in the link.
1685
1686      As above, we again permit a common symbol in a regular object to
1687      override a definition in a shared object if the shared object
1688      symbol is a function or is weak.  */
1689
1690   flip = NULL;
1691   if (!newdyn
1692       && (newdef
1693           || (bfd_is_com_section (sec)
1694               && (oldweak || oldfunc)))
1695       && olddyn
1696       && olddef
1697       && h->def_dynamic)
1698     {
1699       /* Change the hash table entry to undefined, and let
1700          _bfd_generic_link_add_one_symbol do the right thing with the
1701          new definition.  */
1702
1703       h->root.type = bfd_link_hash_undefined;
1704       h->root.u.undef.abfd = h->root.u.def.section->owner;
1705       *size_change_ok = TRUE;
1706
1707       olddef = FALSE;
1708       olddyncommon = FALSE;
1709
1710       /* We again permit a type change when a common symbol may be
1711          overriding a function.  */
1712
1713       if (bfd_is_com_section (sec))
1714         {
1715           if (oldfunc)
1716             {
1717               /* If a common symbol overrides a function, make sure
1718                  that it isn't defined dynamically nor has type
1719                  function.  */
1720               h->def_dynamic = 0;
1721               h->type = STT_NOTYPE;
1722             }
1723           *type_change_ok = TRUE;
1724         }
1725
1726       if (hi->root.type == bfd_link_hash_indirect)
1727         flip = hi;
1728       else
1729         /* This union may have been set to be non-NULL when this symbol
1730            was seen in a dynamic object.  We must force the union to be
1731            NULL, so that it is correct for a regular symbol.  */
1732         h->verinfo.vertree = NULL;
1733     }
1734
1735   /* Handle the special case of a new common symbol merging with an
1736      old symbol that looks like it might be a common symbol defined in
1737      a shared object.  Note that we have already handled the case in
1738      which a new common symbol should simply override the definition
1739      in the shared library.  */
1740
1741   if (! newdyn
1742       && bfd_is_com_section (sec)
1743       && olddyncommon)
1744     {
1745       /* It would be best if we could set the hash table entry to a
1746          common symbol, but we don't know what to use for the section
1747          or the alignment.  */
1748       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1749                                            bfd_link_hash_common, sym->st_size);
1750
1751       /* If the presumed common symbol in the dynamic object is
1752          larger, pretend that the new symbol has its size.  */
1753
1754       if (h->size > *pvalue)
1755         *pvalue = h->size;
1756
1757       /* We need to remember the alignment required by the symbol
1758          in the dynamic object.  */
1759       BFD_ASSERT (pold_alignment);
1760       *pold_alignment = h->root.u.def.section->alignment_power;
1761
1762       olddef = FALSE;
1763       olddyncommon = FALSE;
1764
1765       h->root.type = bfd_link_hash_undefined;
1766       h->root.u.undef.abfd = h->root.u.def.section->owner;
1767
1768       *size_change_ok = TRUE;
1769       *type_change_ok = TRUE;
1770
1771       if (hi->root.type == bfd_link_hash_indirect)
1772         flip = hi;
1773       else
1774         h->verinfo.vertree = NULL;
1775     }
1776
1777   if (flip != NULL)
1778     {
1779       /* Handle the case where we had a versioned symbol in a dynamic
1780          library and now find a definition in a normal object.  In this
1781          case, we make the versioned symbol point to the normal one.  */
1782       flip->root.type = h->root.type;
1783       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1784       h->root.type = bfd_link_hash_indirect;
1785       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1786       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1787       if (h->def_dynamic)
1788         {
1789           h->def_dynamic = 0;
1790           flip->ref_dynamic = 1;
1791         }
1792     }
1793
1794   return TRUE;
1795 }
1796
1797 /* This function is called to create an indirect symbol from the
1798    default for the symbol with the default version if needed. The
1799    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1800    set DYNSYM if the new indirect symbol is dynamic.  */
1801
1802 static bfd_boolean
1803 _bfd_elf_add_default_symbol (bfd *abfd,
1804                              struct bfd_link_info *info,
1805                              struct elf_link_hash_entry *h,
1806                              const char *name,
1807                              Elf_Internal_Sym *sym,
1808                              asection *sec,
1809                              bfd_vma value,
1810                              bfd **poldbfd,
1811                              bfd_boolean *dynsym)
1812 {
1813   bfd_boolean type_change_ok;
1814   bfd_boolean size_change_ok;
1815   bfd_boolean skip;
1816   char *shortname;
1817   struct elf_link_hash_entry *hi;
1818   struct bfd_link_hash_entry *bh;
1819   const struct elf_backend_data *bed;
1820   bfd_boolean collect;
1821   bfd_boolean dynamic;
1822   bfd_boolean override;
1823   char *p;
1824   size_t len, shortlen;
1825   asection *tmp_sec;
1826   bfd_boolean matched;
1827
1828   if (h->versioned == unversioned || h->versioned == versioned_hidden)
1829     return TRUE;
1830
1831   /* If this symbol has a version, and it is the default version, we
1832      create an indirect symbol from the default name to the fully
1833      decorated name.  This will cause external references which do not
1834      specify a version to be bound to this version of the symbol.  */
1835   p = strchr (name, ELF_VER_CHR);
1836   if (h->versioned == unknown)
1837     {
1838       if (p == NULL)
1839         {
1840           h->versioned = unversioned;
1841           return TRUE;
1842         }
1843       else
1844         {
1845           if (p[1] != ELF_VER_CHR)
1846             {
1847               h->versioned = versioned_hidden;
1848               return TRUE;
1849             }
1850           else
1851             h->versioned = versioned;
1852         }
1853     }
1854   else
1855     {
1856       /* PR ld/19073: We may see an unversioned definition after the
1857          default version.  */
1858       if (p == NULL)
1859         return TRUE;
1860     }
1861
1862   bed = get_elf_backend_data (abfd);
1863   collect = bed->collect;
1864   dynamic = (abfd->flags & DYNAMIC) != 0;
1865
1866   shortlen = p - name;
1867   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1868   if (shortname == NULL)
1869     return FALSE;
1870   memcpy (shortname, name, shortlen);
1871   shortname[shortlen] = '\0';
1872
1873   /* We are going to create a new symbol.  Merge it with any existing
1874      symbol with this name.  For the purposes of the merge, act as
1875      though we were defining the symbol we just defined, although we
1876      actually going to define an indirect symbol.  */
1877   type_change_ok = FALSE;
1878   size_change_ok = FALSE;
1879   matched = TRUE;
1880   tmp_sec = sec;
1881   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1882                               &hi, poldbfd, NULL, NULL, &skip, &override,
1883                               &type_change_ok, &size_change_ok, &matched))
1884     return FALSE;
1885
1886   if (skip)
1887     goto nondefault;
1888
1889   if (hi->def_regular)
1890     {
1891       /* If the undecorated symbol will have a version added by a
1892          script different to H, then don't indirect to/from the
1893          undecorated symbol.  This isn't ideal because we may not yet
1894          have seen symbol versions, if given by a script on the
1895          command line rather than via --version-script.  */
1896       if (hi->verinfo.vertree == NULL && info->version_info != NULL)
1897         {
1898           bfd_boolean hide;
1899
1900           hi->verinfo.vertree
1901             = bfd_find_version_for_sym (info->version_info,
1902                                         hi->root.root.string, &hide);
1903           if (hi->verinfo.vertree != NULL && hide)
1904             {
1905               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
1906               goto nondefault;
1907             }
1908         }
1909       if (hi->verinfo.vertree != NULL
1910           && strcmp (p + 1 + (p[1] == '@'), hi->verinfo.vertree->name) != 0)
1911         goto nondefault;
1912     }
1913
1914   if (! override)
1915     {
1916       /* Add the default symbol if not performing a relocatable link.  */
1917       if (! bfd_link_relocatable (info))
1918         {
1919           bh = &hi->root;
1920           if (! (_bfd_generic_link_add_one_symbol
1921                  (info, abfd, shortname, BSF_INDIRECT,
1922                   bfd_ind_section_ptr,
1923                   0, name, FALSE, collect, &bh)))
1924             return FALSE;
1925           hi = (struct elf_link_hash_entry *) bh;
1926         }
1927     }
1928   else
1929     {
1930       /* In this case the symbol named SHORTNAME is overriding the
1931          indirect symbol we want to add.  We were planning on making
1932          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1933          is the name without a version.  NAME is the fully versioned
1934          name, and it is the default version.
1935
1936          Overriding means that we already saw a definition for the
1937          symbol SHORTNAME in a regular object, and it is overriding
1938          the symbol defined in the dynamic object.
1939
1940          When this happens, we actually want to change NAME, the
1941          symbol we just added, to refer to SHORTNAME.  This will cause
1942          references to NAME in the shared object to become references
1943          to SHORTNAME in the regular object.  This is what we expect
1944          when we override a function in a shared object: that the
1945          references in the shared object will be mapped to the
1946          definition in the regular object.  */
1947
1948       while (hi->root.type == bfd_link_hash_indirect
1949              || hi->root.type == bfd_link_hash_warning)
1950         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1951
1952       h->root.type = bfd_link_hash_indirect;
1953       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1954       if (h->def_dynamic)
1955         {
1956           h->def_dynamic = 0;
1957           hi->ref_dynamic = 1;
1958           if (hi->ref_regular
1959               || hi->def_regular)
1960             {
1961               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1962                 return FALSE;
1963             }
1964         }
1965
1966       /* Now set HI to H, so that the following code will set the
1967          other fields correctly.  */
1968       hi = h;
1969     }
1970
1971   /* Check if HI is a warning symbol.  */
1972   if (hi->root.type == bfd_link_hash_warning)
1973     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1974
1975   /* If there is a duplicate definition somewhere, then HI may not
1976      point to an indirect symbol.  We will have reported an error to
1977      the user in that case.  */
1978
1979   if (hi->root.type == bfd_link_hash_indirect)
1980     {
1981       struct elf_link_hash_entry *ht;
1982
1983       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1984       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
1985
1986       /* A reference to the SHORTNAME symbol from a dynamic library
1987          will be satisfied by the versioned symbol at runtime.  In
1988          effect, we have a reference to the versioned symbol.  */
1989       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1990       hi->dynamic_def |= ht->dynamic_def;
1991
1992       /* See if the new flags lead us to realize that the symbol must
1993          be dynamic.  */
1994       if (! *dynsym)
1995         {
1996           if (! dynamic)
1997             {
1998               if (! bfd_link_executable (info)
1999                   || hi->def_dynamic
2000                   || hi->ref_dynamic)
2001                 *dynsym = TRUE;
2002             }
2003           else
2004             {
2005               if (hi->ref_regular)
2006                 *dynsym = TRUE;
2007             }
2008         }
2009     }
2010
2011   /* We also need to define an indirection from the nondefault version
2012      of the symbol.  */
2013
2014 nondefault:
2015   len = strlen (name);
2016   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
2017   if (shortname == NULL)
2018     return FALSE;
2019   memcpy (shortname, name, shortlen);
2020   memcpy (shortname + shortlen, p + 1, len - shortlen);
2021
2022   /* Once again, merge with any existing symbol.  */
2023   type_change_ok = FALSE;
2024   size_change_ok = FALSE;
2025   tmp_sec = sec;
2026   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
2027                               &hi, poldbfd, NULL, NULL, &skip, &override,
2028                               &type_change_ok, &size_change_ok, &matched))
2029     return FALSE;
2030
2031   if (skip)
2032     return TRUE;
2033
2034   if (override)
2035     {
2036       /* Here SHORTNAME is a versioned name, so we don't expect to see
2037          the type of override we do in the case above unless it is
2038          overridden by a versioned definition.  */
2039       if (hi->root.type != bfd_link_hash_defined
2040           && hi->root.type != bfd_link_hash_defweak)
2041         _bfd_error_handler
2042           /* xgettext:c-format */
2043           (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
2044            abfd, shortname);
2045     }
2046   else
2047     {
2048       bh = &hi->root;
2049       if (! (_bfd_generic_link_add_one_symbol
2050              (info, abfd, shortname, BSF_INDIRECT,
2051               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
2052         return FALSE;
2053       hi = (struct elf_link_hash_entry *) bh;
2054
2055       /* If there is a duplicate definition somewhere, then HI may not
2056          point to an indirect symbol.  We will have reported an error
2057          to the user in that case.  */
2058
2059       if (hi->root.type == bfd_link_hash_indirect)
2060         {
2061           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
2062           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
2063           hi->dynamic_def |= h->dynamic_def;
2064
2065           /* See if the new flags lead us to realize that the symbol
2066              must be dynamic.  */
2067           if (! *dynsym)
2068             {
2069               if (! dynamic)
2070                 {
2071                   if (! bfd_link_executable (info)
2072                       || hi->ref_dynamic)
2073                     *dynsym = TRUE;
2074                 }
2075               else
2076                 {
2077                   if (hi->ref_regular)
2078                     *dynsym = TRUE;
2079                 }
2080             }
2081         }
2082     }
2083
2084   return TRUE;
2085 }
2086 \f
2087 /* This routine is used to export all defined symbols into the dynamic
2088    symbol table.  It is called via elf_link_hash_traverse.  */
2089
2090 static bfd_boolean
2091 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
2092 {
2093   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2094
2095   /* Ignore indirect symbols.  These are added by the versioning code.  */
2096   if (h->root.type == bfd_link_hash_indirect)
2097     return TRUE;
2098
2099   /* Ignore this if we won't export it.  */
2100   if (!eif->info->export_dynamic && !h->dynamic)
2101     return TRUE;
2102
2103   if (h->dynindx == -1
2104       && (h->def_regular || h->ref_regular)
2105       && ! bfd_hide_sym_by_version (eif->info->version_info,
2106                                     h->root.root.string))
2107     {
2108       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2109         {
2110           eif->failed = TRUE;
2111           return FALSE;
2112         }
2113     }
2114
2115   return TRUE;
2116 }
2117 \f
2118 /* Look through the symbols which are defined in other shared
2119    libraries and referenced here.  Update the list of version
2120    dependencies.  This will be put into the .gnu.version_r section.
2121    This function is called via elf_link_hash_traverse.  */
2122
2123 static bfd_boolean
2124 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
2125                                          void *data)
2126 {
2127   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
2128   Elf_Internal_Verneed *t;
2129   Elf_Internal_Vernaux *a;
2130   bfd_size_type amt;
2131
2132   /* We only care about symbols defined in shared objects with version
2133      information.  */
2134   if (!h->def_dynamic
2135       || h->def_regular
2136       || h->dynindx == -1
2137       || h->verinfo.verdef == NULL
2138       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
2139           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
2140     return TRUE;
2141
2142   /* See if we already know about this version.  */
2143   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
2144        t != NULL;
2145        t = t->vn_nextref)
2146     {
2147       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
2148         continue;
2149
2150       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
2151         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
2152           return TRUE;
2153
2154       break;
2155     }
2156
2157   /* This is a new version.  Add it to tree we are building.  */
2158
2159   if (t == NULL)
2160     {
2161       amt = sizeof *t;
2162       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
2163       if (t == NULL)
2164         {
2165           rinfo->failed = TRUE;
2166           return FALSE;
2167         }
2168
2169       t->vn_bfd = h->verinfo.verdef->vd_bfd;
2170       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
2171       elf_tdata (rinfo->info->output_bfd)->verref = t;
2172     }
2173
2174   amt = sizeof *a;
2175   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
2176   if (a == NULL)
2177     {
2178       rinfo->failed = TRUE;
2179       return FALSE;
2180     }
2181
2182   /* Note that we are copying a string pointer here, and testing it
2183      above.  If bfd_elf_string_from_elf_section is ever changed to
2184      discard the string data when low in memory, this will have to be
2185      fixed.  */
2186   a->vna_nodename = h->verinfo.verdef->vd_nodename;
2187
2188   a->vna_flags = h->verinfo.verdef->vd_flags;
2189   a->vna_nextptr = t->vn_auxptr;
2190
2191   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
2192   ++rinfo->vers;
2193
2194   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
2195
2196   t->vn_auxptr = a;
2197
2198   return TRUE;
2199 }
2200
2201 /* Figure out appropriate versions for all the symbols.  We may not
2202    have the version number script until we have read all of the input
2203    files, so until that point we don't know which symbols should be
2204    local.  This function is called via elf_link_hash_traverse.  */
2205
2206 static bfd_boolean
2207 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2208 {
2209   struct elf_info_failed *sinfo;
2210   struct bfd_link_info *info;
2211   const struct elf_backend_data *bed;
2212   struct elf_info_failed eif;
2213   char *p;
2214
2215   sinfo = (struct elf_info_failed *) data;
2216   info = sinfo->info;
2217
2218   /* Fix the symbol flags.  */
2219   eif.failed = FALSE;
2220   eif.info = info;
2221   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2222     {
2223       if (eif.failed)
2224         sinfo->failed = TRUE;
2225       return FALSE;
2226     }
2227
2228   /* We only need version numbers for symbols defined in regular
2229      objects.  */
2230   if (!h->def_regular)
2231     return TRUE;
2232
2233   bed = get_elf_backend_data (info->output_bfd);
2234   p = strchr (h->root.root.string, ELF_VER_CHR);
2235   if (p != NULL && h->verinfo.vertree == NULL)
2236     {
2237       struct bfd_elf_version_tree *t;
2238
2239       ++p;
2240       if (*p == ELF_VER_CHR)
2241         ++p;
2242
2243       /* If there is no version string, we can just return out.  */
2244       if (*p == '\0')
2245         return TRUE;
2246
2247       /* Look for the version.  If we find it, it is no longer weak.  */
2248       for (t = sinfo->info->version_info; t != NULL; t = t->next)
2249         {
2250           if (strcmp (t->name, p) == 0)
2251             {
2252               size_t len;
2253               char *alc;
2254               struct bfd_elf_version_expr *d;
2255
2256               len = p - h->root.root.string;
2257               alc = (char *) bfd_malloc (len);
2258               if (alc == NULL)
2259                 {
2260                   sinfo->failed = TRUE;
2261                   return FALSE;
2262                 }
2263               memcpy (alc, h->root.root.string, len - 1);
2264               alc[len - 1] = '\0';
2265               if (alc[len - 2] == ELF_VER_CHR)
2266                 alc[len - 2] = '\0';
2267
2268               h->verinfo.vertree = t;
2269               t->used = TRUE;
2270               d = NULL;
2271
2272               if (t->globals.list != NULL)
2273                 d = (*t->match) (&t->globals, NULL, alc);
2274
2275               /* See if there is anything to force this symbol to
2276                  local scope.  */
2277               if (d == NULL && t->locals.list != NULL)
2278                 {
2279                   d = (*t->match) (&t->locals, NULL, alc);
2280                   if (d != NULL
2281                       && h->dynindx != -1
2282                       && ! info->export_dynamic)
2283                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2284                 }
2285
2286               free (alc);
2287               break;
2288             }
2289         }
2290
2291       /* If we are building an application, we need to create a
2292          version node for this version.  */
2293       if (t == NULL && bfd_link_executable (info))
2294         {
2295           struct bfd_elf_version_tree **pp;
2296           int version_index;
2297
2298           /* If we aren't going to export this symbol, we don't need
2299              to worry about it.  */
2300           if (h->dynindx == -1)
2301             return TRUE;
2302
2303           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd,
2304                                                           sizeof *t);
2305           if (t == NULL)
2306             {
2307               sinfo->failed = TRUE;
2308               return FALSE;
2309             }
2310
2311           t->name = p;
2312           t->name_indx = (unsigned int) -1;
2313           t->used = TRUE;
2314
2315           version_index = 1;
2316           /* Don't count anonymous version tag.  */
2317           if (sinfo->info->version_info != NULL
2318               && sinfo->info->version_info->vernum == 0)
2319             version_index = 0;
2320           for (pp = &sinfo->info->version_info;
2321                *pp != NULL;
2322                pp = &(*pp)->next)
2323             ++version_index;
2324           t->vernum = version_index;
2325
2326           *pp = t;
2327
2328           h->verinfo.vertree = t;
2329         }
2330       else if (t == NULL)
2331         {
2332           /* We could not find the version for a symbol when
2333              generating a shared archive.  Return an error.  */
2334           _bfd_error_handler
2335             /* xgettext:c-format */
2336             (_("%B: version node not found for symbol %s"),
2337              info->output_bfd, h->root.root.string);
2338           bfd_set_error (bfd_error_bad_value);
2339           sinfo->failed = TRUE;
2340           return FALSE;
2341         }
2342     }
2343
2344   /* If we don't have a version for this symbol, see if we can find
2345      something.  */
2346   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2347     {
2348       bfd_boolean hide;
2349
2350       h->verinfo.vertree
2351         = bfd_find_version_for_sym (sinfo->info->version_info,
2352                                     h->root.root.string, &hide);
2353       if (h->verinfo.vertree != NULL && hide)
2354         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2355     }
2356
2357   return TRUE;
2358 }
2359 \f
2360 /* Read and swap the relocs from the section indicated by SHDR.  This
2361    may be either a REL or a RELA section.  The relocations are
2362    translated into RELA relocations and stored in INTERNAL_RELOCS,
2363    which should have already been allocated to contain enough space.
2364    The EXTERNAL_RELOCS are a buffer where the external form of the
2365    relocations should be stored.
2366
2367    Returns FALSE if something goes wrong.  */
2368
2369 static bfd_boolean
2370 elf_link_read_relocs_from_section (bfd *abfd,
2371                                    asection *sec,
2372                                    Elf_Internal_Shdr *shdr,
2373                                    void *external_relocs,
2374                                    Elf_Internal_Rela *internal_relocs)
2375 {
2376   const struct elf_backend_data *bed;
2377   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2378   const bfd_byte *erela;
2379   const bfd_byte *erelaend;
2380   Elf_Internal_Rela *irela;
2381   Elf_Internal_Shdr *symtab_hdr;
2382   size_t nsyms;
2383
2384   /* Position ourselves at the start of the section.  */
2385   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2386     return FALSE;
2387
2388   /* Read the relocations.  */
2389   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2390     return FALSE;
2391
2392   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2393   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2394
2395   bed = get_elf_backend_data (abfd);
2396
2397   /* Convert the external relocations to the internal format.  */
2398   if (shdr->sh_entsize == bed->s->sizeof_rel)
2399     swap_in = bed->s->swap_reloc_in;
2400   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2401     swap_in = bed->s->swap_reloca_in;
2402   else
2403     {
2404       bfd_set_error (bfd_error_wrong_format);
2405       return FALSE;
2406     }
2407
2408   erela = (const bfd_byte *) external_relocs;
2409   erelaend = erela + shdr->sh_size;
2410   irela = internal_relocs;
2411   while (erela < erelaend)
2412     {
2413       bfd_vma r_symndx;
2414
2415       (*swap_in) (abfd, erela, irela);
2416       r_symndx = ELF32_R_SYM (irela->r_info);
2417       if (bed->s->arch_size == 64)
2418         r_symndx >>= 24;
2419       if (nsyms > 0)
2420         {
2421           if ((size_t) r_symndx >= nsyms)
2422             {
2423               _bfd_error_handler
2424                 /* xgettext:c-format */
2425                 (_("%B: bad reloc symbol index (%#Lx >= %#lx)"
2426                    " for offset %#Lx in section `%A'"),
2427                  abfd, r_symndx, (unsigned long) nsyms,
2428                  irela->r_offset, sec);
2429               bfd_set_error (bfd_error_bad_value);
2430               return FALSE;
2431             }
2432         }
2433       else if (r_symndx != STN_UNDEF)
2434         {
2435           _bfd_error_handler
2436             /* xgettext:c-format */
2437             (_("%B: non-zero symbol index (%#Lx)"
2438                " for offset %#Lx in section `%A'"
2439                " when the object file has no symbol table"),
2440              abfd, r_symndx,
2441              irela->r_offset, sec);
2442           bfd_set_error (bfd_error_bad_value);
2443           return FALSE;
2444         }
2445       irela += bed->s->int_rels_per_ext_rel;
2446       erela += shdr->sh_entsize;
2447     }
2448
2449   return TRUE;
2450 }
2451
2452 /* Read and swap the relocs for a section O.  They may have been
2453    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2454    not NULL, they are used as buffers to read into.  They are known to
2455    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2456    the return value is allocated using either malloc or bfd_alloc,
2457    according to the KEEP_MEMORY argument.  If O has two relocation
2458    sections (both REL and RELA relocations), then the REL_HDR
2459    relocations will appear first in INTERNAL_RELOCS, followed by the
2460    RELA_HDR relocations.  */
2461
2462 Elf_Internal_Rela *
2463 _bfd_elf_link_read_relocs (bfd *abfd,
2464                            asection *o,
2465                            void *external_relocs,
2466                            Elf_Internal_Rela *internal_relocs,
2467                            bfd_boolean keep_memory)
2468 {
2469   void *alloc1 = NULL;
2470   Elf_Internal_Rela *alloc2 = NULL;
2471   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2472   struct bfd_elf_section_data *esdo = elf_section_data (o);
2473   Elf_Internal_Rela *internal_rela_relocs;
2474
2475   if (esdo->relocs != NULL)
2476     return esdo->relocs;
2477
2478   if (o->reloc_count == 0)
2479     return NULL;
2480
2481   if (internal_relocs == NULL)
2482     {
2483       bfd_size_type size;
2484
2485       size = (bfd_size_type) o->reloc_count * sizeof (Elf_Internal_Rela);
2486       if (keep_memory)
2487         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2488       else
2489         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2490       if (internal_relocs == NULL)
2491         goto error_return;
2492     }
2493
2494   if (external_relocs == NULL)
2495     {
2496       bfd_size_type size = 0;
2497
2498       if (esdo->rel.hdr)
2499         size += esdo->rel.hdr->sh_size;
2500       if (esdo->rela.hdr)
2501         size += esdo->rela.hdr->sh_size;
2502
2503       alloc1 = bfd_malloc (size);
2504       if (alloc1 == NULL)
2505         goto error_return;
2506       external_relocs = alloc1;
2507     }
2508
2509   internal_rela_relocs = internal_relocs;
2510   if (esdo->rel.hdr)
2511     {
2512       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2513                                               external_relocs,
2514                                               internal_relocs))
2515         goto error_return;
2516       external_relocs = (((bfd_byte *) external_relocs)
2517                          + esdo->rel.hdr->sh_size);
2518       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2519                                * bed->s->int_rels_per_ext_rel);
2520     }
2521
2522   if (esdo->rela.hdr
2523       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2524                                               external_relocs,
2525                                               internal_rela_relocs)))
2526     goto error_return;
2527
2528   /* Cache the results for next time, if we can.  */
2529   if (keep_memory)
2530     esdo->relocs = internal_relocs;
2531
2532   if (alloc1 != NULL)
2533     free (alloc1);
2534
2535   /* Don't free alloc2, since if it was allocated we are passing it
2536      back (under the name of internal_relocs).  */
2537
2538   return internal_relocs;
2539
2540  error_return:
2541   if (alloc1 != NULL)
2542     free (alloc1);
2543   if (alloc2 != NULL)
2544     {
2545       if (keep_memory)
2546         bfd_release (abfd, alloc2);
2547       else
2548         free (alloc2);
2549     }
2550   return NULL;
2551 }
2552
2553 /* Compute the size of, and allocate space for, REL_HDR which is the
2554    section header for a section containing relocations for O.  */
2555
2556 static bfd_boolean
2557 _bfd_elf_link_size_reloc_section (bfd *abfd,
2558                                   struct bfd_elf_section_reloc_data *reldata)
2559 {
2560   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2561
2562   /* That allows us to calculate the size of the section.  */
2563   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2564
2565   /* The contents field must last into write_object_contents, so we
2566      allocate it with bfd_alloc rather than malloc.  Also since we
2567      cannot be sure that the contents will actually be filled in,
2568      we zero the allocated space.  */
2569   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2570   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2571     return FALSE;
2572
2573   if (reldata->hashes == NULL && reldata->count)
2574     {
2575       struct elf_link_hash_entry **p;
2576
2577       p = ((struct elf_link_hash_entry **)
2578            bfd_zmalloc (reldata->count * sizeof (*p)));
2579       if (p == NULL)
2580         return FALSE;
2581
2582       reldata->hashes = p;
2583     }
2584
2585   return TRUE;
2586 }
2587
2588 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2589    originated from the section given by INPUT_REL_HDR) to the
2590    OUTPUT_BFD.  */
2591
2592 bfd_boolean
2593 _bfd_elf_link_output_relocs (bfd *output_bfd,
2594                              asection *input_section,
2595                              Elf_Internal_Shdr *input_rel_hdr,
2596                              Elf_Internal_Rela *internal_relocs,
2597                              struct elf_link_hash_entry **rel_hash
2598                                ATTRIBUTE_UNUSED)
2599 {
2600   Elf_Internal_Rela *irela;
2601   Elf_Internal_Rela *irelaend;
2602   bfd_byte *erel;
2603   struct bfd_elf_section_reloc_data *output_reldata;
2604   asection *output_section;
2605   const struct elf_backend_data *bed;
2606   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2607   struct bfd_elf_section_data *esdo;
2608
2609   output_section = input_section->output_section;
2610
2611   bed = get_elf_backend_data (output_bfd);
2612   esdo = elf_section_data (output_section);
2613   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2614     {
2615       output_reldata = &esdo->rel;
2616       swap_out = bed->s->swap_reloc_out;
2617     }
2618   else if (esdo->rela.hdr
2619            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2620     {
2621       output_reldata = &esdo->rela;
2622       swap_out = bed->s->swap_reloca_out;
2623     }
2624   else
2625     {
2626       _bfd_error_handler
2627         /* xgettext:c-format */
2628         (_("%B: relocation size mismatch in %B section %A"),
2629          output_bfd, input_section->owner, input_section);
2630       bfd_set_error (bfd_error_wrong_format);
2631       return FALSE;
2632     }
2633
2634   erel = output_reldata->hdr->contents;
2635   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2636   irela = internal_relocs;
2637   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2638                       * bed->s->int_rels_per_ext_rel);
2639   while (irela < irelaend)
2640     {
2641       (*swap_out) (output_bfd, irela, erel);
2642       irela += bed->s->int_rels_per_ext_rel;
2643       erel += input_rel_hdr->sh_entsize;
2644     }
2645
2646   /* Bump the counter, so that we know where to add the next set of
2647      relocations.  */
2648   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2649
2650   return TRUE;
2651 }
2652 \f
2653 /* Make weak undefined symbols in PIE dynamic.  */
2654
2655 bfd_boolean
2656 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2657                                  struct elf_link_hash_entry *h)
2658 {
2659   if (bfd_link_pie (info)
2660       && h->dynindx == -1
2661       && h->root.type == bfd_link_hash_undefweak)
2662     return bfd_elf_link_record_dynamic_symbol (info, h);
2663
2664   return TRUE;
2665 }
2666
2667 /* Fix up the flags for a symbol.  This handles various cases which
2668    can only be fixed after all the input files are seen.  This is
2669    currently called by both adjust_dynamic_symbol and
2670    assign_sym_version, which is unnecessary but perhaps more robust in
2671    the face of future changes.  */
2672
2673 static bfd_boolean
2674 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2675                            struct elf_info_failed *eif)
2676 {
2677   const struct elf_backend_data *bed;
2678
2679   /* If this symbol was mentioned in a non-ELF file, try to set
2680      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2681      permit a non-ELF file to correctly refer to a symbol defined in
2682      an ELF dynamic object.  */
2683   if (h->non_elf)
2684     {
2685       while (h->root.type == bfd_link_hash_indirect)
2686         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2687
2688       if (h->root.type != bfd_link_hash_defined
2689           && h->root.type != bfd_link_hash_defweak)
2690         {
2691           h->ref_regular = 1;
2692           h->ref_regular_nonweak = 1;
2693         }
2694       else
2695         {
2696           if (h->root.u.def.section->owner != NULL
2697               && (bfd_get_flavour (h->root.u.def.section->owner)
2698                   == bfd_target_elf_flavour))
2699             {
2700               h->ref_regular = 1;
2701               h->ref_regular_nonweak = 1;
2702             }
2703           else
2704             h->def_regular = 1;
2705         }
2706
2707       if (h->dynindx == -1
2708           && (h->def_dynamic
2709               || h->ref_dynamic))
2710         {
2711           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2712             {
2713               eif->failed = TRUE;
2714               return FALSE;
2715             }
2716         }
2717     }
2718   else
2719     {
2720       /* Unfortunately, NON_ELF is only correct if the symbol
2721          was first seen in a non-ELF file.  Fortunately, if the symbol
2722          was first seen in an ELF file, we're probably OK unless the
2723          symbol was defined in a non-ELF file.  Catch that case here.
2724          FIXME: We're still in trouble if the symbol was first seen in
2725          a dynamic object, and then later in a non-ELF regular object.  */
2726       if ((h->root.type == bfd_link_hash_defined
2727            || h->root.type == bfd_link_hash_defweak)
2728           && !h->def_regular
2729           && (h->root.u.def.section->owner != NULL
2730               ? (bfd_get_flavour (h->root.u.def.section->owner)
2731                  != bfd_target_elf_flavour)
2732               : (bfd_is_abs_section (h->root.u.def.section)
2733                  && !h->def_dynamic)))
2734         h->def_regular = 1;
2735     }
2736
2737   /* Backend specific symbol fixup.  */
2738   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2739   if (bed->elf_backend_fixup_symbol
2740       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2741     return FALSE;
2742
2743   /* If this is a final link, and the symbol was defined as a common
2744      symbol in a regular object file, and there was no definition in
2745      any dynamic object, then the linker will have allocated space for
2746      the symbol in a common section but the DEF_REGULAR
2747      flag will not have been set.  */
2748   if (h->root.type == bfd_link_hash_defined
2749       && !h->def_regular
2750       && h->ref_regular
2751       && !h->def_dynamic
2752       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2753     h->def_regular = 1;
2754
2755   /* If a weak undefined symbol has non-default visibility, we also
2756      hide it from the dynamic linker.  */
2757   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2758       && h->root.type == bfd_link_hash_undefweak)
2759     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2760
2761   /* A hidden versioned symbol in executable should be forced local if
2762      it is is locally defined, not referenced by shared library and not
2763      exported.  */
2764   else if (bfd_link_executable (eif->info)
2765            && h->versioned == versioned_hidden
2766            && !eif->info->export_dynamic
2767            && !h->dynamic
2768            && !h->ref_dynamic
2769            && h->def_regular)
2770     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2771
2772   /* If -Bsymbolic was used (which means to bind references to global
2773      symbols to the definition within the shared object), and this
2774      symbol was defined in a regular object, then it actually doesn't
2775      need a PLT entry.  Likewise, if the symbol has non-default
2776      visibility.  If the symbol has hidden or internal visibility, we
2777      will force it local.  */
2778   else if (h->needs_plt
2779            && bfd_link_pic (eif->info)
2780            && is_elf_hash_table (eif->info->hash)
2781            && (SYMBOLIC_BIND (eif->info, h)
2782                || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2783            && h->def_regular)
2784     {
2785       bfd_boolean force_local;
2786
2787       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2788                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2789       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2790     }
2791
2792   /* If this is a weak defined symbol in a dynamic object, and we know
2793      the real definition in the dynamic object, copy interesting flags
2794      over to the real definition.  */
2795   if (h->is_weakalias)
2796     {
2797       struct elf_link_hash_entry *def = weakdef (h);
2798
2799       /* If the real definition is defined by a regular object file,
2800          don't do anything special.  See the longer description in
2801          _bfd_elf_adjust_dynamic_symbol, below.  */
2802       if (def->def_regular)
2803         {
2804           h = def;
2805           while ((h = h->u.alias) != def)
2806             h->is_weakalias = 0;
2807         }
2808       else
2809         {
2810           while (h->root.type == bfd_link_hash_indirect)
2811             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2812           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2813                       || h->root.type == bfd_link_hash_defweak);
2814           BFD_ASSERT (def->def_dynamic);
2815           BFD_ASSERT (def->root.type == bfd_link_hash_defined);
2816           (*bed->elf_backend_copy_indirect_symbol) (eif->info, def, h);
2817         }
2818     }
2819
2820   return TRUE;
2821 }
2822
2823 /* Make the backend pick a good value for a dynamic symbol.  This is
2824    called via elf_link_hash_traverse, and also calls itself
2825    recursively.  */
2826
2827 static bfd_boolean
2828 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2829 {
2830   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2831   struct elf_link_hash_table *htab;
2832   const struct elf_backend_data *bed;
2833
2834   if (! is_elf_hash_table (eif->info->hash))
2835     return FALSE;
2836
2837   /* Ignore indirect symbols.  These are added by the versioning code.  */
2838   if (h->root.type == bfd_link_hash_indirect)
2839     return TRUE;
2840
2841   /* Fix the symbol flags.  */
2842   if (! _bfd_elf_fix_symbol_flags (h, eif))
2843     return FALSE;
2844
2845   htab = elf_hash_table (eif->info);
2846   bed = get_elf_backend_data (htab->dynobj);
2847
2848   if (h->root.type == bfd_link_hash_undefweak)
2849     {
2850       if (eif->info->dynamic_undefined_weak == 0)
2851         (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2852       else if (eif->info->dynamic_undefined_weak > 0
2853                && h->ref_regular
2854                && ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2855                && !bfd_hide_sym_by_version (eif->info->version_info,
2856                                             h->root.root.string))
2857         {
2858           if (!bfd_elf_link_record_dynamic_symbol (eif->info, h))
2859             {
2860               eif->failed = TRUE;
2861               return FALSE;
2862             }
2863         }
2864     }
2865
2866   /* If this symbol does not require a PLT entry, and it is not
2867      defined by a dynamic object, or is not referenced by a regular
2868      object, ignore it.  We do have to handle a weak defined symbol,
2869      even if no regular object refers to it, if we decided to add it
2870      to the dynamic symbol table.  FIXME: Do we normally need to worry
2871      about symbols which are defined by one dynamic object and
2872      referenced by another one?  */
2873   if (!h->needs_plt
2874       && h->type != STT_GNU_IFUNC
2875       && (h->def_regular
2876           || !h->def_dynamic
2877           || (!h->ref_regular
2878               && (!h->is_weakalias || weakdef (h)->dynindx == -1))))
2879     {
2880       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2881       return TRUE;
2882     }
2883
2884   /* If we've already adjusted this symbol, don't do it again.  This
2885      can happen via a recursive call.  */
2886   if (h->dynamic_adjusted)
2887     return TRUE;
2888
2889   /* Don't look at this symbol again.  Note that we must set this
2890      after checking the above conditions, because we may look at a
2891      symbol once, decide not to do anything, and then get called
2892      recursively later after REF_REGULAR is set below.  */
2893   h->dynamic_adjusted = 1;
2894
2895   /* If this is a weak definition, and we know a real definition, and
2896      the real symbol is not itself defined by a regular object file,
2897      then get a good value for the real definition.  We handle the
2898      real symbol first, for the convenience of the backend routine.
2899
2900      Note that there is a confusing case here.  If the real definition
2901      is defined by a regular object file, we don't get the real symbol
2902      from the dynamic object, but we do get the weak symbol.  If the
2903      processor backend uses a COPY reloc, then if some routine in the
2904      dynamic object changes the real symbol, we will not see that
2905      change in the corresponding weak symbol.  This is the way other
2906      ELF linkers work as well, and seems to be a result of the shared
2907      library model.
2908
2909      I will clarify this issue.  Most SVR4 shared libraries define the
2910      variable _timezone and define timezone as a weak synonym.  The
2911      tzset call changes _timezone.  If you write
2912        extern int timezone;
2913        int _timezone = 5;
2914        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2915      you might expect that, since timezone is a synonym for _timezone,
2916      the same number will print both times.  However, if the processor
2917      backend uses a COPY reloc, then actually timezone will be copied
2918      into your process image, and, since you define _timezone
2919      yourself, _timezone will not.  Thus timezone and _timezone will
2920      wind up at different memory locations.  The tzset call will set
2921      _timezone, leaving timezone unchanged.  */
2922
2923   if (h->is_weakalias)
2924     {
2925       struct elf_link_hash_entry *def = weakdef (h);
2926
2927       /* If we get to this point, there is an implicit reference to
2928          the alias by a regular object file via the weak symbol H.  */
2929       def->ref_regular = 1;
2930
2931       /* Ensure that the backend adjust_dynamic_symbol function sees
2932          the strong alias before H by recursively calling ourselves.  */
2933       if (!_bfd_elf_adjust_dynamic_symbol (def, eif))
2934         return FALSE;
2935     }
2936
2937   /* If a symbol has no type and no size and does not require a PLT
2938      entry, then we are probably about to do the wrong thing here: we
2939      are probably going to create a COPY reloc for an empty object.
2940      This case can arise when a shared object is built with assembly
2941      code, and the assembly code fails to set the symbol type.  */
2942   if (h->size == 0
2943       && h->type == STT_NOTYPE
2944       && !h->needs_plt)
2945     _bfd_error_handler
2946       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2947        h->root.root.string);
2948
2949   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2950     {
2951       eif->failed = TRUE;
2952       return FALSE;
2953     }
2954
2955   return TRUE;
2956 }
2957
2958 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2959    DYNBSS.  */
2960
2961 bfd_boolean
2962 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
2963                               struct elf_link_hash_entry *h,
2964                               asection *dynbss)
2965 {
2966   unsigned int power_of_two;
2967   bfd_vma mask;
2968   asection *sec = h->root.u.def.section;
2969
2970   /* The section alignment of the definition is the maximum alignment
2971      requirement of symbols defined in the section.  Since we don't
2972      know the symbol alignment requirement, we start with the
2973      maximum alignment and check low bits of the symbol address
2974      for the minimum alignment.  */
2975   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2976   mask = ((bfd_vma) 1 << power_of_two) - 1;
2977   while ((h->root.u.def.value & mask) != 0)
2978     {
2979        mask >>= 1;
2980        --power_of_two;
2981     }
2982
2983   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
2984                                                 dynbss))
2985     {
2986       /* Adjust the section alignment if needed.  */
2987       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
2988                                        power_of_two))
2989         return FALSE;
2990     }
2991
2992   /* We make sure that the symbol will be aligned properly.  */
2993   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
2994
2995   /* Define the symbol as being at this point in DYNBSS.  */
2996   h->root.u.def.section = dynbss;
2997   h->root.u.def.value = dynbss->size;
2998
2999   /* Increment the size of DYNBSS to make room for the symbol.  */
3000   dynbss->size += h->size;
3001
3002   /* No error if extern_protected_data is true.  */
3003   if (h->protected_def
3004       && (!info->extern_protected_data
3005           || (info->extern_protected_data < 0
3006               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
3007     info->callbacks->einfo
3008       (_("%P: copy reloc against protected `%T' is dangerous\n"),
3009        h->root.root.string);
3010
3011   return TRUE;
3012 }
3013
3014 /* Adjust all external symbols pointing into SEC_MERGE sections
3015    to reflect the object merging within the sections.  */
3016
3017 static bfd_boolean
3018 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
3019 {
3020   asection *sec;
3021
3022   if ((h->root.type == bfd_link_hash_defined
3023        || h->root.type == bfd_link_hash_defweak)
3024       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
3025       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
3026     {
3027       bfd *output_bfd = (bfd *) data;
3028
3029       h->root.u.def.value =
3030         _bfd_merged_section_offset (output_bfd,
3031                                     &h->root.u.def.section,
3032                                     elf_section_data (sec)->sec_info,
3033                                     h->root.u.def.value);
3034     }
3035
3036   return TRUE;
3037 }
3038
3039 /* Returns false if the symbol referred to by H should be considered
3040    to resolve local to the current module, and true if it should be
3041    considered to bind dynamically.  */
3042
3043 bfd_boolean
3044 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
3045                            struct bfd_link_info *info,
3046                            bfd_boolean not_local_protected)
3047 {
3048   bfd_boolean binding_stays_local_p;
3049   const struct elf_backend_data *bed;
3050   struct elf_link_hash_table *hash_table;
3051
3052   if (h == NULL)
3053     return FALSE;
3054
3055   while (h->root.type == bfd_link_hash_indirect
3056          || h->root.type == bfd_link_hash_warning)
3057     h = (struct elf_link_hash_entry *) h->root.u.i.link;
3058
3059   /* If it was forced local, then clearly it's not dynamic.  */
3060   if (h->dynindx == -1)
3061     return FALSE;
3062   if (h->forced_local)
3063     return FALSE;
3064
3065   /* Identify the cases where name binding rules say that a
3066      visible symbol resolves locally.  */
3067   binding_stays_local_p = (bfd_link_executable (info)
3068                            || SYMBOLIC_BIND (info, h));
3069
3070   switch (ELF_ST_VISIBILITY (h->other))
3071     {
3072     case STV_INTERNAL:
3073     case STV_HIDDEN:
3074       return FALSE;
3075
3076     case STV_PROTECTED:
3077       hash_table = elf_hash_table (info);
3078       if (!is_elf_hash_table (hash_table))
3079         return FALSE;
3080
3081       bed = get_elf_backend_data (hash_table->dynobj);
3082
3083       /* Proper resolution for function pointer equality may require
3084          that these symbols perhaps be resolved dynamically, even though
3085          we should be resolving them to the current module.  */
3086       if (!not_local_protected || !bed->is_function_type (h->type))
3087         binding_stays_local_p = TRUE;
3088       break;
3089
3090     default:
3091       break;
3092     }
3093
3094   /* If it isn't defined locally, then clearly it's dynamic.  */
3095   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
3096     return TRUE;
3097
3098   /* Otherwise, the symbol is dynamic if binding rules don't tell
3099      us that it remains local.  */
3100   return !binding_stays_local_p;
3101 }
3102
3103 /* Return true if the symbol referred to by H should be considered
3104    to resolve local to the current module, and false otherwise.  Differs
3105    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
3106    undefined symbols.  The two functions are virtually identical except
3107    for the place where dynindx == -1 is tested.  If that test is true,
3108    _bfd_elf_dynamic_symbol_p will say the symbol is local, while
3109    _bfd_elf_symbol_refs_local_p will say the symbol is local only for
3110    defined symbols.
3111    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
3112    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
3113    treatment of undefined weak symbols.  For those that do not make
3114    undefined weak symbols dynamic, both functions may return false.  */
3115
3116 bfd_boolean
3117 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
3118                               struct bfd_link_info *info,
3119                               bfd_boolean local_protected)
3120 {
3121   const struct elf_backend_data *bed;
3122   struct elf_link_hash_table *hash_table;
3123
3124   /* If it's a local sym, of course we resolve locally.  */
3125   if (h == NULL)
3126     return TRUE;
3127
3128   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
3129   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
3130       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
3131     return TRUE;
3132
3133   /* Forced local symbols resolve locally.  */
3134   if (h->forced_local)
3135     return TRUE;
3136
3137   /* Common symbols that become definitions don't get the DEF_REGULAR
3138      flag set, so test it first, and don't bail out.  */
3139   if (ELF_COMMON_DEF_P (h))
3140     /* Do nothing.  */;
3141   /* If we don't have a definition in a regular file, then we can't
3142      resolve locally.  The sym is either undefined or dynamic.  */
3143   else if (!h->def_regular)
3144     return FALSE;
3145
3146   /* Non-dynamic symbols resolve locally.  */
3147   if (h->dynindx == -1)
3148     return TRUE;
3149
3150   /* At this point, we know the symbol is defined and dynamic.  In an
3151      executable it must resolve locally, likewise when building symbolic
3152      shared libraries.  */
3153   if (bfd_link_executable (info) || SYMBOLIC_BIND (info, h))
3154     return TRUE;
3155
3156   /* Now deal with defined dynamic symbols in shared libraries.  Ones
3157      with default visibility might not resolve locally.  */
3158   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
3159     return FALSE;
3160
3161   hash_table = elf_hash_table (info);
3162   if (!is_elf_hash_table (hash_table))
3163     return TRUE;
3164
3165   bed = get_elf_backend_data (hash_table->dynobj);
3166
3167   /* If extern_protected_data is false, STV_PROTECTED non-function
3168      symbols are local.  */
3169   if ((!info->extern_protected_data
3170        || (info->extern_protected_data < 0
3171            && !bed->extern_protected_data))
3172       && !bed->is_function_type (h->type))
3173     return TRUE;
3174
3175   /* Function pointer equality tests may require that STV_PROTECTED
3176      symbols be treated as dynamic symbols.  If the address of a
3177      function not defined in an executable is set to that function's
3178      plt entry in the executable, then the address of the function in
3179      a shared library must also be the plt entry in the executable.  */
3180   return local_protected;
3181 }
3182
3183 /* Caches some TLS segment info, and ensures that the TLS segment vma is
3184    aligned.  Returns the first TLS output section.  */
3185
3186 struct bfd_section *
3187 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
3188 {
3189   struct bfd_section *sec, *tls;
3190   unsigned int align = 0;
3191
3192   for (sec = obfd->sections; sec != NULL; sec = sec->next)
3193     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
3194       break;
3195   tls = sec;
3196
3197   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
3198     if (sec->alignment_power > align)
3199       align = sec->alignment_power;
3200
3201   elf_hash_table (info)->tls_sec = tls;
3202
3203   /* Ensure the alignment of the first section is the largest alignment,
3204      so that the tls segment starts aligned.  */
3205   if (tls != NULL)
3206     tls->alignment_power = align;
3207
3208   return tls;
3209 }
3210
3211 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
3212 static bfd_boolean
3213 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
3214                                   Elf_Internal_Sym *sym)
3215 {
3216   const struct elf_backend_data *bed;
3217
3218   /* Local symbols do not count, but target specific ones might.  */
3219   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
3220       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
3221     return FALSE;
3222
3223   bed = get_elf_backend_data (abfd);
3224   /* Function symbols do not count.  */
3225   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
3226     return FALSE;
3227
3228   /* If the section is undefined, then so is the symbol.  */
3229   if (sym->st_shndx == SHN_UNDEF)
3230     return FALSE;
3231
3232   /* If the symbol is defined in the common section, then
3233      it is a common definition and so does not count.  */
3234   if (bed->common_definition (sym))
3235     return FALSE;
3236
3237   /* If the symbol is in a target specific section then we
3238      must rely upon the backend to tell us what it is.  */
3239   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3240     /* FIXME - this function is not coded yet:
3241
3242        return _bfd_is_global_symbol_definition (abfd, sym);
3243
3244        Instead for now assume that the definition is not global,
3245        Even if this is wrong, at least the linker will behave
3246        in the same way that it used to do.  */
3247     return FALSE;
3248
3249   return TRUE;
3250 }
3251
3252 /* Search the symbol table of the archive element of the archive ABFD
3253    whose archive map contains a mention of SYMDEF, and determine if
3254    the symbol is defined in this element.  */
3255 static bfd_boolean
3256 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3257 {
3258   Elf_Internal_Shdr * hdr;
3259   size_t symcount;
3260   size_t extsymcount;
3261   size_t extsymoff;
3262   Elf_Internal_Sym *isymbuf;
3263   Elf_Internal_Sym *isym;
3264   Elf_Internal_Sym *isymend;
3265   bfd_boolean result;
3266
3267   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3268   if (abfd == NULL)
3269     return FALSE;
3270
3271   if (! bfd_check_format (abfd, bfd_object))
3272     return FALSE;
3273
3274   /* Select the appropriate symbol table.  If we don't know if the
3275      object file is an IR object, give linker LTO plugin a chance to
3276      get the correct symbol table.  */
3277   if (abfd->plugin_format == bfd_plugin_yes
3278 #if BFD_SUPPORTS_PLUGINS
3279       || (abfd->plugin_format == bfd_plugin_unknown
3280           && bfd_link_plugin_object_p (abfd))
3281 #endif
3282       )
3283     {
3284       /* Use the IR symbol table if the object has been claimed by
3285          plugin.  */
3286       abfd = abfd->plugin_dummy_bfd;
3287       hdr = &elf_tdata (abfd)->symtab_hdr;
3288     }
3289   else if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3290     hdr = &elf_tdata (abfd)->symtab_hdr;
3291   else
3292     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3293
3294   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3295
3296   /* The sh_info field of the symtab header tells us where the
3297      external symbols start.  We don't care about the local symbols.  */
3298   if (elf_bad_symtab (abfd))
3299     {
3300       extsymcount = symcount;
3301       extsymoff = 0;
3302     }
3303   else
3304     {
3305       extsymcount = symcount - hdr->sh_info;
3306       extsymoff = hdr->sh_info;
3307     }
3308
3309   if (extsymcount == 0)
3310     return FALSE;
3311
3312   /* Read in the symbol table.  */
3313   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3314                                   NULL, NULL, NULL);
3315   if (isymbuf == NULL)
3316     return FALSE;
3317
3318   /* Scan the symbol table looking for SYMDEF.  */
3319   result = FALSE;
3320   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3321     {
3322       const char *name;
3323
3324       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3325                                               isym->st_name);
3326       if (name == NULL)
3327         break;
3328
3329       if (strcmp (name, symdef->name) == 0)
3330         {
3331           result = is_global_data_symbol_definition (abfd, isym);
3332           break;
3333         }
3334     }
3335
3336   free (isymbuf);
3337
3338   return result;
3339 }
3340 \f
3341 /* Add an entry to the .dynamic table.  */
3342
3343 bfd_boolean
3344 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3345                             bfd_vma tag,
3346                             bfd_vma val)
3347 {
3348   struct elf_link_hash_table *hash_table;
3349   const struct elf_backend_data *bed;
3350   asection *s;
3351   bfd_size_type newsize;
3352   bfd_byte *newcontents;
3353   Elf_Internal_Dyn dyn;
3354
3355   hash_table = elf_hash_table (info);
3356   if (! is_elf_hash_table (hash_table))
3357     return FALSE;
3358
3359   bed = get_elf_backend_data (hash_table->dynobj);
3360   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3361   BFD_ASSERT (s != NULL);
3362
3363   newsize = s->size + bed->s->sizeof_dyn;
3364   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3365   if (newcontents == NULL)
3366     return FALSE;
3367
3368   dyn.d_tag = tag;
3369   dyn.d_un.d_val = val;
3370   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3371
3372   s->size = newsize;
3373   s->contents = newcontents;
3374
3375   return TRUE;
3376 }
3377
3378 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3379    otherwise just check whether one already exists.  Returns -1 on error,
3380    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3381
3382 static int
3383 elf_add_dt_needed_tag (bfd *abfd,
3384                        struct bfd_link_info *info,
3385                        const char *soname,
3386                        bfd_boolean do_it)
3387 {
3388   struct elf_link_hash_table *hash_table;
3389   size_t strindex;
3390
3391   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3392     return -1;
3393
3394   hash_table = elf_hash_table (info);
3395   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3396   if (strindex == (size_t) -1)
3397     return -1;
3398
3399   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3400     {
3401       asection *sdyn;
3402       const struct elf_backend_data *bed;
3403       bfd_byte *extdyn;
3404
3405       bed = get_elf_backend_data (hash_table->dynobj);
3406       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3407       if (sdyn != NULL)
3408         for (extdyn = sdyn->contents;
3409              extdyn < sdyn->contents + sdyn->size;
3410              extdyn += bed->s->sizeof_dyn)
3411           {
3412             Elf_Internal_Dyn dyn;
3413
3414             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3415             if (dyn.d_tag == DT_NEEDED
3416                 && dyn.d_un.d_val == strindex)
3417               {
3418                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3419                 return 1;
3420               }
3421           }
3422     }
3423
3424   if (do_it)
3425     {
3426       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3427         return -1;
3428
3429       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3430         return -1;
3431     }
3432   else
3433     /* We were just checking for existence of the tag.  */
3434     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3435
3436   return 0;
3437 }
3438
3439 /* Return true if SONAME is on the needed list between NEEDED and STOP
3440    (or the end of list if STOP is NULL), and needed by a library that
3441    will be loaded.  */
3442
3443 static bfd_boolean
3444 on_needed_list (const char *soname,
3445                 struct bfd_link_needed_list *needed,
3446                 struct bfd_link_needed_list *stop)
3447 {
3448   struct bfd_link_needed_list *look;
3449   for (look = needed; look != stop; look = look->next)
3450     if (strcmp (soname, look->name) == 0
3451         && ((elf_dyn_lib_class (look->by) & DYN_AS_NEEDED) == 0
3452             /* If needed by a library that itself is not directly
3453                needed, recursively check whether that library is
3454                indirectly needed.  Since we add DT_NEEDED entries to
3455                the end of the list, library dependencies appear after
3456                the library.  Therefore search prior to the current
3457                LOOK, preventing possible infinite recursion.  */
3458             || on_needed_list (elf_dt_name (look->by), needed, look)))
3459       return TRUE;
3460
3461   return FALSE;
3462 }
3463
3464 /* Sort symbol by value, section, and size.  */
3465 static int
3466 elf_sort_symbol (const void *arg1, const void *arg2)
3467 {
3468   const struct elf_link_hash_entry *h1;
3469   const struct elf_link_hash_entry *h2;
3470   bfd_signed_vma vdiff;
3471
3472   h1 = *(const struct elf_link_hash_entry **) arg1;
3473   h2 = *(const struct elf_link_hash_entry **) arg2;
3474   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3475   if (vdiff != 0)
3476     return vdiff > 0 ? 1 : -1;
3477   else
3478     {
3479       int sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3480       if (sdiff != 0)
3481         return sdiff > 0 ? 1 : -1;
3482     }
3483   vdiff = h1->size - h2->size;
3484   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3485 }
3486
3487 /* This function is used to adjust offsets into .dynstr for
3488    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3489
3490 static bfd_boolean
3491 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3492 {
3493   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3494
3495   if (h->dynindx != -1)
3496     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3497   return TRUE;
3498 }
3499
3500 /* Assign string offsets in .dynstr, update all structures referencing
3501    them.  */
3502
3503 static bfd_boolean
3504 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3505 {
3506   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3507   struct elf_link_local_dynamic_entry *entry;
3508   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3509   bfd *dynobj = hash_table->dynobj;
3510   asection *sdyn;
3511   bfd_size_type size;
3512   const struct elf_backend_data *bed;
3513   bfd_byte *extdyn;
3514
3515   _bfd_elf_strtab_finalize (dynstr);
3516   size = _bfd_elf_strtab_size (dynstr);
3517
3518   bed = get_elf_backend_data (dynobj);
3519   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3520   BFD_ASSERT (sdyn != NULL);
3521
3522   /* Update all .dynamic entries referencing .dynstr strings.  */
3523   for (extdyn = sdyn->contents;
3524        extdyn < sdyn->contents + sdyn->size;
3525        extdyn += bed->s->sizeof_dyn)
3526     {
3527       Elf_Internal_Dyn dyn;
3528
3529       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3530       switch (dyn.d_tag)
3531         {
3532         case DT_STRSZ:
3533           dyn.d_un.d_val = size;
3534           break;
3535         case DT_NEEDED:
3536         case DT_SONAME:
3537         case DT_RPATH:
3538         case DT_RUNPATH:
3539         case DT_FILTER:
3540         case DT_AUXILIARY:
3541         case DT_AUDIT:
3542         case DT_DEPAUDIT:
3543           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3544           break;
3545         default:
3546           continue;
3547         }
3548       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3549     }
3550
3551   /* Now update local dynamic symbols.  */
3552   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3553     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3554                                                   entry->isym.st_name);
3555
3556   /* And the rest of dynamic symbols.  */
3557   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3558
3559   /* Adjust version definitions.  */
3560   if (elf_tdata (output_bfd)->cverdefs)
3561     {
3562       asection *s;
3563       bfd_byte *p;
3564       size_t i;
3565       Elf_Internal_Verdef def;
3566       Elf_Internal_Verdaux defaux;
3567
3568       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3569       p = s->contents;
3570       do
3571         {
3572           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3573                                    &def);
3574           p += sizeof (Elf_External_Verdef);
3575           if (def.vd_aux != sizeof (Elf_External_Verdef))
3576             continue;
3577           for (i = 0; i < def.vd_cnt; ++i)
3578             {
3579               _bfd_elf_swap_verdaux_in (output_bfd,
3580                                         (Elf_External_Verdaux *) p, &defaux);
3581               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3582                                                         defaux.vda_name);
3583               _bfd_elf_swap_verdaux_out (output_bfd,
3584                                          &defaux, (Elf_External_Verdaux *) p);
3585               p += sizeof (Elf_External_Verdaux);
3586             }
3587         }
3588       while (def.vd_next);
3589     }
3590
3591   /* Adjust version references.  */
3592   if (elf_tdata (output_bfd)->verref)
3593     {
3594       asection *s;
3595       bfd_byte *p;
3596       size_t i;
3597       Elf_Internal_Verneed need;
3598       Elf_Internal_Vernaux needaux;
3599
3600       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3601       p = s->contents;
3602       do
3603         {
3604           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3605                                     &need);
3606           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3607           _bfd_elf_swap_verneed_out (output_bfd, &need,
3608                                      (Elf_External_Verneed *) p);
3609           p += sizeof (Elf_External_Verneed);
3610           for (i = 0; i < need.vn_cnt; ++i)
3611             {
3612               _bfd_elf_swap_vernaux_in (output_bfd,
3613                                         (Elf_External_Vernaux *) p, &needaux);
3614               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3615                                                          needaux.vna_name);
3616               _bfd_elf_swap_vernaux_out (output_bfd,
3617                                          &needaux,
3618                                          (Elf_External_Vernaux *) p);
3619               p += sizeof (Elf_External_Vernaux);
3620             }
3621         }
3622       while (need.vn_next);
3623     }
3624
3625   return TRUE;
3626 }
3627 \f
3628 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3629    The default is to only match when the INPUT and OUTPUT are exactly
3630    the same target.  */
3631
3632 bfd_boolean
3633 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3634                                     const bfd_target *output)
3635 {
3636   return input == output;
3637 }
3638
3639 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3640    This version is used when different targets for the same architecture
3641    are virtually identical.  */
3642
3643 bfd_boolean
3644 _bfd_elf_relocs_compatible (const bfd_target *input,
3645                             const bfd_target *output)
3646 {
3647   const struct elf_backend_data *obed, *ibed;
3648
3649   if (input == output)
3650     return TRUE;
3651
3652   ibed = xvec_get_elf_backend_data (input);
3653   obed = xvec_get_elf_backend_data (output);
3654
3655   if (ibed->arch != obed->arch)
3656     return FALSE;
3657
3658   /* If both backends are using this function, deem them compatible.  */
3659   return ibed->relocs_compatible == obed->relocs_compatible;
3660 }
3661
3662 /* Make a special call to the linker "notice" function to tell it that
3663    we are about to handle an as-needed lib, or have finished
3664    processing the lib.  */
3665
3666 bfd_boolean
3667 _bfd_elf_notice_as_needed (bfd *ibfd,
3668                            struct bfd_link_info *info,
3669                            enum notice_asneeded_action act)
3670 {
3671   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3672 }
3673
3674 /* Check relocations an ELF object file.  */
3675
3676 bfd_boolean
3677 _bfd_elf_link_check_relocs (bfd *abfd, struct bfd_link_info *info)
3678 {
3679   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3680   struct elf_link_hash_table *htab = elf_hash_table (info);
3681
3682   /* If this object is the same format as the output object, and it is
3683      not a shared library, then let the backend look through the
3684      relocs.
3685
3686      This is required to build global offset table entries and to
3687      arrange for dynamic relocs.  It is not required for the
3688      particular common case of linking non PIC code, even when linking
3689      against shared libraries, but unfortunately there is no way of
3690      knowing whether an object file has been compiled PIC or not.
3691      Looking through the relocs is not particularly time consuming.
3692      The problem is that we must either (1) keep the relocs in memory,
3693      which causes the linker to require additional runtime memory or
3694      (2) read the relocs twice from the input file, which wastes time.
3695      This would be a good case for using mmap.
3696
3697      I have no idea how to handle linking PIC code into a file of a
3698      different format.  It probably can't be done.  */
3699   if ((abfd->flags & DYNAMIC) == 0
3700       && is_elf_hash_table (htab)
3701       && bed->check_relocs != NULL
3702       && elf_object_id (abfd) == elf_hash_table_id (htab)
3703       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
3704     {
3705       asection *o;
3706
3707       for (o = abfd->sections; o != NULL; o = o->next)
3708         {
3709           Elf_Internal_Rela *internal_relocs;
3710           bfd_boolean ok;
3711
3712           /* Don't check relocations in excluded sections.  */
3713           if ((o->flags & SEC_RELOC) == 0
3714               || (o->flags & SEC_EXCLUDE) != 0
3715               || o->reloc_count == 0
3716               || ((info->strip == strip_all || info->strip == strip_debugger)
3717                   && (o->flags & SEC_DEBUGGING) != 0)
3718               || bfd_is_abs_section (o->output_section))
3719             continue;
3720
3721           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
3722                                                        info->keep_memory);
3723           if (internal_relocs == NULL)
3724             return FALSE;
3725
3726           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
3727
3728           if (elf_section_data (o)->relocs != internal_relocs)
3729             free (internal_relocs);
3730
3731           if (! ok)
3732             return FALSE;
3733         }
3734     }
3735
3736   return TRUE;
3737 }
3738
3739 /* Add symbols from an ELF object file to the linker hash table.  */
3740
3741 static bfd_boolean
3742 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3743 {
3744   Elf_Internal_Ehdr *ehdr;
3745   Elf_Internal_Shdr *hdr;
3746   size_t symcount;
3747   size_t extsymcount;
3748   size_t extsymoff;
3749   struct elf_link_hash_entry **sym_hash;
3750   bfd_boolean dynamic;
3751   Elf_External_Versym *extversym = NULL;
3752   Elf_External_Versym *ever;
3753   struct elf_link_hash_entry *weaks;
3754   struct elf_link_hash_entry **nondeflt_vers = NULL;
3755   size_t nondeflt_vers_cnt = 0;
3756   Elf_Internal_Sym *isymbuf = NULL;
3757   Elf_Internal_Sym *isym;
3758   Elf_Internal_Sym *isymend;
3759   const struct elf_backend_data *bed;
3760   bfd_boolean add_needed;
3761   struct elf_link_hash_table *htab;
3762   bfd_size_type amt;
3763   void *alloc_mark = NULL;
3764   struct bfd_hash_entry **old_table = NULL;
3765   unsigned int old_size = 0;
3766   unsigned int old_count = 0;
3767   void *old_tab = NULL;
3768   void *old_ent;
3769   struct bfd_link_hash_entry *old_undefs = NULL;
3770   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3771   void *old_strtab = NULL;
3772   size_t tabsize = 0;
3773   asection *s;
3774   bfd_boolean just_syms;
3775
3776   htab = elf_hash_table (info);
3777   bed = get_elf_backend_data (abfd);
3778
3779   if ((abfd->flags & DYNAMIC) == 0)
3780     dynamic = FALSE;
3781   else
3782     {
3783       dynamic = TRUE;
3784
3785       /* You can't use -r against a dynamic object.  Also, there's no
3786          hope of using a dynamic object which does not exactly match
3787          the format of the output file.  */
3788       if (bfd_link_relocatable (info)
3789           || !is_elf_hash_table (htab)
3790           || info->output_bfd->xvec != abfd->xvec)
3791         {
3792           if (bfd_link_relocatable (info))
3793             bfd_set_error (bfd_error_invalid_operation);
3794           else
3795             bfd_set_error (bfd_error_wrong_format);
3796           goto error_return;
3797         }
3798     }
3799
3800   ehdr = elf_elfheader (abfd);
3801   if (info->warn_alternate_em
3802       && bed->elf_machine_code != ehdr->e_machine
3803       && ((bed->elf_machine_alt1 != 0
3804            && ehdr->e_machine == bed->elf_machine_alt1)
3805           || (bed->elf_machine_alt2 != 0
3806               && ehdr->e_machine == bed->elf_machine_alt2)))
3807     info->callbacks->einfo
3808       /* xgettext:c-format */
3809       (_("%P: alternate ELF machine code found (%d) in %B, expecting %d\n"),
3810        ehdr->e_machine, abfd, bed->elf_machine_code);
3811
3812   /* As a GNU extension, any input sections which are named
3813      .gnu.warning.SYMBOL are treated as warning symbols for the given
3814      symbol.  This differs from .gnu.warning sections, which generate
3815      warnings when they are included in an output file.  */
3816   /* PR 12761: Also generate this warning when building shared libraries.  */
3817   for (s = abfd->sections; s != NULL; s = s->next)
3818     {
3819       const char *name;
3820
3821       name = bfd_get_section_name (abfd, s);
3822       if (CONST_STRNEQ (name, ".gnu.warning."))
3823         {
3824           char *msg;
3825           bfd_size_type sz;
3826
3827           name += sizeof ".gnu.warning." - 1;
3828
3829           /* If this is a shared object, then look up the symbol
3830              in the hash table.  If it is there, and it is already
3831              been defined, then we will not be using the entry
3832              from this shared object, so we don't need to warn.
3833              FIXME: If we see the definition in a regular object
3834              later on, we will warn, but we shouldn't.  The only
3835              fix is to keep track of what warnings we are supposed
3836              to emit, and then handle them all at the end of the
3837              link.  */
3838           if (dynamic)
3839             {
3840               struct elf_link_hash_entry *h;
3841
3842               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3843
3844               /* FIXME: What about bfd_link_hash_common?  */
3845               if (h != NULL
3846                   && (h->root.type == bfd_link_hash_defined
3847                       || h->root.type == bfd_link_hash_defweak))
3848                 continue;
3849             }
3850
3851           sz = s->size;
3852           msg = (char *) bfd_alloc (abfd, sz + 1);
3853           if (msg == NULL)
3854             goto error_return;
3855
3856           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3857             goto error_return;
3858
3859           msg[sz] = '\0';
3860
3861           if (! (_bfd_generic_link_add_one_symbol
3862                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3863                   FALSE, bed->collect, NULL)))
3864             goto error_return;
3865
3866           if (bfd_link_executable (info))
3867             {
3868               /* Clobber the section size so that the warning does
3869                  not get copied into the output file.  */
3870               s->size = 0;
3871
3872               /* Also set SEC_EXCLUDE, so that symbols defined in
3873                  the warning section don't get copied to the output.  */
3874               s->flags |= SEC_EXCLUDE;
3875             }
3876         }
3877     }
3878
3879   just_syms = ((s = abfd->sections) != NULL
3880                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3881
3882   add_needed = TRUE;
3883   if (! dynamic)
3884     {
3885       /* If we are creating a shared library, create all the dynamic
3886          sections immediately.  We need to attach them to something,
3887          so we attach them to this BFD, provided it is the right
3888          format and is not from ld --just-symbols.  Always create the
3889          dynamic sections for -E/--dynamic-list.  FIXME: If there
3890          are no input BFD's of the same format as the output, we can't
3891          make a shared library.  */
3892       if (!just_syms
3893           && (bfd_link_pic (info)
3894               || (!bfd_link_relocatable (info)
3895                   && info->nointerp
3896                   && (info->export_dynamic || info->dynamic)))
3897           && is_elf_hash_table (htab)
3898           && info->output_bfd->xvec == abfd->xvec
3899           && !htab->dynamic_sections_created)
3900         {
3901           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3902             goto error_return;
3903         }
3904     }
3905   else if (!is_elf_hash_table (htab))
3906     goto error_return;
3907   else
3908     {
3909       const char *soname = NULL;
3910       char *audit = NULL;
3911       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3912       const Elf_Internal_Phdr *phdr;
3913       int ret;
3914
3915       /* ld --just-symbols and dynamic objects don't mix very well.
3916          ld shouldn't allow it.  */
3917       if (just_syms)
3918         abort ();
3919
3920       /* If this dynamic lib was specified on the command line with
3921          --as-needed in effect, then we don't want to add a DT_NEEDED
3922          tag unless the lib is actually used.  Similary for libs brought
3923          in by another lib's DT_NEEDED.  When --no-add-needed is used
3924          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3925          any dynamic library in DT_NEEDED tags in the dynamic lib at
3926          all.  */
3927       add_needed = (elf_dyn_lib_class (abfd)
3928                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3929                        | DYN_NO_NEEDED)) == 0;
3930
3931       s = bfd_get_section_by_name (abfd, ".dynamic");
3932       if (s != NULL)
3933         {
3934           bfd_byte *dynbuf;
3935           bfd_byte *extdyn;
3936           unsigned int elfsec;
3937           unsigned long shlink;
3938
3939           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3940             {
3941 error_free_dyn:
3942               free (dynbuf);
3943               goto error_return;
3944             }
3945
3946           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3947           if (elfsec == SHN_BAD)
3948             goto error_free_dyn;
3949           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3950
3951           for (extdyn = dynbuf;
3952                extdyn < dynbuf + s->size;
3953                extdyn += bed->s->sizeof_dyn)
3954             {
3955               Elf_Internal_Dyn dyn;
3956
3957               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3958               if (dyn.d_tag == DT_SONAME)
3959                 {
3960                   unsigned int tagv = dyn.d_un.d_val;
3961                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3962                   if (soname == NULL)
3963                     goto error_free_dyn;
3964                 }
3965               if (dyn.d_tag == DT_NEEDED)
3966                 {
3967                   struct bfd_link_needed_list *n, **pn;
3968                   char *fnm, *anm;
3969                   unsigned int tagv = dyn.d_un.d_val;
3970
3971                   amt = sizeof (struct bfd_link_needed_list);
3972                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3973                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3974                   if (n == NULL || fnm == NULL)
3975                     goto error_free_dyn;
3976                   amt = strlen (fnm) + 1;
3977                   anm = (char *) bfd_alloc (abfd, amt);
3978                   if (anm == NULL)
3979                     goto error_free_dyn;
3980                   memcpy (anm, fnm, amt);
3981                   n->name = anm;
3982                   n->by = abfd;
3983                   n->next = NULL;
3984                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
3985                     ;
3986                   *pn = n;
3987                 }
3988               if (dyn.d_tag == DT_RUNPATH)
3989                 {
3990                   struct bfd_link_needed_list *n, **pn;
3991                   char *fnm, *anm;
3992                   unsigned int tagv = dyn.d_un.d_val;
3993
3994                   amt = sizeof (struct bfd_link_needed_list);
3995                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3996                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3997                   if (n == NULL || fnm == NULL)
3998                     goto error_free_dyn;
3999                   amt = strlen (fnm) + 1;
4000                   anm = (char *) bfd_alloc (abfd, amt);
4001                   if (anm == NULL)
4002                     goto error_free_dyn;
4003                   memcpy (anm, fnm, amt);
4004                   n->name = anm;
4005                   n->by = abfd;
4006                   n->next = NULL;
4007                   for (pn = & runpath;
4008                        *pn != NULL;
4009                        pn = &(*pn)->next)
4010                     ;
4011                   *pn = n;
4012                 }
4013               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
4014               if (!runpath && dyn.d_tag == DT_RPATH)
4015                 {
4016                   struct bfd_link_needed_list *n, **pn;
4017                   char *fnm, *anm;
4018                   unsigned int tagv = dyn.d_un.d_val;
4019
4020                   amt = sizeof (struct bfd_link_needed_list);
4021                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
4022                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4023                   if (n == NULL || fnm == NULL)
4024                     goto error_free_dyn;
4025                   amt = strlen (fnm) + 1;
4026                   anm = (char *) bfd_alloc (abfd, amt);
4027                   if (anm == NULL)
4028                     goto error_free_dyn;
4029                   memcpy (anm, fnm, amt);
4030                   n->name = anm;
4031                   n->by = abfd;
4032                   n->next = NULL;
4033                   for (pn = & rpath;
4034                        *pn != NULL;
4035                        pn = &(*pn)->next)
4036                     ;
4037                   *pn = n;
4038                 }
4039               if (dyn.d_tag == DT_AUDIT)
4040                 {
4041                   unsigned int tagv = dyn.d_un.d_val;
4042                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4043                 }
4044             }
4045
4046           free (dynbuf);
4047         }
4048
4049       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
4050          frees all more recently bfd_alloc'd blocks as well.  */
4051       if (runpath)
4052         rpath = runpath;
4053
4054       if (rpath)
4055         {
4056           struct bfd_link_needed_list **pn;
4057           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
4058             ;
4059           *pn = rpath;
4060         }
4061
4062       /* If we have a PT_GNU_RELRO program header, mark as read-only
4063          all sections contained fully therein.  This makes relro
4064          shared library sections appear as they will at run-time.  */
4065       phdr = elf_tdata (abfd)->phdr + elf_elfheader (abfd)->e_phnum;
4066       while (--phdr >= elf_tdata (abfd)->phdr)
4067         if (phdr->p_type == PT_GNU_RELRO)
4068           {
4069             for (s = abfd->sections; s != NULL; s = s->next)
4070               if ((s->flags & SEC_ALLOC) != 0
4071                   && s->vma >= phdr->p_vaddr
4072                   && s->vma + s->size <= phdr->p_vaddr + phdr->p_memsz)
4073                 s->flags |= SEC_READONLY;
4074             break;
4075           }
4076
4077       /* We do not want to include any of the sections in a dynamic
4078          object in the output file.  We hack by simply clobbering the
4079          list of sections in the BFD.  This could be handled more
4080          cleanly by, say, a new section flag; the existing
4081          SEC_NEVER_LOAD flag is not the one we want, because that one
4082          still implies that the section takes up space in the output
4083          file.  */
4084       bfd_section_list_clear (abfd);
4085
4086       /* Find the name to use in a DT_NEEDED entry that refers to this
4087          object.  If the object has a DT_SONAME entry, we use it.
4088          Otherwise, if the generic linker stuck something in
4089          elf_dt_name, we use that.  Otherwise, we just use the file
4090          name.  */
4091       if (soname == NULL || *soname == '\0')
4092         {
4093           soname = elf_dt_name (abfd);
4094           if (soname == NULL || *soname == '\0')
4095             soname = bfd_get_filename (abfd);
4096         }
4097
4098       /* Save the SONAME because sometimes the linker emulation code
4099          will need to know it.  */
4100       elf_dt_name (abfd) = soname;
4101
4102       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4103       if (ret < 0)
4104         goto error_return;
4105
4106       /* If we have already included this dynamic object in the
4107          link, just ignore it.  There is no reason to include a
4108          particular dynamic object more than once.  */
4109       if (ret > 0)
4110         return TRUE;
4111
4112       /* Save the DT_AUDIT entry for the linker emulation code. */
4113       elf_dt_audit (abfd) = audit;
4114     }
4115
4116   /* If this is a dynamic object, we always link against the .dynsym
4117      symbol table, not the .symtab symbol table.  The dynamic linker
4118      will only see the .dynsym symbol table, so there is no reason to
4119      look at .symtab for a dynamic object.  */
4120
4121   if (! dynamic || elf_dynsymtab (abfd) == 0)
4122     hdr = &elf_tdata (abfd)->symtab_hdr;
4123   else
4124     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
4125
4126   symcount = hdr->sh_size / bed->s->sizeof_sym;
4127
4128   /* The sh_info field of the symtab header tells us where the
4129      external symbols start.  We don't care about the local symbols at
4130      this point.  */
4131   if (elf_bad_symtab (abfd))
4132     {
4133       extsymcount = symcount;
4134       extsymoff = 0;
4135     }
4136   else
4137     {
4138       extsymcount = symcount - hdr->sh_info;
4139       extsymoff = hdr->sh_info;
4140     }
4141
4142   sym_hash = elf_sym_hashes (abfd);
4143   if (extsymcount != 0)
4144     {
4145       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
4146                                       NULL, NULL, NULL);
4147       if (isymbuf == NULL)
4148         goto error_return;
4149
4150       if (sym_hash == NULL)
4151         {
4152           /* We store a pointer to the hash table entry for each
4153              external symbol.  */
4154           amt = extsymcount;
4155           amt *= sizeof (struct elf_link_hash_entry *);
4156           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
4157           if (sym_hash == NULL)
4158             goto error_free_sym;
4159           elf_sym_hashes (abfd) = sym_hash;
4160         }
4161     }
4162
4163   if (dynamic)
4164     {
4165       /* Read in any version definitions.  */
4166       if (!_bfd_elf_slurp_version_tables (abfd,
4167                                           info->default_imported_symver))
4168         goto error_free_sym;
4169
4170       /* Read in the symbol versions, but don't bother to convert them
4171          to internal format.  */
4172       if (elf_dynversym (abfd) != 0)
4173         {
4174           Elf_Internal_Shdr *versymhdr;
4175
4176           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
4177           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
4178           if (extversym == NULL)
4179             goto error_free_sym;
4180           amt = versymhdr->sh_size;
4181           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
4182               || bfd_bread (extversym, amt, abfd) != amt)
4183             goto error_free_vers;
4184         }
4185     }
4186
4187   /* If we are loading an as-needed shared lib, save the symbol table
4188      state before we start adding symbols.  If the lib turns out
4189      to be unneeded, restore the state.  */
4190   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4191     {
4192       unsigned int i;
4193       size_t entsize;
4194
4195       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
4196         {
4197           struct bfd_hash_entry *p;
4198           struct elf_link_hash_entry *h;
4199
4200           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4201             {
4202               h = (struct elf_link_hash_entry *) p;
4203               entsize += htab->root.table.entsize;
4204               if (h->root.type == bfd_link_hash_warning)
4205                 entsize += htab->root.table.entsize;
4206             }
4207         }
4208
4209       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
4210       old_tab = bfd_malloc (tabsize + entsize);
4211       if (old_tab == NULL)
4212         goto error_free_vers;
4213
4214       /* Remember the current objalloc pointer, so that all mem for
4215          symbols added can later be reclaimed.  */
4216       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
4217       if (alloc_mark == NULL)
4218         goto error_free_vers;
4219
4220       /* Make a special call to the linker "notice" function to
4221          tell it that we are about to handle an as-needed lib.  */
4222       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
4223         goto error_free_vers;
4224
4225       /* Clone the symbol table.  Remember some pointers into the
4226          symbol table, and dynamic symbol count.  */
4227       old_ent = (char *) old_tab + tabsize;
4228       memcpy (old_tab, htab->root.table.table, tabsize);
4229       old_undefs = htab->root.undefs;
4230       old_undefs_tail = htab->root.undefs_tail;
4231       old_table = htab->root.table.table;
4232       old_size = htab->root.table.size;
4233       old_count = htab->root.table.count;
4234       old_strtab = _bfd_elf_strtab_save (htab->dynstr);
4235       if (old_strtab == NULL)
4236         goto error_free_vers;
4237
4238       for (i = 0; i < htab->root.table.size; i++)
4239         {
4240           struct bfd_hash_entry *p;
4241           struct elf_link_hash_entry *h;
4242
4243           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4244             {
4245               memcpy (old_ent, p, htab->root.table.entsize);
4246               old_ent = (char *) old_ent + htab->root.table.entsize;
4247               h = (struct elf_link_hash_entry *) p;
4248               if (h->root.type == bfd_link_hash_warning)
4249                 {
4250                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
4251                   old_ent = (char *) old_ent + htab->root.table.entsize;
4252                 }
4253             }
4254         }
4255     }
4256
4257   weaks = NULL;
4258   ever = extversym != NULL ? extversym + extsymoff : NULL;
4259   for (isym = isymbuf, isymend = isymbuf + extsymcount;
4260        isym < isymend;
4261        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
4262     {
4263       int bind;
4264       bfd_vma value;
4265       asection *sec, *new_sec;
4266       flagword flags;
4267       const char *name;
4268       struct elf_link_hash_entry *h;
4269       struct elf_link_hash_entry *hi;
4270       bfd_boolean definition;
4271       bfd_boolean size_change_ok;
4272       bfd_boolean type_change_ok;
4273       bfd_boolean new_weak;
4274       bfd_boolean old_weak;
4275       bfd_boolean override;
4276       bfd_boolean common;
4277       bfd_boolean discarded;
4278       unsigned int old_alignment;
4279       bfd *old_bfd;
4280       bfd_boolean matched;
4281
4282       override = FALSE;
4283
4284       flags = BSF_NO_FLAGS;
4285       sec = NULL;
4286       value = isym->st_value;
4287       common = bed->common_definition (isym);
4288       if (common && info->inhibit_common_definition)
4289         {
4290           /* Treat common symbol as undefined for --no-define-common.  */
4291           isym->st_shndx = SHN_UNDEF;
4292           common = FALSE;
4293         }
4294       discarded = FALSE;
4295
4296       bind = ELF_ST_BIND (isym->st_info);
4297       switch (bind)
4298         {
4299         case STB_LOCAL:
4300           /* This should be impossible, since ELF requires that all
4301              global symbols follow all local symbols, and that sh_info
4302              point to the first global symbol.  Unfortunately, Irix 5
4303              screws this up.  */
4304           continue;
4305
4306         case STB_GLOBAL:
4307           if (isym->st_shndx != SHN_UNDEF && !common)
4308             flags = BSF_GLOBAL;
4309           break;
4310
4311         case STB_WEAK:
4312           flags = BSF_WEAK;
4313           break;
4314
4315         case STB_GNU_UNIQUE:
4316           flags = BSF_GNU_UNIQUE;
4317           break;
4318
4319         default:
4320           /* Leave it up to the processor backend.  */
4321           break;
4322         }
4323
4324       if (isym->st_shndx == SHN_UNDEF)
4325         sec = bfd_und_section_ptr;
4326       else if (isym->st_shndx == SHN_ABS)
4327         sec = bfd_abs_section_ptr;
4328       else if (isym->st_shndx == SHN_COMMON)
4329         {
4330           sec = bfd_com_section_ptr;
4331           /* What ELF calls the size we call the value.  What ELF
4332              calls the value we call the alignment.  */
4333           value = isym->st_size;
4334         }
4335       else
4336         {
4337           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
4338           if (sec == NULL)
4339             sec = bfd_abs_section_ptr;
4340           else if (discarded_section (sec))
4341             {
4342               /* Symbols from discarded section are undefined.  We keep
4343                  its visibility.  */
4344               sec = bfd_und_section_ptr;
4345               discarded = TRUE;
4346               isym->st_shndx = SHN_UNDEF;
4347             }
4348           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
4349             value -= sec->vma;
4350         }
4351
4352       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4353                                               isym->st_name);
4354       if (name == NULL)
4355         goto error_free_vers;
4356
4357       if (isym->st_shndx == SHN_COMMON
4358           && (abfd->flags & BFD_PLUGIN) != 0)
4359         {
4360           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4361
4362           if (xc == NULL)
4363             {
4364               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4365                                  | SEC_EXCLUDE);
4366               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4367               if (xc == NULL)
4368                 goto error_free_vers;
4369             }
4370           sec = xc;
4371         }
4372       else if (isym->st_shndx == SHN_COMMON
4373                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4374                && !bfd_link_relocatable (info))
4375         {
4376           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4377
4378           if (tcomm == NULL)
4379             {
4380               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4381                                  | SEC_LINKER_CREATED);
4382               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4383               if (tcomm == NULL)
4384                 goto error_free_vers;
4385             }
4386           sec = tcomm;
4387         }
4388       else if (bed->elf_add_symbol_hook)
4389         {
4390           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4391                                              &sec, &value))
4392             goto error_free_vers;
4393
4394           /* The hook function sets the name to NULL if this symbol
4395              should be skipped for some reason.  */
4396           if (name == NULL)
4397             continue;
4398         }
4399
4400       /* Sanity check that all possibilities were handled.  */
4401       if (sec == NULL)
4402         {
4403           bfd_set_error (bfd_error_bad_value);
4404           goto error_free_vers;
4405         }
4406
4407       /* Silently discard TLS symbols from --just-syms.  There's
4408          no way to combine a static TLS block with a new TLS block
4409          for this executable.  */
4410       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4411           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4412         continue;
4413
4414       if (bfd_is_und_section (sec)
4415           || bfd_is_com_section (sec))
4416         definition = FALSE;
4417       else
4418         definition = TRUE;
4419
4420       size_change_ok = FALSE;
4421       type_change_ok = bed->type_change_ok;
4422       old_weak = FALSE;
4423       matched = FALSE;
4424       old_alignment = 0;
4425       old_bfd = NULL;
4426       new_sec = sec;
4427
4428       if (is_elf_hash_table (htab))
4429         {
4430           Elf_Internal_Versym iver;
4431           unsigned int vernum = 0;
4432           bfd_boolean skip;
4433
4434           if (ever == NULL)
4435             {
4436               if (info->default_imported_symver)
4437                 /* Use the default symbol version created earlier.  */
4438                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4439               else
4440                 iver.vs_vers = 0;
4441             }
4442           else
4443             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4444
4445           vernum = iver.vs_vers & VERSYM_VERSION;
4446
4447           /* If this is a hidden symbol, or if it is not version
4448              1, we append the version name to the symbol name.
4449              However, we do not modify a non-hidden absolute symbol
4450              if it is not a function, because it might be the version
4451              symbol itself.  FIXME: What if it isn't?  */
4452           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4453               || (vernum > 1
4454                   && (!bfd_is_abs_section (sec)
4455                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4456             {
4457               const char *verstr;
4458               size_t namelen, verlen, newlen;
4459               char *newname, *p;
4460
4461               if (isym->st_shndx != SHN_UNDEF)
4462                 {
4463                   if (vernum > elf_tdata (abfd)->cverdefs)
4464                     verstr = NULL;
4465                   else if (vernum > 1)
4466                     verstr =
4467                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4468                   else
4469                     verstr = "";
4470
4471                   if (verstr == NULL)
4472                     {
4473                       _bfd_error_handler
4474                         /* xgettext:c-format */
4475                         (_("%B: %s: invalid version %u (max %d)"),
4476                          abfd, name, vernum,
4477                          elf_tdata (abfd)->cverdefs);
4478                       bfd_set_error (bfd_error_bad_value);
4479                       goto error_free_vers;
4480                     }
4481                 }
4482               else
4483                 {
4484                   /* We cannot simply test for the number of
4485                      entries in the VERNEED section since the
4486                      numbers for the needed versions do not start
4487                      at 0.  */
4488                   Elf_Internal_Verneed *t;
4489
4490                   verstr = NULL;
4491                   for (t = elf_tdata (abfd)->verref;
4492                        t != NULL;
4493                        t = t->vn_nextref)
4494                     {
4495                       Elf_Internal_Vernaux *a;
4496
4497                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4498                         {
4499                           if (a->vna_other == vernum)
4500                             {
4501                               verstr = a->vna_nodename;
4502                               break;
4503                             }
4504                         }
4505                       if (a != NULL)
4506                         break;
4507                     }
4508                   if (verstr == NULL)
4509                     {
4510                       _bfd_error_handler
4511                         /* xgettext:c-format */
4512                         (_("%B: %s: invalid needed version %d"),
4513                          abfd, name, vernum);
4514                       bfd_set_error (bfd_error_bad_value);
4515                       goto error_free_vers;
4516                     }
4517                 }
4518
4519               namelen = strlen (name);
4520               verlen = strlen (verstr);
4521               newlen = namelen + verlen + 2;
4522               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4523                   && isym->st_shndx != SHN_UNDEF)
4524                 ++newlen;
4525
4526               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4527               if (newname == NULL)
4528                 goto error_free_vers;
4529               memcpy (newname, name, namelen);
4530               p = newname + namelen;
4531               *p++ = ELF_VER_CHR;
4532               /* If this is a defined non-hidden version symbol,
4533                  we add another @ to the name.  This indicates the
4534                  default version of the symbol.  */
4535               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4536                   && isym->st_shndx != SHN_UNDEF)
4537                 *p++ = ELF_VER_CHR;
4538               memcpy (p, verstr, verlen + 1);
4539
4540               name = newname;
4541             }
4542
4543           /* If this symbol has default visibility and the user has
4544              requested we not re-export it, then mark it as hidden.  */
4545           if (!bfd_is_und_section (sec)
4546               && !dynamic
4547               && abfd->no_export
4548               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4549             isym->st_other = (STV_HIDDEN
4550                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4551
4552           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4553                                       sym_hash, &old_bfd, &old_weak,
4554                                       &old_alignment, &skip, &override,
4555                                       &type_change_ok, &size_change_ok,
4556                                       &matched))
4557             goto error_free_vers;
4558
4559           if (skip)
4560             continue;
4561
4562           /* Override a definition only if the new symbol matches the
4563              existing one.  */
4564           if (override && matched)
4565             definition = FALSE;
4566
4567           h = *sym_hash;
4568           while (h->root.type == bfd_link_hash_indirect
4569                  || h->root.type == bfd_link_hash_warning)
4570             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4571
4572           if (elf_tdata (abfd)->verdef != NULL
4573               && vernum > 1
4574               && definition)
4575             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4576         }
4577
4578       if (! (_bfd_generic_link_add_one_symbol
4579              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4580               (struct bfd_link_hash_entry **) sym_hash)))
4581         goto error_free_vers;
4582
4583       if ((flags & BSF_GNU_UNIQUE)
4584           && (abfd->flags & DYNAMIC) == 0
4585           && bfd_get_flavour (info->output_bfd) == bfd_target_elf_flavour)
4586         elf_tdata (info->output_bfd)->has_gnu_symbols |= elf_gnu_symbol_unique;
4587
4588       h = *sym_hash;
4589       /* We need to make sure that indirect symbol dynamic flags are
4590          updated.  */
4591       hi = h;
4592       while (h->root.type == bfd_link_hash_indirect
4593              || h->root.type == bfd_link_hash_warning)
4594         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4595
4596       /* Setting the index to -3 tells elf_link_output_extsym that
4597          this symbol is defined in a discarded section.  */
4598       if (discarded)
4599         h->indx = -3;
4600
4601       *sym_hash = h;
4602
4603       new_weak = (flags & BSF_WEAK) != 0;
4604       if (dynamic
4605           && definition
4606           && new_weak
4607           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4608           && is_elf_hash_table (htab)
4609           && h->u.alias == NULL)
4610         {
4611           /* Keep a list of all weak defined non function symbols from
4612              a dynamic object, using the alias field.  Later in this
4613              function we will set the alias field to the correct
4614              value.  We only put non-function symbols from dynamic
4615              objects on this list, because that happens to be the only
4616              time we need to know the normal symbol corresponding to a
4617              weak symbol, and the information is time consuming to
4618              figure out.  If the alias field is not already NULL,
4619              then this symbol was already defined by some previous
4620              dynamic object, and we will be using that previous
4621              definition anyhow.  */
4622
4623           h->u.alias = weaks;
4624           weaks = h;
4625         }
4626
4627       /* Set the alignment of a common symbol.  */
4628       if ((common || bfd_is_com_section (sec))
4629           && h->root.type == bfd_link_hash_common)
4630         {
4631           unsigned int align;
4632
4633           if (common)
4634             align = bfd_log2 (isym->st_value);
4635           else
4636             {
4637               /* The new symbol is a common symbol in a shared object.
4638                  We need to get the alignment from the section.  */
4639               align = new_sec->alignment_power;
4640             }
4641           if (align > old_alignment)
4642             h->root.u.c.p->alignment_power = align;
4643           else
4644             h->root.u.c.p->alignment_power = old_alignment;
4645         }
4646
4647       if (is_elf_hash_table (htab))
4648         {
4649           /* Set a flag in the hash table entry indicating the type of
4650              reference or definition we just found.  A dynamic symbol
4651              is one which is referenced or defined by both a regular
4652              object and a shared object.  */
4653           bfd_boolean dynsym = FALSE;
4654
4655           /* Plugin symbols aren't normal.  Don't set def_regular or
4656              ref_regular for them, or make them dynamic.  */
4657           if ((abfd->flags & BFD_PLUGIN) != 0)
4658             ;
4659           else if (! dynamic)
4660             {
4661               if (! definition)
4662                 {
4663                   h->ref_regular = 1;
4664                   if (bind != STB_WEAK)
4665                     h->ref_regular_nonweak = 1;
4666                 }
4667               else
4668                 {
4669                   h->def_regular = 1;
4670                   if (h->def_dynamic)
4671                     {
4672                       h->def_dynamic = 0;
4673                       h->ref_dynamic = 1;
4674                     }
4675                 }
4676
4677               /* If the indirect symbol has been forced local, don't
4678                  make the real symbol dynamic.  */
4679               if ((h == hi || !hi->forced_local)
4680                   && (bfd_link_dll (info)
4681                       || h->def_dynamic
4682                       || h->ref_dynamic))
4683                 dynsym = TRUE;
4684             }
4685           else
4686             {
4687               if (! definition)
4688                 {
4689                   h->ref_dynamic = 1;
4690                   hi->ref_dynamic = 1;
4691                 }
4692               else
4693                 {
4694                   h->def_dynamic = 1;
4695                   hi->def_dynamic = 1;
4696                 }
4697
4698               /* If the indirect symbol has been forced local, don't
4699                  make the real symbol dynamic.  */
4700               if ((h == hi || !hi->forced_local)
4701                   && (h->def_regular
4702                       || h->ref_regular
4703                       || (h->is_weakalias
4704                           && weakdef (h)->dynindx != -1)))
4705                 dynsym = TRUE;
4706             }
4707
4708           /* Check to see if we need to add an indirect symbol for
4709              the default name.  */
4710           if (definition
4711               || (!override && h->root.type == bfd_link_hash_common))
4712             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4713                                               sec, value, &old_bfd, &dynsym))
4714               goto error_free_vers;
4715
4716           /* Check the alignment when a common symbol is involved. This
4717              can change when a common symbol is overridden by a normal
4718              definition or a common symbol is ignored due to the old
4719              normal definition. We need to make sure the maximum
4720              alignment is maintained.  */
4721           if ((old_alignment || common)
4722               && h->root.type != bfd_link_hash_common)
4723             {
4724               unsigned int common_align;
4725               unsigned int normal_align;
4726               unsigned int symbol_align;
4727               bfd *normal_bfd;
4728               bfd *common_bfd;
4729
4730               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4731                           || h->root.type == bfd_link_hash_defweak);
4732
4733               symbol_align = ffs (h->root.u.def.value) - 1;
4734               if (h->root.u.def.section->owner != NULL
4735                   && (h->root.u.def.section->owner->flags
4736                        & (DYNAMIC | BFD_PLUGIN)) == 0)
4737                 {
4738                   normal_align = h->root.u.def.section->alignment_power;
4739                   if (normal_align > symbol_align)
4740                     normal_align = symbol_align;
4741                 }
4742               else
4743                 normal_align = symbol_align;
4744
4745               if (old_alignment)
4746                 {
4747                   common_align = old_alignment;
4748                   common_bfd = old_bfd;
4749                   normal_bfd = abfd;
4750                 }
4751               else
4752                 {
4753                   common_align = bfd_log2 (isym->st_value);
4754                   common_bfd = abfd;
4755                   normal_bfd = old_bfd;
4756                 }
4757
4758               if (normal_align < common_align)
4759                 {
4760                   /* PR binutils/2735 */
4761                   if (normal_bfd == NULL)
4762                     _bfd_error_handler
4763                       /* xgettext:c-format */
4764                       (_("Warning: alignment %u of common symbol `%s' in %B is"
4765                          " greater than the alignment (%u) of its section %A"),
4766                        1 << common_align, name, common_bfd,
4767                        1 << normal_align, h->root.u.def.section);
4768                   else
4769                     _bfd_error_handler
4770                       /* xgettext:c-format */
4771                       (_("Warning: alignment %u of symbol `%s' in %B"
4772                          " is smaller than %u in %B"),
4773                        1 << normal_align, name, normal_bfd,
4774                        1 << common_align, common_bfd);
4775                 }
4776             }
4777
4778           /* Remember the symbol size if it isn't undefined.  */
4779           if (isym->st_size != 0
4780               && isym->st_shndx != SHN_UNDEF
4781               && (definition || h->size == 0))
4782             {
4783               if (h->size != 0
4784                   && h->size != isym->st_size
4785                   && ! size_change_ok)
4786                 _bfd_error_handler
4787                   /* xgettext:c-format */
4788                   (_("Warning: size of symbol `%s' changed"
4789                      " from %Lu in %B to %Lu in %B"),
4790                    name, h->size, old_bfd, isym->st_size, abfd);
4791
4792               h->size = isym->st_size;
4793             }
4794
4795           /* If this is a common symbol, then we always want H->SIZE
4796              to be the size of the common symbol.  The code just above
4797              won't fix the size if a common symbol becomes larger.  We
4798              don't warn about a size change here, because that is
4799              covered by --warn-common.  Allow changes between different
4800              function types.  */
4801           if (h->root.type == bfd_link_hash_common)
4802             h->size = h->root.u.c.size;
4803
4804           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4805               && ((definition && !new_weak)
4806                   || (old_weak && h->root.type == bfd_link_hash_common)
4807                   || h->type == STT_NOTYPE))
4808             {
4809               unsigned int type = ELF_ST_TYPE (isym->st_info);
4810
4811               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4812                  symbol.  */
4813               if (type == STT_GNU_IFUNC
4814                   && (abfd->flags & DYNAMIC) != 0)
4815                 type = STT_FUNC;
4816
4817               if (h->type != type)
4818                 {
4819                   if (h->type != STT_NOTYPE && ! type_change_ok)
4820                     /* xgettext:c-format */
4821                     _bfd_error_handler
4822                       (_("Warning: type of symbol `%s' changed"
4823                          " from %d to %d in %B"),
4824                        name, h->type, type, abfd);
4825
4826                   h->type = type;
4827                 }
4828             }
4829
4830           /* Merge st_other field.  */
4831           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4832
4833           /* We don't want to make debug symbol dynamic.  */
4834           if (definition
4835               && (sec->flags & SEC_DEBUGGING)
4836               && !bfd_link_relocatable (info))
4837             dynsym = FALSE;
4838
4839           /* Nor should we make plugin symbols dynamic.  */
4840           if ((abfd->flags & BFD_PLUGIN) != 0)
4841             dynsym = FALSE;
4842
4843           if (definition)
4844             {
4845               h->target_internal = isym->st_target_internal;
4846               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4847             }
4848
4849           if (definition && !dynamic)
4850             {
4851               char *p = strchr (name, ELF_VER_CHR);
4852               if (p != NULL && p[1] != ELF_VER_CHR)
4853                 {
4854                   /* Queue non-default versions so that .symver x, x@FOO
4855                      aliases can be checked.  */
4856                   if (!nondeflt_vers)
4857                     {
4858                       amt = ((isymend - isym + 1)
4859                              * sizeof (struct elf_link_hash_entry *));
4860                       nondeflt_vers
4861                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
4862                       if (!nondeflt_vers)
4863                         goto error_free_vers;
4864                     }
4865                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4866                 }
4867             }
4868
4869           if (dynsym && h->dynindx == -1)
4870             {
4871               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4872                 goto error_free_vers;
4873               if (h->is_weakalias
4874                   && weakdef (h)->dynindx == -1)
4875                 {
4876                   if (!bfd_elf_link_record_dynamic_symbol (info, weakdef (h)))
4877                     goto error_free_vers;
4878                 }
4879             }
4880           else if (h->dynindx != -1)
4881             /* If the symbol already has a dynamic index, but
4882                visibility says it should not be visible, turn it into
4883                a local symbol.  */
4884             switch (ELF_ST_VISIBILITY (h->other))
4885               {
4886               case STV_INTERNAL:
4887               case STV_HIDDEN:
4888                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4889                 dynsym = FALSE;
4890                 break;
4891               }
4892
4893           /* Don't add DT_NEEDED for references from the dummy bfd nor
4894              for unmatched symbol.  */
4895           if (!add_needed
4896               && matched
4897               && definition
4898               && ((dynsym
4899                    && h->ref_regular_nonweak
4900                    && (old_bfd == NULL
4901                        || (old_bfd->flags & BFD_PLUGIN) == 0))
4902                   || (h->ref_dynamic_nonweak
4903                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4904                       && !on_needed_list (elf_dt_name (abfd),
4905                                           htab->needed, NULL))))
4906             {
4907               int ret;
4908               const char *soname = elf_dt_name (abfd);
4909
4910               info->callbacks->minfo ("%!", soname, old_bfd,
4911                                       h->root.root.string);
4912
4913               /* A symbol from a library loaded via DT_NEEDED of some
4914                  other library is referenced by a regular object.
4915                  Add a DT_NEEDED entry for it.  Issue an error if
4916                  --no-add-needed is used and the reference was not
4917                  a weak one.  */
4918               if (old_bfd != NULL
4919                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4920                 {
4921                   _bfd_error_handler
4922                     /* xgettext:c-format */
4923                     (_("%B: undefined reference to symbol '%s'"),
4924                      old_bfd, name);
4925                   bfd_set_error (bfd_error_missing_dso);
4926                   goto error_free_vers;
4927                 }
4928
4929               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4930                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4931
4932               add_needed = TRUE;
4933               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4934               if (ret < 0)
4935                 goto error_free_vers;
4936
4937               BFD_ASSERT (ret == 0);
4938             }
4939         }
4940     }
4941
4942   if (info->lto_plugin_active
4943       && !bfd_link_relocatable (info)
4944       && (abfd->flags & BFD_PLUGIN) == 0
4945       && !just_syms
4946       && extsymcount)
4947     {
4948       int r_sym_shift;
4949
4950       if (bed->s->arch_size == 32)
4951         r_sym_shift = 8;
4952       else
4953         r_sym_shift = 32;
4954
4955       /* If linker plugin is enabled, set non_ir_ref_regular on symbols
4956          referenced in regular objects so that linker plugin will get
4957          the correct symbol resolution.  */
4958
4959       sym_hash = elf_sym_hashes (abfd);
4960       for (s = abfd->sections; s != NULL; s = s->next)
4961         {
4962           Elf_Internal_Rela *internal_relocs;
4963           Elf_Internal_Rela *rel, *relend;
4964
4965           /* Don't check relocations in excluded sections.  */
4966           if ((s->flags & SEC_RELOC) == 0
4967               || s->reloc_count == 0
4968               || (s->flags & SEC_EXCLUDE) != 0
4969               || ((info->strip == strip_all
4970                    || info->strip == strip_debugger)
4971                   && (s->flags & SEC_DEBUGGING) != 0))
4972             continue;
4973
4974           internal_relocs = _bfd_elf_link_read_relocs (abfd, s, NULL,
4975                                                        NULL,
4976                                                        info->keep_memory);
4977           if (internal_relocs == NULL)
4978             goto error_free_vers;
4979
4980           rel = internal_relocs;
4981           relend = rel + s->reloc_count;
4982           for ( ; rel < relend; rel++)
4983             {
4984               unsigned long r_symndx = rel->r_info >> r_sym_shift;
4985               struct elf_link_hash_entry *h;
4986
4987               /* Skip local symbols.  */
4988               if (r_symndx < extsymoff)
4989                 continue;
4990
4991               h = sym_hash[r_symndx - extsymoff];
4992               if (h != NULL)
4993                 h->root.non_ir_ref_regular = 1;
4994             }
4995
4996           if (elf_section_data (s)->relocs != internal_relocs)
4997             free (internal_relocs);
4998         }
4999     }
5000
5001   if (extversym != NULL)
5002     {
5003       free (extversym);
5004       extversym = NULL;
5005     }
5006
5007   if (isymbuf != NULL)
5008     {
5009       free (isymbuf);
5010       isymbuf = NULL;
5011     }
5012
5013   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
5014     {
5015       unsigned int i;
5016
5017       /* Restore the symbol table.  */
5018       old_ent = (char *) old_tab + tabsize;
5019       memset (elf_sym_hashes (abfd), 0,
5020               extsymcount * sizeof (struct elf_link_hash_entry *));
5021       htab->root.table.table = old_table;
5022       htab->root.table.size = old_size;
5023       htab->root.table.count = old_count;
5024       memcpy (htab->root.table.table, old_tab, tabsize);
5025       htab->root.undefs = old_undefs;
5026       htab->root.undefs_tail = old_undefs_tail;
5027       _bfd_elf_strtab_restore (htab->dynstr, old_strtab);
5028       free (old_strtab);
5029       old_strtab = NULL;
5030       for (i = 0; i < htab->root.table.size; i++)
5031         {
5032           struct bfd_hash_entry *p;
5033           struct elf_link_hash_entry *h;
5034           bfd_size_type size;
5035           unsigned int alignment_power;
5036           unsigned int non_ir_ref_dynamic;
5037
5038           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
5039             {
5040               h = (struct elf_link_hash_entry *) p;
5041               if (h->root.type == bfd_link_hash_warning)
5042                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
5043
5044               /* Preserve the maximum alignment and size for common
5045                  symbols even if this dynamic lib isn't on DT_NEEDED
5046                  since it can still be loaded at run time by another
5047                  dynamic lib.  */
5048               if (h->root.type == bfd_link_hash_common)
5049                 {
5050                   size = h->root.u.c.size;
5051                   alignment_power = h->root.u.c.p->alignment_power;
5052                 }
5053               else
5054                 {
5055                   size = 0;
5056                   alignment_power = 0;
5057                 }
5058               /* Preserve non_ir_ref_dynamic so that this symbol
5059                  will be exported when the dynamic lib becomes needed
5060                  in the second pass.  */
5061               non_ir_ref_dynamic = h->root.non_ir_ref_dynamic;
5062               memcpy (p, old_ent, htab->root.table.entsize);
5063               old_ent = (char *) old_ent + htab->root.table.entsize;
5064               h = (struct elf_link_hash_entry *) p;
5065               if (h->root.type == bfd_link_hash_warning)
5066                 {
5067                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
5068                   old_ent = (char *) old_ent + htab->root.table.entsize;
5069                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
5070                 }
5071               if (h->root.type == bfd_link_hash_common)
5072                 {
5073                   if (size > h->root.u.c.size)
5074                     h->root.u.c.size = size;
5075                   if (alignment_power > h->root.u.c.p->alignment_power)
5076                     h->root.u.c.p->alignment_power = alignment_power;
5077                 }
5078               h->root.non_ir_ref_dynamic = non_ir_ref_dynamic;
5079             }
5080         }
5081
5082       /* Make a special call to the linker "notice" function to
5083          tell it that symbols added for crefs may need to be removed.  */
5084       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
5085         goto error_free_vers;
5086
5087       free (old_tab);
5088       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
5089                            alloc_mark);
5090       if (nondeflt_vers != NULL)
5091         free (nondeflt_vers);
5092       return TRUE;
5093     }
5094
5095   if (old_tab != NULL)
5096     {
5097       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
5098         goto error_free_vers;
5099       free (old_tab);
5100       old_tab = NULL;
5101     }
5102
5103   /* Now that all the symbols from this input file are created, if
5104      not performing a relocatable link, handle .symver foo, foo@BAR
5105      such that any relocs against foo become foo@BAR.  */
5106   if (!bfd_link_relocatable (info) && nondeflt_vers != NULL)
5107     {
5108       size_t cnt, symidx;
5109
5110       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
5111         {
5112           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
5113           char *shortname, *p;
5114
5115           p = strchr (h->root.root.string, ELF_VER_CHR);
5116           if (p == NULL
5117               || (h->root.type != bfd_link_hash_defined
5118                   && h->root.type != bfd_link_hash_defweak))
5119             continue;
5120
5121           amt = p - h->root.root.string;
5122           shortname = (char *) bfd_malloc (amt + 1);
5123           if (!shortname)
5124             goto error_free_vers;
5125           memcpy (shortname, h->root.root.string, amt);
5126           shortname[amt] = '\0';
5127
5128           hi = (struct elf_link_hash_entry *)
5129                bfd_link_hash_lookup (&htab->root, shortname,
5130                                      FALSE, FALSE, FALSE);
5131           if (hi != NULL
5132               && hi->root.type == h->root.type
5133               && hi->root.u.def.value == h->root.u.def.value
5134               && hi->root.u.def.section == h->root.u.def.section)
5135             {
5136               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
5137               hi->root.type = bfd_link_hash_indirect;
5138               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
5139               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
5140               sym_hash = elf_sym_hashes (abfd);
5141               if (sym_hash)
5142                 for (symidx = 0; symidx < extsymcount; ++symidx)
5143                   if (sym_hash[symidx] == hi)
5144                     {
5145                       sym_hash[symidx] = h;
5146                       break;
5147                     }
5148             }
5149           free (shortname);
5150         }
5151       free (nondeflt_vers);
5152       nondeflt_vers = NULL;
5153     }
5154
5155   /* Now set the alias field correctly for all the weak defined
5156      symbols we found.  The only way to do this is to search all the
5157      symbols.  Since we only need the information for non functions in
5158      dynamic objects, that's the only time we actually put anything on
5159      the list WEAKS.  We need this information so that if a regular
5160      object refers to a symbol defined weakly in a dynamic object, the
5161      real symbol in the dynamic object is also put in the dynamic
5162      symbols; we also must arrange for both symbols to point to the
5163      same memory location.  We could handle the general case of symbol
5164      aliasing, but a general symbol alias can only be generated in
5165      assembler code, handling it correctly would be very time
5166      consuming, and other ELF linkers don't handle general aliasing
5167      either.  */
5168   if (weaks != NULL)
5169     {
5170       struct elf_link_hash_entry **hpp;
5171       struct elf_link_hash_entry **hppend;
5172       struct elf_link_hash_entry **sorted_sym_hash;
5173       struct elf_link_hash_entry *h;
5174       size_t sym_count;
5175
5176       /* Since we have to search the whole symbol list for each weak
5177          defined symbol, search time for N weak defined symbols will be
5178          O(N^2). Binary search will cut it down to O(NlogN).  */
5179       amt = extsymcount;
5180       amt *= sizeof (struct elf_link_hash_entry *);
5181       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
5182       if (sorted_sym_hash == NULL)
5183         goto error_return;
5184       sym_hash = sorted_sym_hash;
5185       hpp = elf_sym_hashes (abfd);
5186       hppend = hpp + extsymcount;
5187       sym_count = 0;
5188       for (; hpp < hppend; hpp++)
5189         {
5190           h = *hpp;
5191           if (h != NULL
5192               && h->root.type == bfd_link_hash_defined
5193               && !bed->is_function_type (h->type))
5194             {
5195               *sym_hash = h;
5196               sym_hash++;
5197               sym_count++;
5198             }
5199         }
5200
5201       qsort (sorted_sym_hash, sym_count,
5202              sizeof (struct elf_link_hash_entry *),
5203              elf_sort_symbol);
5204
5205       while (weaks != NULL)
5206         {
5207           struct elf_link_hash_entry *hlook;
5208           asection *slook;
5209           bfd_vma vlook;
5210           size_t i, j, idx = 0;
5211
5212           hlook = weaks;
5213           weaks = hlook->u.alias;
5214           hlook->u.alias = NULL;
5215
5216           if (hlook->root.type != bfd_link_hash_defined
5217               && hlook->root.type != bfd_link_hash_defweak)
5218             continue;
5219
5220           slook = hlook->root.u.def.section;
5221           vlook = hlook->root.u.def.value;
5222
5223           i = 0;
5224           j = sym_count;
5225           while (i != j)
5226             {
5227               bfd_signed_vma vdiff;
5228               idx = (i + j) / 2;
5229               h = sorted_sym_hash[idx];
5230               vdiff = vlook - h->root.u.def.value;
5231               if (vdiff < 0)
5232                 j = idx;
5233               else if (vdiff > 0)
5234                 i = idx + 1;
5235               else
5236                 {
5237                   int sdiff = slook->id - h->root.u.def.section->id;
5238                   if (sdiff < 0)
5239                     j = idx;
5240                   else if (sdiff > 0)
5241                     i = idx + 1;
5242                   else
5243                     break;
5244                 }
5245             }
5246
5247           /* We didn't find a value/section match.  */
5248           if (i == j)
5249             continue;
5250
5251           /* With multiple aliases, or when the weak symbol is already
5252              strongly defined, we have multiple matching symbols and
5253              the binary search above may land on any of them.  Step
5254              one past the matching symbol(s).  */
5255           while (++idx != j)
5256             {
5257               h = sorted_sym_hash[idx];
5258               if (h->root.u.def.section != slook
5259                   || h->root.u.def.value != vlook)
5260                 break;
5261             }
5262
5263           /* Now look back over the aliases.  Since we sorted by size
5264              as well as value and section, we'll choose the one with
5265              the largest size.  */
5266           while (idx-- != i)
5267             {
5268               h = sorted_sym_hash[idx];
5269
5270               /* Stop if value or section doesn't match.  */
5271               if (h->root.u.def.section != slook
5272                   || h->root.u.def.value != vlook)
5273                 break;
5274               else if (h != hlook)
5275                 {
5276                   struct elf_link_hash_entry *t;
5277
5278                   hlook->u.alias = h;
5279                   hlook->is_weakalias = 1;
5280                   t = h;
5281                   if (t->u.alias != NULL)
5282                     while (t->u.alias != h)
5283                       t = t->u.alias;
5284                   t->u.alias = hlook;
5285
5286                   /* If the weak definition is in the list of dynamic
5287                      symbols, make sure the real definition is put
5288                      there as well.  */
5289                   if (hlook->dynindx != -1 && h->dynindx == -1)
5290                     {
5291                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
5292                         {
5293                         err_free_sym_hash:
5294                           free (sorted_sym_hash);
5295                           goto error_return;
5296                         }
5297                     }
5298
5299                   /* If the real definition is in the list of dynamic
5300                      symbols, make sure the weak definition is put
5301                      there as well.  If we don't do this, then the
5302                      dynamic loader might not merge the entries for the
5303                      real definition and the weak definition.  */
5304                   if (h->dynindx != -1 && hlook->dynindx == -1)
5305                     {
5306                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
5307                         goto err_free_sym_hash;
5308                     }
5309                   break;
5310                 }
5311             }
5312         }
5313
5314       free (sorted_sym_hash);
5315     }
5316
5317   if (bed->check_directives
5318       && !(*bed->check_directives) (abfd, info))
5319     return FALSE;
5320
5321   /* If this is a non-traditional link, try to optimize the handling
5322      of the .stab/.stabstr sections.  */
5323   if (! dynamic
5324       && ! info->traditional_format
5325       && is_elf_hash_table (htab)
5326       && (info->strip != strip_all && info->strip != strip_debugger))
5327     {
5328       asection *stabstr;
5329
5330       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
5331       if (stabstr != NULL)
5332         {
5333           bfd_size_type string_offset = 0;
5334           asection *stab;
5335
5336           for (stab = abfd->sections; stab; stab = stab->next)
5337             if (CONST_STRNEQ (stab->name, ".stab")
5338                 && (!stab->name[5] ||
5339                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
5340                 && (stab->flags & SEC_MERGE) == 0
5341                 && !bfd_is_abs_section (stab->output_section))
5342               {
5343                 struct bfd_elf_section_data *secdata;
5344
5345                 secdata = elf_section_data (stab);
5346                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
5347                                                stabstr, &secdata->sec_info,
5348                                                &string_offset))
5349                   goto error_return;
5350                 if (secdata->sec_info)
5351                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
5352             }
5353         }
5354     }
5355
5356   if (is_elf_hash_table (htab) && add_needed)
5357     {
5358       /* Add this bfd to the loaded list.  */
5359       struct elf_link_loaded_list *n;
5360
5361       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
5362       if (n == NULL)
5363         goto error_return;
5364       n->abfd = abfd;
5365       n->next = htab->loaded;
5366       htab->loaded = n;
5367     }
5368
5369   return TRUE;
5370
5371  error_free_vers:
5372   if (old_tab != NULL)
5373     free (old_tab);
5374   if (old_strtab != NULL)
5375     free (old_strtab);
5376   if (nondeflt_vers != NULL)
5377     free (nondeflt_vers);
5378   if (extversym != NULL)
5379     free (extversym);
5380  error_free_sym:
5381   if (isymbuf != NULL)
5382     free (isymbuf);
5383  error_return:
5384   return FALSE;
5385 }
5386
5387 /* Return the linker hash table entry of a symbol that might be
5388    satisfied by an archive symbol.  Return -1 on error.  */
5389
5390 struct elf_link_hash_entry *
5391 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5392                                 struct bfd_link_info *info,
5393                                 const char *name)
5394 {
5395   struct elf_link_hash_entry *h;
5396   char *p, *copy;
5397   size_t len, first;
5398
5399   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5400   if (h != NULL)
5401     return h;
5402
5403   /* If this is a default version (the name contains @@), look up the
5404      symbol again with only one `@' as well as without the version.
5405      The effect is that references to the symbol with and without the
5406      version will be matched by the default symbol in the archive.  */
5407
5408   p = strchr (name, ELF_VER_CHR);
5409   if (p == NULL || p[1] != ELF_VER_CHR)
5410     return h;
5411
5412   /* First check with only one `@'.  */
5413   len = strlen (name);
5414   copy = (char *) bfd_alloc (abfd, len);
5415   if (copy == NULL)
5416     return (struct elf_link_hash_entry *) 0 - 1;
5417
5418   first = p - name + 1;
5419   memcpy (copy, name, first);
5420   memcpy (copy + first, name + first + 1, len - first);
5421
5422   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5423   if (h == NULL)
5424     {
5425       /* We also need to check references to the symbol without the
5426          version.  */
5427       copy[first - 1] = '\0';
5428       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5429                                 FALSE, FALSE, TRUE);
5430     }
5431
5432   bfd_release (abfd, copy);
5433   return h;
5434 }
5435
5436 /* Add symbols from an ELF archive file to the linker hash table.  We
5437    don't use _bfd_generic_link_add_archive_symbols because we need to
5438    handle versioned symbols.
5439
5440    Fortunately, ELF archive handling is simpler than that done by
5441    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5442    oddities.  In ELF, if we find a symbol in the archive map, and the
5443    symbol is currently undefined, we know that we must pull in that
5444    object file.
5445
5446    Unfortunately, we do have to make multiple passes over the symbol
5447    table until nothing further is resolved.  */
5448
5449 static bfd_boolean
5450 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5451 {
5452   symindex c;
5453   unsigned char *included = NULL;
5454   carsym *symdefs;
5455   bfd_boolean loop;
5456   bfd_size_type amt;
5457   const struct elf_backend_data *bed;
5458   struct elf_link_hash_entry * (*archive_symbol_lookup)
5459     (bfd *, struct bfd_link_info *, const char *);
5460
5461   if (! bfd_has_map (abfd))
5462     {
5463       /* An empty archive is a special case.  */
5464       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5465         return TRUE;
5466       bfd_set_error (bfd_error_no_armap);
5467       return FALSE;
5468     }
5469
5470   /* Keep track of all symbols we know to be already defined, and all
5471      files we know to be already included.  This is to speed up the
5472      second and subsequent passes.  */
5473   c = bfd_ardata (abfd)->symdef_count;
5474   if (c == 0)
5475     return TRUE;
5476   amt = c;
5477   amt *= sizeof (*included);
5478   included = (unsigned char *) bfd_zmalloc (amt);
5479   if (included == NULL)
5480     return FALSE;
5481
5482   symdefs = bfd_ardata (abfd)->symdefs;
5483   bed = get_elf_backend_data (abfd);
5484   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5485
5486   do
5487     {
5488       file_ptr last;
5489       symindex i;
5490       carsym *symdef;
5491       carsym *symdefend;
5492
5493       loop = FALSE;
5494       last = -1;
5495
5496       symdef = symdefs;
5497       symdefend = symdef + c;
5498       for (i = 0; symdef < symdefend; symdef++, i++)
5499         {
5500           struct elf_link_hash_entry *h;
5501           bfd *element;
5502           struct bfd_link_hash_entry *undefs_tail;
5503           symindex mark;
5504
5505           if (included[i])
5506             continue;
5507           if (symdef->file_offset == last)
5508             {
5509               included[i] = TRUE;
5510               continue;
5511             }
5512
5513           h = archive_symbol_lookup (abfd, info, symdef->name);
5514           if (h == (struct elf_link_hash_entry *) 0 - 1)
5515             goto error_return;
5516
5517           if (h == NULL)
5518             continue;
5519
5520           if (h->root.type == bfd_link_hash_common)
5521             {
5522               /* We currently have a common symbol.  The archive map contains
5523                  a reference to this symbol, so we may want to include it.  We
5524                  only want to include it however, if this archive element
5525                  contains a definition of the symbol, not just another common
5526                  declaration of it.
5527
5528                  Unfortunately some archivers (including GNU ar) will put
5529                  declarations of common symbols into their archive maps, as
5530                  well as real definitions, so we cannot just go by the archive
5531                  map alone.  Instead we must read in the element's symbol
5532                  table and check that to see what kind of symbol definition
5533                  this is.  */
5534               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5535                 continue;
5536             }
5537           else if (h->root.type != bfd_link_hash_undefined)
5538             {
5539               if (h->root.type != bfd_link_hash_undefweak)
5540                 /* Symbol must be defined.  Don't check it again.  */
5541                 included[i] = TRUE;
5542               continue;
5543             }
5544
5545           /* We need to include this archive member.  */
5546           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5547           if (element == NULL)
5548             goto error_return;
5549
5550           if (! bfd_check_format (element, bfd_object))
5551             goto error_return;
5552
5553           undefs_tail = info->hash->undefs_tail;
5554
5555           if (!(*info->callbacks
5556                 ->add_archive_element) (info, element, symdef->name, &element))
5557             continue;
5558           if (!bfd_link_add_symbols (element, info))
5559             goto error_return;
5560
5561           /* If there are any new undefined symbols, we need to make
5562              another pass through the archive in order to see whether
5563              they can be defined.  FIXME: This isn't perfect, because
5564              common symbols wind up on undefs_tail and because an
5565              undefined symbol which is defined later on in this pass
5566              does not require another pass.  This isn't a bug, but it
5567              does make the code less efficient than it could be.  */
5568           if (undefs_tail != info->hash->undefs_tail)
5569             loop = TRUE;
5570
5571           /* Look backward to mark all symbols from this object file
5572              which we have already seen in this pass.  */
5573           mark = i;
5574           do
5575             {
5576               included[mark] = TRUE;
5577               if (mark == 0)
5578                 break;
5579               --mark;
5580             }
5581           while (symdefs[mark].file_offset == symdef->file_offset);
5582
5583           /* We mark subsequent symbols from this object file as we go
5584              on through the loop.  */
5585           last = symdef->file_offset;
5586         }
5587     }
5588   while (loop);
5589
5590   free (included);
5591
5592   return TRUE;
5593
5594  error_return:
5595   if (included != NULL)
5596     free (included);
5597   return FALSE;
5598 }
5599
5600 /* Given an ELF BFD, add symbols to the global hash table as
5601    appropriate.  */
5602
5603 bfd_boolean
5604 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5605 {
5606   switch (bfd_get_format (abfd))
5607     {
5608     case bfd_object:
5609       return elf_link_add_object_symbols (abfd, info);
5610     case bfd_archive:
5611       return elf_link_add_archive_symbols (abfd, info);
5612     default:
5613       bfd_set_error (bfd_error_wrong_format);
5614       return FALSE;
5615     }
5616 }
5617 \f
5618 struct hash_codes_info
5619 {
5620   unsigned long *hashcodes;
5621   bfd_boolean error;
5622 };
5623
5624 /* This function will be called though elf_link_hash_traverse to store
5625    all hash value of the exported symbols in an array.  */
5626
5627 static bfd_boolean
5628 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5629 {
5630   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5631   const char *name;
5632   unsigned long ha;
5633   char *alc = NULL;
5634
5635   /* Ignore indirect symbols.  These are added by the versioning code.  */
5636   if (h->dynindx == -1)
5637     return TRUE;
5638
5639   name = h->root.root.string;
5640   if (h->versioned >= versioned)
5641     {
5642       char *p = strchr (name, ELF_VER_CHR);
5643       if (p != NULL)
5644         {
5645           alc = (char *) bfd_malloc (p - name + 1);
5646           if (alc == NULL)
5647             {
5648               inf->error = TRUE;
5649               return FALSE;
5650             }
5651           memcpy (alc, name, p - name);
5652           alc[p - name] = '\0';
5653           name = alc;
5654         }
5655     }
5656
5657   /* Compute the hash value.  */
5658   ha = bfd_elf_hash (name);
5659
5660   /* Store the found hash value in the array given as the argument.  */
5661   *(inf->hashcodes)++ = ha;
5662
5663   /* And store it in the struct so that we can put it in the hash table
5664      later.  */
5665   h->u.elf_hash_value = ha;
5666
5667   if (alc != NULL)
5668     free (alc);
5669
5670   return TRUE;
5671 }
5672
5673 struct collect_gnu_hash_codes
5674 {
5675   bfd *output_bfd;
5676   const struct elf_backend_data *bed;
5677   unsigned long int nsyms;
5678   unsigned long int maskbits;
5679   unsigned long int *hashcodes;
5680   unsigned long int *hashval;
5681   unsigned long int *indx;
5682   unsigned long int *counts;
5683   bfd_vma *bitmask;
5684   bfd_byte *contents;
5685   long int min_dynindx;
5686   unsigned long int bucketcount;
5687   unsigned long int symindx;
5688   long int local_indx;
5689   long int shift1, shift2;
5690   unsigned long int mask;
5691   bfd_boolean error;
5692 };
5693
5694 /* This function will be called though elf_link_hash_traverse to store
5695    all hash value of the exported symbols in an array.  */
5696
5697 static bfd_boolean
5698 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5699 {
5700   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5701   const char *name;
5702   unsigned long ha;
5703   char *alc = NULL;
5704
5705   /* Ignore indirect symbols.  These are added by the versioning code.  */
5706   if (h->dynindx == -1)
5707     return TRUE;
5708
5709   /* Ignore also local symbols and undefined symbols.  */
5710   if (! (*s->bed->elf_hash_symbol) (h))
5711     return TRUE;
5712
5713   name = h->root.root.string;
5714   if (h->versioned >= versioned)
5715     {
5716       char *p = strchr (name, ELF_VER_CHR);
5717       if (p != NULL)
5718         {
5719           alc = (char *) bfd_malloc (p - name + 1);
5720           if (alc == NULL)
5721             {
5722               s->error = TRUE;
5723               return FALSE;
5724             }
5725           memcpy (alc, name, p - name);
5726           alc[p - name] = '\0';
5727           name = alc;
5728         }
5729     }
5730
5731   /* Compute the hash value.  */
5732   ha = bfd_elf_gnu_hash (name);
5733
5734   /* Store the found hash value in the array for compute_bucket_count,
5735      and also for .dynsym reordering purposes.  */
5736   s->hashcodes[s->nsyms] = ha;
5737   s->hashval[h->dynindx] = ha;
5738   ++s->nsyms;
5739   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5740     s->min_dynindx = h->dynindx;
5741
5742   if (alc != NULL)
5743     free (alc);
5744
5745   return TRUE;
5746 }
5747
5748 /* This function will be called though elf_link_hash_traverse to do
5749    final dynaminc symbol renumbering.  */
5750
5751 static bfd_boolean
5752 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5753 {
5754   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5755   unsigned long int bucket;
5756   unsigned long int val;
5757
5758   /* Ignore indirect symbols.  */
5759   if (h->dynindx == -1)
5760     return TRUE;
5761
5762   /* Ignore also local symbols and undefined symbols.  */
5763   if (! (*s->bed->elf_hash_symbol) (h))
5764     {
5765       if (h->dynindx >= s->min_dynindx)
5766         h->dynindx = s->local_indx++;
5767       return TRUE;
5768     }
5769
5770   bucket = s->hashval[h->dynindx] % s->bucketcount;
5771   val = (s->hashval[h->dynindx] >> s->shift1)
5772         & ((s->maskbits >> s->shift1) - 1);
5773   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5774   s->bitmask[val]
5775     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5776   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5777   if (s->counts[bucket] == 1)
5778     /* Last element terminates the chain.  */
5779     val |= 1;
5780   bfd_put_32 (s->output_bfd, val,
5781               s->contents + (s->indx[bucket] - s->symindx) * 4);
5782   --s->counts[bucket];
5783   h->dynindx = s->indx[bucket]++;
5784   return TRUE;
5785 }
5786
5787 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5788
5789 bfd_boolean
5790 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5791 {
5792   return !(h->forced_local
5793            || h->root.type == bfd_link_hash_undefined
5794            || h->root.type == bfd_link_hash_undefweak
5795            || ((h->root.type == bfd_link_hash_defined
5796                 || h->root.type == bfd_link_hash_defweak)
5797                && h->root.u.def.section->output_section == NULL));
5798 }
5799
5800 /* Array used to determine the number of hash table buckets to use
5801    based on the number of symbols there are.  If there are fewer than
5802    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5803    fewer than 37 we use 17 buckets, and so forth.  We never use more
5804    than 32771 buckets.  */
5805
5806 static const size_t elf_buckets[] =
5807 {
5808   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5809   16411, 32771, 0
5810 };
5811
5812 /* Compute bucket count for hashing table.  We do not use a static set
5813    of possible tables sizes anymore.  Instead we determine for all
5814    possible reasonable sizes of the table the outcome (i.e., the
5815    number of collisions etc) and choose the best solution.  The
5816    weighting functions are not too simple to allow the table to grow
5817    without bounds.  Instead one of the weighting factors is the size.
5818    Therefore the result is always a good payoff between few collisions
5819    (= short chain lengths) and table size.  */
5820 static size_t
5821 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5822                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5823                       unsigned long int nsyms,
5824                       int gnu_hash)
5825 {
5826   size_t best_size = 0;
5827   unsigned long int i;
5828
5829   /* We have a problem here.  The following code to optimize the table
5830      size requires an integer type with more the 32 bits.  If
5831      BFD_HOST_U_64_BIT is set we know about such a type.  */
5832 #ifdef BFD_HOST_U_64_BIT
5833   if (info->optimize)
5834     {
5835       size_t minsize;
5836       size_t maxsize;
5837       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5838       bfd *dynobj = elf_hash_table (info)->dynobj;
5839       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5840       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5841       unsigned long int *counts;
5842       bfd_size_type amt;
5843       unsigned int no_improvement_count = 0;
5844
5845       /* Possible optimization parameters: if we have NSYMS symbols we say
5846          that the hashing table must at least have NSYMS/4 and at most
5847          2*NSYMS buckets.  */
5848       minsize = nsyms / 4;
5849       if (minsize == 0)
5850         minsize = 1;
5851       best_size = maxsize = nsyms * 2;
5852       if (gnu_hash)
5853         {
5854           if (minsize < 2)
5855             minsize = 2;
5856           if ((best_size & 31) == 0)
5857             ++best_size;
5858         }
5859
5860       /* Create array where we count the collisions in.  We must use bfd_malloc
5861          since the size could be large.  */
5862       amt = maxsize;
5863       amt *= sizeof (unsigned long int);
5864       counts = (unsigned long int *) bfd_malloc (amt);
5865       if (counts == NULL)
5866         return 0;
5867
5868       /* Compute the "optimal" size for the hash table.  The criteria is a
5869          minimal chain length.  The minor criteria is (of course) the size
5870          of the table.  */
5871       for (i = minsize; i < maxsize; ++i)
5872         {
5873           /* Walk through the array of hashcodes and count the collisions.  */
5874           BFD_HOST_U_64_BIT max;
5875           unsigned long int j;
5876           unsigned long int fact;
5877
5878           if (gnu_hash && (i & 31) == 0)
5879             continue;
5880
5881           memset (counts, '\0', i * sizeof (unsigned long int));
5882
5883           /* Determine how often each hash bucket is used.  */
5884           for (j = 0; j < nsyms; ++j)
5885             ++counts[hashcodes[j] % i];
5886
5887           /* For the weight function we need some information about the
5888              pagesize on the target.  This is information need not be 100%
5889              accurate.  Since this information is not available (so far) we
5890              define it here to a reasonable default value.  If it is crucial
5891              to have a better value some day simply define this value.  */
5892 # ifndef BFD_TARGET_PAGESIZE
5893 #  define BFD_TARGET_PAGESIZE   (4096)
5894 # endif
5895
5896           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5897              and the chains.  */
5898           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5899
5900 # if 1
5901           /* Variant 1: optimize for short chains.  We add the squares
5902              of all the chain lengths (which favors many small chain
5903              over a few long chains).  */
5904           for (j = 0; j < i; ++j)
5905             max += counts[j] * counts[j];
5906
5907           /* This adds penalties for the overall size of the table.  */
5908           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5909           max *= fact * fact;
5910 # else
5911           /* Variant 2: Optimize a lot more for small table.  Here we
5912              also add squares of the size but we also add penalties for
5913              empty slots (the +1 term).  */
5914           for (j = 0; j < i; ++j)
5915             max += (1 + counts[j]) * (1 + counts[j]);
5916
5917           /* The overall size of the table is considered, but not as
5918              strong as in variant 1, where it is squared.  */
5919           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5920           max *= fact;
5921 # endif
5922
5923           /* Compare with current best results.  */
5924           if (max < best_chlen)
5925             {
5926               best_chlen = max;
5927               best_size = i;
5928               no_improvement_count = 0;
5929             }
5930           /* PR 11843: Avoid futile long searches for the best bucket size
5931              when there are a large number of symbols.  */
5932           else if (++no_improvement_count == 100)
5933             break;
5934         }
5935
5936       free (counts);
5937     }
5938   else
5939 #endif /* defined (BFD_HOST_U_64_BIT) */
5940     {
5941       /* This is the fallback solution if no 64bit type is available or if we
5942          are not supposed to spend much time on optimizations.  We select the
5943          bucket count using a fixed set of numbers.  */
5944       for (i = 0; elf_buckets[i] != 0; i++)
5945         {
5946           best_size = elf_buckets[i];
5947           if (nsyms < elf_buckets[i + 1])
5948             break;
5949         }
5950       if (gnu_hash && best_size < 2)
5951         best_size = 2;
5952     }
5953
5954   return best_size;
5955 }
5956
5957 /* Size any SHT_GROUP section for ld -r.  */
5958
5959 bfd_boolean
5960 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5961 {
5962   bfd *ibfd;
5963   asection *s;
5964
5965   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5966     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5967         && (s = ibfd->sections) != NULL
5968         && s->sec_info_type != SEC_INFO_TYPE_JUST_SYMS
5969         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5970       return FALSE;
5971   return TRUE;
5972 }
5973
5974 /* Set a default stack segment size.  The value in INFO wins.  If it
5975    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
5976    undefined it is initialized.  */
5977
5978 bfd_boolean
5979 bfd_elf_stack_segment_size (bfd *output_bfd,
5980                             struct bfd_link_info *info,
5981                             const char *legacy_symbol,
5982                             bfd_vma default_size)
5983 {
5984   struct elf_link_hash_entry *h = NULL;
5985
5986   /* Look for legacy symbol.  */
5987   if (legacy_symbol)
5988     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
5989                               FALSE, FALSE, FALSE);
5990   if (h && (h->root.type == bfd_link_hash_defined
5991             || h->root.type == bfd_link_hash_defweak)
5992       && h->def_regular
5993       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
5994     {
5995       /* The symbol has no type if specified on the command line.  */
5996       h->type = STT_OBJECT;
5997       if (info->stacksize)
5998         /* xgettext:c-format */
5999         _bfd_error_handler (_("%B: stack size specified and %s set"),
6000                             output_bfd, legacy_symbol);
6001       else if (h->root.u.def.section != bfd_abs_section_ptr)
6002         /* xgettext:c-format */
6003         _bfd_error_handler (_("%B: %s not absolute"),
6004                             output_bfd, legacy_symbol);
6005       else
6006         info->stacksize = h->root.u.def.value;
6007     }
6008
6009   if (!info->stacksize)
6010     /* If the user didn't set a size, or explicitly inhibit the
6011        size, set it now.  */
6012     info->stacksize = default_size;
6013
6014   /* Provide the legacy symbol, if it is referenced.  */
6015   if (h && (h->root.type == bfd_link_hash_undefined
6016             || h->root.type == bfd_link_hash_undefweak))
6017     {
6018       struct bfd_link_hash_entry *bh = NULL;
6019
6020       if (!(_bfd_generic_link_add_one_symbol
6021             (info, output_bfd, legacy_symbol,
6022              BSF_GLOBAL, bfd_abs_section_ptr,
6023              info->stacksize >= 0 ? info->stacksize : 0,
6024              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
6025         return FALSE;
6026
6027       h = (struct elf_link_hash_entry *) bh;
6028       h->def_regular = 1;
6029       h->type = STT_OBJECT;
6030     }
6031
6032   return TRUE;
6033 }
6034
6035 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
6036
6037 struct elf_gc_sweep_symbol_info
6038 {
6039   struct bfd_link_info *info;
6040   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
6041                        bfd_boolean);
6042 };
6043
6044 static bfd_boolean
6045 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
6046 {
6047   if (!h->mark
6048       && (((h->root.type == bfd_link_hash_defined
6049             || h->root.type == bfd_link_hash_defweak)
6050            && !((h->def_regular || ELF_COMMON_DEF_P (h))
6051                 && h->root.u.def.section->gc_mark))
6052           || h->root.type == bfd_link_hash_undefined
6053           || h->root.type == bfd_link_hash_undefweak))
6054     {
6055       struct elf_gc_sweep_symbol_info *inf;
6056
6057       inf = (struct elf_gc_sweep_symbol_info *) data;
6058       (*inf->hide_symbol) (inf->info, h, TRUE);
6059       h->def_regular = 0;
6060       h->ref_regular = 0;
6061       h->ref_regular_nonweak = 0;
6062     }
6063
6064   return TRUE;
6065 }
6066
6067 /* Set up the sizes and contents of the ELF dynamic sections.  This is
6068    called by the ELF linker emulation before_allocation routine.  We
6069    must set the sizes of the sections before the linker sets the
6070    addresses of the various sections.  */
6071
6072 bfd_boolean
6073 bfd_elf_size_dynamic_sections (bfd *output_bfd,
6074                                const char *soname,
6075                                const char *rpath,
6076                                const char *filter_shlib,
6077                                const char *audit,
6078                                const char *depaudit,
6079                                const char * const *auxiliary_filters,
6080                                struct bfd_link_info *info,
6081                                asection **sinterpptr)
6082 {
6083   bfd *dynobj;
6084   const struct elf_backend_data *bed;
6085
6086   *sinterpptr = NULL;
6087
6088   if (!is_elf_hash_table (info->hash))
6089     return TRUE;
6090
6091   dynobj = elf_hash_table (info)->dynobj;
6092
6093   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6094     {
6095       struct bfd_elf_version_tree *verdefs;
6096       struct elf_info_failed asvinfo;
6097       struct bfd_elf_version_tree *t;
6098       struct bfd_elf_version_expr *d;
6099       asection *s;
6100       size_t soname_indx;
6101
6102       /* If we are supposed to export all symbols into the dynamic symbol
6103          table (this is not the normal case), then do so.  */
6104       if (info->export_dynamic
6105           || (bfd_link_executable (info) && info->dynamic))
6106         {
6107           struct elf_info_failed eif;
6108
6109           eif.info = info;
6110           eif.failed = FALSE;
6111           elf_link_hash_traverse (elf_hash_table (info),
6112                                   _bfd_elf_export_symbol,
6113                                   &eif);
6114           if (eif.failed)
6115             return FALSE;
6116         }
6117
6118       if (soname != NULL)
6119         {
6120           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6121                                              soname, TRUE);
6122           if (soname_indx == (size_t) -1
6123               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
6124             return FALSE;
6125         }
6126       else
6127         soname_indx = (size_t) -1;
6128
6129       /* Make all global versions with definition.  */
6130       for (t = info->version_info; t != NULL; t = t->next)
6131         for (d = t->globals.list; d != NULL; d = d->next)
6132           if (!d->symver && d->literal)
6133             {
6134               const char *verstr, *name;
6135               size_t namelen, verlen, newlen;
6136               char *newname, *p, leading_char;
6137               struct elf_link_hash_entry *newh;
6138
6139               leading_char = bfd_get_symbol_leading_char (output_bfd);
6140               name = d->pattern;
6141               namelen = strlen (name) + (leading_char != '\0');
6142               verstr = t->name;
6143               verlen = strlen (verstr);
6144               newlen = namelen + verlen + 3;
6145
6146               newname = (char *) bfd_malloc (newlen);
6147               if (newname == NULL)
6148                 return FALSE;
6149               newname[0] = leading_char;
6150               memcpy (newname + (leading_char != '\0'), name, namelen);
6151
6152               /* Check the hidden versioned definition.  */
6153               p = newname + namelen;
6154               *p++ = ELF_VER_CHR;
6155               memcpy (p, verstr, verlen + 1);
6156               newh = elf_link_hash_lookup (elf_hash_table (info),
6157                                            newname, FALSE, FALSE,
6158                                            FALSE);
6159               if (newh == NULL
6160                   || (newh->root.type != bfd_link_hash_defined
6161                       && newh->root.type != bfd_link_hash_defweak))
6162                 {
6163                   /* Check the default versioned definition.  */
6164                   *p++ = ELF_VER_CHR;
6165                   memcpy (p, verstr, verlen + 1);
6166                   newh = elf_link_hash_lookup (elf_hash_table (info),
6167                                                newname, FALSE, FALSE,
6168                                                FALSE);
6169                 }
6170               free (newname);
6171
6172               /* Mark this version if there is a definition and it is
6173                  not defined in a shared object.  */
6174               if (newh != NULL
6175                   && !newh->def_dynamic
6176                   && (newh->root.type == bfd_link_hash_defined
6177                       || newh->root.type == bfd_link_hash_defweak))
6178                 d->symver = 1;
6179             }
6180
6181       /* Attach all the symbols to their version information.  */
6182       asvinfo.info = info;
6183       asvinfo.failed = FALSE;
6184
6185       elf_link_hash_traverse (elf_hash_table (info),
6186                               _bfd_elf_link_assign_sym_version,
6187                               &asvinfo);
6188       if (asvinfo.failed)
6189         return FALSE;
6190
6191       if (!info->allow_undefined_version)
6192         {
6193           /* Check if all global versions have a definition.  */
6194           bfd_boolean all_defined = TRUE;
6195           for (t = info->version_info; t != NULL; t = t->next)
6196             for (d = t->globals.list; d != NULL; d = d->next)
6197               if (d->literal && !d->symver && !d->script)
6198                 {
6199                   _bfd_error_handler
6200                     (_("%s: undefined version: %s"),
6201                      d->pattern, t->name);
6202                   all_defined = FALSE;
6203                 }
6204
6205           if (!all_defined)
6206             {
6207               bfd_set_error (bfd_error_bad_value);
6208               return FALSE;
6209             }
6210         }
6211
6212       /* Set up the version definition section.  */
6213       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6214       BFD_ASSERT (s != NULL);
6215
6216       /* We may have created additional version definitions if we are
6217          just linking a regular application.  */
6218       verdefs = info->version_info;
6219
6220       /* Skip anonymous version tag.  */
6221       if (verdefs != NULL && verdefs->vernum == 0)
6222         verdefs = verdefs->next;
6223
6224       if (verdefs == NULL && !info->create_default_symver)
6225         s->flags |= SEC_EXCLUDE;
6226       else
6227         {
6228           unsigned int cdefs;
6229           bfd_size_type size;
6230           bfd_byte *p;
6231           Elf_Internal_Verdef def;
6232           Elf_Internal_Verdaux defaux;
6233           struct bfd_link_hash_entry *bh;
6234           struct elf_link_hash_entry *h;
6235           const char *name;
6236
6237           cdefs = 0;
6238           size = 0;
6239
6240           /* Make space for the base version.  */
6241           size += sizeof (Elf_External_Verdef);
6242           size += sizeof (Elf_External_Verdaux);
6243           ++cdefs;
6244
6245           /* Make space for the default version.  */
6246           if (info->create_default_symver)
6247             {
6248               size += sizeof (Elf_External_Verdef);
6249               ++cdefs;
6250             }
6251
6252           for (t = verdefs; t != NULL; t = t->next)
6253             {
6254               struct bfd_elf_version_deps *n;
6255
6256               /* Don't emit base version twice.  */
6257               if (t->vernum == 0)
6258                 continue;
6259
6260               size += sizeof (Elf_External_Verdef);
6261               size += sizeof (Elf_External_Verdaux);
6262               ++cdefs;
6263
6264               for (n = t->deps; n != NULL; n = n->next)
6265                 size += sizeof (Elf_External_Verdaux);
6266             }
6267
6268           s->size = size;
6269           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6270           if (s->contents == NULL && s->size != 0)
6271             return FALSE;
6272
6273           /* Fill in the version definition section.  */
6274
6275           p = s->contents;
6276
6277           def.vd_version = VER_DEF_CURRENT;
6278           def.vd_flags = VER_FLG_BASE;
6279           def.vd_ndx = 1;
6280           def.vd_cnt = 1;
6281           if (info->create_default_symver)
6282             {
6283               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6284               def.vd_next = sizeof (Elf_External_Verdef);
6285             }
6286           else
6287             {
6288               def.vd_aux = sizeof (Elf_External_Verdef);
6289               def.vd_next = (sizeof (Elf_External_Verdef)
6290                              + sizeof (Elf_External_Verdaux));
6291             }
6292
6293           if (soname_indx != (size_t) -1)
6294             {
6295               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6296                                       soname_indx);
6297               def.vd_hash = bfd_elf_hash (soname);
6298               defaux.vda_name = soname_indx;
6299               name = soname;
6300             }
6301           else
6302             {
6303               size_t indx;
6304
6305               name = lbasename (output_bfd->filename);
6306               def.vd_hash = bfd_elf_hash (name);
6307               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6308                                           name, FALSE);
6309               if (indx == (size_t) -1)
6310                 return FALSE;
6311               defaux.vda_name = indx;
6312             }
6313           defaux.vda_next = 0;
6314
6315           _bfd_elf_swap_verdef_out (output_bfd, &def,
6316                                     (Elf_External_Verdef *) p);
6317           p += sizeof (Elf_External_Verdef);
6318           if (info->create_default_symver)
6319             {
6320               /* Add a symbol representing this version.  */
6321               bh = NULL;
6322               if (! (_bfd_generic_link_add_one_symbol
6323                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6324                       0, NULL, FALSE,
6325                       get_elf_backend_data (dynobj)->collect, &bh)))
6326                 return FALSE;
6327               h = (struct elf_link_hash_entry *) bh;
6328               h->non_elf = 0;
6329               h->def_regular = 1;
6330               h->type = STT_OBJECT;
6331               h->verinfo.vertree = NULL;
6332
6333               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6334                 return FALSE;
6335
6336               /* Create a duplicate of the base version with the same
6337                  aux block, but different flags.  */
6338               def.vd_flags = 0;
6339               def.vd_ndx = 2;
6340               def.vd_aux = sizeof (Elf_External_Verdef);
6341               if (verdefs)
6342                 def.vd_next = (sizeof (Elf_External_Verdef)
6343                                + sizeof (Elf_External_Verdaux));
6344               else
6345                 def.vd_next = 0;
6346               _bfd_elf_swap_verdef_out (output_bfd, &def,
6347                                         (Elf_External_Verdef *) p);
6348               p += sizeof (Elf_External_Verdef);
6349             }
6350           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6351                                      (Elf_External_Verdaux *) p);
6352           p += sizeof (Elf_External_Verdaux);
6353
6354           for (t = verdefs; t != NULL; t = t->next)
6355             {
6356               unsigned int cdeps;
6357               struct bfd_elf_version_deps *n;
6358
6359               /* Don't emit the base version twice.  */
6360               if (t->vernum == 0)
6361                 continue;
6362
6363               cdeps = 0;
6364               for (n = t->deps; n != NULL; n = n->next)
6365                 ++cdeps;
6366
6367               /* Add a symbol representing this version.  */
6368               bh = NULL;
6369               if (! (_bfd_generic_link_add_one_symbol
6370                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6371                       0, NULL, FALSE,
6372                       get_elf_backend_data (dynobj)->collect, &bh)))
6373                 return FALSE;
6374               h = (struct elf_link_hash_entry *) bh;
6375               h->non_elf = 0;
6376               h->def_regular = 1;
6377               h->type = STT_OBJECT;
6378               h->verinfo.vertree = t;
6379
6380               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6381                 return FALSE;
6382
6383               def.vd_version = VER_DEF_CURRENT;
6384               def.vd_flags = 0;
6385               if (t->globals.list == NULL
6386                   && t->locals.list == NULL
6387                   && ! t->used)
6388                 def.vd_flags |= VER_FLG_WEAK;
6389               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6390               def.vd_cnt = cdeps + 1;
6391               def.vd_hash = bfd_elf_hash (t->name);
6392               def.vd_aux = sizeof (Elf_External_Verdef);
6393               def.vd_next = 0;
6394
6395               /* If a basever node is next, it *must* be the last node in
6396                  the chain, otherwise Verdef construction breaks.  */
6397               if (t->next != NULL && t->next->vernum == 0)
6398                 BFD_ASSERT (t->next->next == NULL);
6399
6400               if (t->next != NULL && t->next->vernum != 0)
6401                 def.vd_next = (sizeof (Elf_External_Verdef)
6402                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6403
6404               _bfd_elf_swap_verdef_out (output_bfd, &def,
6405                                         (Elf_External_Verdef *) p);
6406               p += sizeof (Elf_External_Verdef);
6407
6408               defaux.vda_name = h->dynstr_index;
6409               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6410                                       h->dynstr_index);
6411               defaux.vda_next = 0;
6412               if (t->deps != NULL)
6413                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6414               t->name_indx = defaux.vda_name;
6415
6416               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6417                                          (Elf_External_Verdaux *) p);
6418               p += sizeof (Elf_External_Verdaux);
6419
6420               for (n = t->deps; n != NULL; n = n->next)
6421                 {
6422                   if (n->version_needed == NULL)
6423                     {
6424                       /* This can happen if there was an error in the
6425                          version script.  */
6426                       defaux.vda_name = 0;
6427                     }
6428                   else
6429                     {
6430                       defaux.vda_name = n->version_needed->name_indx;
6431                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6432                                               defaux.vda_name);
6433                     }
6434                   if (n->next == NULL)
6435                     defaux.vda_next = 0;
6436                   else
6437                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6438
6439                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6440                                              (Elf_External_Verdaux *) p);
6441                   p += sizeof (Elf_External_Verdaux);
6442                 }
6443             }
6444
6445           elf_tdata (output_bfd)->cverdefs = cdefs;
6446         }
6447     }
6448
6449   bed = get_elf_backend_data (output_bfd);
6450
6451   if (info->gc_sections && bed->can_gc_sections)
6452     {
6453       struct elf_gc_sweep_symbol_info sweep_info;
6454
6455       /* Remove the symbols that were in the swept sections from the
6456          dynamic symbol table.  */
6457       sweep_info.info = info;
6458       sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
6459       elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
6460                               &sweep_info);
6461     }
6462
6463   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6464     {
6465       asection *s;
6466       struct elf_find_verdep_info sinfo;
6467
6468       /* Work out the size of the version reference section.  */
6469
6470       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6471       BFD_ASSERT (s != NULL);
6472
6473       sinfo.info = info;
6474       sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6475       if (sinfo.vers == 0)
6476         sinfo.vers = 1;
6477       sinfo.failed = FALSE;
6478
6479       elf_link_hash_traverse (elf_hash_table (info),
6480                               _bfd_elf_link_find_version_dependencies,
6481                               &sinfo);
6482       if (sinfo.failed)
6483         return FALSE;
6484
6485       if (elf_tdata (output_bfd)->verref == NULL)
6486         s->flags |= SEC_EXCLUDE;
6487       else
6488         {
6489           Elf_Internal_Verneed *vn;
6490           unsigned int size;
6491           unsigned int crefs;
6492           bfd_byte *p;
6493
6494           /* Build the version dependency section.  */
6495           size = 0;
6496           crefs = 0;
6497           for (vn = elf_tdata (output_bfd)->verref;
6498                vn != NULL;
6499                vn = vn->vn_nextref)
6500             {
6501               Elf_Internal_Vernaux *a;
6502
6503               size += sizeof (Elf_External_Verneed);
6504               ++crefs;
6505               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6506                 size += sizeof (Elf_External_Vernaux);
6507             }
6508
6509           s->size = size;
6510           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6511           if (s->contents == NULL)
6512             return FALSE;
6513
6514           p = s->contents;
6515           for (vn = elf_tdata (output_bfd)->verref;
6516                vn != NULL;
6517                vn = vn->vn_nextref)
6518             {
6519               unsigned int caux;
6520               Elf_Internal_Vernaux *a;
6521               size_t indx;
6522
6523               caux = 0;
6524               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6525                 ++caux;
6526
6527               vn->vn_version = VER_NEED_CURRENT;
6528               vn->vn_cnt = caux;
6529               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6530                                           elf_dt_name (vn->vn_bfd) != NULL
6531                                           ? elf_dt_name (vn->vn_bfd)
6532                                           : lbasename (vn->vn_bfd->filename),
6533                                           FALSE);
6534               if (indx == (size_t) -1)
6535                 return FALSE;
6536               vn->vn_file = indx;
6537               vn->vn_aux = sizeof (Elf_External_Verneed);
6538               if (vn->vn_nextref == NULL)
6539                 vn->vn_next = 0;
6540               else
6541                 vn->vn_next = (sizeof (Elf_External_Verneed)
6542                                + caux * sizeof (Elf_External_Vernaux));
6543
6544               _bfd_elf_swap_verneed_out (output_bfd, vn,
6545                                          (Elf_External_Verneed *) p);
6546               p += sizeof (Elf_External_Verneed);
6547
6548               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6549                 {
6550                   a->vna_hash = bfd_elf_hash (a->vna_nodename);
6551                   indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6552                                               a->vna_nodename, FALSE);
6553                   if (indx == (size_t) -1)
6554                     return FALSE;
6555                   a->vna_name = indx;
6556                   if (a->vna_nextptr == NULL)
6557                     a->vna_next = 0;
6558                   else
6559                     a->vna_next = sizeof (Elf_External_Vernaux);
6560
6561                   _bfd_elf_swap_vernaux_out (output_bfd, a,
6562                                              (Elf_External_Vernaux *) p);
6563                   p += sizeof (Elf_External_Vernaux);
6564                 }
6565             }
6566
6567           elf_tdata (output_bfd)->cverrefs = crefs;
6568         }
6569     }
6570
6571   /* Any syms created from now on start with -1 in
6572      got.refcount/offset and plt.refcount/offset.  */
6573   elf_hash_table (info)->init_got_refcount
6574     = elf_hash_table (info)->init_got_offset;
6575   elf_hash_table (info)->init_plt_refcount
6576     = elf_hash_table (info)->init_plt_offset;
6577
6578   if (bfd_link_relocatable (info)
6579       && !_bfd_elf_size_group_sections (info))
6580     return FALSE;
6581
6582   /* The backend may have to create some sections regardless of whether
6583      we're dynamic or not.  */
6584   if (bed->elf_backend_always_size_sections
6585       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
6586     return FALSE;
6587
6588   /* Determine any GNU_STACK segment requirements, after the backend
6589      has had a chance to set a default segment size.  */
6590   if (info->execstack)
6591     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
6592   else if (info->noexecstack)
6593     elf_stack_flags (output_bfd) = PF_R | PF_W;
6594   else
6595     {
6596       bfd *inputobj;
6597       asection *notesec = NULL;
6598       int exec = 0;
6599
6600       for (inputobj = info->input_bfds;
6601            inputobj;
6602            inputobj = inputobj->link.next)
6603         {
6604           asection *s;
6605
6606           if (inputobj->flags
6607               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
6608             continue;
6609           s = inputobj->sections;
6610           if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
6611             continue;
6612
6613           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
6614           if (s)
6615             {
6616               if (s->flags & SEC_CODE)
6617                 exec = PF_X;
6618               notesec = s;
6619             }
6620           else if (bed->default_execstack)
6621             exec = PF_X;
6622         }
6623       if (notesec || info->stacksize > 0)
6624         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
6625       if (notesec && exec && bfd_link_relocatable (info)
6626           && notesec->output_section != bfd_abs_section_ptr)
6627         notesec->output_section->flags |= SEC_CODE;
6628     }
6629
6630   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6631     {
6632       struct elf_info_failed eif;
6633       struct elf_link_hash_entry *h;
6634       asection *dynstr;
6635       asection *s;
6636
6637       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
6638       BFD_ASSERT (*sinterpptr != NULL || !bfd_link_executable (info) || info->nointerp);
6639
6640       if (info->symbolic)
6641         {
6642           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
6643             return FALSE;
6644           info->flags |= DF_SYMBOLIC;
6645         }
6646
6647       if (rpath != NULL)
6648         {
6649           size_t indx;
6650           bfd_vma tag;
6651
6652           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
6653                                       TRUE);
6654           if (indx == (size_t) -1)
6655             return FALSE;
6656
6657           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
6658           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
6659             return FALSE;
6660         }
6661
6662       if (filter_shlib != NULL)
6663         {
6664           size_t indx;
6665
6666           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6667                                       filter_shlib, TRUE);
6668           if (indx == (size_t) -1
6669               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
6670             return FALSE;
6671         }
6672
6673       if (auxiliary_filters != NULL)
6674         {
6675           const char * const *p;
6676
6677           for (p = auxiliary_filters; *p != NULL; p++)
6678             {
6679               size_t indx;
6680
6681               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6682                                           *p, TRUE);
6683               if (indx == (size_t) -1
6684                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
6685                 return FALSE;
6686             }
6687         }
6688
6689       if (audit != NULL)
6690         {
6691           size_t indx;
6692
6693           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
6694                                       TRUE);
6695           if (indx == (size_t) -1
6696               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
6697             return FALSE;
6698         }
6699
6700       if (depaudit != NULL)
6701         {
6702           size_t indx;
6703
6704           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
6705                                       TRUE);
6706           if (indx == (size_t) -1
6707               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
6708             return FALSE;
6709         }
6710
6711       eif.info = info;
6712       eif.failed = FALSE;
6713
6714       /* Find all symbols which were defined in a dynamic object and make
6715          the backend pick a reasonable value for them.  */
6716       elf_link_hash_traverse (elf_hash_table (info),
6717                               _bfd_elf_adjust_dynamic_symbol,
6718                               &eif);
6719       if (eif.failed)
6720         return FALSE;
6721
6722       /* Add some entries to the .dynamic section.  We fill in some of the
6723          values later, in bfd_elf_final_link, but we must add the entries
6724          now so that we know the final size of the .dynamic section.  */
6725
6726       /* If there are initialization and/or finalization functions to
6727          call then add the corresponding DT_INIT/DT_FINI entries.  */
6728       h = (info->init_function
6729            ? elf_link_hash_lookup (elf_hash_table (info),
6730                                    info->init_function, FALSE,
6731                                    FALSE, FALSE)
6732            : NULL);
6733       if (h != NULL
6734           && (h->ref_regular
6735               || h->def_regular))
6736         {
6737           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
6738             return FALSE;
6739         }
6740       h = (info->fini_function
6741            ? elf_link_hash_lookup (elf_hash_table (info),
6742                                    info->fini_function, FALSE,
6743                                    FALSE, FALSE)
6744            : NULL);
6745       if (h != NULL
6746           && (h->ref_regular
6747               || h->def_regular))
6748         {
6749           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
6750             return FALSE;
6751         }
6752
6753       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
6754       if (s != NULL && s->linker_has_input)
6755         {
6756           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
6757           if (! bfd_link_executable (info))
6758             {
6759               bfd *sub;
6760               asection *o;
6761
6762               for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
6763                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour
6764                     && (o = sub->sections) != NULL
6765                     && o->sec_info_type != SEC_INFO_TYPE_JUST_SYMS)
6766                   for (o = sub->sections; o != NULL; o = o->next)
6767                     if (elf_section_data (o)->this_hdr.sh_type
6768                         == SHT_PREINIT_ARRAY)
6769                       {
6770                         _bfd_error_handler
6771                           (_("%B: .preinit_array section is not allowed in DSO"),
6772                            sub);
6773                         break;
6774                       }
6775
6776               bfd_set_error (bfd_error_nonrepresentable_section);
6777               return FALSE;
6778             }
6779
6780           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6781               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6782             return FALSE;
6783         }
6784       s = bfd_get_section_by_name (output_bfd, ".init_array");
6785       if (s != NULL && s->linker_has_input)
6786         {
6787           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6788               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6789             return FALSE;
6790         }
6791       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6792       if (s != NULL && s->linker_has_input)
6793         {
6794           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6795               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6796             return FALSE;
6797         }
6798
6799       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6800       /* If .dynstr is excluded from the link, we don't want any of
6801          these tags.  Strictly, we should be checking each section
6802          individually;  This quick check covers for the case where
6803          someone does a /DISCARD/ : { *(*) }.  */
6804       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6805         {
6806           bfd_size_type strsize;
6807
6808           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6809           if ((info->emit_hash
6810                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6811               || (info->emit_gnu_hash
6812                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6813               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6814               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6815               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6816               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6817                                               bed->s->sizeof_sym))
6818             return FALSE;
6819         }
6820     }
6821
6822   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6823     return FALSE;
6824
6825   /* The backend must work out the sizes of all the other dynamic
6826      sections.  */
6827   if (dynobj != NULL
6828       && bed->elf_backend_size_dynamic_sections != NULL
6829       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6830     return FALSE;
6831
6832   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6833     {
6834       unsigned long section_sym_count;
6835
6836       if (elf_tdata (output_bfd)->cverdefs)
6837         {
6838           unsigned int crefs = elf_tdata (output_bfd)->cverdefs;
6839
6840           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6841               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, crefs))
6842             return FALSE;
6843         }
6844
6845       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6846         {
6847           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6848             return FALSE;
6849         }
6850       else if (info->flags & DF_BIND_NOW)
6851         {
6852           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6853             return FALSE;
6854         }
6855
6856       if (info->flags_1)
6857         {
6858           if (bfd_link_executable (info))
6859             info->flags_1 &= ~ (DF_1_INITFIRST
6860                                 | DF_1_NODELETE
6861                                 | DF_1_NOOPEN);
6862           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6863             return FALSE;
6864         }
6865
6866       if (elf_tdata (output_bfd)->cverrefs)
6867         {
6868           unsigned int crefs = elf_tdata (output_bfd)->cverrefs;
6869
6870           if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6871               || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6872             return FALSE;
6873         }
6874
6875       if ((elf_tdata (output_bfd)->cverrefs == 0
6876            && elf_tdata (output_bfd)->cverdefs == 0)
6877           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6878                                              &section_sym_count) <= 1)
6879         {
6880           asection *s;
6881
6882           s = bfd_get_linker_section (dynobj, ".gnu.version");
6883           s->flags |= SEC_EXCLUDE;
6884         }
6885     }
6886   return TRUE;
6887 }
6888
6889 /* Find the first non-excluded output section.  We'll use its
6890    section symbol for some emitted relocs.  */
6891 void
6892 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6893 {
6894   asection *s;
6895
6896   for (s = output_bfd->sections; s != NULL; s = s->next)
6897     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6898         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6899       {
6900         elf_hash_table (info)->text_index_section = s;
6901         break;
6902       }
6903 }
6904
6905 /* Find two non-excluded output sections, one for code, one for data.
6906    We'll use their section symbols for some emitted relocs.  */
6907 void
6908 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6909 {
6910   asection *s;
6911
6912   /* Data first, since setting text_index_section changes
6913      _bfd_elf_link_omit_section_dynsym.  */
6914   for (s = output_bfd->sections; s != NULL; s = s->next)
6915     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6916         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6917       {
6918         elf_hash_table (info)->data_index_section = s;
6919         break;
6920       }
6921
6922   for (s = output_bfd->sections; s != NULL; s = s->next)
6923     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6924          == (SEC_ALLOC | SEC_READONLY))
6925         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6926       {
6927         elf_hash_table (info)->text_index_section = s;
6928         break;
6929       }
6930
6931   if (elf_hash_table (info)->text_index_section == NULL)
6932     elf_hash_table (info)->text_index_section
6933       = elf_hash_table (info)->data_index_section;
6934 }
6935
6936 bfd_boolean
6937 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6938 {
6939   const struct elf_backend_data *bed;
6940   unsigned long section_sym_count;
6941   bfd_size_type dynsymcount = 0;
6942
6943   if (!is_elf_hash_table (info->hash))
6944     return TRUE;
6945
6946   bed = get_elf_backend_data (output_bfd);
6947   (*bed->elf_backend_init_index_section) (output_bfd, info);
6948
6949   /* Assign dynsym indices.  In a shared library we generate a section
6950      symbol for each output section, which come first.  Next come all
6951      of the back-end allocated local dynamic syms, followed by the rest
6952      of the global symbols.
6953
6954      This is usually not needed for static binaries, however backends
6955      can request to always do it, e.g. the MIPS backend uses dynamic
6956      symbol counts to lay out GOT, which will be produced in the
6957      presence of GOT relocations even in static binaries (holding fixed
6958      data in that case, to satisfy those relocations).  */
6959
6960   if (elf_hash_table (info)->dynamic_sections_created
6961       || bed->always_renumber_dynsyms)
6962     dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6963                                                   &section_sym_count);
6964
6965   if (elf_hash_table (info)->dynamic_sections_created)
6966     {
6967       bfd *dynobj;
6968       asection *s;
6969       unsigned int dtagcount;
6970
6971       dynobj = elf_hash_table (info)->dynobj;
6972
6973       /* Work out the size of the symbol version section.  */
6974       s = bfd_get_linker_section (dynobj, ".gnu.version");
6975       BFD_ASSERT (s != NULL);
6976       if ((s->flags & SEC_EXCLUDE) == 0)
6977         {
6978           s->size = dynsymcount * sizeof (Elf_External_Versym);
6979           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6980           if (s->contents == NULL)
6981             return FALSE;
6982
6983           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6984             return FALSE;
6985         }
6986
6987       /* Set the size of the .dynsym and .hash sections.  We counted
6988          the number of dynamic symbols in elf_link_add_object_symbols.
6989          We will build the contents of .dynsym and .hash when we build
6990          the final symbol table, because until then we do not know the
6991          correct value to give the symbols.  We built the .dynstr
6992          section as we went along in elf_link_add_object_symbols.  */
6993       s = elf_hash_table (info)->dynsym;
6994       BFD_ASSERT (s != NULL);
6995       s->size = dynsymcount * bed->s->sizeof_sym;
6996
6997       s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6998       if (s->contents == NULL)
6999         return FALSE;
7000
7001       /* The first entry in .dynsym is a dummy symbol.  Clear all the
7002          section syms, in case we don't output them all.  */
7003       ++section_sym_count;
7004       memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
7005
7006       elf_hash_table (info)->bucketcount = 0;
7007
7008       /* Compute the size of the hashing table.  As a side effect this
7009          computes the hash values for all the names we export.  */
7010       if (info->emit_hash)
7011         {
7012           unsigned long int *hashcodes;
7013           struct hash_codes_info hashinf;
7014           bfd_size_type amt;
7015           unsigned long int nsyms;
7016           size_t bucketcount;
7017           size_t hash_entry_size;
7018
7019           /* Compute the hash values for all exported symbols.  At the same
7020              time store the values in an array so that we could use them for
7021              optimizations.  */
7022           amt = dynsymcount * sizeof (unsigned long int);
7023           hashcodes = (unsigned long int *) bfd_malloc (amt);
7024           if (hashcodes == NULL)
7025             return FALSE;
7026           hashinf.hashcodes = hashcodes;
7027           hashinf.error = FALSE;
7028
7029           /* Put all hash values in HASHCODES.  */
7030           elf_link_hash_traverse (elf_hash_table (info),
7031                                   elf_collect_hash_codes, &hashinf);
7032           if (hashinf.error)
7033             {
7034               free (hashcodes);
7035               return FALSE;
7036             }
7037
7038           nsyms = hashinf.hashcodes - hashcodes;
7039           bucketcount
7040             = compute_bucket_count (info, hashcodes, nsyms, 0);
7041           free (hashcodes);
7042
7043           if (bucketcount == 0 && nsyms > 0)
7044             return FALSE;
7045
7046           elf_hash_table (info)->bucketcount = bucketcount;
7047
7048           s = bfd_get_linker_section (dynobj, ".hash");
7049           BFD_ASSERT (s != NULL);
7050           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
7051           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
7052           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7053           if (s->contents == NULL)
7054             return FALSE;
7055
7056           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
7057           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
7058                    s->contents + hash_entry_size);
7059         }
7060
7061       if (info->emit_gnu_hash)
7062         {
7063           size_t i, cnt;
7064           unsigned char *contents;
7065           struct collect_gnu_hash_codes cinfo;
7066           bfd_size_type amt;
7067           size_t bucketcount;
7068
7069           memset (&cinfo, 0, sizeof (cinfo));
7070
7071           /* Compute the hash values for all exported symbols.  At the same
7072              time store the values in an array so that we could use them for
7073              optimizations.  */
7074           amt = dynsymcount * 2 * sizeof (unsigned long int);
7075           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
7076           if (cinfo.hashcodes == NULL)
7077             return FALSE;
7078
7079           cinfo.hashval = cinfo.hashcodes + dynsymcount;
7080           cinfo.min_dynindx = -1;
7081           cinfo.output_bfd = output_bfd;
7082           cinfo.bed = bed;
7083
7084           /* Put all hash values in HASHCODES.  */
7085           elf_link_hash_traverse (elf_hash_table (info),
7086                                   elf_collect_gnu_hash_codes, &cinfo);
7087           if (cinfo.error)
7088             {
7089               free (cinfo.hashcodes);
7090               return FALSE;
7091             }
7092
7093           bucketcount
7094             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
7095
7096           if (bucketcount == 0)
7097             {
7098               free (cinfo.hashcodes);
7099               return FALSE;
7100             }
7101
7102           s = bfd_get_linker_section (dynobj, ".gnu.hash");
7103           BFD_ASSERT (s != NULL);
7104
7105           if (cinfo.nsyms == 0)
7106             {
7107               /* Empty .gnu.hash section is special.  */
7108               BFD_ASSERT (cinfo.min_dynindx == -1);
7109               free (cinfo.hashcodes);
7110               s->size = 5 * 4 + bed->s->arch_size / 8;
7111               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7112               if (contents == NULL)
7113                 return FALSE;
7114               s->contents = contents;
7115               /* 1 empty bucket.  */
7116               bfd_put_32 (output_bfd, 1, contents);
7117               /* SYMIDX above the special symbol 0.  */
7118               bfd_put_32 (output_bfd, 1, contents + 4);
7119               /* Just one word for bitmask.  */
7120               bfd_put_32 (output_bfd, 1, contents + 8);
7121               /* Only hash fn bloom filter.  */
7122               bfd_put_32 (output_bfd, 0, contents + 12);
7123               /* No hashes are valid - empty bitmask.  */
7124               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
7125               /* No hashes in the only bucket.  */
7126               bfd_put_32 (output_bfd, 0,
7127                           contents + 16 + bed->s->arch_size / 8);
7128             }
7129           else
7130             {
7131               unsigned long int maskwords, maskbitslog2, x;
7132               BFD_ASSERT (cinfo.min_dynindx != -1);
7133
7134               x = cinfo.nsyms;
7135               maskbitslog2 = 1;
7136               while ((x >>= 1) != 0)
7137                 ++maskbitslog2;
7138               if (maskbitslog2 < 3)
7139                 maskbitslog2 = 5;
7140               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
7141                 maskbitslog2 = maskbitslog2 + 3;
7142               else
7143                 maskbitslog2 = maskbitslog2 + 2;
7144               if (bed->s->arch_size == 64)
7145                 {
7146                   if (maskbitslog2 == 5)
7147                     maskbitslog2 = 6;
7148                   cinfo.shift1 = 6;
7149                 }
7150               else
7151                 cinfo.shift1 = 5;
7152               cinfo.mask = (1 << cinfo.shift1) - 1;
7153               cinfo.shift2 = maskbitslog2;
7154               cinfo.maskbits = 1 << maskbitslog2;
7155               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
7156               amt = bucketcount * sizeof (unsigned long int) * 2;
7157               amt += maskwords * sizeof (bfd_vma);
7158               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
7159               if (cinfo.bitmask == NULL)
7160                 {
7161                   free (cinfo.hashcodes);
7162                   return FALSE;
7163                 }
7164
7165               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
7166               cinfo.indx = cinfo.counts + bucketcount;
7167               cinfo.symindx = dynsymcount - cinfo.nsyms;
7168               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
7169
7170               /* Determine how often each hash bucket is used.  */
7171               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
7172               for (i = 0; i < cinfo.nsyms; ++i)
7173                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
7174
7175               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
7176                 if (cinfo.counts[i] != 0)
7177                   {
7178                     cinfo.indx[i] = cnt;
7179                     cnt += cinfo.counts[i];
7180                   }
7181               BFD_ASSERT (cnt == dynsymcount);
7182               cinfo.bucketcount = bucketcount;
7183               cinfo.local_indx = cinfo.min_dynindx;
7184
7185               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
7186               s->size += cinfo.maskbits / 8;
7187               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7188               if (contents == NULL)
7189                 {
7190                   free (cinfo.bitmask);
7191                   free (cinfo.hashcodes);
7192                   return FALSE;
7193                 }
7194
7195               s->contents = contents;
7196               bfd_put_32 (output_bfd, bucketcount, contents);
7197               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
7198               bfd_put_32 (output_bfd, maskwords, contents + 8);
7199               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
7200               contents += 16 + cinfo.maskbits / 8;
7201
7202               for (i = 0; i < bucketcount; ++i)
7203                 {
7204                   if (cinfo.counts[i] == 0)
7205                     bfd_put_32 (output_bfd, 0, contents);
7206                   else
7207                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
7208                   contents += 4;
7209                 }
7210
7211               cinfo.contents = contents;
7212
7213               /* Renumber dynamic symbols, populate .gnu.hash section.  */
7214               elf_link_hash_traverse (elf_hash_table (info),
7215                                       elf_renumber_gnu_hash_syms, &cinfo);
7216
7217               contents = s->contents + 16;
7218               for (i = 0; i < maskwords; ++i)
7219                 {
7220                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
7221                            contents);
7222                   contents += bed->s->arch_size / 8;
7223                 }
7224
7225               free (cinfo.bitmask);
7226               free (cinfo.hashcodes);
7227             }
7228         }
7229
7230       s = bfd_get_linker_section (dynobj, ".dynstr");
7231       BFD_ASSERT (s != NULL);
7232
7233       elf_finalize_dynstr (output_bfd, info);
7234
7235       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
7236
7237       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
7238         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
7239           return FALSE;
7240     }
7241
7242   return TRUE;
7243 }
7244 \f
7245 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
7246
7247 static void
7248 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
7249                             asection *sec)
7250 {
7251   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
7252   sec->sec_info_type = SEC_INFO_TYPE_NONE;
7253 }
7254
7255 /* Finish SHF_MERGE section merging.  */
7256
7257 bfd_boolean
7258 _bfd_elf_merge_sections (bfd *obfd, struct bfd_link_info *info)
7259 {
7260   bfd *ibfd;
7261   asection *sec;
7262
7263   if (!is_elf_hash_table (info->hash))
7264     return FALSE;
7265
7266   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
7267     if ((ibfd->flags & DYNAMIC) == 0
7268         && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
7269         && (elf_elfheader (ibfd)->e_ident[EI_CLASS]
7270             == get_elf_backend_data (obfd)->s->elfclass))
7271       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
7272         if ((sec->flags & SEC_MERGE) != 0
7273             && !bfd_is_abs_section (sec->output_section))
7274           {
7275             struct bfd_elf_section_data *secdata;
7276
7277             secdata = elf_section_data (sec);
7278             if (! _bfd_add_merge_section (obfd,
7279                                           &elf_hash_table (info)->merge_info,
7280                                           sec, &secdata->sec_info))
7281               return FALSE;
7282             else if (secdata->sec_info)
7283               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
7284           }
7285
7286   if (elf_hash_table (info)->merge_info != NULL)
7287     _bfd_merge_sections (obfd, info, elf_hash_table (info)->merge_info,
7288                          merge_sections_remove_hook);
7289   return TRUE;
7290 }
7291
7292 /* Create an entry in an ELF linker hash table.  */
7293
7294 struct bfd_hash_entry *
7295 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
7296                             struct bfd_hash_table *table,
7297                             const char *string)
7298 {
7299   /* Allocate the structure if it has not already been allocated by a
7300      subclass.  */
7301   if (entry == NULL)
7302     {
7303       entry = (struct bfd_hash_entry *)
7304         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
7305       if (entry == NULL)
7306         return entry;
7307     }
7308
7309   /* Call the allocation method of the superclass.  */
7310   entry = _bfd_link_hash_newfunc (entry, table, string);
7311   if (entry != NULL)
7312     {
7313       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
7314       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
7315
7316       /* Set local fields.  */
7317       ret->indx = -1;
7318       ret->dynindx = -1;
7319       ret->got = htab->init_got_refcount;
7320       ret->plt = htab->init_plt_refcount;
7321       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
7322                               - offsetof (struct elf_link_hash_entry, size)));
7323       /* Assume that we have been called by a non-ELF symbol reader.
7324          This flag is then reset by the code which reads an ELF input
7325          file.  This ensures that a symbol created by a non-ELF symbol
7326          reader will have the flag set correctly.  */
7327       ret->non_elf = 1;
7328     }
7329
7330   return entry;
7331 }
7332
7333 /* Copy data from an indirect symbol to its direct symbol, hiding the
7334    old indirect symbol.  Also used for copying flags to a weakdef.  */
7335
7336 void
7337 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
7338                                   struct elf_link_hash_entry *dir,
7339                                   struct elf_link_hash_entry *ind)
7340 {
7341   struct elf_link_hash_table *htab;
7342
7343   /* Copy down any references that we may have already seen to the
7344      symbol which just became indirect.  */
7345
7346   if (dir->versioned != versioned_hidden)
7347     dir->ref_dynamic |= ind->ref_dynamic;
7348   dir->ref_regular |= ind->ref_regular;
7349   dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
7350   dir->non_got_ref |= ind->non_got_ref;
7351   dir->needs_plt |= ind->needs_plt;
7352   dir->pointer_equality_needed |= ind->pointer_equality_needed;
7353
7354   if (ind->root.type != bfd_link_hash_indirect)
7355     return;
7356
7357   /* Copy over the global and procedure linkage table refcount entries.
7358      These may have been already set up by a check_relocs routine.  */
7359   htab = elf_hash_table (info);
7360   if (ind->got.refcount > htab->init_got_refcount.refcount)
7361     {
7362       if (dir->got.refcount < 0)
7363         dir->got.refcount = 0;
7364       dir->got.refcount += ind->got.refcount;
7365       ind->got.refcount = htab->init_got_refcount.refcount;
7366     }
7367
7368   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
7369     {
7370       if (dir->plt.refcount < 0)
7371         dir->plt.refcount = 0;
7372       dir->plt.refcount += ind->plt.refcount;
7373       ind->plt.refcount = htab->init_plt_refcount.refcount;
7374     }
7375
7376   if (ind->dynindx != -1)
7377     {
7378       if (dir->dynindx != -1)
7379         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
7380       dir->dynindx = ind->dynindx;
7381       dir->dynstr_index = ind->dynstr_index;
7382       ind->dynindx = -1;
7383       ind->dynstr_index = 0;
7384     }
7385 }
7386
7387 void
7388 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
7389                                 struct elf_link_hash_entry *h,
7390                                 bfd_boolean force_local)
7391 {
7392   /* STT_GNU_IFUNC symbol must go through PLT.  */
7393   if (h->type != STT_GNU_IFUNC)
7394     {
7395       h->plt = elf_hash_table (info)->init_plt_offset;
7396       h->needs_plt = 0;
7397     }
7398   if (force_local)
7399     {
7400       h->forced_local = 1;
7401       if (h->dynindx != -1)
7402         {
7403           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
7404                                   h->dynstr_index);
7405           h->dynindx = -1;
7406           h->dynstr_index = 0;
7407         }
7408     }
7409 }
7410
7411 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
7412    caller.  */
7413
7414 bfd_boolean
7415 _bfd_elf_link_hash_table_init
7416   (struct elf_link_hash_table *table,
7417    bfd *abfd,
7418    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
7419                                       struct bfd_hash_table *,
7420                                       const char *),
7421    unsigned int entsize,
7422    enum elf_target_id target_id)
7423 {
7424   bfd_boolean ret;
7425   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
7426
7427   table->init_got_refcount.refcount = can_refcount - 1;
7428   table->init_plt_refcount.refcount = can_refcount - 1;
7429   table->init_got_offset.offset = -(bfd_vma) 1;
7430   table->init_plt_offset.offset = -(bfd_vma) 1;
7431   /* The first dynamic symbol is a dummy.  */
7432   table->dynsymcount = 1;
7433
7434   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
7435
7436   table->root.type = bfd_link_elf_hash_table;
7437   table->hash_table_id = target_id;
7438
7439   return ret;
7440 }
7441
7442 /* Create an ELF linker hash table.  */
7443
7444 struct bfd_link_hash_table *
7445 _bfd_elf_link_hash_table_create (bfd *abfd)
7446 {
7447   struct elf_link_hash_table *ret;
7448   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7449
7450   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7451   if (ret == NULL)
7452     return NULL;
7453
7454   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7455                                        sizeof (struct elf_link_hash_entry),
7456                                        GENERIC_ELF_DATA))
7457     {
7458       free (ret);
7459       return NULL;
7460     }
7461   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7462
7463   return &ret->root;
7464 }
7465
7466 /* Destroy an ELF linker hash table.  */
7467
7468 void
7469 _bfd_elf_link_hash_table_free (bfd *obfd)
7470 {
7471   struct elf_link_hash_table *htab;
7472
7473   htab = (struct elf_link_hash_table *) obfd->link.hash;
7474   if (htab->dynstr != NULL)
7475     _bfd_elf_strtab_free (htab->dynstr);
7476   _bfd_merge_sections_free (htab->merge_info);
7477   _bfd_generic_link_hash_table_free (obfd);
7478 }
7479
7480 /* This is a hook for the ELF emulation code in the generic linker to
7481    tell the backend linker what file name to use for the DT_NEEDED
7482    entry for a dynamic object.  */
7483
7484 void
7485 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7486 {
7487   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7488       && bfd_get_format (abfd) == bfd_object)
7489     elf_dt_name (abfd) = name;
7490 }
7491
7492 int
7493 bfd_elf_get_dyn_lib_class (bfd *abfd)
7494 {
7495   int lib_class;
7496   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7497       && bfd_get_format (abfd) == bfd_object)
7498     lib_class = elf_dyn_lib_class (abfd);
7499   else
7500     lib_class = 0;
7501   return lib_class;
7502 }
7503
7504 void
7505 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7506 {
7507   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7508       && bfd_get_format (abfd) == bfd_object)
7509     elf_dyn_lib_class (abfd) = lib_class;
7510 }
7511
7512 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7513    the linker ELF emulation code.  */
7514
7515 struct bfd_link_needed_list *
7516 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7517                          struct bfd_link_info *info)
7518 {
7519   if (! is_elf_hash_table (info->hash))
7520     return NULL;
7521   return elf_hash_table (info)->needed;
7522 }
7523
7524 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7525    hook for the linker ELF emulation code.  */
7526
7527 struct bfd_link_needed_list *
7528 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7529                           struct bfd_link_info *info)
7530 {
7531   if (! is_elf_hash_table (info->hash))
7532     return NULL;
7533   return elf_hash_table (info)->runpath;
7534 }
7535
7536 /* Get the name actually used for a dynamic object for a link.  This
7537    is the SONAME entry if there is one.  Otherwise, it is the string
7538    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7539
7540 const char *
7541 bfd_elf_get_dt_soname (bfd *abfd)
7542 {
7543   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7544       && bfd_get_format (abfd) == bfd_object)
7545     return elf_dt_name (abfd);
7546   return NULL;
7547 }
7548
7549 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7550    the ELF linker emulation code.  */
7551
7552 bfd_boolean
7553 bfd_elf_get_bfd_needed_list (bfd *abfd,
7554                              struct bfd_link_needed_list **pneeded)
7555 {
7556   asection *s;
7557   bfd_byte *dynbuf = NULL;
7558   unsigned int elfsec;
7559   unsigned long shlink;
7560   bfd_byte *extdyn, *extdynend;
7561   size_t extdynsize;
7562   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7563
7564   *pneeded = NULL;
7565
7566   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7567       || bfd_get_format (abfd) != bfd_object)
7568     return TRUE;
7569
7570   s = bfd_get_section_by_name (abfd, ".dynamic");
7571   if (s == NULL || s->size == 0)
7572     return TRUE;
7573
7574   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7575     goto error_return;
7576
7577   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7578   if (elfsec == SHN_BAD)
7579     goto error_return;
7580
7581   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7582
7583   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7584   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7585
7586   extdyn = dynbuf;
7587   extdynend = extdyn + s->size;
7588   for (; extdyn < extdynend; extdyn += extdynsize)
7589     {
7590       Elf_Internal_Dyn dyn;
7591
7592       (*swap_dyn_in) (abfd, extdyn, &dyn);
7593
7594       if (dyn.d_tag == DT_NULL)
7595         break;
7596
7597       if (dyn.d_tag == DT_NEEDED)
7598         {
7599           const char *string;
7600           struct bfd_link_needed_list *l;
7601           unsigned int tagv = dyn.d_un.d_val;
7602           bfd_size_type amt;
7603
7604           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7605           if (string == NULL)
7606             goto error_return;
7607
7608           amt = sizeof *l;
7609           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7610           if (l == NULL)
7611             goto error_return;
7612
7613           l->by = abfd;
7614           l->name = string;
7615           l->next = *pneeded;
7616           *pneeded = l;
7617         }
7618     }
7619
7620   free (dynbuf);
7621
7622   return TRUE;
7623
7624  error_return:
7625   if (dynbuf != NULL)
7626     free (dynbuf);
7627   return FALSE;
7628 }
7629
7630 struct elf_symbuf_symbol
7631 {
7632   unsigned long st_name;        /* Symbol name, index in string tbl */
7633   unsigned char st_info;        /* Type and binding attributes */
7634   unsigned char st_other;       /* Visibilty, and target specific */
7635 };
7636
7637 struct elf_symbuf_head
7638 {
7639   struct elf_symbuf_symbol *ssym;
7640   size_t count;
7641   unsigned int st_shndx;
7642 };
7643
7644 struct elf_symbol
7645 {
7646   union
7647     {
7648       Elf_Internal_Sym *isym;
7649       struct elf_symbuf_symbol *ssym;
7650     } u;
7651   const char *name;
7652 };
7653
7654 /* Sort references to symbols by ascending section number.  */
7655
7656 static int
7657 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7658 {
7659   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7660   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7661
7662   return s1->st_shndx - s2->st_shndx;
7663 }
7664
7665 static int
7666 elf_sym_name_compare (const void *arg1, const void *arg2)
7667 {
7668   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7669   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7670   return strcmp (s1->name, s2->name);
7671 }
7672
7673 static struct elf_symbuf_head *
7674 elf_create_symbuf (size_t symcount, Elf_Internal_Sym *isymbuf)
7675 {
7676   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7677   struct elf_symbuf_symbol *ssym;
7678   struct elf_symbuf_head *ssymbuf, *ssymhead;
7679   size_t i, shndx_count, total_size;
7680
7681   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7682   if (indbuf == NULL)
7683     return NULL;
7684
7685   for (ind = indbuf, i = 0; i < symcount; i++)
7686     if (isymbuf[i].st_shndx != SHN_UNDEF)
7687       *ind++ = &isymbuf[i];
7688   indbufend = ind;
7689
7690   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7691          elf_sort_elf_symbol);
7692
7693   shndx_count = 0;
7694   if (indbufend > indbuf)
7695     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7696       if (ind[0]->st_shndx != ind[1]->st_shndx)
7697         shndx_count++;
7698
7699   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7700                 + (indbufend - indbuf) * sizeof (*ssym));
7701   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7702   if (ssymbuf == NULL)
7703     {
7704       free (indbuf);
7705       return NULL;
7706     }
7707
7708   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7709   ssymbuf->ssym = NULL;
7710   ssymbuf->count = shndx_count;
7711   ssymbuf->st_shndx = 0;
7712   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7713     {
7714       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7715         {
7716           ssymhead++;
7717           ssymhead->ssym = ssym;
7718           ssymhead->count = 0;
7719           ssymhead->st_shndx = (*ind)->st_shndx;
7720         }
7721       ssym->st_name = (*ind)->st_name;
7722       ssym->st_info = (*ind)->st_info;
7723       ssym->st_other = (*ind)->st_other;
7724       ssymhead->count++;
7725     }
7726   BFD_ASSERT ((size_t) (ssymhead - ssymbuf) == shndx_count
7727               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7728                   == total_size));
7729
7730   free (indbuf);
7731   return ssymbuf;
7732 }
7733
7734 /* Check if 2 sections define the same set of local and global
7735    symbols.  */
7736
7737 static bfd_boolean
7738 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7739                                    struct bfd_link_info *info)
7740 {
7741   bfd *bfd1, *bfd2;
7742   const struct elf_backend_data *bed1, *bed2;
7743   Elf_Internal_Shdr *hdr1, *hdr2;
7744   size_t symcount1, symcount2;
7745   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7746   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7747   Elf_Internal_Sym *isym, *isymend;
7748   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7749   size_t count1, count2, i;
7750   unsigned int shndx1, shndx2;
7751   bfd_boolean result;
7752
7753   bfd1 = sec1->owner;
7754   bfd2 = sec2->owner;
7755
7756   /* Both sections have to be in ELF.  */
7757   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7758       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7759     return FALSE;
7760
7761   if (elf_section_type (sec1) != elf_section_type (sec2))
7762     return FALSE;
7763
7764   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7765   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7766   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7767     return FALSE;
7768
7769   bed1 = get_elf_backend_data (bfd1);
7770   bed2 = get_elf_backend_data (bfd2);
7771   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7772   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7773   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7774   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7775
7776   if (symcount1 == 0 || symcount2 == 0)
7777     return FALSE;
7778
7779   result = FALSE;
7780   isymbuf1 = NULL;
7781   isymbuf2 = NULL;
7782   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7783   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7784
7785   if (ssymbuf1 == NULL)
7786     {
7787       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7788                                        NULL, NULL, NULL);
7789       if (isymbuf1 == NULL)
7790         goto done;
7791
7792       if (!info->reduce_memory_overheads)
7793         elf_tdata (bfd1)->symbuf = ssymbuf1
7794           = elf_create_symbuf (symcount1, isymbuf1);
7795     }
7796
7797   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7798     {
7799       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7800                                        NULL, NULL, NULL);
7801       if (isymbuf2 == NULL)
7802         goto done;
7803
7804       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7805         elf_tdata (bfd2)->symbuf = ssymbuf2
7806           = elf_create_symbuf (symcount2, isymbuf2);
7807     }
7808
7809   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7810     {
7811       /* Optimized faster version.  */
7812       size_t lo, hi, mid;
7813       struct elf_symbol *symp;
7814       struct elf_symbuf_symbol *ssym, *ssymend;
7815
7816       lo = 0;
7817       hi = ssymbuf1->count;
7818       ssymbuf1++;
7819       count1 = 0;
7820       while (lo < hi)
7821         {
7822           mid = (lo + hi) / 2;
7823           if (shndx1 < ssymbuf1[mid].st_shndx)
7824             hi = mid;
7825           else if (shndx1 > ssymbuf1[mid].st_shndx)
7826             lo = mid + 1;
7827           else
7828             {
7829               count1 = ssymbuf1[mid].count;
7830               ssymbuf1 += mid;
7831               break;
7832             }
7833         }
7834
7835       lo = 0;
7836       hi = ssymbuf2->count;
7837       ssymbuf2++;
7838       count2 = 0;
7839       while (lo < hi)
7840         {
7841           mid = (lo + hi) / 2;
7842           if (shndx2 < ssymbuf2[mid].st_shndx)
7843             hi = mid;
7844           else if (shndx2 > ssymbuf2[mid].st_shndx)
7845             lo = mid + 1;
7846           else
7847             {
7848               count2 = ssymbuf2[mid].count;
7849               ssymbuf2 += mid;
7850               break;
7851             }
7852         }
7853
7854       if (count1 == 0 || count2 == 0 || count1 != count2)
7855         goto done;
7856
7857       symtable1
7858         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
7859       symtable2
7860         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
7861       if (symtable1 == NULL || symtable2 == NULL)
7862         goto done;
7863
7864       symp = symtable1;
7865       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7866            ssym < ssymend; ssym++, symp++)
7867         {
7868           symp->u.ssym = ssym;
7869           symp->name = bfd_elf_string_from_elf_section (bfd1,
7870                                                         hdr1->sh_link,
7871                                                         ssym->st_name);
7872         }
7873
7874       symp = symtable2;
7875       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7876            ssym < ssymend; ssym++, symp++)
7877         {
7878           symp->u.ssym = ssym;
7879           symp->name = bfd_elf_string_from_elf_section (bfd2,
7880                                                         hdr2->sh_link,
7881                                                         ssym->st_name);
7882         }
7883
7884       /* Sort symbol by name.  */
7885       qsort (symtable1, count1, sizeof (struct elf_symbol),
7886              elf_sym_name_compare);
7887       qsort (symtable2, count1, sizeof (struct elf_symbol),
7888              elf_sym_name_compare);
7889
7890       for (i = 0; i < count1; i++)
7891         /* Two symbols must have the same binding, type and name.  */
7892         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7893             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7894             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7895           goto done;
7896
7897       result = TRUE;
7898       goto done;
7899     }
7900
7901   symtable1 = (struct elf_symbol *)
7902       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7903   symtable2 = (struct elf_symbol *)
7904       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7905   if (symtable1 == NULL || symtable2 == NULL)
7906     goto done;
7907
7908   /* Count definitions in the section.  */
7909   count1 = 0;
7910   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7911     if (isym->st_shndx == shndx1)
7912       symtable1[count1++].u.isym = isym;
7913
7914   count2 = 0;
7915   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7916     if (isym->st_shndx == shndx2)
7917       symtable2[count2++].u.isym = isym;
7918
7919   if (count1 == 0 || count2 == 0 || count1 != count2)
7920     goto done;
7921
7922   for (i = 0; i < count1; i++)
7923     symtable1[i].name
7924       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7925                                          symtable1[i].u.isym->st_name);
7926
7927   for (i = 0; i < count2; i++)
7928     symtable2[i].name
7929       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7930                                          symtable2[i].u.isym->st_name);
7931
7932   /* Sort symbol by name.  */
7933   qsort (symtable1, count1, sizeof (struct elf_symbol),
7934          elf_sym_name_compare);
7935   qsort (symtable2, count1, sizeof (struct elf_symbol),
7936          elf_sym_name_compare);
7937
7938   for (i = 0; i < count1; i++)
7939     /* Two symbols must have the same binding, type and name.  */
7940     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7941         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7942         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7943       goto done;
7944
7945   result = TRUE;
7946
7947 done:
7948   if (symtable1)
7949     free (symtable1);
7950   if (symtable2)
7951     free (symtable2);
7952   if (isymbuf1)
7953     free (isymbuf1);
7954   if (isymbuf2)
7955     free (isymbuf2);
7956
7957   return result;
7958 }
7959
7960 /* Return TRUE if 2 section types are compatible.  */
7961
7962 bfd_boolean
7963 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7964                                  bfd *bbfd, const asection *bsec)
7965 {
7966   if (asec == NULL
7967       || bsec == NULL
7968       || abfd->xvec->flavour != bfd_target_elf_flavour
7969       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7970     return TRUE;
7971
7972   return elf_section_type (asec) == elf_section_type (bsec);
7973 }
7974 \f
7975 /* Final phase of ELF linker.  */
7976
7977 /* A structure we use to avoid passing large numbers of arguments.  */
7978
7979 struct elf_final_link_info
7980 {
7981   /* General link information.  */
7982   struct bfd_link_info *info;
7983   /* Output BFD.  */
7984   bfd *output_bfd;
7985   /* Symbol string table.  */
7986   struct elf_strtab_hash *symstrtab;
7987   /* .hash section.  */
7988   asection *hash_sec;
7989   /* symbol version section (.gnu.version).  */
7990   asection *symver_sec;
7991   /* Buffer large enough to hold contents of any section.  */
7992   bfd_byte *contents;
7993   /* Buffer large enough to hold external relocs of any section.  */
7994   void *external_relocs;
7995   /* Buffer large enough to hold internal relocs of any section.  */
7996   Elf_Internal_Rela *internal_relocs;
7997   /* Buffer large enough to hold external local symbols of any input
7998      BFD.  */
7999   bfd_byte *external_syms;
8000   /* And a buffer for symbol section indices.  */
8001   Elf_External_Sym_Shndx *locsym_shndx;
8002   /* Buffer large enough to hold internal local symbols of any input
8003      BFD.  */
8004   Elf_Internal_Sym *internal_syms;
8005   /* Array large enough to hold a symbol index for each local symbol
8006      of any input BFD.  */
8007   long *indices;
8008   /* Array large enough to hold a section pointer for each local
8009      symbol of any input BFD.  */
8010   asection **sections;
8011   /* Buffer for SHT_SYMTAB_SHNDX section.  */
8012   Elf_External_Sym_Shndx *symshndxbuf;
8013   /* Number of STT_FILE syms seen.  */
8014   size_t filesym_count;
8015 };
8016
8017 /* This struct is used to pass information to elf_link_output_extsym.  */
8018
8019 struct elf_outext_info
8020 {
8021   bfd_boolean failed;
8022   bfd_boolean localsyms;
8023   bfd_boolean file_sym_done;
8024   struct elf_final_link_info *flinfo;
8025 };
8026
8027
8028 /* Support for evaluating a complex relocation.
8029
8030    Complex relocations are generalized, self-describing relocations.  The
8031    implementation of them consists of two parts: complex symbols, and the
8032    relocations themselves.
8033
8034    The relocations are use a reserved elf-wide relocation type code (R_RELC
8035    external / BFD_RELOC_RELC internal) and an encoding of relocation field
8036    information (start bit, end bit, word width, etc) into the addend.  This
8037    information is extracted from CGEN-generated operand tables within gas.
8038
8039    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
8040    internal) representing prefix-notation expressions, including but not
8041    limited to those sorts of expressions normally encoded as addends in the
8042    addend field.  The symbol mangling format is:
8043
8044    <node> := <literal>
8045           |  <unary-operator> ':' <node>
8046           |  <binary-operator> ':' <node> ':' <node>
8047           ;
8048
8049    <literal> := 's' <digits=N> ':' <N character symbol name>
8050              |  'S' <digits=N> ':' <N character section name>
8051              |  '#' <hexdigits>
8052              ;
8053
8054    <binary-operator> := as in C
8055    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
8056
8057 static void
8058 set_symbol_value (bfd *bfd_with_globals,
8059                   Elf_Internal_Sym *isymbuf,
8060                   size_t locsymcount,
8061                   size_t symidx,
8062                   bfd_vma val)
8063 {
8064   struct elf_link_hash_entry **sym_hashes;
8065   struct elf_link_hash_entry *h;
8066   size_t extsymoff = locsymcount;
8067
8068   if (symidx < locsymcount)
8069     {
8070       Elf_Internal_Sym *sym;
8071
8072       sym = isymbuf + symidx;
8073       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
8074         {
8075           /* It is a local symbol: move it to the
8076              "absolute" section and give it a value.  */
8077           sym->st_shndx = SHN_ABS;
8078           sym->st_value = val;
8079           return;
8080         }
8081       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
8082       extsymoff = 0;
8083     }
8084
8085   /* It is a global symbol: set its link type
8086      to "defined" and give it a value.  */
8087
8088   sym_hashes = elf_sym_hashes (bfd_with_globals);
8089   h = sym_hashes [symidx - extsymoff];
8090   while (h->root.type == bfd_link_hash_indirect
8091          || h->root.type == bfd_link_hash_warning)
8092     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8093   h->root.type = bfd_link_hash_defined;
8094   h->root.u.def.value = val;
8095   h->root.u.def.section = bfd_abs_section_ptr;
8096 }
8097
8098 static bfd_boolean
8099 resolve_symbol (const char *name,
8100                 bfd *input_bfd,
8101                 struct elf_final_link_info *flinfo,
8102                 bfd_vma *result,
8103                 Elf_Internal_Sym *isymbuf,
8104                 size_t locsymcount)
8105 {
8106   Elf_Internal_Sym *sym;
8107   struct bfd_link_hash_entry *global_entry;
8108   const char *candidate = NULL;
8109   Elf_Internal_Shdr *symtab_hdr;
8110   size_t i;
8111
8112   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
8113
8114   for (i = 0; i < locsymcount; ++ i)
8115     {
8116       sym = isymbuf + i;
8117
8118       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
8119         continue;
8120
8121       candidate = bfd_elf_string_from_elf_section (input_bfd,
8122                                                    symtab_hdr->sh_link,
8123                                                    sym->st_name);
8124 #ifdef DEBUG
8125       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
8126               name, candidate, (unsigned long) sym->st_value);
8127 #endif
8128       if (candidate && strcmp (candidate, name) == 0)
8129         {
8130           asection *sec = flinfo->sections [i];
8131
8132           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
8133           *result += sec->output_offset + sec->output_section->vma;
8134 #ifdef DEBUG
8135           printf ("Found symbol with value %8.8lx\n",
8136                   (unsigned long) *result);
8137 #endif
8138           return TRUE;
8139         }
8140     }
8141
8142   /* Hmm, haven't found it yet. perhaps it is a global.  */
8143   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
8144                                        FALSE, FALSE, TRUE);
8145   if (!global_entry)
8146     return FALSE;
8147
8148   if (global_entry->type == bfd_link_hash_defined
8149       || global_entry->type == bfd_link_hash_defweak)
8150     {
8151       *result = (global_entry->u.def.value
8152                  + global_entry->u.def.section->output_section->vma
8153                  + global_entry->u.def.section->output_offset);
8154 #ifdef DEBUG
8155       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
8156               global_entry->root.string, (unsigned long) *result);
8157 #endif
8158       return TRUE;
8159     }
8160
8161   return FALSE;
8162 }
8163
8164 /* Looks up NAME in SECTIONS.  If found sets RESULT to NAME's address (in
8165    bytes) and returns TRUE, otherwise returns FALSE.  Accepts pseudo-section
8166    names like "foo.end" which is the end address of section "foo".  */
8167    
8168 static bfd_boolean
8169 resolve_section (const char *name,
8170                  asection *sections,
8171                  bfd_vma *result,
8172                  bfd * abfd)
8173 {
8174   asection *curr;
8175   unsigned int len;
8176
8177   for (curr = sections; curr; curr = curr->next)
8178     if (strcmp (curr->name, name) == 0)
8179       {
8180         *result = curr->vma;
8181         return TRUE;
8182       }
8183
8184   /* Hmm. still haven't found it. try pseudo-section names.  */
8185   /* FIXME: This could be coded more efficiently...  */
8186   for (curr = sections; curr; curr = curr->next)
8187     {
8188       len = strlen (curr->name);
8189       if (len > strlen (name))
8190         continue;
8191
8192       if (strncmp (curr->name, name, len) == 0)
8193         {
8194           if (strncmp (".end", name + len, 4) == 0)
8195             {
8196               *result = curr->vma + curr->size / bfd_octets_per_byte (abfd);
8197               return TRUE;
8198             }
8199
8200           /* Insert more pseudo-section names here, if you like.  */
8201         }
8202     }
8203
8204   return FALSE;
8205 }
8206
8207 static void
8208 undefined_reference (const char *reftype, const char *name)
8209 {
8210   /* xgettext:c-format */
8211   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
8212                       reftype, name);
8213 }
8214
8215 static bfd_boolean
8216 eval_symbol (bfd_vma *result,
8217              const char **symp,
8218              bfd *input_bfd,
8219              struct elf_final_link_info *flinfo,
8220              bfd_vma dot,
8221              Elf_Internal_Sym *isymbuf,
8222              size_t locsymcount,
8223              int signed_p)
8224 {
8225   size_t len;
8226   size_t symlen;
8227   bfd_vma a;
8228   bfd_vma b;
8229   char symbuf[4096];
8230   const char *sym = *symp;
8231   const char *symend;
8232   bfd_boolean symbol_is_section = FALSE;
8233
8234   len = strlen (sym);
8235   symend = sym + len;
8236
8237   if (len < 1 || len > sizeof (symbuf))
8238     {
8239       bfd_set_error (bfd_error_invalid_operation);
8240       return FALSE;
8241     }
8242
8243   switch (* sym)
8244     {
8245     case '.':
8246       *result = dot;
8247       *symp = sym + 1;
8248       return TRUE;
8249
8250     case '#':
8251       ++sym;
8252       *result = strtoul (sym, (char **) symp, 16);
8253       return TRUE;
8254
8255     case 'S':
8256       symbol_is_section = TRUE;
8257       /* Fall through.  */
8258     case 's':
8259       ++sym;
8260       symlen = strtol (sym, (char **) symp, 10);
8261       sym = *symp + 1; /* Skip the trailing ':'.  */
8262
8263       if (symend < sym || symlen + 1 > sizeof (symbuf))
8264         {
8265           bfd_set_error (bfd_error_invalid_operation);
8266           return FALSE;
8267         }
8268
8269       memcpy (symbuf, sym, symlen);
8270       symbuf[symlen] = '\0';
8271       *symp = sym + symlen;
8272
8273       /* Is it always possible, with complex symbols, that gas "mis-guessed"
8274          the symbol as a section, or vice-versa. so we're pretty liberal in our
8275          interpretation here; section means "try section first", not "must be a
8276          section", and likewise with symbol.  */
8277
8278       if (symbol_is_section)
8279         {
8280           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result, input_bfd)
8281               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
8282                                   isymbuf, locsymcount))
8283             {
8284               undefined_reference ("section", symbuf);
8285               return FALSE;
8286             }
8287         }
8288       else
8289         {
8290           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
8291                                isymbuf, locsymcount)
8292               && !resolve_section (symbuf, flinfo->output_bfd->sections,
8293                                    result, input_bfd))
8294             {
8295               undefined_reference ("symbol", symbuf);
8296               return FALSE;
8297             }
8298         }
8299
8300       return TRUE;
8301
8302       /* All that remains are operators.  */
8303
8304 #define UNARY_OP(op)                                            \
8305   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8306     {                                                           \
8307       sym += strlen (#op);                                      \
8308       if (*sym == ':')                                          \
8309         ++sym;                                                  \
8310       *symp = sym;                                              \
8311       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8312                         isymbuf, locsymcount, signed_p))        \
8313         return FALSE;                                           \
8314       if (signed_p)                                             \
8315         *result = op ((bfd_signed_vma) a);                      \
8316       else                                                      \
8317         *result = op a;                                         \
8318       return TRUE;                                              \
8319     }
8320
8321 #define BINARY_OP(op)                                           \
8322   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8323     {                                                           \
8324       sym += strlen (#op);                                      \
8325       if (*sym == ':')                                          \
8326         ++sym;                                                  \
8327       *symp = sym;                                              \
8328       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8329                         isymbuf, locsymcount, signed_p))        \
8330         return FALSE;                                           \
8331       ++*symp;                                                  \
8332       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
8333                         isymbuf, locsymcount, signed_p))        \
8334         return FALSE;                                           \
8335       if (signed_p)                                             \
8336         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
8337       else                                                      \
8338         *result = a op b;                                       \
8339       return TRUE;                                              \
8340     }
8341
8342     default:
8343       UNARY_OP  (0-);
8344       BINARY_OP (<<);
8345       BINARY_OP (>>);
8346       BINARY_OP (==);
8347       BINARY_OP (!=);
8348       BINARY_OP (<=);
8349       BINARY_OP (>=);
8350       BINARY_OP (&&);
8351       BINARY_OP (||);
8352       UNARY_OP  (~);
8353       UNARY_OP  (!);
8354       BINARY_OP (*);
8355       BINARY_OP (/);
8356       BINARY_OP (%);
8357       BINARY_OP (^);
8358       BINARY_OP (|);
8359       BINARY_OP (&);
8360       BINARY_OP (+);
8361       BINARY_OP (-);
8362       BINARY_OP (<);
8363       BINARY_OP (>);
8364 #undef UNARY_OP
8365 #undef BINARY_OP
8366       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
8367       bfd_set_error (bfd_error_invalid_operation);
8368       return FALSE;
8369     }
8370 }
8371
8372 static void
8373 put_value (bfd_vma size,
8374            unsigned long chunksz,
8375            bfd *input_bfd,
8376            bfd_vma x,
8377            bfd_byte *location)
8378 {
8379   location += (size - chunksz);
8380
8381   for (; size; size -= chunksz, location -= chunksz)
8382     {
8383       switch (chunksz)
8384         {
8385         case 1:
8386           bfd_put_8 (input_bfd, x, location);
8387           x >>= 8;
8388           break;
8389         case 2:
8390           bfd_put_16 (input_bfd, x, location);
8391           x >>= 16;
8392           break;
8393         case 4:
8394           bfd_put_32 (input_bfd, x, location);
8395           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
8396           x >>= 16;
8397           x >>= 16;
8398           break;
8399 #ifdef BFD64
8400         case 8:
8401           bfd_put_64 (input_bfd, x, location);
8402           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
8403           x >>= 32;
8404           x >>= 32;
8405           break;
8406 #endif
8407         default:
8408           abort ();
8409           break;
8410         }
8411     }
8412 }
8413
8414 static bfd_vma
8415 get_value (bfd_vma size,
8416            unsigned long chunksz,
8417            bfd *input_bfd,
8418            bfd_byte *location)
8419 {
8420   int shift;
8421   bfd_vma x = 0;
8422
8423   /* Sanity checks.  */
8424   BFD_ASSERT (chunksz <= sizeof (x)
8425               && size >= chunksz
8426               && chunksz != 0
8427               && (size % chunksz) == 0
8428               && input_bfd != NULL
8429               && location != NULL);
8430
8431   if (chunksz == sizeof (x))
8432     {
8433       BFD_ASSERT (size == chunksz);
8434
8435       /* Make sure that we do not perform an undefined shift operation.
8436          We know that size == chunksz so there will only be one iteration
8437          of the loop below.  */
8438       shift = 0;
8439     }
8440   else
8441     shift = 8 * chunksz;
8442
8443   for (; size; size -= chunksz, location += chunksz)
8444     {
8445       switch (chunksz)
8446         {
8447         case 1:
8448           x = (x << shift) | bfd_get_8 (input_bfd, location);
8449           break;
8450         case 2:
8451           x = (x << shift) | bfd_get_16 (input_bfd, location);
8452           break;
8453         case 4:
8454           x = (x << shift) | bfd_get_32 (input_bfd, location);
8455           break;
8456 #ifdef BFD64
8457         case 8:
8458           x = (x << shift) | bfd_get_64 (input_bfd, location);
8459           break;
8460 #endif
8461         default:
8462           abort ();
8463         }
8464     }
8465   return x;
8466 }
8467
8468 static void
8469 decode_complex_addend (unsigned long *start,   /* in bits */
8470                        unsigned long *oplen,   /* in bits */
8471                        unsigned long *len,     /* in bits */
8472                        unsigned long *wordsz,  /* in bytes */
8473                        unsigned long *chunksz, /* in bytes */
8474                        unsigned long *lsb0_p,
8475                        unsigned long *signed_p,
8476                        unsigned long *trunc_p,
8477                        unsigned long encoded)
8478 {
8479   * start     =  encoded        & 0x3F;
8480   * len       = (encoded >>  6) & 0x3F;
8481   * oplen     = (encoded >> 12) & 0x3F;
8482   * wordsz    = (encoded >> 18) & 0xF;
8483   * chunksz   = (encoded >> 22) & 0xF;
8484   * lsb0_p    = (encoded >> 27) & 1;
8485   * signed_p  = (encoded >> 28) & 1;
8486   * trunc_p   = (encoded >> 29) & 1;
8487 }
8488
8489 bfd_reloc_status_type
8490 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8491                                     asection *input_section ATTRIBUTE_UNUSED,
8492                                     bfd_byte *contents,
8493                                     Elf_Internal_Rela *rel,
8494                                     bfd_vma relocation)
8495 {
8496   bfd_vma shift, x, mask;
8497   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8498   bfd_reloc_status_type r;
8499
8500   /*  Perform this reloc, since it is complex.
8501       (this is not to say that it necessarily refers to a complex
8502       symbol; merely that it is a self-describing CGEN based reloc.
8503       i.e. the addend has the complete reloc information (bit start, end,
8504       word size, etc) encoded within it.).  */
8505
8506   decode_complex_addend (&start, &oplen, &len, &wordsz,
8507                          &chunksz, &lsb0_p, &signed_p,
8508                          &trunc_p, rel->r_addend);
8509
8510   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8511
8512   if (lsb0_p)
8513     shift = (start + 1) - len;
8514   else
8515     shift = (8 * wordsz) - (start + len);
8516
8517   x = get_value (wordsz, chunksz, input_bfd,
8518                  contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8519
8520 #ifdef DEBUG
8521   printf ("Doing complex reloc: "
8522           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8523           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8524           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8525           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8526           oplen, (unsigned long) x, (unsigned long) mask,
8527           (unsigned long) relocation);
8528 #endif
8529
8530   r = bfd_reloc_ok;
8531   if (! trunc_p)
8532     /* Now do an overflow check.  */
8533     r = bfd_check_overflow ((signed_p
8534                              ? complain_overflow_signed
8535                              : complain_overflow_unsigned),
8536                             len, 0, (8 * wordsz),
8537                             relocation);
8538
8539   /* Do the deed.  */
8540   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8541
8542 #ifdef DEBUG
8543   printf ("           relocation: %8.8lx\n"
8544           "         shifted mask: %8.8lx\n"
8545           " shifted/masked reloc: %8.8lx\n"
8546           "               result: %8.8lx\n",
8547           (unsigned long) relocation, (unsigned long) (mask << shift),
8548           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8549 #endif
8550   put_value (wordsz, chunksz, input_bfd, x,
8551              contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8552   return r;
8553 }
8554
8555 /* Functions to read r_offset from external (target order) reloc
8556    entry.  Faster than bfd_getl32 et al, because we let the compiler
8557    know the value is aligned.  */
8558
8559 static bfd_vma
8560 ext32l_r_offset (const void *p)
8561 {
8562   union aligned32
8563   {
8564     uint32_t v;
8565     unsigned char c[4];
8566   };
8567   const union aligned32 *a
8568     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8569
8570   uint32_t aval = (  (uint32_t) a->c[0]
8571                    | (uint32_t) a->c[1] << 8
8572                    | (uint32_t) a->c[2] << 16
8573                    | (uint32_t) a->c[3] << 24);
8574   return aval;
8575 }
8576
8577 static bfd_vma
8578 ext32b_r_offset (const void *p)
8579 {
8580   union aligned32
8581   {
8582     uint32_t v;
8583     unsigned char c[4];
8584   };
8585   const union aligned32 *a
8586     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8587
8588   uint32_t aval = (  (uint32_t) a->c[0] << 24
8589                    | (uint32_t) a->c[1] << 16
8590                    | (uint32_t) a->c[2] << 8
8591                    | (uint32_t) a->c[3]);
8592   return aval;
8593 }
8594
8595 #ifdef BFD_HOST_64_BIT
8596 static bfd_vma
8597 ext64l_r_offset (const void *p)
8598 {
8599   union aligned64
8600   {
8601     uint64_t v;
8602     unsigned char c[8];
8603   };
8604   const union aligned64 *a
8605     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8606
8607   uint64_t aval = (  (uint64_t) a->c[0]
8608                    | (uint64_t) a->c[1] << 8
8609                    | (uint64_t) a->c[2] << 16
8610                    | (uint64_t) a->c[3] << 24
8611                    | (uint64_t) a->c[4] << 32
8612                    | (uint64_t) a->c[5] << 40
8613                    | (uint64_t) a->c[6] << 48
8614                    | (uint64_t) a->c[7] << 56);
8615   return aval;
8616 }
8617
8618 static bfd_vma
8619 ext64b_r_offset (const void *p)
8620 {
8621   union aligned64
8622   {
8623     uint64_t v;
8624     unsigned char c[8];
8625   };
8626   const union aligned64 *a
8627     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8628
8629   uint64_t aval = (  (uint64_t) a->c[0] << 56
8630                    | (uint64_t) a->c[1] << 48
8631                    | (uint64_t) a->c[2] << 40
8632                    | (uint64_t) a->c[3] << 32
8633                    | (uint64_t) a->c[4] << 24
8634                    | (uint64_t) a->c[5] << 16
8635                    | (uint64_t) a->c[6] << 8
8636                    | (uint64_t) a->c[7]);
8637   return aval;
8638 }
8639 #endif
8640
8641 /* When performing a relocatable link, the input relocations are
8642    preserved.  But, if they reference global symbols, the indices
8643    referenced must be updated.  Update all the relocations found in
8644    RELDATA.  */
8645
8646 static bfd_boolean
8647 elf_link_adjust_relocs (bfd *abfd,
8648                         asection *sec,
8649                         struct bfd_elf_section_reloc_data *reldata,
8650                         bfd_boolean sort,
8651                         struct bfd_link_info *info)
8652 {
8653   unsigned int i;
8654   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8655   bfd_byte *erela;
8656   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8657   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8658   bfd_vma r_type_mask;
8659   int r_sym_shift;
8660   unsigned int count = reldata->count;
8661   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8662
8663   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8664     {
8665       swap_in = bed->s->swap_reloc_in;
8666       swap_out = bed->s->swap_reloc_out;
8667     }
8668   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8669     {
8670       swap_in = bed->s->swap_reloca_in;
8671       swap_out = bed->s->swap_reloca_out;
8672     }
8673   else
8674     abort ();
8675
8676   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8677     abort ();
8678
8679   if (bed->s->arch_size == 32)
8680     {
8681       r_type_mask = 0xff;
8682       r_sym_shift = 8;
8683     }
8684   else
8685     {
8686       r_type_mask = 0xffffffff;
8687       r_sym_shift = 32;
8688     }
8689
8690   erela = reldata->hdr->contents;
8691   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8692     {
8693       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8694       unsigned int j;
8695
8696       if (*rel_hash == NULL)
8697         continue;
8698
8699       if ((*rel_hash)->indx == -2
8700           && info->gc_sections
8701           && ! info->gc_keep_exported)
8702         {
8703           /* PR 21524: Let the user know if a symbol was removed by garbage collection.  */
8704           _bfd_error_handler (_("%B:%A: error: relocation references symbol %s which was removed by garbage collection."),
8705                               abfd, sec,
8706                               (*rel_hash)->root.root.string);
8707           _bfd_error_handler (_("%B:%A: error: try relinking with --gc-keep-exported enabled."),
8708                               abfd, sec);
8709           bfd_set_error (bfd_error_invalid_operation);
8710           return FALSE;
8711         }
8712       BFD_ASSERT ((*rel_hash)->indx >= 0);
8713
8714       (*swap_in) (abfd, erela, irela);
8715       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8716         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8717                            | (irela[j].r_info & r_type_mask));
8718       (*swap_out) (abfd, irela, erela);
8719     }
8720
8721   if (bed->elf_backend_update_relocs)
8722     (*bed->elf_backend_update_relocs) (sec, reldata);
8723
8724   if (sort && count != 0)
8725     {
8726       bfd_vma (*ext_r_off) (const void *);
8727       bfd_vma r_off;
8728       size_t elt_size;
8729       bfd_byte *base, *end, *p, *loc;
8730       bfd_byte *buf = NULL;
8731
8732       if (bed->s->arch_size == 32)
8733         {
8734           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8735             ext_r_off = ext32l_r_offset;
8736           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8737             ext_r_off = ext32b_r_offset;
8738           else
8739             abort ();
8740         }
8741       else
8742         {
8743 #ifdef BFD_HOST_64_BIT
8744           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8745             ext_r_off = ext64l_r_offset;
8746           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8747             ext_r_off = ext64b_r_offset;
8748           else
8749 #endif
8750             abort ();
8751         }
8752
8753       /*  Must use a stable sort here.  A modified insertion sort,
8754           since the relocs are mostly sorted already.  */
8755       elt_size = reldata->hdr->sh_entsize;
8756       base = reldata->hdr->contents;
8757       end = base + count * elt_size;
8758       if (elt_size > sizeof (Elf64_External_Rela))
8759         abort ();
8760
8761       /* Ensure the first element is lowest.  This acts as a sentinel,
8762          speeding the main loop below.  */
8763       r_off = (*ext_r_off) (base);
8764       for (p = loc = base; (p += elt_size) < end; )
8765         {
8766           bfd_vma r_off2 = (*ext_r_off) (p);
8767           if (r_off > r_off2)
8768             {
8769               r_off = r_off2;
8770               loc = p;
8771             }
8772         }
8773       if (loc != base)
8774         {
8775           /* Don't just swap *base and *loc as that changes the order
8776              of the original base[0] and base[1] if they happen to
8777              have the same r_offset.  */
8778           bfd_byte onebuf[sizeof (Elf64_External_Rela)];
8779           memcpy (onebuf, loc, elt_size);
8780           memmove (base + elt_size, base, loc - base);
8781           memcpy (base, onebuf, elt_size);
8782         }
8783
8784       for (p = base + elt_size; (p += elt_size) < end; )
8785         {
8786           /* base to p is sorted, *p is next to insert.  */
8787           r_off = (*ext_r_off) (p);
8788           /* Search the sorted region for location to insert.  */
8789           loc = p - elt_size;
8790           while (r_off < (*ext_r_off) (loc))
8791             loc -= elt_size;
8792           loc += elt_size;
8793           if (loc != p)
8794             {
8795               /* Chances are there is a run of relocs to insert here,
8796                  from one of more input files.  Files are not always
8797                  linked in order due to the way elf_link_input_bfd is
8798                  called.  See pr17666.  */
8799               size_t sortlen = p - loc;
8800               bfd_vma r_off2 = (*ext_r_off) (loc);
8801               size_t runlen = elt_size;
8802               size_t buf_size = 96 * 1024;
8803               while (p + runlen < end
8804                      && (sortlen <= buf_size
8805                          || runlen + elt_size <= buf_size)
8806                      && r_off2 > (*ext_r_off) (p + runlen))
8807                 runlen += elt_size;
8808               if (buf == NULL)
8809                 {
8810                   buf = bfd_malloc (buf_size);
8811                   if (buf == NULL)
8812                     return FALSE;
8813                 }
8814               if (runlen < sortlen)
8815                 {
8816                   memcpy (buf, p, runlen);
8817                   memmove (loc + runlen, loc, sortlen);
8818                   memcpy (loc, buf, runlen);
8819                 }
8820               else
8821                 {
8822                   memcpy (buf, loc, sortlen);
8823                   memmove (loc, p, runlen);
8824                   memcpy (loc + runlen, buf, sortlen);
8825                 }
8826               p += runlen - elt_size;
8827             }
8828         }
8829       /* Hashes are no longer valid.  */
8830       free (reldata->hashes);
8831       reldata->hashes = NULL;
8832       free (buf);
8833     }
8834   return TRUE;
8835 }
8836
8837 struct elf_link_sort_rela
8838 {
8839   union {
8840     bfd_vma offset;
8841     bfd_vma sym_mask;
8842   } u;
8843   enum elf_reloc_type_class type;
8844   /* We use this as an array of size int_rels_per_ext_rel.  */
8845   Elf_Internal_Rela rela[1];
8846 };
8847
8848 static int
8849 elf_link_sort_cmp1 (const void *A, const void *B)
8850 {
8851   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8852   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8853   int relativea, relativeb;
8854
8855   relativea = a->type == reloc_class_relative;
8856   relativeb = b->type == reloc_class_relative;
8857
8858   if (relativea < relativeb)
8859     return 1;
8860   if (relativea > relativeb)
8861     return -1;
8862   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8863     return -1;
8864   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8865     return 1;
8866   if (a->rela->r_offset < b->rela->r_offset)
8867     return -1;
8868   if (a->rela->r_offset > b->rela->r_offset)
8869     return 1;
8870   return 0;
8871 }
8872
8873 static int
8874 elf_link_sort_cmp2 (const void *A, const void *B)
8875 {
8876   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8877   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8878
8879   if (a->type < b->type)
8880     return -1;
8881   if (a->type > b->type)
8882     return 1;
8883   if (a->u.offset < b->u.offset)
8884     return -1;
8885   if (a->u.offset > b->u.offset)
8886     return 1;
8887   if (a->rela->r_offset < b->rela->r_offset)
8888     return -1;
8889   if (a->rela->r_offset > b->rela->r_offset)
8890     return 1;
8891   return 0;
8892 }
8893
8894 static size_t
8895 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8896 {
8897   asection *dynamic_relocs;
8898   asection *rela_dyn;
8899   asection *rel_dyn;
8900   bfd_size_type count, size;
8901   size_t i, ret, sort_elt, ext_size;
8902   bfd_byte *sort, *s_non_relative, *p;
8903   struct elf_link_sort_rela *sq;
8904   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8905   int i2e = bed->s->int_rels_per_ext_rel;
8906   unsigned int opb = bfd_octets_per_byte (abfd);
8907   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8908   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8909   struct bfd_link_order *lo;
8910   bfd_vma r_sym_mask;
8911   bfd_boolean use_rela;
8912
8913   /* Find a dynamic reloc section.  */
8914   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8915   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8916   if (rela_dyn != NULL && rela_dyn->size > 0
8917       && rel_dyn != NULL && rel_dyn->size > 0)
8918     {
8919       bfd_boolean use_rela_initialised = FALSE;
8920
8921       /* This is just here to stop gcc from complaining.
8922          Its initialization checking code is not perfect.  */
8923       use_rela = TRUE;
8924
8925       /* Both sections are present.  Examine the sizes
8926          of the indirect sections to help us choose.  */
8927       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8928         if (lo->type == bfd_indirect_link_order)
8929           {
8930             asection *o = lo->u.indirect.section;
8931
8932             if ((o->size % bed->s->sizeof_rela) == 0)
8933               {
8934                 if ((o->size % bed->s->sizeof_rel) == 0)
8935                   /* Section size is divisible by both rel and rela sizes.
8936                      It is of no help to us.  */
8937                   ;
8938                 else
8939                   {
8940                     /* Section size is only divisible by rela.  */
8941                     if (use_rela_initialised && !use_rela)
8942                       {
8943                         _bfd_error_handler (_("%B: Unable to sort relocs - "
8944                                               "they are in more than one size"),
8945                                             abfd);
8946                         bfd_set_error (bfd_error_invalid_operation);
8947                         return 0;
8948                       }
8949                     else
8950                       {
8951                         use_rela = TRUE;
8952                         use_rela_initialised = TRUE;
8953                       }
8954                   }
8955               }
8956             else if ((o->size % bed->s->sizeof_rel) == 0)
8957               {
8958                 /* Section size is only divisible by rel.  */
8959                 if (use_rela_initialised && use_rela)
8960                   {
8961                     _bfd_error_handler (_("%B: Unable to sort relocs - "
8962                                           "they are in more than one size"),
8963                                         abfd);
8964                     bfd_set_error (bfd_error_invalid_operation);
8965                     return 0;
8966                   }
8967                 else
8968                   {
8969                     use_rela = FALSE;
8970                     use_rela_initialised = TRUE;
8971                   }
8972               }
8973             else
8974               {
8975                 /* The section size is not divisible by either -
8976                    something is wrong.  */
8977                 _bfd_error_handler (_("%B: Unable to sort relocs - "
8978                                       "they are of an unknown size"), abfd);
8979                 bfd_set_error (bfd_error_invalid_operation);
8980                 return 0;
8981               }
8982           }
8983
8984       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8985         if (lo->type == bfd_indirect_link_order)
8986           {
8987             asection *o = lo->u.indirect.section;
8988
8989             if ((o->size % bed->s->sizeof_rela) == 0)
8990               {
8991                 if ((o->size % bed->s->sizeof_rel) == 0)
8992                   /* Section size is divisible by both rel and rela sizes.
8993                      It is of no help to us.  */
8994                   ;
8995                 else
8996                   {
8997                     /* Section size is only divisible by rela.  */
8998                     if (use_rela_initialised && !use_rela)
8999                       {
9000                         _bfd_error_handler (_("%B: Unable to sort relocs - "
9001                                               "they are in more than one size"),
9002                                             abfd);
9003                         bfd_set_error (bfd_error_invalid_operation);
9004                         return 0;
9005                       }
9006                     else
9007                       {
9008                         use_rela = TRUE;
9009                         use_rela_initialised = TRUE;
9010                       }
9011                   }
9012               }
9013             else if ((o->size % bed->s->sizeof_rel) == 0)
9014               {
9015                 /* Section size is only divisible by rel.  */
9016                 if (use_rela_initialised && use_rela)
9017                   {
9018                     _bfd_error_handler (_("%B: Unable to sort relocs - "
9019                                           "they are in more than one size"),
9020                                         abfd);
9021                     bfd_set_error (bfd_error_invalid_operation);
9022                     return 0;
9023                   }
9024                 else
9025                   {
9026                     use_rela = FALSE;
9027                     use_rela_initialised = TRUE;
9028                   }
9029               }
9030             else
9031               {
9032                 /* The section size is not divisible by either -
9033                    something is wrong.  */
9034                 _bfd_error_handler (_("%B: Unable to sort relocs - "
9035                                       "they are of an unknown size"), abfd);
9036                 bfd_set_error (bfd_error_invalid_operation);
9037                 return 0;
9038               }
9039           }
9040
9041       if (! use_rela_initialised)
9042         /* Make a guess.  */
9043         use_rela = TRUE;
9044     }
9045   else if (rela_dyn != NULL && rela_dyn->size > 0)
9046     use_rela = TRUE;
9047   else if (rel_dyn != NULL && rel_dyn->size > 0)
9048     use_rela = FALSE;
9049   else
9050     return 0;
9051
9052   if (use_rela)
9053     {
9054       dynamic_relocs = rela_dyn;
9055       ext_size = bed->s->sizeof_rela;
9056       swap_in = bed->s->swap_reloca_in;
9057       swap_out = bed->s->swap_reloca_out;
9058     }
9059   else
9060     {
9061       dynamic_relocs = rel_dyn;
9062       ext_size = bed->s->sizeof_rel;
9063       swap_in = bed->s->swap_reloc_in;
9064       swap_out = bed->s->swap_reloc_out;
9065     }
9066
9067   size = 0;
9068   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9069     if (lo->type == bfd_indirect_link_order)
9070       size += lo->u.indirect.section->size;
9071
9072   if (size != dynamic_relocs->size)
9073     return 0;
9074
9075   sort_elt = (sizeof (struct elf_link_sort_rela)
9076               + (i2e - 1) * sizeof (Elf_Internal_Rela));
9077
9078   count = dynamic_relocs->size / ext_size;
9079   if (count == 0)
9080     return 0;
9081   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
9082
9083   if (sort == NULL)
9084     {
9085       (*info->callbacks->warning)
9086         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
9087       return 0;
9088     }
9089
9090   if (bed->s->arch_size == 32)
9091     r_sym_mask = ~(bfd_vma) 0xff;
9092   else
9093     r_sym_mask = ~(bfd_vma) 0xffffffff;
9094
9095   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9096     if (lo->type == bfd_indirect_link_order)
9097       {
9098         bfd_byte *erel, *erelend;
9099         asection *o = lo->u.indirect.section;
9100
9101         if (o->contents == NULL && o->size != 0)
9102           {
9103             /* This is a reloc section that is being handled as a normal
9104                section.  See bfd_section_from_shdr.  We can't combine
9105                relocs in this case.  */
9106             free (sort);
9107             return 0;
9108           }
9109         erel = o->contents;
9110         erelend = o->contents + o->size;
9111         p = sort + o->output_offset * opb / ext_size * sort_elt;
9112
9113         while (erel < erelend)
9114           {
9115             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9116
9117             (*swap_in) (abfd, erel, s->rela);
9118             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
9119             s->u.sym_mask = r_sym_mask;
9120             p += sort_elt;
9121             erel += ext_size;
9122           }
9123       }
9124
9125   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
9126
9127   for (i = 0, p = sort; i < count; i++, p += sort_elt)
9128     {
9129       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9130       if (s->type != reloc_class_relative)
9131         break;
9132     }
9133   ret = i;
9134   s_non_relative = p;
9135
9136   sq = (struct elf_link_sort_rela *) s_non_relative;
9137   for (; i < count; i++, p += sort_elt)
9138     {
9139       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
9140       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
9141         sq = sp;
9142       sp->u.offset = sq->rela->r_offset;
9143     }
9144
9145   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
9146
9147   struct elf_link_hash_table *htab = elf_hash_table (info);
9148   if (htab->srelplt && htab->srelplt->output_section == dynamic_relocs)
9149     {
9150       /* We have plt relocs in .rela.dyn.  */
9151       sq = (struct elf_link_sort_rela *) sort;
9152       for (i = 0; i < count; i++)
9153         if (sq[count - i - 1].type != reloc_class_plt)
9154           break;
9155       if (i != 0 && htab->srelplt->size == i * ext_size)
9156         {
9157           struct bfd_link_order **plo;
9158           /* Put srelplt link_order last.  This is so the output_offset
9159              set in the next loop is correct for DT_JMPREL.  */
9160           for (plo = &dynamic_relocs->map_head.link_order; *plo != NULL; )
9161             if ((*plo)->type == bfd_indirect_link_order
9162                 && (*plo)->u.indirect.section == htab->srelplt)
9163               {
9164                 lo = *plo;
9165                 *plo = lo->next;
9166               }
9167             else
9168               plo = &(*plo)->next;
9169           *plo = lo;
9170           lo->next = NULL;
9171           dynamic_relocs->map_tail.link_order = lo;
9172         }
9173     }
9174
9175   p = sort;
9176   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9177     if (lo->type == bfd_indirect_link_order)
9178       {
9179         bfd_byte *erel, *erelend;
9180         asection *o = lo->u.indirect.section;
9181
9182         erel = o->contents;
9183         erelend = o->contents + o->size;
9184         o->output_offset = (p - sort) / sort_elt * ext_size / opb;
9185         while (erel < erelend)
9186           {
9187             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9188             (*swap_out) (abfd, s->rela, erel);
9189             p += sort_elt;
9190             erel += ext_size;
9191           }
9192       }
9193
9194   free (sort);
9195   *psec = dynamic_relocs;
9196   return ret;
9197 }
9198
9199 /* Add a symbol to the output symbol string table.  */
9200
9201 static int
9202 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
9203                            const char *name,
9204                            Elf_Internal_Sym *elfsym,
9205                            asection *input_sec,
9206                            struct elf_link_hash_entry *h)
9207 {
9208   int (*output_symbol_hook)
9209     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
9210      struct elf_link_hash_entry *);
9211   struct elf_link_hash_table *hash_table;
9212   const struct elf_backend_data *bed;
9213   bfd_size_type strtabsize;
9214
9215   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9216
9217   bed = get_elf_backend_data (flinfo->output_bfd);
9218   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
9219   if (output_symbol_hook != NULL)
9220     {
9221       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
9222       if (ret != 1)
9223         return ret;
9224     }
9225
9226   if (name == NULL
9227       || *name == '\0'
9228       || (input_sec->flags & SEC_EXCLUDE))
9229     elfsym->st_name = (unsigned long) -1;
9230   else
9231     {
9232       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
9233          to get the final offset for st_name.  */
9234       elfsym->st_name
9235         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
9236                                                name, FALSE);
9237       if (elfsym->st_name == (unsigned long) -1)
9238         return 0;
9239     }
9240
9241   hash_table = elf_hash_table (flinfo->info);
9242   strtabsize = hash_table->strtabsize;
9243   if (strtabsize <= hash_table->strtabcount)
9244     {
9245       strtabsize += strtabsize;
9246       hash_table->strtabsize = strtabsize;
9247       strtabsize *= sizeof (*hash_table->strtab);
9248       hash_table->strtab
9249         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
9250                                                  strtabsize);
9251       if (hash_table->strtab == NULL)
9252         return 0;
9253     }
9254   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
9255   hash_table->strtab[hash_table->strtabcount].dest_index
9256     = hash_table->strtabcount;
9257   hash_table->strtab[hash_table->strtabcount].destshndx_index
9258     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
9259
9260   bfd_get_symcount (flinfo->output_bfd) += 1;
9261   hash_table->strtabcount += 1;
9262
9263   return 1;
9264 }
9265
9266 /* Swap symbols out to the symbol table and flush the output symbols to
9267    the file.  */
9268
9269 static bfd_boolean
9270 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
9271 {
9272   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
9273   bfd_size_type amt;
9274   size_t i;
9275   const struct elf_backend_data *bed;
9276   bfd_byte *symbuf;
9277   Elf_Internal_Shdr *hdr;
9278   file_ptr pos;
9279   bfd_boolean ret;
9280
9281   if (!hash_table->strtabcount)
9282     return TRUE;
9283
9284   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9285
9286   bed = get_elf_backend_data (flinfo->output_bfd);
9287
9288   amt = bed->s->sizeof_sym * hash_table->strtabcount;
9289   symbuf = (bfd_byte *) bfd_malloc (amt);
9290   if (symbuf == NULL)
9291     return FALSE;
9292
9293   if (flinfo->symshndxbuf)
9294     {
9295       amt = sizeof (Elf_External_Sym_Shndx);
9296       amt *= bfd_get_symcount (flinfo->output_bfd);
9297       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
9298       if (flinfo->symshndxbuf == NULL)
9299         {
9300           free (symbuf);
9301           return FALSE;
9302         }
9303     }
9304
9305   for (i = 0; i < hash_table->strtabcount; i++)
9306     {
9307       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
9308       if (elfsym->sym.st_name == (unsigned long) -1)
9309         elfsym->sym.st_name = 0;
9310       else
9311         elfsym->sym.st_name
9312           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
9313                                                     elfsym->sym.st_name);
9314       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
9315                                ((bfd_byte *) symbuf
9316                                 + (elfsym->dest_index
9317                                    * bed->s->sizeof_sym)),
9318                                (flinfo->symshndxbuf
9319                                 + elfsym->destshndx_index));
9320     }
9321
9322   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
9323   pos = hdr->sh_offset + hdr->sh_size;
9324   amt = hash_table->strtabcount * bed->s->sizeof_sym;
9325   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
9326       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
9327     {
9328       hdr->sh_size += amt;
9329       ret = TRUE;
9330     }
9331   else
9332     ret = FALSE;
9333
9334   free (symbuf);
9335
9336   free (hash_table->strtab);
9337   hash_table->strtab = NULL;
9338
9339   return ret;
9340 }
9341
9342 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
9343
9344 static bfd_boolean
9345 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
9346 {
9347   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
9348       && sym->st_shndx < SHN_LORESERVE)
9349     {
9350       /* The gABI doesn't support dynamic symbols in output sections
9351          beyond 64k.  */
9352       _bfd_error_handler
9353         /* xgettext:c-format */
9354         (_("%B: Too many sections: %d (>= %d)"),
9355          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
9356       bfd_set_error (bfd_error_nonrepresentable_section);
9357       return FALSE;
9358     }
9359   return TRUE;
9360 }
9361
9362 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
9363    allowing an unsatisfied unversioned symbol in the DSO to match a
9364    versioned symbol that would normally require an explicit version.
9365    We also handle the case that a DSO references a hidden symbol
9366    which may be satisfied by a versioned symbol in another DSO.  */
9367
9368 static bfd_boolean
9369 elf_link_check_versioned_symbol (struct bfd_link_info *info,
9370                                  const struct elf_backend_data *bed,
9371                                  struct elf_link_hash_entry *h)
9372 {
9373   bfd *abfd;
9374   struct elf_link_loaded_list *loaded;
9375
9376   if (!is_elf_hash_table (info->hash))
9377     return FALSE;
9378
9379   /* Check indirect symbol.  */
9380   while (h->root.type == bfd_link_hash_indirect)
9381     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9382
9383   switch (h->root.type)
9384     {
9385     default:
9386       abfd = NULL;
9387       break;
9388
9389     case bfd_link_hash_undefined:
9390     case bfd_link_hash_undefweak:
9391       abfd = h->root.u.undef.abfd;
9392       if (abfd == NULL
9393           || (abfd->flags & DYNAMIC) == 0
9394           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
9395         return FALSE;
9396       break;
9397
9398     case bfd_link_hash_defined:
9399     case bfd_link_hash_defweak:
9400       abfd = h->root.u.def.section->owner;
9401       break;
9402
9403     case bfd_link_hash_common:
9404       abfd = h->root.u.c.p->section->owner;
9405       break;
9406     }
9407   BFD_ASSERT (abfd != NULL);
9408
9409   for (loaded = elf_hash_table (info)->loaded;
9410        loaded != NULL;
9411        loaded = loaded->next)
9412     {
9413       bfd *input;
9414       Elf_Internal_Shdr *hdr;
9415       size_t symcount;
9416       size_t extsymcount;
9417       size_t extsymoff;
9418       Elf_Internal_Shdr *versymhdr;
9419       Elf_Internal_Sym *isym;
9420       Elf_Internal_Sym *isymend;
9421       Elf_Internal_Sym *isymbuf;
9422       Elf_External_Versym *ever;
9423       Elf_External_Versym *extversym;
9424
9425       input = loaded->abfd;
9426
9427       /* We check each DSO for a possible hidden versioned definition.  */
9428       if (input == abfd
9429           || (input->flags & DYNAMIC) == 0
9430           || elf_dynversym (input) == 0)
9431         continue;
9432
9433       hdr = &elf_tdata (input)->dynsymtab_hdr;
9434
9435       symcount = hdr->sh_size / bed->s->sizeof_sym;
9436       if (elf_bad_symtab (input))
9437         {
9438           extsymcount = symcount;
9439           extsymoff = 0;
9440         }
9441       else
9442         {
9443           extsymcount = symcount - hdr->sh_info;
9444           extsymoff = hdr->sh_info;
9445         }
9446
9447       if (extsymcount == 0)
9448         continue;
9449
9450       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
9451                                       NULL, NULL, NULL);
9452       if (isymbuf == NULL)
9453         return FALSE;
9454
9455       /* Read in any version definitions.  */
9456       versymhdr = &elf_tdata (input)->dynversym_hdr;
9457       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
9458       if (extversym == NULL)
9459         goto error_ret;
9460
9461       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
9462           || (bfd_bread (extversym, versymhdr->sh_size, input)
9463               != versymhdr->sh_size))
9464         {
9465           free (extversym);
9466         error_ret:
9467           free (isymbuf);
9468           return FALSE;
9469         }
9470
9471       ever = extversym + extsymoff;
9472       isymend = isymbuf + extsymcount;
9473       for (isym = isymbuf; isym < isymend; isym++, ever++)
9474         {
9475           const char *name;
9476           Elf_Internal_Versym iver;
9477           unsigned short version_index;
9478
9479           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
9480               || isym->st_shndx == SHN_UNDEF)
9481             continue;
9482
9483           name = bfd_elf_string_from_elf_section (input,
9484                                                   hdr->sh_link,
9485                                                   isym->st_name);
9486           if (strcmp (name, h->root.root.string) != 0)
9487             continue;
9488
9489           _bfd_elf_swap_versym_in (input, ever, &iver);
9490
9491           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
9492               && !(h->def_regular
9493                    && h->forced_local))
9494             {
9495               /* If we have a non-hidden versioned sym, then it should
9496                  have provided a definition for the undefined sym unless
9497                  it is defined in a non-shared object and forced local.
9498                */
9499               abort ();
9500             }
9501
9502           version_index = iver.vs_vers & VERSYM_VERSION;
9503           if (version_index == 1 || version_index == 2)
9504             {
9505               /* This is the base or first version.  We can use it.  */
9506               free (extversym);
9507               free (isymbuf);
9508               return TRUE;
9509             }
9510         }
9511
9512       free (extversym);
9513       free (isymbuf);
9514     }
9515
9516   return FALSE;
9517 }
9518
9519 /* Convert ELF common symbol TYPE.  */
9520
9521 static int
9522 elf_link_convert_common_type (struct bfd_link_info *info, int type)
9523 {
9524   /* Commom symbol can only appear in relocatable link.  */
9525   if (!bfd_link_relocatable (info))
9526     abort ();
9527   switch (info->elf_stt_common)
9528     {
9529     case unchanged:
9530       break;
9531     case elf_stt_common:
9532       type = STT_COMMON;
9533       break;
9534     case no_elf_stt_common:
9535       type = STT_OBJECT;
9536       break;
9537     }
9538   return type;
9539 }
9540
9541 /* Add an external symbol to the symbol table.  This is called from
9542    the hash table traversal routine.  When generating a shared object,
9543    we go through the symbol table twice.  The first time we output
9544    anything that might have been forced to local scope in a version
9545    script.  The second time we output the symbols that are still
9546    global symbols.  */
9547
9548 static bfd_boolean
9549 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
9550 {
9551   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
9552   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
9553   struct elf_final_link_info *flinfo = eoinfo->flinfo;
9554   bfd_boolean strip;
9555   Elf_Internal_Sym sym;
9556   asection *input_sec;
9557   const struct elf_backend_data *bed;
9558   long indx;
9559   int ret;
9560   unsigned int type;
9561
9562   if (h->root.type == bfd_link_hash_warning)
9563     {
9564       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9565       if (h->root.type == bfd_link_hash_new)
9566         return TRUE;
9567     }
9568
9569   /* Decide whether to output this symbol in this pass.  */
9570   if (eoinfo->localsyms)
9571     {
9572       if (!h->forced_local)
9573         return TRUE;
9574     }
9575   else
9576     {
9577       if (h->forced_local)
9578         return TRUE;
9579     }
9580
9581   bed = get_elf_backend_data (flinfo->output_bfd);
9582
9583   if (h->root.type == bfd_link_hash_undefined)
9584     {
9585       /* If we have an undefined symbol reference here then it must have
9586          come from a shared library that is being linked in.  (Undefined
9587          references in regular files have already been handled unless
9588          they are in unreferenced sections which are removed by garbage
9589          collection).  */
9590       bfd_boolean ignore_undef = FALSE;
9591
9592       /* Some symbols may be special in that the fact that they're
9593          undefined can be safely ignored - let backend determine that.  */
9594       if (bed->elf_backend_ignore_undef_symbol)
9595         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9596
9597       /* If we are reporting errors for this situation then do so now.  */
9598       if (!ignore_undef
9599           && h->ref_dynamic
9600           && (!h->ref_regular || flinfo->info->gc_sections)
9601           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9602           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9603         (*flinfo->info->callbacks->undefined_symbol)
9604           (flinfo->info, h->root.root.string,
9605            h->ref_regular ? NULL : h->root.u.undef.abfd,
9606            NULL, 0,
9607            flinfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR);
9608
9609       /* Strip a global symbol defined in a discarded section.  */
9610       if (h->indx == -3)
9611         return TRUE;
9612     }
9613
9614   /* We should also warn if a forced local symbol is referenced from
9615      shared libraries.  */
9616   if (bfd_link_executable (flinfo->info)
9617       && h->forced_local
9618       && h->ref_dynamic
9619       && h->def_regular
9620       && !h->dynamic_def
9621       && h->ref_dynamic_nonweak
9622       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9623     {
9624       bfd *def_bfd;
9625       const char *msg;
9626       struct elf_link_hash_entry *hi = h;
9627
9628       /* Check indirect symbol.  */
9629       while (hi->root.type == bfd_link_hash_indirect)
9630         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9631
9632       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9633         /* xgettext:c-format */
9634         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
9635       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9636         /* xgettext:c-format */
9637         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
9638       else
9639         /* xgettext:c-format */
9640         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
9641       def_bfd = flinfo->output_bfd;
9642       if (hi->root.u.def.section != bfd_abs_section_ptr)
9643         def_bfd = hi->root.u.def.section->owner;
9644       _bfd_error_handler (msg, flinfo->output_bfd,
9645                           h->root.root.string, def_bfd);
9646       bfd_set_error (bfd_error_bad_value);
9647       eoinfo->failed = TRUE;
9648       return FALSE;
9649     }
9650
9651   /* We don't want to output symbols that have never been mentioned by
9652      a regular file, or that we have been told to strip.  However, if
9653      h->indx is set to -2, the symbol is used by a reloc and we must
9654      output it.  */
9655   strip = FALSE;
9656   if (h->indx == -2)
9657     ;
9658   else if ((h->def_dynamic
9659             || h->ref_dynamic
9660             || h->root.type == bfd_link_hash_new)
9661            && !h->def_regular
9662            && !h->ref_regular)
9663     strip = TRUE;
9664   else if (flinfo->info->strip == strip_all)
9665     strip = TRUE;
9666   else if (flinfo->info->strip == strip_some
9667            && bfd_hash_lookup (flinfo->info->keep_hash,
9668                                h->root.root.string, FALSE, FALSE) == NULL)
9669     strip = TRUE;
9670   else if ((h->root.type == bfd_link_hash_defined
9671             || h->root.type == bfd_link_hash_defweak)
9672            && ((flinfo->info->strip_discarded
9673                 && discarded_section (h->root.u.def.section))
9674                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9675                    && h->root.u.def.section->owner != NULL
9676                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9677     strip = TRUE;
9678   else if ((h->root.type == bfd_link_hash_undefined
9679             || h->root.type == bfd_link_hash_undefweak)
9680            && h->root.u.undef.abfd != NULL
9681            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9682     strip = TRUE;
9683
9684   type = h->type;
9685
9686   /* If we're stripping it, and it's not a dynamic symbol, there's
9687      nothing else to do.   However, if it is a forced local symbol or
9688      an ifunc symbol we need to give the backend finish_dynamic_symbol
9689      function a chance to make it dynamic.  */
9690   if (strip
9691       && h->dynindx == -1
9692       && type != STT_GNU_IFUNC
9693       && !h->forced_local)
9694     return TRUE;
9695
9696   sym.st_value = 0;
9697   sym.st_size = h->size;
9698   sym.st_other = h->other;
9699   switch (h->root.type)
9700     {
9701     default:
9702     case bfd_link_hash_new:
9703     case bfd_link_hash_warning:
9704       abort ();
9705       return FALSE;
9706
9707     case bfd_link_hash_undefined:
9708     case bfd_link_hash_undefweak:
9709       input_sec = bfd_und_section_ptr;
9710       sym.st_shndx = SHN_UNDEF;
9711       break;
9712
9713     case bfd_link_hash_defined:
9714     case bfd_link_hash_defweak:
9715       {
9716         input_sec = h->root.u.def.section;
9717         if (input_sec->output_section != NULL)
9718           {
9719             sym.st_shndx =
9720               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9721                                                  input_sec->output_section);
9722             if (sym.st_shndx == SHN_BAD)
9723               {
9724                 _bfd_error_handler
9725                   /* xgettext:c-format */
9726                   (_("%B: could not find output section %A for input section %A"),
9727                    flinfo->output_bfd, input_sec->output_section, input_sec);
9728                 bfd_set_error (bfd_error_nonrepresentable_section);
9729                 eoinfo->failed = TRUE;
9730                 return FALSE;
9731               }
9732
9733             /* ELF symbols in relocatable files are section relative,
9734                but in nonrelocatable files they are virtual
9735                addresses.  */
9736             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9737             if (!bfd_link_relocatable (flinfo->info))
9738               {
9739                 sym.st_value += input_sec->output_section->vma;
9740                 if (h->type == STT_TLS)
9741                   {
9742                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9743                     if (tls_sec != NULL)
9744                       sym.st_value -= tls_sec->vma;
9745                   }
9746               }
9747           }
9748         else
9749           {
9750             BFD_ASSERT (input_sec->owner == NULL
9751                         || (input_sec->owner->flags & DYNAMIC) != 0);
9752             sym.st_shndx = SHN_UNDEF;
9753             input_sec = bfd_und_section_ptr;
9754           }
9755       }
9756       break;
9757
9758     case bfd_link_hash_common:
9759       input_sec = h->root.u.c.p->section;
9760       sym.st_shndx = bed->common_section_index (input_sec);
9761       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9762       break;
9763
9764     case bfd_link_hash_indirect:
9765       /* These symbols are created by symbol versioning.  They point
9766          to the decorated version of the name.  For example, if the
9767          symbol foo@@GNU_1.2 is the default, which should be used when
9768          foo is used with no version, then we add an indirect symbol
9769          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9770          since the indirected symbol is already in the hash table.  */
9771       return TRUE;
9772     }
9773
9774   if (type == STT_COMMON || type == STT_OBJECT)
9775     switch (h->root.type)
9776       {
9777       case bfd_link_hash_common:
9778         type = elf_link_convert_common_type (flinfo->info, type);
9779         break;
9780       case bfd_link_hash_defined:
9781       case bfd_link_hash_defweak:
9782         if (bed->common_definition (&sym))
9783           type = elf_link_convert_common_type (flinfo->info, type);
9784         else
9785           type = STT_OBJECT;
9786         break;
9787       case bfd_link_hash_undefined:
9788       case bfd_link_hash_undefweak:
9789         break;
9790       default:
9791         abort ();
9792       }
9793
9794   if (h->forced_local)
9795     {
9796       sym.st_info = ELF_ST_INFO (STB_LOCAL, type);
9797       /* Turn off visibility on local symbol.  */
9798       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9799     }
9800   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9801   else if (h->unique_global && h->def_regular)
9802     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, type);
9803   else if (h->root.type == bfd_link_hash_undefweak
9804            || h->root.type == bfd_link_hash_defweak)
9805     sym.st_info = ELF_ST_INFO (STB_WEAK, type);
9806   else
9807     sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9808   sym.st_target_internal = h->target_internal;
9809
9810   /* Give the processor backend a chance to tweak the symbol value,
9811      and also to finish up anything that needs to be done for this
9812      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9813      forced local syms when non-shared is due to a historical quirk.
9814      STT_GNU_IFUNC symbol must go through PLT.  */
9815   if ((h->type == STT_GNU_IFUNC
9816        && h->def_regular
9817        && !bfd_link_relocatable (flinfo->info))
9818       || ((h->dynindx != -1
9819            || h->forced_local)
9820           && ((bfd_link_pic (flinfo->info)
9821                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9822                    || h->root.type != bfd_link_hash_undefweak))
9823               || !h->forced_local)
9824           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9825     {
9826       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9827              (flinfo->output_bfd, flinfo->info, h, &sym)))
9828         {
9829           eoinfo->failed = TRUE;
9830           return FALSE;
9831         }
9832     }
9833
9834   /* If we are marking the symbol as undefined, and there are no
9835      non-weak references to this symbol from a regular object, then
9836      mark the symbol as weak undefined; if there are non-weak
9837      references, mark the symbol as strong.  We can't do this earlier,
9838      because it might not be marked as undefined until the
9839      finish_dynamic_symbol routine gets through with it.  */
9840   if (sym.st_shndx == SHN_UNDEF
9841       && h->ref_regular
9842       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9843           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9844     {
9845       int bindtype;
9846       type = ELF_ST_TYPE (sym.st_info);
9847
9848       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9849       if (type == STT_GNU_IFUNC)
9850         type = STT_FUNC;
9851
9852       if (h->ref_regular_nonweak)
9853         bindtype = STB_GLOBAL;
9854       else
9855         bindtype = STB_WEAK;
9856       sym.st_info = ELF_ST_INFO (bindtype, type);
9857     }
9858
9859   /* If this is a symbol defined in a dynamic library, don't use the
9860      symbol size from the dynamic library.  Relinking an executable
9861      against a new library may introduce gratuitous changes in the
9862      executable's symbols if we keep the size.  */
9863   if (sym.st_shndx == SHN_UNDEF
9864       && !h->def_regular
9865       && h->def_dynamic)
9866     sym.st_size = 0;
9867
9868   /* If a non-weak symbol with non-default visibility is not defined
9869      locally, it is a fatal error.  */
9870   if (!bfd_link_relocatable (flinfo->info)
9871       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9872       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9873       && h->root.type == bfd_link_hash_undefined
9874       && !h->def_regular)
9875     {
9876       const char *msg;
9877
9878       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9879         /* xgettext:c-format */
9880         msg = _("%B: protected symbol `%s' isn't defined");
9881       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9882         /* xgettext:c-format */
9883         msg = _("%B: internal symbol `%s' isn't defined");
9884       else
9885         /* xgettext:c-format */
9886         msg = _("%B: hidden symbol `%s' isn't defined");
9887       _bfd_error_handler (msg, flinfo->output_bfd, h->root.root.string);
9888       bfd_set_error (bfd_error_bad_value);
9889       eoinfo->failed = TRUE;
9890       return FALSE;
9891     }
9892
9893   /* If this symbol should be put in the .dynsym section, then put it
9894      there now.  We already know the symbol index.  We also fill in
9895      the entry in the .hash section.  */
9896   if (elf_hash_table (flinfo->info)->dynsym != NULL
9897       && h->dynindx != -1
9898       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9899     {
9900       bfd_byte *esym;
9901
9902       /* Since there is no version information in the dynamic string,
9903          if there is no version info in symbol version section, we will
9904          have a run-time problem if not linking executable, referenced
9905          by shared library, or not bound locally.  */
9906       if (h->verinfo.verdef == NULL
9907           && (!bfd_link_executable (flinfo->info)
9908               || h->ref_dynamic
9909               || !h->def_regular))
9910         {
9911           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9912
9913           if (p && p [1] != '\0')
9914             {
9915               _bfd_error_handler
9916                 /* xgettext:c-format */
9917                 (_("%B: No symbol version section for versioned symbol `%s'"),
9918                  flinfo->output_bfd, h->root.root.string);
9919               eoinfo->failed = TRUE;
9920               return FALSE;
9921             }
9922         }
9923
9924       sym.st_name = h->dynstr_index;
9925       esym = (elf_hash_table (flinfo->info)->dynsym->contents
9926               + h->dynindx * bed->s->sizeof_sym);
9927       if (!check_dynsym (flinfo->output_bfd, &sym))
9928         {
9929           eoinfo->failed = TRUE;
9930           return FALSE;
9931         }
9932       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9933
9934       if (flinfo->hash_sec != NULL)
9935         {
9936           size_t hash_entry_size;
9937           bfd_byte *bucketpos;
9938           bfd_vma chain;
9939           size_t bucketcount;
9940           size_t bucket;
9941
9942           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9943           bucket = h->u.elf_hash_value % bucketcount;
9944
9945           hash_entry_size
9946             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9947           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9948                        + (bucket + 2) * hash_entry_size);
9949           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9950           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9951                    bucketpos);
9952           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9953                    ((bfd_byte *) flinfo->hash_sec->contents
9954                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9955         }
9956
9957       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9958         {
9959           Elf_Internal_Versym iversym;
9960           Elf_External_Versym *eversym;
9961
9962           if (!h->def_regular)
9963             {
9964               if (h->verinfo.verdef == NULL
9965                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9966                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9967                 iversym.vs_vers = 0;
9968               else
9969                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9970             }
9971           else
9972             {
9973               if (h->verinfo.vertree == NULL)
9974                 iversym.vs_vers = 1;
9975               else
9976                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9977               if (flinfo->info->create_default_symver)
9978                 iversym.vs_vers++;
9979             }
9980
9981           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
9982              defined locally.  */
9983           if (h->versioned == versioned_hidden && h->def_regular)
9984             iversym.vs_vers |= VERSYM_HIDDEN;
9985
9986           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
9987           eversym += h->dynindx;
9988           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
9989         }
9990     }
9991
9992   /* If the symbol is undefined, and we didn't output it to .dynsym,
9993      strip it from .symtab too.  Obviously we can't do this for
9994      relocatable output or when needed for --emit-relocs.  */
9995   else if (input_sec == bfd_und_section_ptr
9996            && h->indx != -2
9997            /* PR 22319 Do not strip global undefined symbols marked as being needed.  */
9998            && (h->mark != 1 || ELF_ST_BIND (sym.st_info) != STB_GLOBAL)
9999            && !bfd_link_relocatable (flinfo->info))
10000     return TRUE;
10001
10002   /* Also strip others that we couldn't earlier due to dynamic symbol
10003      processing.  */
10004   if (strip)
10005     return TRUE;
10006   if ((input_sec->flags & SEC_EXCLUDE) != 0)
10007     return TRUE;
10008
10009   /* Output a FILE symbol so that following locals are not associated
10010      with the wrong input file.  We need one for forced local symbols
10011      if we've seen more than one FILE symbol or when we have exactly
10012      one FILE symbol but global symbols are present in a file other
10013      than the one with the FILE symbol.  We also need one if linker
10014      defined symbols are present.  In practice these conditions are
10015      always met, so just emit the FILE symbol unconditionally.  */
10016   if (eoinfo->localsyms
10017       && !eoinfo->file_sym_done
10018       && eoinfo->flinfo->filesym_count != 0)
10019     {
10020       Elf_Internal_Sym fsym;
10021
10022       memset (&fsym, 0, sizeof (fsym));
10023       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10024       fsym.st_shndx = SHN_ABS;
10025       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
10026                                       bfd_und_section_ptr, NULL))
10027         return FALSE;
10028
10029       eoinfo->file_sym_done = TRUE;
10030     }
10031
10032   indx = bfd_get_symcount (flinfo->output_bfd);
10033   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
10034                                    input_sec, h);
10035   if (ret == 0)
10036     {
10037       eoinfo->failed = TRUE;
10038       return FALSE;
10039     }
10040   else if (ret == 1)
10041     h->indx = indx;
10042   else if (h->indx == -2)
10043     abort();
10044
10045   return TRUE;
10046 }
10047
10048 /* Return TRUE if special handling is done for relocs in SEC against
10049    symbols defined in discarded sections.  */
10050
10051 static bfd_boolean
10052 elf_section_ignore_discarded_relocs (asection *sec)
10053 {
10054   const struct elf_backend_data *bed;
10055
10056   switch (sec->sec_info_type)
10057     {
10058     case SEC_INFO_TYPE_STABS:
10059     case SEC_INFO_TYPE_EH_FRAME:
10060     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10061       return TRUE;
10062     default:
10063       break;
10064     }
10065
10066   bed = get_elf_backend_data (sec->owner);
10067   if (bed->elf_backend_ignore_discarded_relocs != NULL
10068       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
10069     return TRUE;
10070
10071   return FALSE;
10072 }
10073
10074 /* Return a mask saying how ld should treat relocations in SEC against
10075    symbols defined in discarded sections.  If this function returns
10076    COMPLAIN set, ld will issue a warning message.  If this function
10077    returns PRETEND set, and the discarded section was link-once and the
10078    same size as the kept link-once section, ld will pretend that the
10079    symbol was actually defined in the kept section.  Otherwise ld will
10080    zero the reloc (at least that is the intent, but some cooperation by
10081    the target dependent code is needed, particularly for REL targets).  */
10082
10083 unsigned int
10084 _bfd_elf_default_action_discarded (asection *sec)
10085 {
10086   if (sec->flags & SEC_DEBUGGING)
10087     return PRETEND;
10088
10089   if (strcmp (".eh_frame", sec->name) == 0)
10090     return 0;
10091
10092   if (strcmp (".gcc_except_table", sec->name) == 0)
10093     return 0;
10094
10095   return COMPLAIN | PRETEND;
10096 }
10097
10098 /* Find a match between a section and a member of a section group.  */
10099
10100 static asection *
10101 match_group_member (asection *sec, asection *group,
10102                     struct bfd_link_info *info)
10103 {
10104   asection *first = elf_next_in_group (group);
10105   asection *s = first;
10106
10107   while (s != NULL)
10108     {
10109       if (bfd_elf_match_symbols_in_sections (s, sec, info))
10110         return s;
10111
10112       s = elf_next_in_group (s);
10113       if (s == first)
10114         break;
10115     }
10116
10117   return NULL;
10118 }
10119
10120 /* Check if the kept section of a discarded section SEC can be used
10121    to replace it.  Return the replacement if it is OK.  Otherwise return
10122    NULL.  */
10123
10124 asection *
10125 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
10126 {
10127   asection *kept;
10128
10129   kept = sec->kept_section;
10130   if (kept != NULL)
10131     {
10132       if ((kept->flags & SEC_GROUP) != 0)
10133         kept = match_group_member (sec, kept, info);
10134       if (kept != NULL
10135           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
10136               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
10137         kept = NULL;
10138       sec->kept_section = kept;
10139     }
10140   return kept;
10141 }
10142
10143 /* Link an input file into the linker output file.  This function
10144    handles all the sections and relocations of the input file at once.
10145    This is so that we only have to read the local symbols once, and
10146    don't have to keep them in memory.  */
10147
10148 static bfd_boolean
10149 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
10150 {
10151   int (*relocate_section)
10152     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
10153      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
10154   bfd *output_bfd;
10155   Elf_Internal_Shdr *symtab_hdr;
10156   size_t locsymcount;
10157   size_t extsymoff;
10158   Elf_Internal_Sym *isymbuf;
10159   Elf_Internal_Sym *isym;
10160   Elf_Internal_Sym *isymend;
10161   long *pindex;
10162   asection **ppsection;
10163   asection *o;
10164   const struct elf_backend_data *bed;
10165   struct elf_link_hash_entry **sym_hashes;
10166   bfd_size_type address_size;
10167   bfd_vma r_type_mask;
10168   int r_sym_shift;
10169   bfd_boolean have_file_sym = FALSE;
10170
10171   output_bfd = flinfo->output_bfd;
10172   bed = get_elf_backend_data (output_bfd);
10173   relocate_section = bed->elf_backend_relocate_section;
10174
10175   /* If this is a dynamic object, we don't want to do anything here:
10176      we don't want the local symbols, and we don't want the section
10177      contents.  */
10178   if ((input_bfd->flags & DYNAMIC) != 0)
10179     return TRUE;
10180
10181   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
10182   if (elf_bad_symtab (input_bfd))
10183     {
10184       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
10185       extsymoff = 0;
10186     }
10187   else
10188     {
10189       locsymcount = symtab_hdr->sh_info;
10190       extsymoff = symtab_hdr->sh_info;
10191     }
10192
10193   /* Read the local symbols.  */
10194   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
10195   if (isymbuf == NULL && locsymcount != 0)
10196     {
10197       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
10198                                       flinfo->internal_syms,
10199                                       flinfo->external_syms,
10200                                       flinfo->locsym_shndx);
10201       if (isymbuf == NULL)
10202         return FALSE;
10203     }
10204
10205   /* Find local symbol sections and adjust values of symbols in
10206      SEC_MERGE sections.  Write out those local symbols we know are
10207      going into the output file.  */
10208   isymend = isymbuf + locsymcount;
10209   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
10210        isym < isymend;
10211        isym++, pindex++, ppsection++)
10212     {
10213       asection *isec;
10214       const char *name;
10215       Elf_Internal_Sym osym;
10216       long indx;
10217       int ret;
10218
10219       *pindex = -1;
10220
10221       if (elf_bad_symtab (input_bfd))
10222         {
10223           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
10224             {
10225               *ppsection = NULL;
10226               continue;
10227             }
10228         }
10229
10230       if (isym->st_shndx == SHN_UNDEF)
10231         isec = bfd_und_section_ptr;
10232       else if (isym->st_shndx == SHN_ABS)
10233         isec = bfd_abs_section_ptr;
10234       else if (isym->st_shndx == SHN_COMMON)
10235         isec = bfd_com_section_ptr;
10236       else
10237         {
10238           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
10239           if (isec == NULL)
10240             {
10241               /* Don't attempt to output symbols with st_shnx in the
10242                  reserved range other than SHN_ABS and SHN_COMMON.  */
10243               *ppsection = NULL;
10244               continue;
10245             }
10246           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
10247                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
10248             isym->st_value =
10249               _bfd_merged_section_offset (output_bfd, &isec,
10250                                           elf_section_data (isec)->sec_info,
10251                                           isym->st_value);
10252         }
10253
10254       *ppsection = isec;
10255
10256       /* Don't output the first, undefined, symbol.  In fact, don't
10257          output any undefined local symbol.  */
10258       if (isec == bfd_und_section_ptr)
10259         continue;
10260
10261       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
10262         {
10263           /* We never output section symbols.  Instead, we use the
10264              section symbol of the corresponding section in the output
10265              file.  */
10266           continue;
10267         }
10268
10269       /* If we are stripping all symbols, we don't want to output this
10270          one.  */
10271       if (flinfo->info->strip == strip_all)
10272         continue;
10273
10274       /* If we are discarding all local symbols, we don't want to
10275          output this one.  If we are generating a relocatable output
10276          file, then some of the local symbols may be required by
10277          relocs; we output them below as we discover that they are
10278          needed.  */
10279       if (flinfo->info->discard == discard_all)
10280         continue;
10281
10282       /* If this symbol is defined in a section which we are
10283          discarding, we don't need to keep it.  */
10284       if (isym->st_shndx != SHN_UNDEF
10285           && isym->st_shndx < SHN_LORESERVE
10286           && bfd_section_removed_from_list (output_bfd,
10287                                             isec->output_section))
10288         continue;
10289
10290       /* Get the name of the symbol.  */
10291       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
10292                                               isym->st_name);
10293       if (name == NULL)
10294         return FALSE;
10295
10296       /* See if we are discarding symbols with this name.  */
10297       if ((flinfo->info->strip == strip_some
10298            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
10299                == NULL))
10300           || (((flinfo->info->discard == discard_sec_merge
10301                 && (isec->flags & SEC_MERGE)
10302                 && !bfd_link_relocatable (flinfo->info))
10303                || flinfo->info->discard == discard_l)
10304               && bfd_is_local_label_name (input_bfd, name)))
10305         continue;
10306
10307       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
10308         {
10309           if (input_bfd->lto_output)
10310             /* -flto puts a temp file name here.  This means builds
10311                are not reproducible.  Discard the symbol.  */
10312             continue;
10313           have_file_sym = TRUE;
10314           flinfo->filesym_count += 1;
10315         }
10316       if (!have_file_sym)
10317         {
10318           /* In the absence of debug info, bfd_find_nearest_line uses
10319              FILE symbols to determine the source file for local
10320              function symbols.  Provide a FILE symbol here if input
10321              files lack such, so that their symbols won't be
10322              associated with a previous input file.  It's not the
10323              source file, but the best we can do.  */
10324           have_file_sym = TRUE;
10325           flinfo->filesym_count += 1;
10326           memset (&osym, 0, sizeof (osym));
10327           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10328           osym.st_shndx = SHN_ABS;
10329           if (!elf_link_output_symstrtab (flinfo,
10330                                           (input_bfd->lto_output ? NULL
10331                                            : input_bfd->filename),
10332                                           &osym, bfd_abs_section_ptr,
10333                                           NULL))
10334             return FALSE;
10335         }
10336
10337       osym = *isym;
10338
10339       /* Adjust the section index for the output file.  */
10340       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10341                                                          isec->output_section);
10342       if (osym.st_shndx == SHN_BAD)
10343         return FALSE;
10344
10345       /* ELF symbols in relocatable files are section relative, but
10346          in executable files they are virtual addresses.  Note that
10347          this code assumes that all ELF sections have an associated
10348          BFD section with a reasonable value for output_offset; below
10349          we assume that they also have a reasonable value for
10350          output_section.  Any special sections must be set up to meet
10351          these requirements.  */
10352       osym.st_value += isec->output_offset;
10353       if (!bfd_link_relocatable (flinfo->info))
10354         {
10355           osym.st_value += isec->output_section->vma;
10356           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
10357             {
10358               /* STT_TLS symbols are relative to PT_TLS segment base.  */
10359               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
10360               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
10361             }
10362         }
10363
10364       indx = bfd_get_symcount (output_bfd);
10365       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
10366       if (ret == 0)
10367         return FALSE;
10368       else if (ret == 1)
10369         *pindex = indx;
10370     }
10371
10372   if (bed->s->arch_size == 32)
10373     {
10374       r_type_mask = 0xff;
10375       r_sym_shift = 8;
10376       address_size = 4;
10377     }
10378   else
10379     {
10380       r_type_mask = 0xffffffff;
10381       r_sym_shift = 32;
10382       address_size = 8;
10383     }
10384
10385   /* Relocate the contents of each section.  */
10386   sym_hashes = elf_sym_hashes (input_bfd);
10387   for (o = input_bfd->sections; o != NULL; o = o->next)
10388     {
10389       bfd_byte *contents;
10390
10391       if (! o->linker_mark)
10392         {
10393           /* This section was omitted from the link.  */
10394           continue;
10395         }
10396
10397       if (!flinfo->info->resolve_section_groups
10398           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
10399         {
10400           /* Deal with the group signature symbol.  */
10401           struct bfd_elf_section_data *sec_data = elf_section_data (o);
10402           unsigned long symndx = sec_data->this_hdr.sh_info;
10403           asection *osec = o->output_section;
10404
10405           BFD_ASSERT (bfd_link_relocatable (flinfo->info));
10406           if (symndx >= locsymcount
10407               || (elf_bad_symtab (input_bfd)
10408                   && flinfo->sections[symndx] == NULL))
10409             {
10410               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
10411               while (h->root.type == bfd_link_hash_indirect
10412                      || h->root.type == bfd_link_hash_warning)
10413                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
10414               /* Arrange for symbol to be output.  */
10415               h->indx = -2;
10416               elf_section_data (osec)->this_hdr.sh_info = -2;
10417             }
10418           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
10419             {
10420               /* We'll use the output section target_index.  */
10421               asection *sec = flinfo->sections[symndx]->output_section;
10422               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
10423             }
10424           else
10425             {
10426               if (flinfo->indices[symndx] == -1)
10427                 {
10428                   /* Otherwise output the local symbol now.  */
10429                   Elf_Internal_Sym sym = isymbuf[symndx];
10430                   asection *sec = flinfo->sections[symndx]->output_section;
10431                   const char *name;
10432                   long indx;
10433                   int ret;
10434
10435                   name = bfd_elf_string_from_elf_section (input_bfd,
10436                                                           symtab_hdr->sh_link,
10437                                                           sym.st_name);
10438                   if (name == NULL)
10439                     return FALSE;
10440
10441                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10442                                                                     sec);
10443                   if (sym.st_shndx == SHN_BAD)
10444                     return FALSE;
10445
10446                   sym.st_value += o->output_offset;
10447
10448                   indx = bfd_get_symcount (output_bfd);
10449                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
10450                                                    NULL);
10451                   if (ret == 0)
10452                     return FALSE;
10453                   else if (ret == 1)
10454                     flinfo->indices[symndx] = indx;
10455                   else
10456                     abort ();
10457                 }
10458               elf_section_data (osec)->this_hdr.sh_info
10459                 = flinfo->indices[symndx];
10460             }
10461         }
10462
10463       if ((o->flags & SEC_HAS_CONTENTS) == 0
10464           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
10465         continue;
10466
10467       if ((o->flags & SEC_LINKER_CREATED) != 0)
10468         {
10469           /* Section was created by _bfd_elf_link_create_dynamic_sections
10470              or somesuch.  */
10471           continue;
10472         }
10473
10474       /* Get the contents of the section.  They have been cached by a
10475          relaxation routine.  Note that o is a section in an input
10476          file, so the contents field will not have been set by any of
10477          the routines which work on output files.  */
10478       if (elf_section_data (o)->this_hdr.contents != NULL)
10479         {
10480           contents = elf_section_data (o)->this_hdr.contents;
10481           if (bed->caches_rawsize
10482               && o->rawsize != 0
10483               && o->rawsize < o->size)
10484             {
10485               memcpy (flinfo->contents, contents, o->rawsize);
10486               contents = flinfo->contents;
10487             }
10488         }
10489       else
10490         {
10491           contents = flinfo->contents;
10492           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
10493             return FALSE;
10494         }
10495
10496       if ((o->flags & SEC_RELOC) != 0)
10497         {
10498           Elf_Internal_Rela *internal_relocs;
10499           Elf_Internal_Rela *rel, *relend;
10500           int action_discarded;
10501           int ret;
10502
10503           /* Get the swapped relocs.  */
10504           internal_relocs
10505             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
10506                                          flinfo->internal_relocs, FALSE);
10507           if (internal_relocs == NULL
10508               && o->reloc_count > 0)
10509             return FALSE;
10510
10511           /* We need to reverse-copy input .ctors/.dtors sections if
10512              they are placed in .init_array/.finit_array for output.  */
10513           if (o->size > address_size
10514               && ((strncmp (o->name, ".ctors", 6) == 0
10515                    && strcmp (o->output_section->name,
10516                               ".init_array") == 0)
10517                   || (strncmp (o->name, ".dtors", 6) == 0
10518                       && strcmp (o->output_section->name,
10519                                  ".fini_array") == 0))
10520               && (o->name[6] == 0 || o->name[6] == '.'))
10521             {
10522               if (o->size * bed->s->int_rels_per_ext_rel
10523                   != o->reloc_count * address_size)
10524                 {
10525                   _bfd_error_handler
10526                     /* xgettext:c-format */
10527                     (_("error: %B: size of section %A is not "
10528                        "multiple of address size"),
10529                      input_bfd, o);
10530                   bfd_set_error (bfd_error_bad_value);
10531                   return FALSE;
10532                 }
10533               o->flags |= SEC_ELF_REVERSE_COPY;
10534             }
10535
10536           action_discarded = -1;
10537           if (!elf_section_ignore_discarded_relocs (o))
10538             action_discarded = (*bed->action_discarded) (o);
10539
10540           /* Run through the relocs evaluating complex reloc symbols and
10541              looking for relocs against symbols from discarded sections
10542              or section symbols from removed link-once sections.
10543              Complain about relocs against discarded sections.  Zero
10544              relocs against removed link-once sections.  */
10545
10546           rel = internal_relocs;
10547           relend = rel + o->reloc_count;
10548           for ( ; rel < relend; rel++)
10549             {
10550               unsigned long r_symndx = rel->r_info >> r_sym_shift;
10551               unsigned int s_type;
10552               asection **ps, *sec;
10553               struct elf_link_hash_entry *h = NULL;
10554               const char *sym_name;
10555
10556               if (r_symndx == STN_UNDEF)
10557                 continue;
10558
10559               if (r_symndx >= locsymcount
10560                   || (elf_bad_symtab (input_bfd)
10561                       && flinfo->sections[r_symndx] == NULL))
10562                 {
10563                   h = sym_hashes[r_symndx - extsymoff];
10564
10565                   /* Badly formatted input files can contain relocs that
10566                      reference non-existant symbols.  Check here so that
10567                      we do not seg fault.  */
10568                   if (h == NULL)
10569                     {
10570                       _bfd_error_handler
10571                         /* xgettext:c-format */
10572                         (_("error: %B contains a reloc (%#Lx) for section %A "
10573                            "that references a non-existent global symbol"),
10574                          input_bfd, rel->r_info, o);
10575                       bfd_set_error (bfd_error_bad_value);
10576                       return FALSE;
10577                     }
10578
10579                   while (h->root.type == bfd_link_hash_indirect
10580                          || h->root.type == bfd_link_hash_warning)
10581                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10582
10583                   s_type = h->type;
10584
10585                   /* If a plugin symbol is referenced from a non-IR file,
10586                      mark the symbol as undefined.  Note that the
10587                      linker may attach linker created dynamic sections
10588                      to the plugin bfd.  Symbols defined in linker
10589                      created sections are not plugin symbols.  */
10590                   if ((h->root.non_ir_ref_regular
10591                        || h->root.non_ir_ref_dynamic)
10592                       && (h->root.type == bfd_link_hash_defined
10593                           || h->root.type == bfd_link_hash_defweak)
10594                       && (h->root.u.def.section->flags
10595                           & SEC_LINKER_CREATED) == 0
10596                       && h->root.u.def.section->owner != NULL
10597                       && (h->root.u.def.section->owner->flags
10598                           & BFD_PLUGIN) != 0)
10599                     {
10600                       h->root.type = bfd_link_hash_undefined;
10601                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10602                     }
10603
10604                   ps = NULL;
10605                   if (h->root.type == bfd_link_hash_defined
10606                       || h->root.type == bfd_link_hash_defweak)
10607                     ps = &h->root.u.def.section;
10608
10609                   sym_name = h->root.root.string;
10610                 }
10611               else
10612                 {
10613                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10614
10615                   s_type = ELF_ST_TYPE (sym->st_info);
10616                   ps = &flinfo->sections[r_symndx];
10617                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10618                                                sym, *ps);
10619                 }
10620
10621               if ((s_type == STT_RELC || s_type == STT_SRELC)
10622                   && !bfd_link_relocatable (flinfo->info))
10623                 {
10624                   bfd_vma val;
10625                   bfd_vma dot = (rel->r_offset
10626                                  + o->output_offset + o->output_section->vma);
10627 #ifdef DEBUG
10628                   printf ("Encountered a complex symbol!");
10629                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10630                           input_bfd->filename, o->name,
10631                           (long) (rel - internal_relocs));
10632                   printf (" symbol: idx  %8.8lx, name %s\n",
10633                           r_symndx, sym_name);
10634                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10635                           (unsigned long) rel->r_info,
10636                           (unsigned long) rel->r_offset);
10637 #endif
10638                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10639                                     isymbuf, locsymcount, s_type == STT_SRELC))
10640                     return FALSE;
10641
10642                   /* Symbol evaluated OK.  Update to absolute value.  */
10643                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10644                                     r_symndx, val);
10645                   continue;
10646                 }
10647
10648               if (action_discarded != -1 && ps != NULL)
10649                 {
10650                   /* Complain if the definition comes from a
10651                      discarded section.  */
10652                   if ((sec = *ps) != NULL && discarded_section (sec))
10653                     {
10654                       BFD_ASSERT (r_symndx != STN_UNDEF);
10655                       if (action_discarded & COMPLAIN)
10656                         (*flinfo->info->callbacks->einfo)
10657                           /* xgettext:c-format */
10658                           (_("%X`%s' referenced in section `%A' of %B: "
10659                              "defined in discarded section `%A' of %B\n"),
10660                            sym_name, o, input_bfd, sec, sec->owner);
10661
10662                       /* Try to do the best we can to support buggy old
10663                          versions of gcc.  Pretend that the symbol is
10664                          really defined in the kept linkonce section.
10665                          FIXME: This is quite broken.  Modifying the
10666                          symbol here means we will be changing all later
10667                          uses of the symbol, not just in this section.  */
10668                       if (action_discarded & PRETEND)
10669                         {
10670                           asection *kept;
10671
10672                           kept = _bfd_elf_check_kept_section (sec,
10673                                                               flinfo->info);
10674                           if (kept != NULL)
10675                             {
10676                               *ps = kept;
10677                               continue;
10678                             }
10679                         }
10680                     }
10681                 }
10682             }
10683
10684           /* Relocate the section by invoking a back end routine.
10685
10686              The back end routine is responsible for adjusting the
10687              section contents as necessary, and (if using Rela relocs
10688              and generating a relocatable output file) adjusting the
10689              reloc addend as necessary.
10690
10691              The back end routine does not have to worry about setting
10692              the reloc address or the reloc symbol index.
10693
10694              The back end routine is given a pointer to the swapped in
10695              internal symbols, and can access the hash table entries
10696              for the external symbols via elf_sym_hashes (input_bfd).
10697
10698              When generating relocatable output, the back end routine
10699              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10700              output symbol is going to be a section symbol
10701              corresponding to the output section, which will require
10702              the addend to be adjusted.  */
10703
10704           ret = (*relocate_section) (output_bfd, flinfo->info,
10705                                      input_bfd, o, contents,
10706                                      internal_relocs,
10707                                      isymbuf,
10708                                      flinfo->sections);
10709           if (!ret)
10710             return FALSE;
10711
10712           if (ret == 2
10713               || bfd_link_relocatable (flinfo->info)
10714               || flinfo->info->emitrelocations)
10715             {
10716               Elf_Internal_Rela *irela;
10717               Elf_Internal_Rela *irelaend, *irelamid;
10718               bfd_vma last_offset;
10719               struct elf_link_hash_entry **rel_hash;
10720               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10721               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10722               unsigned int next_erel;
10723               bfd_boolean rela_normal;
10724               struct bfd_elf_section_data *esdi, *esdo;
10725
10726               esdi = elf_section_data (o);
10727               esdo = elf_section_data (o->output_section);
10728               rela_normal = FALSE;
10729
10730               /* Adjust the reloc addresses and symbol indices.  */
10731
10732               irela = internal_relocs;
10733               irelaend = irela + o->reloc_count;
10734               rel_hash = esdo->rel.hashes + esdo->rel.count;
10735               /* We start processing the REL relocs, if any.  When we reach
10736                  IRELAMID in the loop, we switch to the RELA relocs.  */
10737               irelamid = irela;
10738               if (esdi->rel.hdr != NULL)
10739                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10740                              * bed->s->int_rels_per_ext_rel);
10741               rel_hash_list = rel_hash;
10742               rela_hash_list = NULL;
10743               last_offset = o->output_offset;
10744               if (!bfd_link_relocatable (flinfo->info))
10745                 last_offset += o->output_section->vma;
10746               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10747                 {
10748                   unsigned long r_symndx;
10749                   asection *sec;
10750                   Elf_Internal_Sym sym;
10751
10752                   if (next_erel == bed->s->int_rels_per_ext_rel)
10753                     {
10754                       rel_hash++;
10755                       next_erel = 0;
10756                     }
10757
10758                   if (irela == irelamid)
10759                     {
10760                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10761                       rela_hash_list = rel_hash;
10762                       rela_normal = bed->rela_normal;
10763                     }
10764
10765                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10766                                                              flinfo->info, o,
10767                                                              irela->r_offset);
10768                   if (irela->r_offset >= (bfd_vma) -2)
10769                     {
10770                       /* This is a reloc for a deleted entry or somesuch.
10771                          Turn it into an R_*_NONE reloc, at the same
10772                          offset as the last reloc.  elf_eh_frame.c and
10773                          bfd_elf_discard_info rely on reloc offsets
10774                          being ordered.  */
10775                       irela->r_offset = last_offset;
10776                       irela->r_info = 0;
10777                       irela->r_addend = 0;
10778                       continue;
10779                     }
10780
10781                   irela->r_offset += o->output_offset;
10782
10783                   /* Relocs in an executable have to be virtual addresses.  */
10784                   if (!bfd_link_relocatable (flinfo->info))
10785                     irela->r_offset += o->output_section->vma;
10786
10787                   last_offset = irela->r_offset;
10788
10789                   r_symndx = irela->r_info >> r_sym_shift;
10790                   if (r_symndx == STN_UNDEF)
10791                     continue;
10792
10793                   if (r_symndx >= locsymcount
10794                       || (elf_bad_symtab (input_bfd)
10795                           && flinfo->sections[r_symndx] == NULL))
10796                     {
10797                       struct elf_link_hash_entry *rh;
10798                       unsigned long indx;
10799
10800                       /* This is a reloc against a global symbol.  We
10801                          have not yet output all the local symbols, so
10802                          we do not know the symbol index of any global
10803                          symbol.  We set the rel_hash entry for this
10804                          reloc to point to the global hash table entry
10805                          for this symbol.  The symbol index is then
10806                          set at the end of bfd_elf_final_link.  */
10807                       indx = r_symndx - extsymoff;
10808                       rh = elf_sym_hashes (input_bfd)[indx];
10809                       while (rh->root.type == bfd_link_hash_indirect
10810                              || rh->root.type == bfd_link_hash_warning)
10811                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10812
10813                       /* Setting the index to -2 tells
10814                          elf_link_output_extsym that this symbol is
10815                          used by a reloc.  */
10816                       BFD_ASSERT (rh->indx < 0);
10817                       rh->indx = -2;
10818                       *rel_hash = rh;
10819
10820                       continue;
10821                     }
10822
10823                   /* This is a reloc against a local symbol.  */
10824
10825                   *rel_hash = NULL;
10826                   sym = isymbuf[r_symndx];
10827                   sec = flinfo->sections[r_symndx];
10828                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10829                     {
10830                       /* I suppose the backend ought to fill in the
10831                          section of any STT_SECTION symbol against a
10832                          processor specific section.  */
10833                       r_symndx = STN_UNDEF;
10834                       if (bfd_is_abs_section (sec))
10835                         ;
10836                       else if (sec == NULL || sec->owner == NULL)
10837                         {
10838                           bfd_set_error (bfd_error_bad_value);
10839                           return FALSE;
10840                         }
10841                       else
10842                         {
10843                           asection *osec = sec->output_section;
10844
10845                           /* If we have discarded a section, the output
10846                              section will be the absolute section.  In
10847                              case of discarded SEC_MERGE sections, use
10848                              the kept section.  relocate_section should
10849                              have already handled discarded linkonce
10850                              sections.  */
10851                           if (bfd_is_abs_section (osec)
10852                               && sec->kept_section != NULL
10853                               && sec->kept_section->output_section != NULL)
10854                             {
10855                               osec = sec->kept_section->output_section;
10856                               irela->r_addend -= osec->vma;
10857                             }
10858
10859                           if (!bfd_is_abs_section (osec))
10860                             {
10861                               r_symndx = osec->target_index;
10862                               if (r_symndx == STN_UNDEF)
10863                                 {
10864                                   irela->r_addend += osec->vma;
10865                                   osec = _bfd_nearby_section (output_bfd, osec,
10866                                                               osec->vma);
10867                                   irela->r_addend -= osec->vma;
10868                                   r_symndx = osec->target_index;
10869                                 }
10870                             }
10871                         }
10872
10873                       /* Adjust the addend according to where the
10874                          section winds up in the output section.  */
10875                       if (rela_normal)
10876                         irela->r_addend += sec->output_offset;
10877                     }
10878                   else
10879                     {
10880                       if (flinfo->indices[r_symndx] == -1)
10881                         {
10882                           unsigned long shlink;
10883                           const char *name;
10884                           asection *osec;
10885                           long indx;
10886
10887                           if (flinfo->info->strip == strip_all)
10888                             {
10889                               /* You can't do ld -r -s.  */
10890                               bfd_set_error (bfd_error_invalid_operation);
10891                               return FALSE;
10892                             }
10893
10894                           /* This symbol was skipped earlier, but
10895                              since it is needed by a reloc, we
10896                              must output it now.  */
10897                           shlink = symtab_hdr->sh_link;
10898                           name = (bfd_elf_string_from_elf_section
10899                                   (input_bfd, shlink, sym.st_name));
10900                           if (name == NULL)
10901                             return FALSE;
10902
10903                           osec = sec->output_section;
10904                           sym.st_shndx =
10905                             _bfd_elf_section_from_bfd_section (output_bfd,
10906                                                                osec);
10907                           if (sym.st_shndx == SHN_BAD)
10908                             return FALSE;
10909
10910                           sym.st_value += sec->output_offset;
10911                           if (!bfd_link_relocatable (flinfo->info))
10912                             {
10913                               sym.st_value += osec->vma;
10914                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10915                                 {
10916                                   /* STT_TLS symbols are relative to PT_TLS
10917                                      segment base.  */
10918                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10919                                               ->tls_sec != NULL);
10920                                   sym.st_value -= (elf_hash_table (flinfo->info)
10921                                                    ->tls_sec->vma);
10922                                 }
10923                             }
10924
10925                           indx = bfd_get_symcount (output_bfd);
10926                           ret = elf_link_output_symstrtab (flinfo, name,
10927                                                            &sym, sec,
10928                                                            NULL);
10929                           if (ret == 0)
10930                             return FALSE;
10931                           else if (ret == 1)
10932                             flinfo->indices[r_symndx] = indx;
10933                           else
10934                             abort ();
10935                         }
10936
10937                       r_symndx = flinfo->indices[r_symndx];
10938                     }
10939
10940                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10941                                    | (irela->r_info & r_type_mask));
10942                 }
10943
10944               /* Swap out the relocs.  */
10945               input_rel_hdr = esdi->rel.hdr;
10946               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10947                 {
10948                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10949                                                      input_rel_hdr,
10950                                                      internal_relocs,
10951                                                      rel_hash_list))
10952                     return FALSE;
10953                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10954                                       * bed->s->int_rels_per_ext_rel);
10955                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10956                 }
10957
10958               input_rela_hdr = esdi->rela.hdr;
10959               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10960                 {
10961                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10962                                                      input_rela_hdr,
10963                                                      internal_relocs,
10964                                                      rela_hash_list))
10965                     return FALSE;
10966                 }
10967             }
10968         }
10969
10970       /* Write out the modified section contents.  */
10971       if (bed->elf_backend_write_section
10972           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10973                                                 contents))
10974         {
10975           /* Section written out.  */
10976         }
10977       else switch (o->sec_info_type)
10978         {
10979         case SEC_INFO_TYPE_STABS:
10980           if (! (_bfd_write_section_stabs
10981                  (output_bfd,
10982                   &elf_hash_table (flinfo->info)->stab_info,
10983                   o, &elf_section_data (o)->sec_info, contents)))
10984             return FALSE;
10985           break;
10986         case SEC_INFO_TYPE_MERGE:
10987           if (! _bfd_write_merged_section (output_bfd, o,
10988                                            elf_section_data (o)->sec_info))
10989             return FALSE;
10990           break;
10991         case SEC_INFO_TYPE_EH_FRAME:
10992           {
10993             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
10994                                                    o, contents))
10995               return FALSE;
10996           }
10997           break;
10998         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10999           {
11000             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
11001                                                          flinfo->info,
11002                                                          o, contents))
11003               return FALSE;
11004           }
11005           break;
11006         default:
11007           {
11008             if (! (o->flags & SEC_EXCLUDE))
11009               {
11010                 file_ptr offset = (file_ptr) o->output_offset;
11011                 bfd_size_type todo = o->size;
11012
11013                 offset *= bfd_octets_per_byte (output_bfd);
11014
11015                 if ((o->flags & SEC_ELF_REVERSE_COPY))
11016                   {
11017                     /* Reverse-copy input section to output.  */
11018                     do
11019                       {
11020                         todo -= address_size;
11021                         if (! bfd_set_section_contents (output_bfd,
11022                                                         o->output_section,
11023                                                         contents + todo,
11024                                                         offset,
11025                                                         address_size))
11026                           return FALSE;
11027                         if (todo == 0)
11028                           break;
11029                         offset += address_size;
11030                       }
11031                     while (1);
11032                   }
11033                 else if (! bfd_set_section_contents (output_bfd,
11034                                                      o->output_section,
11035                                                      contents,
11036                                                      offset, todo))
11037                   return FALSE;
11038               }
11039           }
11040           break;
11041         }
11042     }
11043
11044   return TRUE;
11045 }
11046
11047 /* Generate a reloc when linking an ELF file.  This is a reloc
11048    requested by the linker, and does not come from any input file.  This
11049    is used to build constructor and destructor tables when linking
11050    with -Ur.  */
11051
11052 static bfd_boolean
11053 elf_reloc_link_order (bfd *output_bfd,
11054                       struct bfd_link_info *info,
11055                       asection *output_section,
11056                       struct bfd_link_order *link_order)
11057 {
11058   reloc_howto_type *howto;
11059   long indx;
11060   bfd_vma offset;
11061   bfd_vma addend;
11062   struct bfd_elf_section_reloc_data *reldata;
11063   struct elf_link_hash_entry **rel_hash_ptr;
11064   Elf_Internal_Shdr *rel_hdr;
11065   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
11066   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
11067   bfd_byte *erel;
11068   unsigned int i;
11069   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
11070
11071   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
11072   if (howto == NULL)
11073     {
11074       bfd_set_error (bfd_error_bad_value);
11075       return FALSE;
11076     }
11077
11078   addend = link_order->u.reloc.p->addend;
11079
11080   if (esdo->rel.hdr)
11081     reldata = &esdo->rel;
11082   else if (esdo->rela.hdr)
11083     reldata = &esdo->rela;
11084   else
11085     {
11086       reldata = NULL;
11087       BFD_ASSERT (0);
11088     }
11089
11090   /* Figure out the symbol index.  */
11091   rel_hash_ptr = reldata->hashes + reldata->count;
11092   if (link_order->type == bfd_section_reloc_link_order)
11093     {
11094       indx = link_order->u.reloc.p->u.section->target_index;
11095       BFD_ASSERT (indx != 0);
11096       *rel_hash_ptr = NULL;
11097     }
11098   else
11099     {
11100       struct elf_link_hash_entry *h;
11101
11102       /* Treat a reloc against a defined symbol as though it were
11103          actually against the section.  */
11104       h = ((struct elf_link_hash_entry *)
11105            bfd_wrapped_link_hash_lookup (output_bfd, info,
11106                                          link_order->u.reloc.p->u.name,
11107                                          FALSE, FALSE, TRUE));
11108       if (h != NULL
11109           && (h->root.type == bfd_link_hash_defined
11110               || h->root.type == bfd_link_hash_defweak))
11111         {
11112           asection *section;
11113
11114           section = h->root.u.def.section;
11115           indx = section->output_section->target_index;
11116           *rel_hash_ptr = NULL;
11117           /* It seems that we ought to add the symbol value to the
11118              addend here, but in practice it has already been added
11119              because it was passed to constructor_callback.  */
11120           addend += section->output_section->vma + section->output_offset;
11121         }
11122       else if (h != NULL)
11123         {
11124           /* Setting the index to -2 tells elf_link_output_extsym that
11125              this symbol is used by a reloc.  */
11126           h->indx = -2;
11127           *rel_hash_ptr = h;
11128           indx = 0;
11129         }
11130       else
11131         {
11132           (*info->callbacks->unattached_reloc)
11133             (info, link_order->u.reloc.p->u.name, NULL, NULL, 0);
11134           indx = 0;
11135         }
11136     }
11137
11138   /* If this is an inplace reloc, we must write the addend into the
11139      object file.  */
11140   if (howto->partial_inplace && addend != 0)
11141     {
11142       bfd_size_type size;
11143       bfd_reloc_status_type rstat;
11144       bfd_byte *buf;
11145       bfd_boolean ok;
11146       const char *sym_name;
11147
11148       size = (bfd_size_type) bfd_get_reloc_size (howto);
11149       buf = (bfd_byte *) bfd_zmalloc (size);
11150       if (buf == NULL && size != 0)
11151         return FALSE;
11152       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
11153       switch (rstat)
11154         {
11155         case bfd_reloc_ok:
11156           break;
11157
11158         default:
11159         case bfd_reloc_outofrange:
11160           abort ();
11161
11162         case bfd_reloc_overflow:
11163           if (link_order->type == bfd_section_reloc_link_order)
11164             sym_name = bfd_section_name (output_bfd,
11165                                          link_order->u.reloc.p->u.section);
11166           else
11167             sym_name = link_order->u.reloc.p->u.name;
11168           (*info->callbacks->reloc_overflow) (info, NULL, sym_name,
11169                                               howto->name, addend, NULL, NULL,
11170                                               (bfd_vma) 0);
11171           break;
11172         }
11173
11174       ok = bfd_set_section_contents (output_bfd, output_section, buf,
11175                                      link_order->offset
11176                                      * bfd_octets_per_byte (output_bfd),
11177                                      size);
11178       free (buf);
11179       if (! ok)
11180         return FALSE;
11181     }
11182
11183   /* The address of a reloc is relative to the section in a
11184      relocatable file, and is a virtual address in an executable
11185      file.  */
11186   offset = link_order->offset;
11187   if (! bfd_link_relocatable (info))
11188     offset += output_section->vma;
11189
11190   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
11191     {
11192       irel[i].r_offset = offset;
11193       irel[i].r_info = 0;
11194       irel[i].r_addend = 0;
11195     }
11196   if (bed->s->arch_size == 32)
11197     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
11198   else
11199     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
11200
11201   rel_hdr = reldata->hdr;
11202   erel = rel_hdr->contents;
11203   if (rel_hdr->sh_type == SHT_REL)
11204     {
11205       erel += reldata->count * bed->s->sizeof_rel;
11206       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
11207     }
11208   else
11209     {
11210       irel[0].r_addend = addend;
11211       erel += reldata->count * bed->s->sizeof_rela;
11212       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
11213     }
11214
11215   ++reldata->count;
11216
11217   return TRUE;
11218 }
11219
11220
11221 /* Get the output vma of the section pointed to by the sh_link field.  */
11222
11223 static bfd_vma
11224 elf_get_linked_section_vma (struct bfd_link_order *p)
11225 {
11226   Elf_Internal_Shdr **elf_shdrp;
11227   asection *s;
11228   int elfsec;
11229
11230   s = p->u.indirect.section;
11231   elf_shdrp = elf_elfsections (s->owner);
11232   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
11233   elfsec = elf_shdrp[elfsec]->sh_link;
11234   /* PR 290:
11235      The Intel C compiler generates SHT_IA_64_UNWIND with
11236      SHF_LINK_ORDER.  But it doesn't set the sh_link or
11237      sh_info fields.  Hence we could get the situation
11238      where elfsec is 0.  */
11239   if (elfsec == 0)
11240     {
11241       const struct elf_backend_data *bed
11242         = get_elf_backend_data (s->owner);
11243       if (bed->link_order_error_handler)
11244         bed->link_order_error_handler
11245           /* xgettext:c-format */
11246           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
11247       return 0;
11248     }
11249   else
11250     {
11251       s = elf_shdrp[elfsec]->bfd_section;
11252       return s->output_section->vma + s->output_offset;
11253     }
11254 }
11255
11256
11257 /* Compare two sections based on the locations of the sections they are
11258    linked to.  Used by elf_fixup_link_order.  */
11259
11260 static int
11261 compare_link_order (const void * a, const void * b)
11262 {
11263   bfd_vma apos;
11264   bfd_vma bpos;
11265
11266   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
11267   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
11268   if (apos < bpos)
11269     return -1;
11270   return apos > bpos;
11271 }
11272
11273
11274 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
11275    order as their linked sections.  Returns false if this could not be done
11276    because an output section includes both ordered and unordered
11277    sections.  Ideally we'd do this in the linker proper.  */
11278
11279 static bfd_boolean
11280 elf_fixup_link_order (bfd *abfd, asection *o)
11281 {
11282   int seen_linkorder;
11283   int seen_other;
11284   int n;
11285   struct bfd_link_order *p;
11286   bfd *sub;
11287   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11288   unsigned elfsec;
11289   struct bfd_link_order **sections;
11290   asection *s, *other_sec, *linkorder_sec;
11291   bfd_vma offset;
11292
11293   other_sec = NULL;
11294   linkorder_sec = NULL;
11295   seen_other = 0;
11296   seen_linkorder = 0;
11297   for (p = o->map_head.link_order; p != NULL; p = p->next)
11298     {
11299       if (p->type == bfd_indirect_link_order)
11300         {
11301           s = p->u.indirect.section;
11302           sub = s->owner;
11303           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11304               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
11305               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
11306               && elfsec < elf_numsections (sub)
11307               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
11308               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
11309             {
11310               seen_linkorder++;
11311               linkorder_sec = s;
11312             }
11313           else
11314             {
11315               seen_other++;
11316               other_sec = s;
11317             }
11318         }
11319       else
11320         seen_other++;
11321
11322       if (seen_other && seen_linkorder)
11323         {
11324           if (other_sec && linkorder_sec)
11325             _bfd_error_handler
11326               /* xgettext:c-format */
11327               (_("%A has both ordered [`%A' in %B] "
11328                  "and unordered [`%A' in %B] sections"),
11329                o, linkorder_sec, linkorder_sec->owner,
11330                other_sec, other_sec->owner);
11331           else
11332             _bfd_error_handler
11333               (_("%A has both ordered and unordered sections"), o);
11334           bfd_set_error (bfd_error_bad_value);
11335           return FALSE;
11336         }
11337     }
11338
11339   if (!seen_linkorder)
11340     return TRUE;
11341
11342   sections = (struct bfd_link_order **)
11343     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
11344   if (sections == NULL)
11345     return FALSE;
11346   seen_linkorder = 0;
11347
11348   for (p = o->map_head.link_order; p != NULL; p = p->next)
11349     {
11350       sections[seen_linkorder++] = p;
11351     }
11352   /* Sort the input sections in the order of their linked section.  */
11353   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
11354          compare_link_order);
11355
11356   /* Change the offsets of the sections.  */
11357   offset = 0;
11358   for (n = 0; n < seen_linkorder; n++)
11359     {
11360       s = sections[n]->u.indirect.section;
11361       offset &= ~(bfd_vma) 0 << s->alignment_power;
11362       s->output_offset = offset / bfd_octets_per_byte (abfd);
11363       sections[n]->offset = offset;
11364       offset += sections[n]->size;
11365     }
11366
11367   free (sections);
11368   return TRUE;
11369 }
11370
11371 /* Generate an import library in INFO->implib_bfd from symbols in ABFD.
11372    Returns TRUE upon success, FALSE otherwise.  */
11373
11374 static bfd_boolean
11375 elf_output_implib (bfd *abfd, struct bfd_link_info *info)
11376 {
11377   bfd_boolean ret = FALSE;
11378   bfd *implib_bfd;
11379   const struct elf_backend_data *bed;
11380   flagword flags;
11381   enum bfd_architecture arch;
11382   unsigned int mach;
11383   asymbol **sympp = NULL;
11384   long symsize;
11385   long symcount;
11386   long src_count;
11387   elf_symbol_type *osymbuf;
11388
11389   implib_bfd = info->out_implib_bfd;
11390   bed = get_elf_backend_data (abfd);
11391
11392   if (!bfd_set_format (implib_bfd, bfd_object))
11393     return FALSE;
11394
11395   /* Use flag from executable but make it a relocatable object.  */
11396   flags = bfd_get_file_flags (abfd);
11397   flags &= ~HAS_RELOC;
11398   if (!bfd_set_start_address (implib_bfd, 0)
11399       || !bfd_set_file_flags (implib_bfd, flags & ~EXEC_P))
11400     return FALSE;
11401
11402   /* Copy architecture of output file to import library file.  */
11403   arch = bfd_get_arch (abfd);
11404   mach = bfd_get_mach (abfd);
11405   if (!bfd_set_arch_mach (implib_bfd, arch, mach)
11406       && (abfd->target_defaulted
11407           || bfd_get_arch (abfd) != bfd_get_arch (implib_bfd)))
11408     return FALSE;
11409
11410   /* Get symbol table size.  */
11411   symsize = bfd_get_symtab_upper_bound (abfd);
11412   if (symsize < 0)
11413     return FALSE;
11414
11415   /* Read in the symbol table.  */
11416   sympp = (asymbol **) xmalloc (symsize);
11417   symcount = bfd_canonicalize_symtab (abfd, sympp);
11418   if (symcount < 0)
11419     goto free_sym_buf;
11420
11421   /* Allow the BFD backend to copy any private header data it
11422      understands from the output BFD to the import library BFD.  */
11423   if (! bfd_copy_private_header_data (abfd, implib_bfd))
11424     goto free_sym_buf;
11425
11426   /* Filter symbols to appear in the import library.  */
11427   if (bed->elf_backend_filter_implib_symbols)
11428     symcount = bed->elf_backend_filter_implib_symbols (abfd, info, sympp,
11429                                                        symcount);
11430   else
11431     symcount = _bfd_elf_filter_global_symbols (abfd, info, sympp, symcount);
11432   if (symcount == 0)
11433     {
11434       bfd_set_error (bfd_error_no_symbols);
11435       _bfd_error_handler (_("%B: no symbol found for import library"),
11436                           implib_bfd);
11437       goto free_sym_buf;
11438     }
11439
11440
11441   /* Make symbols absolute.  */
11442   osymbuf = (elf_symbol_type *) bfd_alloc2 (implib_bfd, symcount,
11443                                             sizeof (*osymbuf));
11444   for (src_count = 0; src_count < symcount; src_count++)
11445     {
11446       memcpy (&osymbuf[src_count], (elf_symbol_type *) sympp[src_count],
11447               sizeof (*osymbuf));
11448       osymbuf[src_count].symbol.section = bfd_abs_section_ptr;
11449       osymbuf[src_count].internal_elf_sym.st_shndx = SHN_ABS;
11450       osymbuf[src_count].symbol.value += sympp[src_count]->section->vma;
11451       osymbuf[src_count].internal_elf_sym.st_value =
11452         osymbuf[src_count].symbol.value;
11453       sympp[src_count] = &osymbuf[src_count].symbol;
11454     }
11455
11456   bfd_set_symtab (implib_bfd, sympp, symcount);
11457
11458   /* Allow the BFD backend to copy any private data it understands
11459      from the output BFD to the import library BFD.  This is done last
11460      to permit the routine to look at the filtered symbol table.  */
11461   if (! bfd_copy_private_bfd_data (abfd, implib_bfd))
11462     goto free_sym_buf;
11463
11464   if (!bfd_close (implib_bfd))
11465     goto free_sym_buf;
11466
11467   ret = TRUE;
11468
11469 free_sym_buf:
11470   free (sympp);
11471   return ret;
11472 }
11473
11474 static void
11475 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
11476 {
11477   asection *o;
11478
11479   if (flinfo->symstrtab != NULL)
11480     _bfd_elf_strtab_free (flinfo->symstrtab);
11481   if (flinfo->contents != NULL)
11482     free (flinfo->contents);
11483   if (flinfo->external_relocs != NULL)
11484     free (flinfo->external_relocs);
11485   if (flinfo->internal_relocs != NULL)
11486     free (flinfo->internal_relocs);
11487   if (flinfo->external_syms != NULL)
11488     free (flinfo->external_syms);
11489   if (flinfo->locsym_shndx != NULL)
11490     free (flinfo->locsym_shndx);
11491   if (flinfo->internal_syms != NULL)
11492     free (flinfo->internal_syms);
11493   if (flinfo->indices != NULL)
11494     free (flinfo->indices);
11495   if (flinfo->sections != NULL)
11496     free (flinfo->sections);
11497   if (flinfo->symshndxbuf != NULL)
11498     free (flinfo->symshndxbuf);
11499   for (o = obfd->sections; o != NULL; o = o->next)
11500     {
11501       struct bfd_elf_section_data *esdo = elf_section_data (o);
11502       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11503         free (esdo->rel.hashes);
11504       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11505         free (esdo->rela.hashes);
11506     }
11507 }
11508
11509 /* Do the final step of an ELF link.  */
11510
11511 bfd_boolean
11512 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
11513 {
11514   bfd_boolean dynamic;
11515   bfd_boolean emit_relocs;
11516   bfd *dynobj;
11517   struct elf_final_link_info flinfo;
11518   asection *o;
11519   struct bfd_link_order *p;
11520   bfd *sub;
11521   bfd_size_type max_contents_size;
11522   bfd_size_type max_external_reloc_size;
11523   bfd_size_type max_internal_reloc_count;
11524   bfd_size_type max_sym_count;
11525   bfd_size_type max_sym_shndx_count;
11526   Elf_Internal_Sym elfsym;
11527   unsigned int i;
11528   Elf_Internal_Shdr *symtab_hdr;
11529   Elf_Internal_Shdr *symtab_shndx_hdr;
11530   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11531   struct elf_outext_info eoinfo;
11532   bfd_boolean merged;
11533   size_t relativecount = 0;
11534   asection *reldyn = 0;
11535   bfd_size_type amt;
11536   asection *attr_section = NULL;
11537   bfd_vma attr_size = 0;
11538   const char *std_attrs_section;
11539   struct elf_link_hash_table *htab = elf_hash_table (info);
11540
11541   if (!is_elf_hash_table (htab))
11542     return FALSE;
11543
11544   if (bfd_link_pic (info))
11545     abfd->flags |= DYNAMIC;
11546
11547   dynamic = htab->dynamic_sections_created;
11548   dynobj = htab->dynobj;
11549
11550   emit_relocs = (bfd_link_relocatable (info)
11551                  || info->emitrelocations);
11552
11553   flinfo.info = info;
11554   flinfo.output_bfd = abfd;
11555   flinfo.symstrtab = _bfd_elf_strtab_init ();
11556   if (flinfo.symstrtab == NULL)
11557     return FALSE;
11558
11559   if (! dynamic)
11560     {
11561       flinfo.hash_sec = NULL;
11562       flinfo.symver_sec = NULL;
11563     }
11564   else
11565     {
11566       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
11567       /* Note that dynsym_sec can be NULL (on VMS).  */
11568       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
11569       /* Note that it is OK if symver_sec is NULL.  */
11570     }
11571
11572   flinfo.contents = NULL;
11573   flinfo.external_relocs = NULL;
11574   flinfo.internal_relocs = NULL;
11575   flinfo.external_syms = NULL;
11576   flinfo.locsym_shndx = NULL;
11577   flinfo.internal_syms = NULL;
11578   flinfo.indices = NULL;
11579   flinfo.sections = NULL;
11580   flinfo.symshndxbuf = NULL;
11581   flinfo.filesym_count = 0;
11582
11583   /* The object attributes have been merged.  Remove the input
11584      sections from the link, and set the contents of the output
11585      secton.  */
11586   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
11587   for (o = abfd->sections; o != NULL; o = o->next)
11588     {
11589       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
11590           || strcmp (o->name, ".gnu.attributes") == 0)
11591         {
11592           for (p = o->map_head.link_order; p != NULL; p = p->next)
11593             {
11594               asection *input_section;
11595
11596               if (p->type != bfd_indirect_link_order)
11597                 continue;
11598               input_section = p->u.indirect.section;
11599               /* Hack: reset the SEC_HAS_CONTENTS flag so that
11600                  elf_link_input_bfd ignores this section.  */
11601               input_section->flags &= ~SEC_HAS_CONTENTS;
11602             }
11603
11604           attr_size = bfd_elf_obj_attr_size (abfd);
11605           if (attr_size)
11606             {
11607               bfd_set_section_size (abfd, o, attr_size);
11608               attr_section = o;
11609               /* Skip this section later on.  */
11610               o->map_head.link_order = NULL;
11611             }
11612           else
11613             o->flags |= SEC_EXCLUDE;
11614         }
11615     }
11616
11617   /* Count up the number of relocations we will output for each output
11618      section, so that we know the sizes of the reloc sections.  We
11619      also figure out some maximum sizes.  */
11620   max_contents_size = 0;
11621   max_external_reloc_size = 0;
11622   max_internal_reloc_count = 0;
11623   max_sym_count = 0;
11624   max_sym_shndx_count = 0;
11625   merged = FALSE;
11626   for (o = abfd->sections; o != NULL; o = o->next)
11627     {
11628       struct bfd_elf_section_data *esdo = elf_section_data (o);
11629       o->reloc_count = 0;
11630
11631       for (p = o->map_head.link_order; p != NULL; p = p->next)
11632         {
11633           unsigned int reloc_count = 0;
11634           unsigned int additional_reloc_count = 0;
11635           struct bfd_elf_section_data *esdi = NULL;
11636
11637           if (p->type == bfd_section_reloc_link_order
11638               || p->type == bfd_symbol_reloc_link_order)
11639             reloc_count = 1;
11640           else if (p->type == bfd_indirect_link_order)
11641             {
11642               asection *sec;
11643
11644               sec = p->u.indirect.section;
11645
11646               /* Mark all sections which are to be included in the
11647                  link.  This will normally be every section.  We need
11648                  to do this so that we can identify any sections which
11649                  the linker has decided to not include.  */
11650               sec->linker_mark = TRUE;
11651
11652               if (sec->flags & SEC_MERGE)
11653                 merged = TRUE;
11654
11655               if (sec->rawsize > max_contents_size)
11656                 max_contents_size = sec->rawsize;
11657               if (sec->size > max_contents_size)
11658                 max_contents_size = sec->size;
11659
11660               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
11661                   && (sec->owner->flags & DYNAMIC) == 0)
11662                 {
11663                   size_t sym_count;
11664
11665                   /* We are interested in just local symbols, not all
11666                      symbols.  */
11667                   if (elf_bad_symtab (sec->owner))
11668                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
11669                                  / bed->s->sizeof_sym);
11670                   else
11671                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
11672
11673                   if (sym_count > max_sym_count)
11674                     max_sym_count = sym_count;
11675
11676                   if (sym_count > max_sym_shndx_count
11677                       && elf_symtab_shndx_list (sec->owner) != NULL)
11678                     max_sym_shndx_count = sym_count;
11679
11680                   if (esdo->this_hdr.sh_type == SHT_REL
11681                       || esdo->this_hdr.sh_type == SHT_RELA)
11682                     /* Some backends use reloc_count in relocation sections
11683                        to count particular types of relocs.  Of course,
11684                        reloc sections themselves can't have relocations.  */
11685                     ;
11686                   else if (emit_relocs)
11687                     {
11688                       reloc_count = sec->reloc_count;
11689                       if (bed->elf_backend_count_additional_relocs)
11690                         {
11691                           int c;
11692                           c = (*bed->elf_backend_count_additional_relocs) (sec);
11693                           additional_reloc_count += c;
11694                         }
11695                     }
11696                   else if (bed->elf_backend_count_relocs)
11697                     reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
11698
11699                   esdi = elf_section_data (sec);
11700
11701                   if ((sec->flags & SEC_RELOC) != 0)
11702                     {
11703                       size_t ext_size = 0;
11704
11705                       if (esdi->rel.hdr != NULL)
11706                         ext_size = esdi->rel.hdr->sh_size;
11707                       if (esdi->rela.hdr != NULL)
11708                         ext_size += esdi->rela.hdr->sh_size;
11709
11710                       if (ext_size > max_external_reloc_size)
11711                         max_external_reloc_size = ext_size;
11712                       if (sec->reloc_count > max_internal_reloc_count)
11713                         max_internal_reloc_count = sec->reloc_count;
11714                     }
11715                 }
11716             }
11717
11718           if (reloc_count == 0)
11719             continue;
11720
11721           reloc_count += additional_reloc_count;
11722           o->reloc_count += reloc_count;
11723
11724           if (p->type == bfd_indirect_link_order && emit_relocs)
11725             {
11726               if (esdi->rel.hdr)
11727                 {
11728                   esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11729                   esdo->rel.count += additional_reloc_count;
11730                 }
11731               if (esdi->rela.hdr)
11732                 {
11733                   esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11734                   esdo->rela.count += additional_reloc_count;
11735                 }
11736             }
11737           else
11738             {
11739               if (o->use_rela_p)
11740                 esdo->rela.count += reloc_count;
11741               else
11742                 esdo->rel.count += reloc_count;
11743             }
11744         }
11745
11746       if (o->reloc_count > 0)
11747         o->flags |= SEC_RELOC;
11748       else
11749         {
11750           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11751              set it (this is probably a bug) and if it is set
11752              assign_section_numbers will create a reloc section.  */
11753           o->flags &=~ SEC_RELOC;
11754         }
11755
11756       /* If the SEC_ALLOC flag is not set, force the section VMA to
11757          zero.  This is done in elf_fake_sections as well, but forcing
11758          the VMA to 0 here will ensure that relocs against these
11759          sections are handled correctly.  */
11760       if ((o->flags & SEC_ALLOC) == 0
11761           && ! o->user_set_vma)
11762         o->vma = 0;
11763     }
11764
11765   if (! bfd_link_relocatable (info) && merged)
11766     elf_link_hash_traverse (htab, _bfd_elf_link_sec_merge_syms, abfd);
11767
11768   /* Figure out the file positions for everything but the symbol table
11769      and the relocs.  We set symcount to force assign_section_numbers
11770      to create a symbol table.  */
11771   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11772   BFD_ASSERT (! abfd->output_has_begun);
11773   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11774     goto error_return;
11775
11776   /* Set sizes, and assign file positions for reloc sections.  */
11777   for (o = abfd->sections; o != NULL; o = o->next)
11778     {
11779       struct bfd_elf_section_data *esdo = elf_section_data (o);
11780       if ((o->flags & SEC_RELOC) != 0)
11781         {
11782           if (esdo->rel.hdr
11783               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11784             goto error_return;
11785
11786           if (esdo->rela.hdr
11787               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11788             goto error_return;
11789         }
11790
11791       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
11792          to count upwards while actually outputting the relocations.  */
11793       esdo->rel.count = 0;
11794       esdo->rela.count = 0;
11795
11796       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
11797         {
11798           /* Cache the section contents so that they can be compressed
11799              later.  Use bfd_malloc since it will be freed by
11800              bfd_compress_section_contents.  */
11801           unsigned char *contents = esdo->this_hdr.contents;
11802           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
11803             abort ();
11804           contents
11805             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
11806           if (contents == NULL)
11807             goto error_return;
11808           esdo->this_hdr.contents = contents;
11809         }
11810     }
11811
11812   /* We have now assigned file positions for all the sections except
11813      .symtab, .strtab, and non-loaded reloc sections.  We start the
11814      .symtab section at the current file position, and write directly
11815      to it.  We build the .strtab section in memory.  */
11816   bfd_get_symcount (abfd) = 0;
11817   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11818   /* sh_name is set in prep_headers.  */
11819   symtab_hdr->sh_type = SHT_SYMTAB;
11820   /* sh_flags, sh_addr and sh_size all start off zero.  */
11821   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
11822   /* sh_link is set in assign_section_numbers.  */
11823   /* sh_info is set below.  */
11824   /* sh_offset is set just below.  */
11825   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
11826
11827   if (max_sym_count < 20)
11828     max_sym_count = 20;
11829   htab->strtabsize = max_sym_count;
11830   amt = max_sym_count * sizeof (struct elf_sym_strtab);
11831   htab->strtab = (struct elf_sym_strtab *) bfd_malloc (amt);
11832   if (htab->strtab == NULL)
11833     goto error_return;
11834   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
11835   flinfo.symshndxbuf
11836     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
11837        ? (Elf_External_Sym_Shndx *) -1 : NULL);
11838
11839   if (info->strip != strip_all || emit_relocs)
11840     {
11841       file_ptr off = elf_next_file_pos (abfd);
11842
11843       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
11844
11845       /* Note that at this point elf_next_file_pos (abfd) is
11846          incorrect.  We do not yet know the size of the .symtab section.
11847          We correct next_file_pos below, after we do know the size.  */
11848
11849       /* Start writing out the symbol table.  The first symbol is always a
11850          dummy symbol.  */
11851       elfsym.st_value = 0;
11852       elfsym.st_size = 0;
11853       elfsym.st_info = 0;
11854       elfsym.st_other = 0;
11855       elfsym.st_shndx = SHN_UNDEF;
11856       elfsym.st_target_internal = 0;
11857       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
11858                                      bfd_und_section_ptr, NULL) != 1)
11859         goto error_return;
11860
11861       /* Output a symbol for each section.  We output these even if we are
11862          discarding local symbols, since they are used for relocs.  These
11863          symbols have no names.  We store the index of each one in the
11864          index field of the section, so that we can find it again when
11865          outputting relocs.  */
11866
11867       elfsym.st_size = 0;
11868       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11869       elfsym.st_other = 0;
11870       elfsym.st_value = 0;
11871       elfsym.st_target_internal = 0;
11872       for (i = 1; i < elf_numsections (abfd); i++)
11873         {
11874           o = bfd_section_from_elf_index (abfd, i);
11875           if (o != NULL)
11876             {
11877               o->target_index = bfd_get_symcount (abfd);
11878               elfsym.st_shndx = i;
11879               if (!bfd_link_relocatable (info))
11880                 elfsym.st_value = o->vma;
11881               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
11882                                              NULL) != 1)
11883                 goto error_return;
11884             }
11885         }
11886     }
11887
11888   /* Allocate some memory to hold information read in from the input
11889      files.  */
11890   if (max_contents_size != 0)
11891     {
11892       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
11893       if (flinfo.contents == NULL)
11894         goto error_return;
11895     }
11896
11897   if (max_external_reloc_size != 0)
11898     {
11899       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
11900       if (flinfo.external_relocs == NULL)
11901         goto error_return;
11902     }
11903
11904   if (max_internal_reloc_count != 0)
11905     {
11906       amt = max_internal_reloc_count * sizeof (Elf_Internal_Rela);
11907       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
11908       if (flinfo.internal_relocs == NULL)
11909         goto error_return;
11910     }
11911
11912   if (max_sym_count != 0)
11913     {
11914       amt = max_sym_count * bed->s->sizeof_sym;
11915       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
11916       if (flinfo.external_syms == NULL)
11917         goto error_return;
11918
11919       amt = max_sym_count * sizeof (Elf_Internal_Sym);
11920       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
11921       if (flinfo.internal_syms == NULL)
11922         goto error_return;
11923
11924       amt = max_sym_count * sizeof (long);
11925       flinfo.indices = (long int *) bfd_malloc (amt);
11926       if (flinfo.indices == NULL)
11927         goto error_return;
11928
11929       amt = max_sym_count * sizeof (asection *);
11930       flinfo.sections = (asection **) bfd_malloc (amt);
11931       if (flinfo.sections == NULL)
11932         goto error_return;
11933     }
11934
11935   if (max_sym_shndx_count != 0)
11936     {
11937       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
11938       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
11939       if (flinfo.locsym_shndx == NULL)
11940         goto error_return;
11941     }
11942
11943   if (htab->tls_sec)
11944     {
11945       bfd_vma base, end = 0;
11946       asection *sec;
11947
11948       for (sec = htab->tls_sec;
11949            sec && (sec->flags & SEC_THREAD_LOCAL);
11950            sec = sec->next)
11951         {
11952           bfd_size_type size = sec->size;
11953
11954           if (size == 0
11955               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11956             {
11957               struct bfd_link_order *ord = sec->map_tail.link_order;
11958
11959               if (ord != NULL)
11960                 size = ord->offset + ord->size;
11961             }
11962           end = sec->vma + size;
11963         }
11964       base = htab->tls_sec->vma;
11965       /* Only align end of TLS section if static TLS doesn't have special
11966          alignment requirements.  */
11967       if (bed->static_tls_alignment == 1)
11968         end = align_power (end, htab->tls_sec->alignment_power);
11969       htab->tls_size = end - base;
11970     }
11971
11972   /* Reorder SHF_LINK_ORDER sections.  */
11973   for (o = abfd->sections; o != NULL; o = o->next)
11974     {
11975       if (!elf_fixup_link_order (abfd, o))
11976         return FALSE;
11977     }
11978
11979   if (!_bfd_elf_fixup_eh_frame_hdr (info))
11980     return FALSE;
11981
11982   /* Since ELF permits relocations to be against local symbols, we
11983      must have the local symbols available when we do the relocations.
11984      Since we would rather only read the local symbols once, and we
11985      would rather not keep them in memory, we handle all the
11986      relocations for a single input file at the same time.
11987
11988      Unfortunately, there is no way to know the total number of local
11989      symbols until we have seen all of them, and the local symbol
11990      indices precede the global symbol indices.  This means that when
11991      we are generating relocatable output, and we see a reloc against
11992      a global symbol, we can not know the symbol index until we have
11993      finished examining all the local symbols to see which ones we are
11994      going to output.  To deal with this, we keep the relocations in
11995      memory, and don't output them until the end of the link.  This is
11996      an unfortunate waste of memory, but I don't see a good way around
11997      it.  Fortunately, it only happens when performing a relocatable
11998      link, which is not the common case.  FIXME: If keep_memory is set
11999      we could write the relocs out and then read them again; I don't
12000      know how bad the memory loss will be.  */
12001
12002   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12003     sub->output_has_begun = FALSE;
12004   for (o = abfd->sections; o != NULL; o = o->next)
12005     {
12006       for (p = o->map_head.link_order; p != NULL; p = p->next)
12007         {
12008           if (p->type == bfd_indirect_link_order
12009               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
12010                   == bfd_target_elf_flavour)
12011               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
12012             {
12013               if (! sub->output_has_begun)
12014                 {
12015                   if (! elf_link_input_bfd (&flinfo, sub))
12016                     goto error_return;
12017                   sub->output_has_begun = TRUE;
12018                 }
12019             }
12020           else if (p->type == bfd_section_reloc_link_order
12021                    || p->type == bfd_symbol_reloc_link_order)
12022             {
12023               if (! elf_reloc_link_order (abfd, info, o, p))
12024                 goto error_return;
12025             }
12026           else
12027             {
12028               if (! _bfd_default_link_order (abfd, info, o, p))
12029                 {
12030                   if (p->type == bfd_indirect_link_order
12031                       && (bfd_get_flavour (sub)
12032                           == bfd_target_elf_flavour)
12033                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
12034                           != bed->s->elfclass))
12035                     {
12036                       const char *iclass, *oclass;
12037
12038                       switch (bed->s->elfclass)
12039                         {
12040                         case ELFCLASS64: oclass = "ELFCLASS64"; break;
12041                         case ELFCLASS32: oclass = "ELFCLASS32"; break;
12042                         case ELFCLASSNONE: oclass = "ELFCLASSNONE"; break;
12043                         default: abort ();
12044                         }
12045
12046                       switch (elf_elfheader (sub)->e_ident[EI_CLASS])
12047                         {
12048                         case ELFCLASS64: iclass = "ELFCLASS64"; break;
12049                         case ELFCLASS32: iclass = "ELFCLASS32"; break;
12050                         case ELFCLASSNONE: iclass = "ELFCLASSNONE"; break;
12051                         default: abort ();
12052                         }
12053
12054                       bfd_set_error (bfd_error_wrong_format);
12055                       _bfd_error_handler
12056                         /* xgettext:c-format */
12057                         (_("%B: file class %s incompatible with %s"),
12058                          sub, iclass, oclass);
12059                     }
12060
12061                   goto error_return;
12062                 }
12063             }
12064         }
12065     }
12066
12067   /* Free symbol buffer if needed.  */
12068   if (!info->reduce_memory_overheads)
12069     {
12070       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12071         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
12072             && elf_tdata (sub)->symbuf)
12073           {
12074             free (elf_tdata (sub)->symbuf);
12075             elf_tdata (sub)->symbuf = NULL;
12076           }
12077     }
12078
12079   /* Output any global symbols that got converted to local in a
12080      version script or due to symbol visibility.  We do this in a
12081      separate step since ELF requires all local symbols to appear
12082      prior to any global symbols.  FIXME: We should only do this if
12083      some global symbols were, in fact, converted to become local.
12084      FIXME: Will this work correctly with the Irix 5 linker?  */
12085   eoinfo.failed = FALSE;
12086   eoinfo.flinfo = &flinfo;
12087   eoinfo.localsyms = TRUE;
12088   eoinfo.file_sym_done = FALSE;
12089   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12090   if (eoinfo.failed)
12091     return FALSE;
12092
12093   /* If backend needs to output some local symbols not present in the hash
12094      table, do it now.  */
12095   if (bed->elf_backend_output_arch_local_syms
12096       && (info->strip != strip_all || emit_relocs))
12097     {
12098       typedef int (*out_sym_func)
12099         (void *, const char *, Elf_Internal_Sym *, asection *,
12100          struct elf_link_hash_entry *);
12101
12102       if (! ((*bed->elf_backend_output_arch_local_syms)
12103              (abfd, info, &flinfo,
12104               (out_sym_func) elf_link_output_symstrtab)))
12105         return FALSE;
12106     }
12107
12108   /* That wrote out all the local symbols.  Finish up the symbol table
12109      with the global symbols. Even if we want to strip everything we
12110      can, we still need to deal with those global symbols that got
12111      converted to local in a version script.  */
12112
12113   /* The sh_info field records the index of the first non local symbol.  */
12114   symtab_hdr->sh_info = bfd_get_symcount (abfd);
12115
12116   if (dynamic
12117       && htab->dynsym != NULL
12118       && htab->dynsym->output_section != bfd_abs_section_ptr)
12119     {
12120       Elf_Internal_Sym sym;
12121       bfd_byte *dynsym = htab->dynsym->contents;
12122
12123       o = htab->dynsym->output_section;
12124       elf_section_data (o)->this_hdr.sh_info = htab->local_dynsymcount + 1;
12125
12126       /* Write out the section symbols for the output sections.  */
12127       if (bfd_link_pic (info)
12128           || htab->is_relocatable_executable)
12129         {
12130           asection *s;
12131
12132           sym.st_size = 0;
12133           sym.st_name = 0;
12134           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
12135           sym.st_other = 0;
12136           sym.st_target_internal = 0;
12137
12138           for (s = abfd->sections; s != NULL; s = s->next)
12139             {
12140               int indx;
12141               bfd_byte *dest;
12142               long dynindx;
12143
12144               dynindx = elf_section_data (s)->dynindx;
12145               if (dynindx <= 0)
12146                 continue;
12147               indx = elf_section_data (s)->this_idx;
12148               BFD_ASSERT (indx > 0);
12149               sym.st_shndx = indx;
12150               if (! check_dynsym (abfd, &sym))
12151                 return FALSE;
12152               sym.st_value = s->vma;
12153               dest = dynsym + dynindx * bed->s->sizeof_sym;
12154               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12155             }
12156         }
12157
12158       /* Write out the local dynsyms.  */
12159       if (htab->dynlocal)
12160         {
12161           struct elf_link_local_dynamic_entry *e;
12162           for (e = htab->dynlocal; e ; e = e->next)
12163             {
12164               asection *s;
12165               bfd_byte *dest;
12166
12167               /* Copy the internal symbol and turn off visibility.
12168                  Note that we saved a word of storage and overwrote
12169                  the original st_name with the dynstr_index.  */
12170               sym = e->isym;
12171               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
12172
12173               s = bfd_section_from_elf_index (e->input_bfd,
12174                                               e->isym.st_shndx);
12175               if (s != NULL)
12176                 {
12177                   sym.st_shndx =
12178                     elf_section_data (s->output_section)->this_idx;
12179                   if (! check_dynsym (abfd, &sym))
12180                     return FALSE;
12181                   sym.st_value = (s->output_section->vma
12182                                   + s->output_offset
12183                                   + e->isym.st_value);
12184                 }
12185
12186               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
12187               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12188             }
12189         }
12190     }
12191
12192   /* We get the global symbols from the hash table.  */
12193   eoinfo.failed = FALSE;
12194   eoinfo.localsyms = FALSE;
12195   eoinfo.flinfo = &flinfo;
12196   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12197   if (eoinfo.failed)
12198     return FALSE;
12199
12200   /* If backend needs to output some symbols not present in the hash
12201      table, do it now.  */
12202   if (bed->elf_backend_output_arch_syms
12203       && (info->strip != strip_all || emit_relocs))
12204     {
12205       typedef int (*out_sym_func)
12206         (void *, const char *, Elf_Internal_Sym *, asection *,
12207          struct elf_link_hash_entry *);
12208
12209       if (! ((*bed->elf_backend_output_arch_syms)
12210              (abfd, info, &flinfo,
12211               (out_sym_func) elf_link_output_symstrtab)))
12212         return FALSE;
12213     }
12214
12215   /* Finalize the .strtab section.  */
12216   _bfd_elf_strtab_finalize (flinfo.symstrtab);
12217
12218   /* Swap out the .strtab section. */
12219   if (!elf_link_swap_symbols_out (&flinfo))
12220     return FALSE;
12221
12222   /* Now we know the size of the symtab section.  */
12223   if (bfd_get_symcount (abfd) > 0)
12224     {
12225       /* Finish up and write out the symbol string table (.strtab)
12226          section.  */
12227       Elf_Internal_Shdr *symstrtab_hdr = NULL;
12228       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
12229
12230       if (elf_symtab_shndx_list (abfd))
12231         {
12232           symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
12233
12234           if (symtab_shndx_hdr != NULL && symtab_shndx_hdr->sh_name != 0)
12235             {
12236               symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
12237               symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
12238               symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
12239               amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
12240               symtab_shndx_hdr->sh_size = amt;
12241
12242               off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
12243                                                                off, TRUE);
12244
12245               if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
12246                   || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
12247                 return FALSE;
12248             }
12249         }
12250
12251       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
12252       /* sh_name was set in prep_headers.  */
12253       symstrtab_hdr->sh_type = SHT_STRTAB;
12254       symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
12255       symstrtab_hdr->sh_addr = 0;
12256       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
12257       symstrtab_hdr->sh_entsize = 0;
12258       symstrtab_hdr->sh_link = 0;
12259       symstrtab_hdr->sh_info = 0;
12260       /* sh_offset is set just below.  */
12261       symstrtab_hdr->sh_addralign = 1;
12262
12263       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
12264                                                        off, TRUE);
12265       elf_next_file_pos (abfd) = off;
12266
12267       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
12268           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
12269         return FALSE;
12270     }
12271
12272   if (info->out_implib_bfd && !elf_output_implib (abfd, info))
12273     {
12274       _bfd_error_handler (_("%B: failed to generate import library"),
12275                           info->out_implib_bfd);
12276       return FALSE;
12277     }
12278
12279   /* Adjust the relocs to have the correct symbol indices.  */
12280   for (o = abfd->sections; o != NULL; o = o->next)
12281     {
12282       struct bfd_elf_section_data *esdo = elf_section_data (o);
12283       bfd_boolean sort;
12284
12285       if ((o->flags & SEC_RELOC) == 0)
12286         continue;
12287
12288       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
12289       if (esdo->rel.hdr != NULL
12290           && !elf_link_adjust_relocs (abfd, o, &esdo->rel, sort, info))
12291         return FALSE;
12292       if (esdo->rela.hdr != NULL
12293           && !elf_link_adjust_relocs (abfd, o, &esdo->rela, sort, info))
12294         return FALSE;
12295
12296       /* Set the reloc_count field to 0 to prevent write_relocs from
12297          trying to swap the relocs out itself.  */
12298       o->reloc_count = 0;
12299     }
12300
12301   if (dynamic && info->combreloc && dynobj != NULL)
12302     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
12303
12304   /* If we are linking against a dynamic object, or generating a
12305      shared library, finish up the dynamic linking information.  */
12306   if (dynamic)
12307     {
12308       bfd_byte *dyncon, *dynconend;
12309
12310       /* Fix up .dynamic entries.  */
12311       o = bfd_get_linker_section (dynobj, ".dynamic");
12312       BFD_ASSERT (o != NULL);
12313
12314       dyncon = o->contents;
12315       dynconend = o->contents + o->size;
12316       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12317         {
12318           Elf_Internal_Dyn dyn;
12319           const char *name;
12320           unsigned int type;
12321           bfd_size_type sh_size;
12322           bfd_vma sh_addr;
12323
12324           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12325
12326           switch (dyn.d_tag)
12327             {
12328             default:
12329               continue;
12330             case DT_NULL:
12331               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
12332                 {
12333                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
12334                     {
12335                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
12336                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
12337                     default: continue;
12338                     }
12339                   dyn.d_un.d_val = relativecount;
12340                   relativecount = 0;
12341                   break;
12342                 }
12343               continue;
12344
12345             case DT_INIT:
12346               name = info->init_function;
12347               goto get_sym;
12348             case DT_FINI:
12349               name = info->fini_function;
12350             get_sym:
12351               {
12352                 struct elf_link_hash_entry *h;
12353
12354                 h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
12355                 if (h != NULL
12356                     && (h->root.type == bfd_link_hash_defined
12357                         || h->root.type == bfd_link_hash_defweak))
12358                   {
12359                     dyn.d_un.d_ptr = h->root.u.def.value;
12360                     o = h->root.u.def.section;
12361                     if (o->output_section != NULL)
12362                       dyn.d_un.d_ptr += (o->output_section->vma
12363                                          + o->output_offset);
12364                     else
12365                       {
12366                         /* The symbol is imported from another shared
12367                            library and does not apply to this one.  */
12368                         dyn.d_un.d_ptr = 0;
12369                       }
12370                     break;
12371                   }
12372               }
12373               continue;
12374
12375             case DT_PREINIT_ARRAYSZ:
12376               name = ".preinit_array";
12377               goto get_out_size;
12378             case DT_INIT_ARRAYSZ:
12379               name = ".init_array";
12380               goto get_out_size;
12381             case DT_FINI_ARRAYSZ:
12382               name = ".fini_array";
12383             get_out_size:
12384               o = bfd_get_section_by_name (abfd, name);
12385               if (o == NULL)
12386                 {
12387                   _bfd_error_handler
12388                     (_("could not find section %s"), name);
12389                   goto error_return;
12390                 }
12391               if (o->size == 0)
12392                 _bfd_error_handler
12393                   (_("warning: %s section has zero size"), name);
12394               dyn.d_un.d_val = o->size;
12395               break;
12396
12397             case DT_PREINIT_ARRAY:
12398               name = ".preinit_array";
12399               goto get_out_vma;
12400             case DT_INIT_ARRAY:
12401               name = ".init_array";
12402               goto get_out_vma;
12403             case DT_FINI_ARRAY:
12404               name = ".fini_array";
12405             get_out_vma:
12406               o = bfd_get_section_by_name (abfd, name);
12407               goto do_vma;
12408
12409             case DT_HASH:
12410               name = ".hash";
12411               goto get_vma;
12412             case DT_GNU_HASH:
12413               name = ".gnu.hash";
12414               goto get_vma;
12415             case DT_STRTAB:
12416               name = ".dynstr";
12417               goto get_vma;
12418             case DT_SYMTAB:
12419               name = ".dynsym";
12420               goto get_vma;
12421             case DT_VERDEF:
12422               name = ".gnu.version_d";
12423               goto get_vma;
12424             case DT_VERNEED:
12425               name = ".gnu.version_r";
12426               goto get_vma;
12427             case DT_VERSYM:
12428               name = ".gnu.version";
12429             get_vma:
12430               o = bfd_get_linker_section (dynobj, name);
12431             do_vma:
12432               if (o == NULL || bfd_is_abs_section (o->output_section))
12433                 {
12434                   _bfd_error_handler
12435                     (_("could not find section %s"), name);
12436                   goto error_return;
12437                 }
12438               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
12439                 {
12440                   _bfd_error_handler
12441                     (_("warning: section '%s' is being made into a note"), name);
12442                   bfd_set_error (bfd_error_nonrepresentable_section);
12443                   goto error_return;
12444                 }
12445               dyn.d_un.d_ptr = o->output_section->vma + o->output_offset;
12446               break;
12447
12448             case DT_REL:
12449             case DT_RELA:
12450             case DT_RELSZ:
12451             case DT_RELASZ:
12452               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
12453                 type = SHT_REL;
12454               else
12455                 type = SHT_RELA;
12456               sh_size = 0;
12457               sh_addr = 0;
12458               for (i = 1; i < elf_numsections (abfd); i++)
12459                 {
12460                   Elf_Internal_Shdr *hdr;
12461
12462                   hdr = elf_elfsections (abfd)[i];
12463                   if (hdr->sh_type == type
12464                       && (hdr->sh_flags & SHF_ALLOC) != 0)
12465                     {
12466                       sh_size += hdr->sh_size;
12467                       if (sh_addr == 0
12468                           || sh_addr > hdr->sh_addr)
12469                         sh_addr = hdr->sh_addr;
12470                     }
12471                 }
12472
12473               if (bed->dtrel_excludes_plt && htab->srelplt != NULL)
12474                 {
12475                   /* Don't count procedure linkage table relocs in the
12476                      overall reloc count.  */
12477                   sh_size -= htab->srelplt->size;
12478                   if (sh_size == 0)
12479                     /* If the size is zero, make the address zero too.
12480                        This is to avoid a glibc bug.  If the backend
12481                        emits DT_RELA/DT_RELASZ even when DT_RELASZ is
12482                        zero, then we'll put DT_RELA at the end of
12483                        DT_JMPREL.  glibc will interpret the end of
12484                        DT_RELA matching the end of DT_JMPREL as the
12485                        case where DT_RELA includes DT_JMPREL, and for
12486                        LD_BIND_NOW will decide that processing DT_RELA
12487                        will process the PLT relocs too.  Net result:
12488                        No PLT relocs applied.  */
12489                     sh_addr = 0;
12490
12491                   /* If .rela.plt is the first .rela section, exclude
12492                      it from DT_RELA.  */
12493                   else if (sh_addr == (htab->srelplt->output_section->vma
12494                                        + htab->srelplt->output_offset))
12495                     sh_addr += htab->srelplt->size;
12496                 }
12497
12498               if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
12499                 dyn.d_un.d_val = sh_size;
12500               else
12501                 dyn.d_un.d_ptr = sh_addr;
12502               break;
12503             }
12504           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
12505         }
12506     }
12507
12508   /* If we have created any dynamic sections, then output them.  */
12509   if (dynobj != NULL)
12510     {
12511       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
12512         goto error_return;
12513
12514       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
12515       if (((info->warn_shared_textrel && bfd_link_pic (info))
12516            || info->error_textrel)
12517           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
12518         {
12519           bfd_byte *dyncon, *dynconend;
12520
12521           dyncon = o->contents;
12522           dynconend = o->contents + o->size;
12523           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12524             {
12525               Elf_Internal_Dyn dyn;
12526
12527               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12528
12529               if (dyn.d_tag == DT_TEXTREL)
12530                 {
12531                   if (info->error_textrel)
12532                     info->callbacks->einfo
12533                       (_("%P%X: read-only segment has dynamic relocations.\n"));
12534                   else
12535                     info->callbacks->einfo
12536                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
12537                   break;
12538                 }
12539             }
12540         }
12541
12542       for (o = dynobj->sections; o != NULL; o = o->next)
12543         {
12544           if ((o->flags & SEC_HAS_CONTENTS) == 0
12545               || o->size == 0
12546               || o->output_section == bfd_abs_section_ptr)
12547             continue;
12548           if ((o->flags & SEC_LINKER_CREATED) == 0)
12549             {
12550               /* At this point, we are only interested in sections
12551                  created by _bfd_elf_link_create_dynamic_sections.  */
12552               continue;
12553             }
12554           if (htab->stab_info.stabstr == o)
12555             continue;
12556           if (htab->eh_info.hdr_sec == o)
12557             continue;
12558           if (strcmp (o->name, ".dynstr") != 0)
12559             {
12560               if (! bfd_set_section_contents (abfd, o->output_section,
12561                                               o->contents,
12562                                               (file_ptr) o->output_offset
12563                                               * bfd_octets_per_byte (abfd),
12564                                               o->size))
12565                 goto error_return;
12566             }
12567           else
12568             {
12569               /* The contents of the .dynstr section are actually in a
12570                  stringtab.  */
12571               file_ptr off;
12572
12573               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
12574               if (bfd_seek (abfd, off, SEEK_SET) != 0
12575                   || !_bfd_elf_strtab_emit (abfd, htab->dynstr))
12576                 goto error_return;
12577             }
12578         }
12579     }
12580
12581   if (!info->resolve_section_groups)
12582     {
12583       bfd_boolean failed = FALSE;
12584
12585       BFD_ASSERT (bfd_link_relocatable (info));
12586       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
12587       if (failed)
12588         goto error_return;
12589     }
12590
12591   /* If we have optimized stabs strings, output them.  */
12592   if (htab->stab_info.stabstr != NULL)
12593     {
12594       if (!_bfd_write_stab_strings (abfd, &htab->stab_info))
12595         goto error_return;
12596     }
12597
12598   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
12599     goto error_return;
12600
12601   elf_final_link_free (abfd, &flinfo);
12602
12603   elf_linker (abfd) = TRUE;
12604
12605   if (attr_section)
12606     {
12607       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
12608       if (contents == NULL)
12609         return FALSE;   /* Bail out and fail.  */
12610       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
12611       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
12612       free (contents);
12613     }
12614
12615   return TRUE;
12616
12617  error_return:
12618   elf_final_link_free (abfd, &flinfo);
12619   return FALSE;
12620 }
12621 \f
12622 /* Initialize COOKIE for input bfd ABFD.  */
12623
12624 static bfd_boolean
12625 init_reloc_cookie (struct elf_reloc_cookie *cookie,
12626                    struct bfd_link_info *info, bfd *abfd)
12627 {
12628   Elf_Internal_Shdr *symtab_hdr;
12629   const struct elf_backend_data *bed;
12630
12631   bed = get_elf_backend_data (abfd);
12632   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12633
12634   cookie->abfd = abfd;
12635   cookie->sym_hashes = elf_sym_hashes (abfd);
12636   cookie->bad_symtab = elf_bad_symtab (abfd);
12637   if (cookie->bad_symtab)
12638     {
12639       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12640       cookie->extsymoff = 0;
12641     }
12642   else
12643     {
12644       cookie->locsymcount = symtab_hdr->sh_info;
12645       cookie->extsymoff = symtab_hdr->sh_info;
12646     }
12647
12648   if (bed->s->arch_size == 32)
12649     cookie->r_sym_shift = 8;
12650   else
12651     cookie->r_sym_shift = 32;
12652
12653   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
12654   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
12655     {
12656       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12657                                               cookie->locsymcount, 0,
12658                                               NULL, NULL, NULL);
12659       if (cookie->locsyms == NULL)
12660         {
12661           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
12662           return FALSE;
12663         }
12664       if (info->keep_memory)
12665         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
12666     }
12667   return TRUE;
12668 }
12669
12670 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
12671
12672 static void
12673 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
12674 {
12675   Elf_Internal_Shdr *symtab_hdr;
12676
12677   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12678   if (cookie->locsyms != NULL
12679       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
12680     free (cookie->locsyms);
12681 }
12682
12683 /* Initialize the relocation information in COOKIE for input section SEC
12684    of input bfd ABFD.  */
12685
12686 static bfd_boolean
12687 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12688                         struct bfd_link_info *info, bfd *abfd,
12689                         asection *sec)
12690 {
12691   if (sec->reloc_count == 0)
12692     {
12693       cookie->rels = NULL;
12694       cookie->relend = NULL;
12695     }
12696   else
12697     {
12698       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
12699                                                 info->keep_memory);
12700       if (cookie->rels == NULL)
12701         return FALSE;
12702       cookie->rel = cookie->rels;
12703       cookie->relend = cookie->rels + sec->reloc_count;
12704     }
12705   cookie->rel = cookie->rels;
12706   return TRUE;
12707 }
12708
12709 /* Free the memory allocated by init_reloc_cookie_rels,
12710    if appropriate.  */
12711
12712 static void
12713 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12714                         asection *sec)
12715 {
12716   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
12717     free (cookie->rels);
12718 }
12719
12720 /* Initialize the whole of COOKIE for input section SEC.  */
12721
12722 static bfd_boolean
12723 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12724                                struct bfd_link_info *info,
12725                                asection *sec)
12726 {
12727   if (!init_reloc_cookie (cookie, info, sec->owner))
12728     goto error1;
12729   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
12730     goto error2;
12731   return TRUE;
12732
12733  error2:
12734   fini_reloc_cookie (cookie, sec->owner);
12735  error1:
12736   return FALSE;
12737 }
12738
12739 /* Free the memory allocated by init_reloc_cookie_for_section,
12740    if appropriate.  */
12741
12742 static void
12743 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12744                                asection *sec)
12745 {
12746   fini_reloc_cookie_rels (cookie, sec);
12747   fini_reloc_cookie (cookie, sec->owner);
12748 }
12749 \f
12750 /* Garbage collect unused sections.  */
12751
12752 /* Default gc_mark_hook.  */
12753
12754 asection *
12755 _bfd_elf_gc_mark_hook (asection *sec,
12756                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12757                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12758                        struct elf_link_hash_entry *h,
12759                        Elf_Internal_Sym *sym)
12760 {
12761   if (h != NULL)
12762     {
12763       switch (h->root.type)
12764         {
12765         case bfd_link_hash_defined:
12766         case bfd_link_hash_defweak:
12767           return h->root.u.def.section;
12768
12769         case bfd_link_hash_common:
12770           return h->root.u.c.p->section;
12771
12772         default:
12773           break;
12774         }
12775     }
12776   else
12777     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12778
12779   return NULL;
12780 }
12781
12782 /* Return the global debug definition section.  */
12783
12784 static asection *
12785 elf_gc_mark_debug_section (asection *sec ATTRIBUTE_UNUSED,
12786                            struct bfd_link_info *info ATTRIBUTE_UNUSED,
12787                            Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12788                            struct elf_link_hash_entry *h,
12789                            Elf_Internal_Sym *sym ATTRIBUTE_UNUSED)
12790 {
12791   if (h != NULL
12792       && (h->root.type == bfd_link_hash_defined
12793           || h->root.type == bfd_link_hash_defweak)
12794       && (h->root.u.def.section->flags & SEC_DEBUGGING) != 0)
12795     return h->root.u.def.section;
12796
12797   return NULL;
12798 }
12799
12800 /* COOKIE->rel describes a relocation against section SEC, which is
12801    a section we've decided to keep.  Return the section that contains
12802    the relocation symbol, or NULL if no section contains it.  */
12803
12804 asection *
12805 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
12806                        elf_gc_mark_hook_fn gc_mark_hook,
12807                        struct elf_reloc_cookie *cookie,
12808                        bfd_boolean *start_stop)
12809 {
12810   unsigned long r_symndx;
12811   struct elf_link_hash_entry *h;
12812
12813   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
12814   if (r_symndx == STN_UNDEF)
12815     return NULL;
12816
12817   if (r_symndx >= cookie->locsymcount
12818       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12819     {
12820       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
12821       if (h == NULL)
12822         {
12823           info->callbacks->einfo (_("%F%P: corrupt input: %B\n"),
12824                                   sec->owner);
12825           return NULL;
12826         }
12827       while (h->root.type == bfd_link_hash_indirect
12828              || h->root.type == bfd_link_hash_warning)
12829         h = (struct elf_link_hash_entry *) h->root.u.i.link;
12830       h->mark = 1;
12831       /* If this symbol is weak and there is a non-weak definition, we
12832          keep the non-weak definition because many backends put
12833          dynamic reloc info on the non-weak definition for code
12834          handling copy relocs.  */
12835       if (h->is_weakalias)
12836         weakdef (h)->mark = 1;
12837
12838       if (start_stop != NULL)
12839         {
12840           /* To work around a glibc bug, mark XXX input sections
12841              when there is a reference to __start_XXX or __stop_XXX
12842              symbols.  */
12843           if (h->start_stop)
12844             {
12845               asection *s = h->u2.start_stop_section;
12846               *start_stop = !s->gc_mark;
12847               return s;
12848             }
12849         }
12850
12851       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
12852     }
12853
12854   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
12855                           &cookie->locsyms[r_symndx]);
12856 }
12857
12858 /* COOKIE->rel describes a relocation against section SEC, which is
12859    a section we've decided to keep.  Mark the section that contains
12860    the relocation symbol.  */
12861
12862 bfd_boolean
12863 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
12864                         asection *sec,
12865                         elf_gc_mark_hook_fn gc_mark_hook,
12866                         struct elf_reloc_cookie *cookie)
12867 {
12868   asection *rsec;
12869   bfd_boolean start_stop = FALSE;
12870
12871   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie, &start_stop);
12872   while (rsec != NULL)
12873     {
12874       if (!rsec->gc_mark)
12875         {
12876           if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
12877               || (rsec->owner->flags & DYNAMIC) != 0)
12878             rsec->gc_mark = 1;
12879           else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
12880             return FALSE;
12881         }
12882       if (!start_stop)
12883         break;
12884       rsec = bfd_get_next_section_by_name (rsec->owner, rsec);
12885     }
12886   return TRUE;
12887 }
12888
12889 /* The mark phase of garbage collection.  For a given section, mark
12890    it and any sections in this section's group, and all the sections
12891    which define symbols to which it refers.  */
12892
12893 bfd_boolean
12894 _bfd_elf_gc_mark (struct bfd_link_info *info,
12895                   asection *sec,
12896                   elf_gc_mark_hook_fn gc_mark_hook)
12897 {
12898   bfd_boolean ret;
12899   asection *group_sec, *eh_frame;
12900
12901   sec->gc_mark = 1;
12902
12903   /* Mark all the sections in the group.  */
12904   group_sec = elf_section_data (sec)->next_in_group;
12905   if (group_sec && !group_sec->gc_mark)
12906     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
12907       return FALSE;
12908
12909   /* Look through the section relocs.  */
12910   ret = TRUE;
12911   eh_frame = elf_eh_frame_section (sec->owner);
12912   if ((sec->flags & SEC_RELOC) != 0
12913       && sec->reloc_count > 0
12914       && sec != eh_frame)
12915     {
12916       struct elf_reloc_cookie cookie;
12917
12918       if (!init_reloc_cookie_for_section (&cookie, info, sec))
12919         ret = FALSE;
12920       else
12921         {
12922           for (; cookie.rel < cookie.relend; cookie.rel++)
12923             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
12924               {
12925                 ret = FALSE;
12926                 break;
12927               }
12928           fini_reloc_cookie_for_section (&cookie, sec);
12929         }
12930     }
12931
12932   if (ret && eh_frame && elf_fde_list (sec))
12933     {
12934       struct elf_reloc_cookie cookie;
12935
12936       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
12937         ret = FALSE;
12938       else
12939         {
12940           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
12941                                       gc_mark_hook, &cookie))
12942             ret = FALSE;
12943           fini_reloc_cookie_for_section (&cookie, eh_frame);
12944         }
12945     }
12946
12947   eh_frame = elf_section_eh_frame_entry (sec);
12948   if (ret && eh_frame && !eh_frame->gc_mark)
12949     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
12950       ret = FALSE;
12951
12952   return ret;
12953 }
12954
12955 /* Scan and mark sections in a special or debug section group.  */
12956
12957 static void
12958 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
12959 {
12960   /* Point to first section of section group.  */
12961   asection *ssec;
12962   /* Used to iterate the section group.  */
12963   asection *msec;
12964
12965   bfd_boolean is_special_grp = TRUE;
12966   bfd_boolean is_debug_grp = TRUE;
12967
12968   /* First scan to see if group contains any section other than debug
12969      and special section.  */
12970   ssec = msec = elf_next_in_group (grp);
12971   do
12972     {
12973       if ((msec->flags & SEC_DEBUGGING) == 0)
12974         is_debug_grp = FALSE;
12975
12976       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
12977         is_special_grp = FALSE;
12978
12979       msec = elf_next_in_group (msec);
12980     }
12981   while (msec != ssec);
12982
12983   /* If this is a pure debug section group or pure special section group,
12984      keep all sections in this group.  */
12985   if (is_debug_grp || is_special_grp)
12986     {
12987       do
12988         {
12989           msec->gc_mark = 1;
12990           msec = elf_next_in_group (msec);
12991         }
12992       while (msec != ssec);
12993     }
12994 }
12995
12996 /* Keep debug and special sections.  */
12997
12998 bfd_boolean
12999 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
13000                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
13001 {
13002   bfd *ibfd;
13003
13004   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13005     {
13006       asection *isec;
13007       bfd_boolean some_kept;
13008       bfd_boolean debug_frag_seen;
13009       bfd_boolean has_kept_debug_info;
13010
13011       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13012         continue;
13013       isec = ibfd->sections;
13014       if (isec == NULL || isec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13015         continue;
13016
13017       /* Ensure all linker created sections are kept,
13018          see if any other section is already marked,
13019          and note if we have any fragmented debug sections.  */
13020       debug_frag_seen = some_kept = has_kept_debug_info = FALSE;
13021       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13022         {
13023           if ((isec->flags & SEC_LINKER_CREATED) != 0)
13024             isec->gc_mark = 1;
13025           else if (isec->gc_mark
13026                    && (isec->flags & SEC_ALLOC) != 0
13027                    && elf_section_type (isec) != SHT_NOTE)
13028             some_kept = TRUE;
13029
13030           if (!debug_frag_seen
13031               && (isec->flags & SEC_DEBUGGING)
13032               && CONST_STRNEQ (isec->name, ".debug_line."))
13033             debug_frag_seen = TRUE;
13034         }
13035
13036       /* If no non-note alloc section in this file will be kept, then
13037          we can toss out the debug and special sections.  */
13038       if (!some_kept)
13039         continue;
13040
13041       /* Keep debug and special sections like .comment when they are
13042          not part of a group.  Also keep section groups that contain
13043          just debug sections or special sections.  */
13044       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13045         {
13046           if ((isec->flags & SEC_GROUP) != 0)
13047             _bfd_elf_gc_mark_debug_special_section_group (isec);
13048           else if (((isec->flags & SEC_DEBUGGING) != 0
13049                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
13050                    && elf_next_in_group (isec) == NULL)
13051             isec->gc_mark = 1;
13052           if (isec->gc_mark && (isec->flags & SEC_DEBUGGING) != 0)
13053             has_kept_debug_info = TRUE;
13054         }
13055
13056       /* Look for CODE sections which are going to be discarded,
13057          and find and discard any fragmented debug sections which
13058          are associated with that code section.  */
13059       if (debug_frag_seen)
13060         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13061           if ((isec->flags & SEC_CODE) != 0
13062               && isec->gc_mark == 0)
13063             {
13064               unsigned int ilen;
13065               asection *dsec;
13066
13067               ilen = strlen (isec->name);
13068
13069               /* Association is determined by the name of the debug
13070                  section containing the name of the code section as
13071                  a suffix.  For example .debug_line.text.foo is a
13072                  debug section associated with .text.foo.  */
13073               for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
13074                 {
13075                   unsigned int dlen;
13076
13077                   if (dsec->gc_mark == 0
13078                       || (dsec->flags & SEC_DEBUGGING) == 0)
13079                     continue;
13080
13081                   dlen = strlen (dsec->name);
13082
13083                   if (dlen > ilen
13084                       && strncmp (dsec->name + (dlen - ilen),
13085                                   isec->name, ilen) == 0)
13086                     dsec->gc_mark = 0;
13087                 }
13088           }
13089
13090       /* Mark debug sections referenced by kept debug sections.  */
13091       if (has_kept_debug_info)
13092         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13093           if (isec->gc_mark
13094               && (isec->flags & SEC_DEBUGGING) != 0)
13095             if (!_bfd_elf_gc_mark (info, isec,
13096                                    elf_gc_mark_debug_section))
13097               return FALSE;
13098     }
13099   return TRUE;
13100 }
13101
13102 static bfd_boolean
13103 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
13104 {
13105   bfd *sub;
13106   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13107
13108   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13109     {
13110       asection *o;
13111
13112       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13113           || elf_object_id (sub) != elf_hash_table_id (elf_hash_table (info))
13114           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13115         continue;
13116       o = sub->sections;
13117       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13118         continue;
13119
13120       for (o = sub->sections; o != NULL; o = o->next)
13121         {
13122           /* When any section in a section group is kept, we keep all
13123              sections in the section group.  If the first member of
13124              the section group is excluded, we will also exclude the
13125              group section.  */
13126           if (o->flags & SEC_GROUP)
13127             {
13128               asection *first = elf_next_in_group (o);
13129               o->gc_mark = first->gc_mark;
13130             }
13131
13132           if (o->gc_mark)
13133             continue;
13134
13135           /* Skip sweeping sections already excluded.  */
13136           if (o->flags & SEC_EXCLUDE)
13137             continue;
13138
13139           /* Since this is early in the link process, it is simple
13140              to remove a section from the output.  */
13141           o->flags |= SEC_EXCLUDE;
13142
13143           if (info->print_gc_sections && o->size != 0)
13144             /* xgettext:c-format */
13145             _bfd_error_handler (_("Removing unused section '%A' in file '%B'"),
13146                                 o, sub);
13147         }
13148     }
13149
13150   return TRUE;
13151 }
13152
13153 /* Propagate collected vtable information.  This is called through
13154    elf_link_hash_traverse.  */
13155
13156 static bfd_boolean
13157 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
13158 {
13159   /* Those that are not vtables.  */
13160   if (h->start_stop
13161       || h->u2.vtable == NULL
13162       || h->u2.vtable->parent == NULL)
13163     return TRUE;
13164
13165   /* Those vtables that do not have parents, we cannot merge.  */
13166   if (h->u2.vtable->parent == (struct elf_link_hash_entry *) -1)
13167     return TRUE;
13168
13169   /* If we've already been done, exit.  */
13170   if (h->u2.vtable->used && h->u2.vtable->used[-1])
13171     return TRUE;
13172
13173   /* Make sure the parent's table is up to date.  */
13174   elf_gc_propagate_vtable_entries_used (h->u2.vtable->parent, okp);
13175
13176   if (h->u2.vtable->used == NULL)
13177     {
13178       /* None of this table's entries were referenced.  Re-use the
13179          parent's table.  */
13180       h->u2.vtable->used = h->u2.vtable->parent->u2.vtable->used;
13181       h->u2.vtable->size = h->u2.vtable->parent->u2.vtable->size;
13182     }
13183   else
13184     {
13185       size_t n;
13186       bfd_boolean *cu, *pu;
13187
13188       /* Or the parent's entries into ours.  */
13189       cu = h->u2.vtable->used;
13190       cu[-1] = TRUE;
13191       pu = h->u2.vtable->parent->u2.vtable->used;
13192       if (pu != NULL)
13193         {
13194           const struct elf_backend_data *bed;
13195           unsigned int log_file_align;
13196
13197           bed = get_elf_backend_data (h->root.u.def.section->owner);
13198           log_file_align = bed->s->log_file_align;
13199           n = h->u2.vtable->parent->u2.vtable->size >> log_file_align;
13200           while (n--)
13201             {
13202               if (*pu)
13203                 *cu = TRUE;
13204               pu++;
13205               cu++;
13206             }
13207         }
13208     }
13209
13210   return TRUE;
13211 }
13212
13213 static bfd_boolean
13214 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
13215 {
13216   asection *sec;
13217   bfd_vma hstart, hend;
13218   Elf_Internal_Rela *relstart, *relend, *rel;
13219   const struct elf_backend_data *bed;
13220   unsigned int log_file_align;
13221
13222   /* Take care of both those symbols that do not describe vtables as
13223      well as those that are not loaded.  */
13224   if (h->start_stop
13225       || h->u2.vtable == NULL
13226       || h->u2.vtable->parent == NULL)
13227     return TRUE;
13228
13229   BFD_ASSERT (h->root.type == bfd_link_hash_defined
13230               || h->root.type == bfd_link_hash_defweak);
13231
13232   sec = h->root.u.def.section;
13233   hstart = h->root.u.def.value;
13234   hend = hstart + h->size;
13235
13236   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
13237   if (!relstart)
13238     return *(bfd_boolean *) okp = FALSE;
13239   bed = get_elf_backend_data (sec->owner);
13240   log_file_align = bed->s->log_file_align;
13241
13242   relend = relstart + sec->reloc_count;
13243
13244   for (rel = relstart; rel < relend; ++rel)
13245     if (rel->r_offset >= hstart && rel->r_offset < hend)
13246       {
13247         /* If the entry is in use, do nothing.  */
13248         if (h->u2.vtable->used
13249             && (rel->r_offset - hstart) < h->u2.vtable->size)
13250           {
13251             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
13252             if (h->u2.vtable->used[entry])
13253               continue;
13254           }
13255         /* Otherwise, kill it.  */
13256         rel->r_offset = rel->r_info = rel->r_addend = 0;
13257       }
13258
13259   return TRUE;
13260 }
13261
13262 /* Mark sections containing dynamically referenced symbols.  When
13263    building shared libraries, we must assume that any visible symbol is
13264    referenced.  */
13265
13266 bfd_boolean
13267 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
13268 {
13269   struct bfd_link_info *info = (struct bfd_link_info *) inf;
13270   struct bfd_elf_dynamic_list *d = info->dynamic_list;
13271
13272   if ((h->root.type == bfd_link_hash_defined
13273        || h->root.type == bfd_link_hash_defweak)
13274       && (h->ref_dynamic
13275           || ((h->def_regular || ELF_COMMON_DEF_P (h))
13276               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
13277               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
13278               && (!bfd_link_executable (info)
13279                   || info->gc_keep_exported
13280                   || info->export_dynamic
13281                   || (h->dynamic
13282                       && d != NULL
13283                       && (*d->match) (&d->head, NULL, h->root.root.string)))
13284               && (h->versioned >= versioned
13285                   || !bfd_hide_sym_by_version (info->version_info,
13286                                                h->root.root.string)))))
13287     h->root.u.def.section->flags |= SEC_KEEP;
13288
13289   return TRUE;
13290 }
13291
13292 /* Keep all sections containing symbols undefined on the command-line,
13293    and the section containing the entry symbol.  */
13294
13295 void
13296 _bfd_elf_gc_keep (struct bfd_link_info *info)
13297 {
13298   struct bfd_sym_chain *sym;
13299
13300   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
13301     {
13302       struct elf_link_hash_entry *h;
13303
13304       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
13305                                 FALSE, FALSE, FALSE);
13306
13307       if (h != NULL
13308           && (h->root.type == bfd_link_hash_defined
13309               || h->root.type == bfd_link_hash_defweak)
13310           && !bfd_is_abs_section (h->root.u.def.section)
13311           && !bfd_is_und_section (h->root.u.def.section))
13312         h->root.u.def.section->flags |= SEC_KEEP;
13313     }
13314 }
13315
13316 bfd_boolean
13317 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
13318                                 struct bfd_link_info *info)
13319 {
13320   bfd *ibfd = info->input_bfds;
13321
13322   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13323     {
13324       asection *sec;
13325       struct elf_reloc_cookie cookie;
13326
13327       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13328         continue;
13329       sec = ibfd->sections;
13330       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13331         continue;
13332
13333       if (!init_reloc_cookie (&cookie, info, ibfd))
13334         return FALSE;
13335
13336       for (sec = ibfd->sections; sec; sec = sec->next)
13337         {
13338           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
13339               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
13340             {
13341               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
13342               fini_reloc_cookie_rels (&cookie, sec);
13343             }
13344         }
13345     }
13346   return TRUE;
13347 }
13348
13349 /* Do mark and sweep of unused sections.  */
13350
13351 bfd_boolean
13352 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
13353 {
13354   bfd_boolean ok = TRUE;
13355   bfd *sub;
13356   elf_gc_mark_hook_fn gc_mark_hook;
13357   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13358   struct elf_link_hash_table *htab;
13359
13360   if (!bed->can_gc_sections
13361       || !is_elf_hash_table (info->hash))
13362     {
13363       _bfd_error_handler(_("Warning: gc-sections option ignored"));
13364       return TRUE;
13365     }
13366
13367   bed->gc_keep (info);
13368   htab = elf_hash_table (info);
13369
13370   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
13371      at the .eh_frame section if we can mark the FDEs individually.  */
13372   for (sub = info->input_bfds;
13373        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
13374        sub = sub->link.next)
13375     {
13376       asection *sec;
13377       struct elf_reloc_cookie cookie;
13378
13379       sec = sub->sections;
13380       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13381         continue;
13382       sec = bfd_get_section_by_name (sub, ".eh_frame");
13383       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
13384         {
13385           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
13386           if (elf_section_data (sec)->sec_info
13387               && (sec->flags & SEC_LINKER_CREATED) == 0)
13388             elf_eh_frame_section (sub) = sec;
13389           fini_reloc_cookie_for_section (&cookie, sec);
13390           sec = bfd_get_next_section_by_name (NULL, sec);
13391         }
13392     }
13393
13394   /* Apply transitive closure to the vtable entry usage info.  */
13395   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
13396   if (!ok)
13397     return FALSE;
13398
13399   /* Kill the vtable relocations that were not used.  */
13400   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
13401   if (!ok)
13402     return FALSE;
13403
13404   /* Mark dynamically referenced symbols.  */
13405   if (htab->dynamic_sections_created || info->gc_keep_exported)
13406     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
13407
13408   /* Grovel through relocs to find out who stays ...  */
13409   gc_mark_hook = bed->gc_mark_hook;
13410   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13411     {
13412       asection *o;
13413
13414       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13415           || elf_object_id (sub) != elf_hash_table_id (htab)
13416           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13417         continue;
13418
13419       o = sub->sections;
13420       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13421         continue;
13422
13423       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
13424          Also treat note sections as a root, if the section is not part
13425          of a group.  */
13426       for (o = sub->sections; o != NULL; o = o->next)
13427         if (!o->gc_mark
13428             && (o->flags & SEC_EXCLUDE) == 0
13429             && ((o->flags & SEC_KEEP) != 0
13430                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
13431                     && elf_next_in_group (o) == NULL )))
13432           {
13433             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
13434               return FALSE;
13435           }
13436     }
13437
13438   /* Allow the backend to mark additional target specific sections.  */
13439   bed->gc_mark_extra_sections (info, gc_mark_hook);
13440
13441   /* ... and mark SEC_EXCLUDE for those that go.  */
13442   return elf_gc_sweep (abfd, info);
13443 }
13444 \f
13445 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
13446
13447 bfd_boolean
13448 bfd_elf_gc_record_vtinherit (bfd *abfd,
13449                              asection *sec,
13450                              struct elf_link_hash_entry *h,
13451                              bfd_vma offset)
13452 {
13453   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
13454   struct elf_link_hash_entry **search, *child;
13455   size_t extsymcount;
13456   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13457
13458   /* The sh_info field of the symtab header tells us where the
13459      external symbols start.  We don't care about the local symbols at
13460      this point.  */
13461   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
13462   if (!elf_bad_symtab (abfd))
13463     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
13464
13465   sym_hashes = elf_sym_hashes (abfd);
13466   sym_hashes_end = sym_hashes + extsymcount;
13467
13468   /* Hunt down the child symbol, which is in this section at the same
13469      offset as the relocation.  */
13470   for (search = sym_hashes; search != sym_hashes_end; ++search)
13471     {
13472       if ((child = *search) != NULL
13473           && (child->root.type == bfd_link_hash_defined
13474               || child->root.type == bfd_link_hash_defweak)
13475           && child->root.u.def.section == sec
13476           && child->root.u.def.value == offset)
13477         goto win;
13478     }
13479
13480   /* xgettext:c-format */
13481   _bfd_error_handler (_("%B: %A+%#Lx: No symbol found for INHERIT"),
13482                       abfd, sec, offset);
13483   bfd_set_error (bfd_error_invalid_operation);
13484   return FALSE;
13485
13486  win:
13487   if (!child->u2.vtable)
13488     {
13489       child->u2.vtable = ((struct elf_link_virtual_table_entry *)
13490                           bfd_zalloc (abfd, sizeof (*child->u2.vtable)));
13491       if (!child->u2.vtable)
13492         return FALSE;
13493     }
13494   if (!h)
13495     {
13496       /* This *should* only be the absolute section.  It could potentially
13497          be that someone has defined a non-global vtable though, which
13498          would be bad.  It isn't worth paging in the local symbols to be
13499          sure though; that case should simply be handled by the assembler.  */
13500
13501       child->u2.vtable->parent = (struct elf_link_hash_entry *) -1;
13502     }
13503   else
13504     child->u2.vtable->parent = h;
13505
13506   return TRUE;
13507 }
13508
13509 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
13510
13511 bfd_boolean
13512 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
13513                            asection *sec ATTRIBUTE_UNUSED,
13514                            struct elf_link_hash_entry *h,
13515                            bfd_vma addend)
13516 {
13517   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13518   unsigned int log_file_align = bed->s->log_file_align;
13519
13520   if (!h->u2.vtable)
13521     {
13522       h->u2.vtable = ((struct elf_link_virtual_table_entry *)
13523                       bfd_zalloc (abfd, sizeof (*h->u2.vtable)));
13524       if (!h->u2.vtable)
13525         return FALSE;
13526     }
13527
13528   if (addend >= h->u2.vtable->size)
13529     {
13530       size_t size, bytes, file_align;
13531       bfd_boolean *ptr = h->u2.vtable->used;
13532
13533       /* While the symbol is undefined, we have to be prepared to handle
13534          a zero size.  */
13535       file_align = 1 << log_file_align;
13536       if (h->root.type == bfd_link_hash_undefined)
13537         size = addend + file_align;
13538       else
13539         {
13540           size = h->size;
13541           if (addend >= size)
13542             {
13543               /* Oops!  We've got a reference past the defined end of
13544                  the table.  This is probably a bug -- shall we warn?  */
13545               size = addend + file_align;
13546             }
13547         }
13548       size = (size + file_align - 1) & -file_align;
13549
13550       /* Allocate one extra entry for use as a "done" flag for the
13551          consolidation pass.  */
13552       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
13553
13554       if (ptr)
13555         {
13556           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
13557
13558           if (ptr != NULL)
13559             {
13560               size_t oldbytes;
13561
13562               oldbytes = (((h->u2.vtable->size >> log_file_align) + 1)
13563                           * sizeof (bfd_boolean));
13564               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
13565             }
13566         }
13567       else
13568         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
13569
13570       if (ptr == NULL)
13571         return FALSE;
13572
13573       /* And arrange for that done flag to be at index -1.  */
13574       h->u2.vtable->used = ptr + 1;
13575       h->u2.vtable->size = size;
13576     }
13577
13578   h->u2.vtable->used[addend >> log_file_align] = TRUE;
13579
13580   return TRUE;
13581 }
13582
13583 /* Map an ELF section header flag to its corresponding string.  */
13584 typedef struct
13585 {
13586   char *flag_name;
13587   flagword flag_value;
13588 } elf_flags_to_name_table;
13589
13590 static elf_flags_to_name_table elf_flags_to_names [] =
13591 {
13592   { "SHF_WRITE", SHF_WRITE },
13593   { "SHF_ALLOC", SHF_ALLOC },
13594   { "SHF_EXECINSTR", SHF_EXECINSTR },
13595   { "SHF_MERGE", SHF_MERGE },
13596   { "SHF_STRINGS", SHF_STRINGS },
13597   { "SHF_INFO_LINK", SHF_INFO_LINK},
13598   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
13599   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
13600   { "SHF_GROUP", SHF_GROUP },
13601   { "SHF_TLS", SHF_TLS },
13602   { "SHF_MASKOS", SHF_MASKOS },
13603   { "SHF_EXCLUDE", SHF_EXCLUDE },
13604 };
13605
13606 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
13607 bfd_boolean
13608 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
13609                               struct flag_info *flaginfo,
13610                               asection *section)
13611 {
13612   const bfd_vma sh_flags = elf_section_flags (section);
13613
13614   if (!flaginfo->flags_initialized)
13615     {
13616       bfd *obfd = info->output_bfd;
13617       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13618       struct flag_info_list *tf = flaginfo->flag_list;
13619       int with_hex = 0;
13620       int without_hex = 0;
13621
13622       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
13623         {
13624           unsigned i;
13625           flagword (*lookup) (char *);
13626
13627           lookup = bed->elf_backend_lookup_section_flags_hook;
13628           if (lookup != NULL)
13629             {
13630               flagword hexval = (*lookup) ((char *) tf->name);
13631
13632               if (hexval != 0)
13633                 {
13634                   if (tf->with == with_flags)
13635                     with_hex |= hexval;
13636                   else if (tf->with == without_flags)
13637                     without_hex |= hexval;
13638                   tf->valid = TRUE;
13639                   continue;
13640                 }
13641             }
13642           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
13643             {
13644               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
13645                 {
13646                   if (tf->with == with_flags)
13647                     with_hex |= elf_flags_to_names[i].flag_value;
13648                   else if (tf->with == without_flags)
13649                     without_hex |= elf_flags_to_names[i].flag_value;
13650                   tf->valid = TRUE;
13651                   break;
13652                 }
13653             }
13654           if (!tf->valid)
13655             {
13656               info->callbacks->einfo
13657                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
13658               return FALSE;
13659             }
13660         }
13661       flaginfo->flags_initialized = TRUE;
13662       flaginfo->only_with_flags |= with_hex;
13663       flaginfo->not_with_flags |= without_hex;
13664     }
13665
13666   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
13667     return FALSE;
13668
13669   if ((flaginfo->not_with_flags & sh_flags) != 0)
13670     return FALSE;
13671
13672   return TRUE;
13673 }
13674
13675 struct alloc_got_off_arg {
13676   bfd_vma gotoff;
13677   struct bfd_link_info *info;
13678 };
13679
13680 /* We need a special top-level link routine to convert got reference counts
13681    to real got offsets.  */
13682
13683 static bfd_boolean
13684 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
13685 {
13686   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
13687   bfd *obfd = gofarg->info->output_bfd;
13688   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13689
13690   if (h->got.refcount > 0)
13691     {
13692       h->got.offset = gofarg->gotoff;
13693       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
13694     }
13695   else
13696     h->got.offset = (bfd_vma) -1;
13697
13698   return TRUE;
13699 }
13700
13701 /* And an accompanying bit to work out final got entry offsets once
13702    we're done.  Should be called from final_link.  */
13703
13704 bfd_boolean
13705 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
13706                                         struct bfd_link_info *info)
13707 {
13708   bfd *i;
13709   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13710   bfd_vma gotoff;
13711   struct alloc_got_off_arg gofarg;
13712
13713   BFD_ASSERT (abfd == info->output_bfd);
13714
13715   if (! is_elf_hash_table (info->hash))
13716     return FALSE;
13717
13718   /* The GOT offset is relative to the .got section, but the GOT header is
13719      put into the .got.plt section, if the backend uses it.  */
13720   if (bed->want_got_plt)
13721     gotoff = 0;
13722   else
13723     gotoff = bed->got_header_size;
13724
13725   /* Do the local .got entries first.  */
13726   for (i = info->input_bfds; i; i = i->link.next)
13727     {
13728       bfd_signed_vma *local_got;
13729       size_t j, locsymcount;
13730       Elf_Internal_Shdr *symtab_hdr;
13731
13732       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13733         continue;
13734
13735       local_got = elf_local_got_refcounts (i);
13736       if (!local_got)
13737         continue;
13738
13739       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13740       if (elf_bad_symtab (i))
13741         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13742       else
13743         locsymcount = symtab_hdr->sh_info;
13744
13745       for (j = 0; j < locsymcount; ++j)
13746         {
13747           if (local_got[j] > 0)
13748             {
13749               local_got[j] = gotoff;
13750               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13751             }
13752           else
13753             local_got[j] = (bfd_vma) -1;
13754         }
13755     }
13756
13757   /* Then the global .got entries.  .plt refcounts are handled by
13758      adjust_dynamic_symbol  */
13759   gofarg.gotoff = gotoff;
13760   gofarg.info = info;
13761   elf_link_hash_traverse (elf_hash_table (info),
13762                           elf_gc_allocate_got_offsets,
13763                           &gofarg);
13764   return TRUE;
13765 }
13766
13767 /* Many folk need no more in the way of final link than this, once
13768    got entry reference counting is enabled.  */
13769
13770 bfd_boolean
13771 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
13772 {
13773   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
13774     return FALSE;
13775
13776   /* Invoke the regular ELF backend linker to do all the work.  */
13777   return bfd_elf_final_link (abfd, info);
13778 }
13779
13780 bfd_boolean
13781 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
13782 {
13783   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
13784
13785   if (rcookie->bad_symtab)
13786     rcookie->rel = rcookie->rels;
13787
13788   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
13789     {
13790       unsigned long r_symndx;
13791
13792       if (! rcookie->bad_symtab)
13793         if (rcookie->rel->r_offset > offset)
13794           return FALSE;
13795       if (rcookie->rel->r_offset != offset)
13796         continue;
13797
13798       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
13799       if (r_symndx == STN_UNDEF)
13800         return TRUE;
13801
13802       if (r_symndx >= rcookie->locsymcount
13803           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13804         {
13805           struct elf_link_hash_entry *h;
13806
13807           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
13808
13809           while (h->root.type == bfd_link_hash_indirect
13810                  || h->root.type == bfd_link_hash_warning)
13811             h = (struct elf_link_hash_entry *) h->root.u.i.link;
13812
13813           if ((h->root.type == bfd_link_hash_defined
13814                || h->root.type == bfd_link_hash_defweak)
13815               && (h->root.u.def.section->owner != rcookie->abfd
13816                   || h->root.u.def.section->kept_section != NULL
13817                   || discarded_section (h->root.u.def.section)))
13818             return TRUE;
13819         }
13820       else
13821         {
13822           /* It's not a relocation against a global symbol,
13823              but it could be a relocation against a local
13824              symbol for a discarded section.  */
13825           asection *isec;
13826           Elf_Internal_Sym *isym;
13827
13828           /* Need to: get the symbol; get the section.  */
13829           isym = &rcookie->locsyms[r_symndx];
13830           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
13831           if (isec != NULL
13832               && (isec->kept_section != NULL
13833                   || discarded_section (isec)))
13834             return TRUE;
13835         }
13836       return FALSE;
13837     }
13838   return FALSE;
13839 }
13840
13841 /* Discard unneeded references to discarded sections.
13842    Returns -1 on error, 1 if any section's size was changed, 0 if
13843    nothing changed.  This function assumes that the relocations are in
13844    sorted order, which is true for all known assemblers.  */
13845
13846 int
13847 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
13848 {
13849   struct elf_reloc_cookie cookie;
13850   asection *o;
13851   bfd *abfd;
13852   int changed = 0;
13853
13854   if (info->traditional_format
13855       || !is_elf_hash_table (info->hash))
13856     return 0;
13857
13858   o = bfd_get_section_by_name (output_bfd, ".stab");
13859   if (o != NULL)
13860     {
13861       asection *i;
13862
13863       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13864         {
13865           if (i->size == 0
13866               || i->reloc_count == 0
13867               || i->sec_info_type != SEC_INFO_TYPE_STABS)
13868             continue;
13869
13870           abfd = i->owner;
13871           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13872             continue;
13873
13874           if (!init_reloc_cookie_for_section (&cookie, info, i))
13875             return -1;
13876
13877           if (_bfd_discard_section_stabs (abfd, i,
13878                                           elf_section_data (i)->sec_info,
13879                                           bfd_elf_reloc_symbol_deleted_p,
13880                                           &cookie))
13881             changed = 1;
13882
13883           fini_reloc_cookie_for_section (&cookie, i);
13884         }
13885     }
13886
13887   o = NULL;
13888   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
13889     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
13890   if (o != NULL)
13891     {
13892       asection *i;
13893       int eh_changed = 0;
13894       unsigned int eh_alignment;
13895
13896       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13897         {
13898           if (i->size == 0)
13899             continue;
13900
13901           abfd = i->owner;
13902           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13903             continue;
13904
13905           if (!init_reloc_cookie_for_section (&cookie, info, i))
13906             return -1;
13907
13908           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
13909           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
13910                                                  bfd_elf_reloc_symbol_deleted_p,
13911                                                  &cookie))
13912             {
13913               eh_changed = 1;
13914               if (i->size != i->rawsize)
13915                 changed = 1;
13916             }
13917
13918           fini_reloc_cookie_for_section (&cookie, i);
13919         }
13920
13921       eh_alignment = 1 << o->alignment_power;
13922       /* Skip over zero terminator, and prevent empty sections from
13923          adding alignment padding at the end.  */
13924       for (i = o->map_tail.s; i != NULL; i = i->map_tail.s)
13925         if (i->size == 0)
13926           i->flags |= SEC_EXCLUDE;
13927         else if (i->size > 4)
13928           break;
13929       /* The last non-empty eh_frame section doesn't need padding.  */
13930       if (i != NULL)
13931         i = i->map_tail.s;
13932       /* Any prior sections must pad the last FDE out to the output
13933          section alignment.  Otherwise we might have zero padding
13934          between sections, which would be seen as a terminator.  */
13935       for (; i != NULL; i = i->map_tail.s)
13936         if (i->size == 4)
13937           /* All but the last zero terminator should have been removed.  */
13938           BFD_FAIL ();
13939         else
13940           {
13941             bfd_size_type size
13942               = (i->size + eh_alignment - 1) & -eh_alignment;
13943             if (i->size != size)
13944               {
13945                 i->size = size;
13946                 changed = 1;
13947                 eh_changed = 1;
13948               }
13949           }
13950       if (eh_changed)
13951         elf_link_hash_traverse (elf_hash_table (info),
13952                                 _bfd_elf_adjust_eh_frame_global_symbol, NULL);
13953     }
13954
13955   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
13956     {
13957       const struct elf_backend_data *bed;
13958       asection *s;
13959
13960       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13961         continue;
13962       s = abfd->sections;
13963       if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13964         continue;
13965
13966       bed = get_elf_backend_data (abfd);
13967
13968       if (bed->elf_backend_discard_info != NULL)
13969         {
13970           if (!init_reloc_cookie (&cookie, info, abfd))
13971             return -1;
13972
13973           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
13974             changed = 1;
13975
13976           fini_reloc_cookie (&cookie, abfd);
13977         }
13978     }
13979
13980   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
13981     _bfd_elf_end_eh_frame_parsing (info);
13982
13983   if (info->eh_frame_hdr_type
13984       && !bfd_link_relocatable (info)
13985       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
13986     changed = 1;
13987
13988   return changed;
13989 }
13990
13991 bfd_boolean
13992 _bfd_elf_section_already_linked (bfd *abfd,
13993                                  asection *sec,
13994                                  struct bfd_link_info *info)
13995 {
13996   flagword flags;
13997   const char *name, *key;
13998   struct bfd_section_already_linked *l;
13999   struct bfd_section_already_linked_hash_entry *already_linked_list;
14000
14001   if (sec->output_section == bfd_abs_section_ptr)
14002     return FALSE;
14003
14004   flags = sec->flags;
14005
14006   /* Return if it isn't a linkonce section.  A comdat group section
14007      also has SEC_LINK_ONCE set.  */
14008   if ((flags & SEC_LINK_ONCE) == 0)
14009     return FALSE;
14010
14011   /* Don't put group member sections on our list of already linked
14012      sections.  They are handled as a group via their group section.  */
14013   if (elf_sec_group (sec) != NULL)
14014     return FALSE;
14015
14016   /* For a SHT_GROUP section, use the group signature as the key.  */
14017   name = sec->name;
14018   if ((flags & SEC_GROUP) != 0
14019       && elf_next_in_group (sec) != NULL
14020       && elf_group_name (elf_next_in_group (sec)) != NULL)
14021     key = elf_group_name (elf_next_in_group (sec));
14022   else
14023     {
14024       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
14025       if (CONST_STRNEQ (name, ".gnu.linkonce.")
14026           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
14027         key++;
14028       else
14029         /* Must be a user linkonce section that doesn't follow gcc's
14030            naming convention.  In this case we won't be matching
14031            single member groups.  */
14032         key = name;
14033     }
14034
14035   already_linked_list = bfd_section_already_linked_table_lookup (key);
14036
14037   for (l = already_linked_list->entry; l != NULL; l = l->next)
14038     {
14039       /* We may have 2 different types of sections on the list: group
14040          sections with a signature of <key> (<key> is some string),
14041          and linkonce sections named .gnu.linkonce.<type>.<key>.
14042          Match like sections.  LTO plugin sections are an exception.
14043          They are always named .gnu.linkonce.t.<key> and match either
14044          type of section.  */
14045       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
14046            && ((flags & SEC_GROUP) != 0
14047                || strcmp (name, l->sec->name) == 0))
14048           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
14049         {
14050           /* The section has already been linked.  See if we should
14051              issue a warning.  */
14052           if (!_bfd_handle_already_linked (sec, l, info))
14053             return FALSE;
14054
14055           if (flags & SEC_GROUP)
14056             {
14057               asection *first = elf_next_in_group (sec);
14058               asection *s = first;
14059
14060               while (s != NULL)
14061                 {
14062                   s->output_section = bfd_abs_section_ptr;
14063                   /* Record which group discards it.  */
14064                   s->kept_section = l->sec;
14065                   s = elf_next_in_group (s);
14066                   /* These lists are circular.  */
14067                   if (s == first)
14068                     break;
14069                 }
14070             }
14071
14072           return TRUE;
14073         }
14074     }
14075
14076   /* A single member comdat group section may be discarded by a
14077      linkonce section and vice versa.  */
14078   if ((flags & SEC_GROUP) != 0)
14079     {
14080       asection *first = elf_next_in_group (sec);
14081
14082       if (first != NULL && elf_next_in_group (first) == first)
14083         /* Check this single member group against linkonce sections.  */
14084         for (l = already_linked_list->entry; l != NULL; l = l->next)
14085           if ((l->sec->flags & SEC_GROUP) == 0
14086               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
14087             {
14088               first->output_section = bfd_abs_section_ptr;
14089               first->kept_section = l->sec;
14090               sec->output_section = bfd_abs_section_ptr;
14091               break;
14092             }
14093     }
14094   else
14095     /* Check this linkonce section against single member groups.  */
14096     for (l = already_linked_list->entry; l != NULL; l = l->next)
14097       if (l->sec->flags & SEC_GROUP)
14098         {
14099           asection *first = elf_next_in_group (l->sec);
14100
14101           if (first != NULL
14102               && elf_next_in_group (first) == first
14103               && bfd_elf_match_symbols_in_sections (first, sec, info))
14104             {
14105               sec->output_section = bfd_abs_section_ptr;
14106               sec->kept_section = first;
14107               break;
14108             }
14109         }
14110
14111   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
14112      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
14113      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
14114      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
14115      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
14116      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
14117      `.gnu.linkonce.t.F' section from a different bfd not requiring any
14118      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
14119      The reverse order cannot happen as there is never a bfd with only the
14120      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
14121      matter as here were are looking only for cross-bfd sections.  */
14122
14123   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
14124     for (l = already_linked_list->entry; l != NULL; l = l->next)
14125       if ((l->sec->flags & SEC_GROUP) == 0
14126           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
14127         {
14128           if (abfd != l->sec->owner)
14129             sec->output_section = bfd_abs_section_ptr;
14130           break;
14131         }
14132
14133   /* This is the first section with this name.  Record it.  */
14134   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
14135     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
14136   return sec->output_section == bfd_abs_section_ptr;
14137 }
14138
14139 bfd_boolean
14140 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
14141 {
14142   return sym->st_shndx == SHN_COMMON;
14143 }
14144
14145 unsigned int
14146 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
14147 {
14148   return SHN_COMMON;
14149 }
14150
14151 asection *
14152 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
14153 {
14154   return bfd_com_section_ptr;
14155 }
14156
14157 bfd_vma
14158 _bfd_elf_default_got_elt_size (bfd *abfd,
14159                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
14160                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
14161                                bfd *ibfd ATTRIBUTE_UNUSED,
14162                                unsigned long symndx ATTRIBUTE_UNUSED)
14163 {
14164   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14165   return bed->s->arch_size / 8;
14166 }
14167
14168 /* Routines to support the creation of dynamic relocs.  */
14169
14170 /* Returns the name of the dynamic reloc section associated with SEC.  */
14171
14172 static const char *
14173 get_dynamic_reloc_section_name (bfd *       abfd,
14174                                 asection *  sec,
14175                                 bfd_boolean is_rela)
14176 {
14177   char *name;
14178   const char *old_name = bfd_get_section_name (NULL, sec);
14179   const char *prefix = is_rela ? ".rela" : ".rel";
14180
14181   if (old_name == NULL)
14182     return NULL;
14183
14184   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
14185   sprintf (name, "%s%s", prefix, old_name);
14186
14187   return name;
14188 }
14189
14190 /* Returns the dynamic reloc section associated with SEC.
14191    If necessary compute the name of the dynamic reloc section based
14192    on SEC's name (looked up in ABFD's string table) and the setting
14193    of IS_RELA.  */
14194
14195 asection *
14196 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
14197                                     asection *  sec,
14198                                     bfd_boolean is_rela)
14199 {
14200   asection * reloc_sec = elf_section_data (sec)->sreloc;
14201
14202   if (reloc_sec == NULL)
14203     {
14204       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14205
14206       if (name != NULL)
14207         {
14208           reloc_sec = bfd_get_linker_section (abfd, name);
14209
14210           if (reloc_sec != NULL)
14211             elf_section_data (sec)->sreloc = reloc_sec;
14212         }
14213     }
14214
14215   return reloc_sec;
14216 }
14217
14218 /* Returns the dynamic reloc section associated with SEC.  If the
14219    section does not exist it is created and attached to the DYNOBJ
14220    bfd and stored in the SRELOC field of SEC's elf_section_data
14221    structure.
14222
14223    ALIGNMENT is the alignment for the newly created section and
14224    IS_RELA defines whether the name should be .rela.<SEC's name>
14225    or .rel.<SEC's name>.  The section name is looked up in the
14226    string table associated with ABFD.  */
14227
14228 asection *
14229 _bfd_elf_make_dynamic_reloc_section (asection *sec,
14230                                      bfd *dynobj,
14231                                      unsigned int alignment,
14232                                      bfd *abfd,
14233                                      bfd_boolean is_rela)
14234 {
14235   asection * reloc_sec = elf_section_data (sec)->sreloc;
14236
14237   if (reloc_sec == NULL)
14238     {
14239       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14240
14241       if (name == NULL)
14242         return NULL;
14243
14244       reloc_sec = bfd_get_linker_section (dynobj, name);
14245
14246       if (reloc_sec == NULL)
14247         {
14248           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
14249                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
14250           if ((sec->flags & SEC_ALLOC) != 0)
14251             flags |= SEC_ALLOC | SEC_LOAD;
14252
14253           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
14254           if (reloc_sec != NULL)
14255             {
14256               /* _bfd_elf_get_sec_type_attr chooses a section type by
14257                  name.  Override as it may be wrong, eg. for a user
14258                  section named "auto" we'll get ".relauto" which is
14259                  seen to be a .rela section.  */
14260               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
14261               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
14262                 reloc_sec = NULL;
14263             }
14264         }
14265
14266       elf_section_data (sec)->sreloc = reloc_sec;
14267     }
14268
14269   return reloc_sec;
14270 }
14271
14272 /* Copy the ELF symbol type and other attributes for a linker script
14273    assignment from HSRC to HDEST.  Generally this should be treated as
14274    if we found a strong non-dynamic definition for HDEST (except that
14275    ld ignores multiple definition errors).  */
14276 void
14277 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
14278                                      struct bfd_link_hash_entry *hdest,
14279                                      struct bfd_link_hash_entry *hsrc)
14280 {
14281   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
14282   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
14283   Elf_Internal_Sym isym;
14284
14285   ehdest->type = ehsrc->type;
14286   ehdest->target_internal = ehsrc->target_internal;
14287
14288   isym.st_other = ehsrc->other;
14289   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
14290 }
14291
14292 /* Append a RELA relocation REL to section S in BFD.  */
14293
14294 void
14295 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14296 {
14297   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14298   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
14299   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
14300   bed->s->swap_reloca_out (abfd, rel, loc);
14301 }
14302
14303 /* Append a REL relocation REL to section S in BFD.  */
14304
14305 void
14306 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14307 {
14308   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14309   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
14310   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
14311   bed->s->swap_reloc_out (abfd, rel, loc);
14312 }
14313
14314 /* Define __start, __stop, .startof. or .sizeof. symbol.  */
14315
14316 struct bfd_link_hash_entry *
14317 bfd_elf_define_start_stop (struct bfd_link_info *info,
14318                            const char *symbol, asection *sec)
14319 {
14320   struct elf_link_hash_entry *h;
14321
14322   h = elf_link_hash_lookup (elf_hash_table (info), symbol,
14323                             FALSE, FALSE, TRUE);
14324   if (h != NULL
14325       && (h->root.type == bfd_link_hash_undefined
14326           || h->root.type == bfd_link_hash_undefweak
14327           || (h->ref_regular && !h->def_regular)))
14328     {
14329       h->root.type = bfd_link_hash_defined;
14330       h->root.u.def.section = sec;
14331       h->root.u.def.value = 0;
14332       h->def_regular = 1;
14333       h->def_dynamic = 0;
14334       h->start_stop = 1;
14335       h->u2.start_stop_section = sec;
14336       if (symbol[0] == '.')
14337         {
14338           /* .startof. and .sizeof. symbols are local.  */
14339           const struct elf_backend_data *bed;
14340           bed = get_elf_backend_data (info->output_bfd);
14341           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
14342         }
14343       else if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
14344         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_PROTECTED;
14345       return &h->root;
14346     }
14347   return NULL;
14348 }