ld: Set non_ir_ref_regular on symbols referenced in regular objects
[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      Do this before setting *type_change_ok or *size_change_ok so that
1475      we warn properly when dynamic library symbols are overridden.  */
1476
1477   if (newdef && !newdyn && olddyn)
1478     newweak = FALSE;
1479   if (olddef && newdyn)
1480     oldweak = FALSE;
1481
1482   /* Allow changes between different types of function symbol.  */
1483   if (newfunc && oldfunc)
1484     *type_change_ok = TRUE;
1485
1486   /* It's OK to change the type if either the existing symbol or the
1487      new symbol is weak.  A type change is also OK if the old symbol
1488      is undefined and the new symbol is defined.  */
1489
1490   if (oldweak
1491       || newweak
1492       || (newdef
1493           && h->root.type == bfd_link_hash_undefined))
1494     *type_change_ok = TRUE;
1495
1496   /* It's OK to change the size if either the existing symbol or the
1497      new symbol is weak, or if the old symbol is undefined.  */
1498
1499   if (*type_change_ok
1500       || h->root.type == bfd_link_hash_undefined)
1501     *size_change_ok = TRUE;
1502
1503   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1504      symbol, respectively, appears to be a common symbol in a dynamic
1505      object.  If a symbol appears in an uninitialized section, and is
1506      not weak, and is not a function, then it may be a common symbol
1507      which was resolved when the dynamic object was created.  We want
1508      to treat such symbols specially, because they raise special
1509      considerations when setting the symbol size: if the symbol
1510      appears as a common symbol in a regular object, and the size in
1511      the regular object is larger, we must make sure that we use the
1512      larger size.  This problematic case can always be avoided in C,
1513      but it must be handled correctly when using Fortran shared
1514      libraries.
1515
1516      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1517      likewise for OLDDYNCOMMON and OLDDEF.
1518
1519      Note that this test is just a heuristic, and that it is quite
1520      possible to have an uninitialized symbol in a shared object which
1521      is really a definition, rather than a common symbol.  This could
1522      lead to some minor confusion when the symbol really is a common
1523      symbol in some regular object.  However, I think it will be
1524      harmless.  */
1525
1526   if (newdyn
1527       && newdef
1528       && !newweak
1529       && (sec->flags & SEC_ALLOC) != 0
1530       && (sec->flags & SEC_LOAD) == 0
1531       && sym->st_size > 0
1532       && !newfunc)
1533     newdyncommon = TRUE;
1534   else
1535     newdyncommon = FALSE;
1536
1537   if (olddyn
1538       && olddef
1539       && h->root.type == bfd_link_hash_defined
1540       && h->def_dynamic
1541       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1542       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1543       && h->size > 0
1544       && !oldfunc)
1545     olddyncommon = TRUE;
1546   else
1547     olddyncommon = FALSE;
1548
1549   /* We now know everything about the old and new symbols.  We ask the
1550      backend to check if we can merge them.  */
1551   if (bed->merge_symbol != NULL)
1552     {
1553       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1554         return FALSE;
1555       sec = *psec;
1556     }
1557
1558   /* There are multiple definitions of a normal symbol.  Skip the
1559      default symbol as well as definition from an IR object.  */
1560   if (olddef && !olddyn && !oldweak && newdef && !newdyn && !newweak
1561       && !default_sym && h->def_regular
1562       && !(oldbfd != NULL
1563            && (oldbfd->flags & BFD_PLUGIN) != 0
1564            && (abfd->flags & BFD_PLUGIN) == 0))
1565     {
1566       /* Handle a multiple definition.  */
1567       (*info->callbacks->multiple_definition) (info, &h->root,
1568                                                abfd, sec, *pvalue);
1569       *skip = TRUE;
1570       return TRUE;
1571     }
1572
1573   /* If both the old and the new symbols look like common symbols in a
1574      dynamic object, set the size of the symbol to the larger of the
1575      two.  */
1576
1577   if (olddyncommon
1578       && newdyncommon
1579       && sym->st_size != h->size)
1580     {
1581       /* Since we think we have two common symbols, issue a multiple
1582          common warning if desired.  Note that we only warn if the
1583          size is different.  If the size is the same, we simply let
1584          the old symbol override the new one as normally happens with
1585          symbols defined in dynamic objects.  */
1586
1587       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1588                                            bfd_link_hash_common, sym->st_size);
1589       if (sym->st_size > h->size)
1590         h->size = sym->st_size;
1591
1592       *size_change_ok = TRUE;
1593     }
1594
1595   /* If we are looking at a dynamic object, and we have found a
1596      definition, we need to see if the symbol was already defined by
1597      some other object.  If so, we want to use the existing
1598      definition, and we do not want to report a multiple symbol
1599      definition error; we do this by clobbering *PSEC to be
1600      bfd_und_section_ptr.
1601
1602      We treat a common symbol as a definition if the symbol in the
1603      shared library is a function, since common symbols always
1604      represent variables; this can cause confusion in principle, but
1605      any such confusion would seem to indicate an erroneous program or
1606      shared library.  We also permit a common symbol in a regular
1607      object to override a weak symbol in a shared object.  */
1608
1609   if (newdyn
1610       && newdef
1611       && (olddef
1612           || (h->root.type == bfd_link_hash_common
1613               && (newweak || newfunc))))
1614     {
1615       *override = TRUE;
1616       newdef = FALSE;
1617       newdyncommon = FALSE;
1618
1619       *psec = sec = bfd_und_section_ptr;
1620       *size_change_ok = TRUE;
1621
1622       /* If we get here when the old symbol is a common symbol, then
1623          we are explicitly letting it override a weak symbol or
1624          function in a dynamic object, and we don't want to warn about
1625          a type change.  If the old symbol is a defined symbol, a type
1626          change warning may still be appropriate.  */
1627
1628       if (h->root.type == bfd_link_hash_common)
1629         *type_change_ok = TRUE;
1630     }
1631
1632   /* Handle the special case of an old common symbol merging with a
1633      new symbol which looks like a common symbol in a shared object.
1634      We change *PSEC and *PVALUE to make the new symbol look like a
1635      common symbol, and let _bfd_generic_link_add_one_symbol do the
1636      right thing.  */
1637
1638   if (newdyncommon
1639       && h->root.type == bfd_link_hash_common)
1640     {
1641       *override = TRUE;
1642       newdef = FALSE;
1643       newdyncommon = FALSE;
1644       *pvalue = sym->st_size;
1645       *psec = sec = bed->common_section (oldsec);
1646       *size_change_ok = TRUE;
1647     }
1648
1649   /* Skip weak definitions of symbols that are already defined.  */
1650   if (newdef && olddef && newweak)
1651     {
1652       /* Don't skip new non-IR weak syms.  */
1653       if (!(oldbfd != NULL
1654             && (oldbfd->flags & BFD_PLUGIN) != 0
1655             && (abfd->flags & BFD_PLUGIN) == 0))
1656         {
1657           newdef = FALSE;
1658           *skip = TRUE;
1659         }
1660
1661       /* Merge st_other.  If the symbol already has a dynamic index,
1662          but visibility says it should not be visible, turn it into a
1663          local symbol.  */
1664       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1665       if (h->dynindx != -1)
1666         switch (ELF_ST_VISIBILITY (h->other))
1667           {
1668           case STV_INTERNAL:
1669           case STV_HIDDEN:
1670             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1671             break;
1672           }
1673     }
1674
1675   /* If the old symbol is from a dynamic object, and the new symbol is
1676      a definition which is not from a dynamic object, then the new
1677      symbol overrides the old symbol.  Symbols from regular files
1678      always take precedence over symbols from dynamic objects, even if
1679      they are defined after the dynamic object in the link.
1680
1681      As above, we again permit a common symbol in a regular object to
1682      override a definition in a shared object if the shared object
1683      symbol is a function or is weak.  */
1684
1685   flip = NULL;
1686   if (!newdyn
1687       && (newdef
1688           || (bfd_is_com_section (sec)
1689               && (oldweak || oldfunc)))
1690       && olddyn
1691       && olddef
1692       && h->def_dynamic)
1693     {
1694       /* Change the hash table entry to undefined, and let
1695          _bfd_generic_link_add_one_symbol do the right thing with the
1696          new definition.  */
1697
1698       h->root.type = bfd_link_hash_undefined;
1699       h->root.u.undef.abfd = h->root.u.def.section->owner;
1700       *size_change_ok = TRUE;
1701
1702       olddef = FALSE;
1703       olddyncommon = FALSE;
1704
1705       /* We again permit a type change when a common symbol may be
1706          overriding a function.  */
1707
1708       if (bfd_is_com_section (sec))
1709         {
1710           if (oldfunc)
1711             {
1712               /* If a common symbol overrides a function, make sure
1713                  that it isn't defined dynamically nor has type
1714                  function.  */
1715               h->def_dynamic = 0;
1716               h->type = STT_NOTYPE;
1717             }
1718           *type_change_ok = TRUE;
1719         }
1720
1721       if (hi->root.type == bfd_link_hash_indirect)
1722         flip = hi;
1723       else
1724         /* This union may have been set to be non-NULL when this symbol
1725            was seen in a dynamic object.  We must force the union to be
1726            NULL, so that it is correct for a regular symbol.  */
1727         h->verinfo.vertree = NULL;
1728     }
1729
1730   /* Handle the special case of a new common symbol merging with an
1731      old symbol that looks like it might be a common symbol defined in
1732      a shared object.  Note that we have already handled the case in
1733      which a new common symbol should simply override the definition
1734      in the shared library.  */
1735
1736   if (! newdyn
1737       && bfd_is_com_section (sec)
1738       && olddyncommon)
1739     {
1740       /* It would be best if we could set the hash table entry to a
1741          common symbol, but we don't know what to use for the section
1742          or the alignment.  */
1743       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1744                                            bfd_link_hash_common, sym->st_size);
1745
1746       /* If the presumed common symbol in the dynamic object is
1747          larger, pretend that the new symbol has its size.  */
1748
1749       if (h->size > *pvalue)
1750         *pvalue = h->size;
1751
1752       /* We need to remember the alignment required by the symbol
1753          in the dynamic object.  */
1754       BFD_ASSERT (pold_alignment);
1755       *pold_alignment = h->root.u.def.section->alignment_power;
1756
1757       olddef = FALSE;
1758       olddyncommon = FALSE;
1759
1760       h->root.type = bfd_link_hash_undefined;
1761       h->root.u.undef.abfd = h->root.u.def.section->owner;
1762
1763       *size_change_ok = TRUE;
1764       *type_change_ok = TRUE;
1765
1766       if (hi->root.type == bfd_link_hash_indirect)
1767         flip = hi;
1768       else
1769         h->verinfo.vertree = NULL;
1770     }
1771
1772   if (flip != NULL)
1773     {
1774       /* Handle the case where we had a versioned symbol in a dynamic
1775          library and now find a definition in a normal object.  In this
1776          case, we make the versioned symbol point to the normal one.  */
1777       flip->root.type = h->root.type;
1778       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1779       h->root.type = bfd_link_hash_indirect;
1780       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1781       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1782       if (h->def_dynamic)
1783         {
1784           h->def_dynamic = 0;
1785           flip->ref_dynamic = 1;
1786         }
1787     }
1788
1789   return TRUE;
1790 }
1791
1792 /* This function is called to create an indirect symbol from the
1793    default for the symbol with the default version if needed. The
1794    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1795    set DYNSYM if the new indirect symbol is dynamic.  */
1796
1797 static bfd_boolean
1798 _bfd_elf_add_default_symbol (bfd *abfd,
1799                              struct bfd_link_info *info,
1800                              struct elf_link_hash_entry *h,
1801                              const char *name,
1802                              Elf_Internal_Sym *sym,
1803                              asection *sec,
1804                              bfd_vma value,
1805                              bfd **poldbfd,
1806                              bfd_boolean *dynsym)
1807 {
1808   bfd_boolean type_change_ok;
1809   bfd_boolean size_change_ok;
1810   bfd_boolean skip;
1811   char *shortname;
1812   struct elf_link_hash_entry *hi;
1813   struct bfd_link_hash_entry *bh;
1814   const struct elf_backend_data *bed;
1815   bfd_boolean collect;
1816   bfd_boolean dynamic;
1817   bfd_boolean override;
1818   char *p;
1819   size_t len, shortlen;
1820   asection *tmp_sec;
1821   bfd_boolean matched;
1822
1823   if (h->versioned == unversioned || h->versioned == versioned_hidden)
1824     return TRUE;
1825
1826   /* If this symbol has a version, and it is the default version, we
1827      create an indirect symbol from the default name to the fully
1828      decorated name.  This will cause external references which do not
1829      specify a version to be bound to this version of the symbol.  */
1830   p = strchr (name, ELF_VER_CHR);
1831   if (h->versioned == unknown)
1832     {
1833       if (p == NULL)
1834         {
1835           h->versioned = unversioned;
1836           return TRUE;
1837         }
1838       else
1839         {
1840           if (p[1] != ELF_VER_CHR)
1841             {
1842               h->versioned = versioned_hidden;
1843               return TRUE;
1844             }
1845           else
1846             h->versioned = versioned;
1847         }
1848     }
1849   else
1850     {
1851       /* PR ld/19073: We may see an unversioned definition after the
1852          default version.  */
1853       if (p == NULL)
1854         return TRUE;
1855     }
1856
1857   bed = get_elf_backend_data (abfd);
1858   collect = bed->collect;
1859   dynamic = (abfd->flags & DYNAMIC) != 0;
1860
1861   shortlen = p - name;
1862   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1863   if (shortname == NULL)
1864     return FALSE;
1865   memcpy (shortname, name, shortlen);
1866   shortname[shortlen] = '\0';
1867
1868   /* We are going to create a new symbol.  Merge it with any existing
1869      symbol with this name.  For the purposes of the merge, act as
1870      though we were defining the symbol we just defined, although we
1871      actually going to define an indirect symbol.  */
1872   type_change_ok = FALSE;
1873   size_change_ok = FALSE;
1874   matched = TRUE;
1875   tmp_sec = sec;
1876   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1877                               &hi, poldbfd, NULL, NULL, &skip, &override,
1878                               &type_change_ok, &size_change_ok, &matched))
1879     return FALSE;
1880
1881   if (skip)
1882     goto nondefault;
1883
1884   if (hi->def_regular)
1885     {
1886       /* If the undecorated symbol will have a version added by a
1887          script different to H, then don't indirect to/from the
1888          undecorated symbol.  This isn't ideal because we may not yet
1889          have seen symbol versions, if given by a script on the
1890          command line rather than via --version-script.  */
1891       if (hi->verinfo.vertree == NULL && info->version_info != NULL)
1892         {
1893           bfd_boolean hide;
1894
1895           hi->verinfo.vertree
1896             = bfd_find_version_for_sym (info->version_info,
1897                                         hi->root.root.string, &hide);
1898           if (hi->verinfo.vertree != NULL && hide)
1899             {
1900               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
1901               goto nondefault;
1902             }
1903         }
1904       if (hi->verinfo.vertree != NULL
1905           && strcmp (p + 1 + (p[1] == '@'), hi->verinfo.vertree->name) != 0)
1906         goto nondefault;
1907     }
1908
1909   if (! override)
1910     {
1911       /* Add the default symbol if not performing a relocatable link.  */
1912       if (! bfd_link_relocatable (info))
1913         {
1914           bh = &hi->root;
1915           if (! (_bfd_generic_link_add_one_symbol
1916                  (info, abfd, shortname, BSF_INDIRECT,
1917                   bfd_ind_section_ptr,
1918                   0, name, FALSE, collect, &bh)))
1919             return FALSE;
1920           hi = (struct elf_link_hash_entry *) bh;
1921         }
1922     }
1923   else
1924     {
1925       /* In this case the symbol named SHORTNAME is overriding the
1926          indirect symbol we want to add.  We were planning on making
1927          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1928          is the name without a version.  NAME is the fully versioned
1929          name, and it is the default version.
1930
1931          Overriding means that we already saw a definition for the
1932          symbol SHORTNAME in a regular object, and it is overriding
1933          the symbol defined in the dynamic object.
1934
1935          When this happens, we actually want to change NAME, the
1936          symbol we just added, to refer to SHORTNAME.  This will cause
1937          references to NAME in the shared object to become references
1938          to SHORTNAME in the regular object.  This is what we expect
1939          when we override a function in a shared object: that the
1940          references in the shared object will be mapped to the
1941          definition in the regular object.  */
1942
1943       while (hi->root.type == bfd_link_hash_indirect
1944              || hi->root.type == bfd_link_hash_warning)
1945         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1946
1947       h->root.type = bfd_link_hash_indirect;
1948       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1949       if (h->def_dynamic)
1950         {
1951           h->def_dynamic = 0;
1952           hi->ref_dynamic = 1;
1953           if (hi->ref_regular
1954               || hi->def_regular)
1955             {
1956               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1957                 return FALSE;
1958             }
1959         }
1960
1961       /* Now set HI to H, so that the following code will set the
1962          other fields correctly.  */
1963       hi = h;
1964     }
1965
1966   /* Check if HI is a warning symbol.  */
1967   if (hi->root.type == bfd_link_hash_warning)
1968     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1969
1970   /* If there is a duplicate definition somewhere, then HI may not
1971      point to an indirect symbol.  We will have reported an error to
1972      the user in that case.  */
1973
1974   if (hi->root.type == bfd_link_hash_indirect)
1975     {
1976       struct elf_link_hash_entry *ht;
1977
1978       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1979       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
1980
1981       /* A reference to the SHORTNAME symbol from a dynamic library
1982          will be satisfied by the versioned symbol at runtime.  In
1983          effect, we have a reference to the versioned symbol.  */
1984       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1985       hi->dynamic_def |= ht->dynamic_def;
1986
1987       /* See if the new flags lead us to realize that the symbol must
1988          be dynamic.  */
1989       if (! *dynsym)
1990         {
1991           if (! dynamic)
1992             {
1993               if (! bfd_link_executable (info)
1994                   || hi->def_dynamic
1995                   || hi->ref_dynamic)
1996                 *dynsym = TRUE;
1997             }
1998           else
1999             {
2000               if (hi->ref_regular)
2001                 *dynsym = TRUE;
2002             }
2003         }
2004     }
2005
2006   /* We also need to define an indirection from the nondefault version
2007      of the symbol.  */
2008
2009 nondefault:
2010   len = strlen (name);
2011   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
2012   if (shortname == NULL)
2013     return FALSE;
2014   memcpy (shortname, name, shortlen);
2015   memcpy (shortname + shortlen, p + 1, len - shortlen);
2016
2017   /* Once again, merge with any existing symbol.  */
2018   type_change_ok = FALSE;
2019   size_change_ok = FALSE;
2020   tmp_sec = sec;
2021   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
2022                               &hi, poldbfd, NULL, NULL, &skip, &override,
2023                               &type_change_ok, &size_change_ok, &matched))
2024     return FALSE;
2025
2026   if (skip)
2027     return TRUE;
2028
2029   if (override)
2030     {
2031       /* Here SHORTNAME is a versioned name, so we don't expect to see
2032          the type of override we do in the case above unless it is
2033          overridden by a versioned definition.  */
2034       if (hi->root.type != bfd_link_hash_defined
2035           && hi->root.type != bfd_link_hash_defweak)
2036         _bfd_error_handler
2037           /* xgettext:c-format */
2038           (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
2039            abfd, shortname);
2040     }
2041   else
2042     {
2043       bh = &hi->root;
2044       if (! (_bfd_generic_link_add_one_symbol
2045              (info, abfd, shortname, BSF_INDIRECT,
2046               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
2047         return FALSE;
2048       hi = (struct elf_link_hash_entry *) bh;
2049
2050       /* If there is a duplicate definition somewhere, then HI may not
2051          point to an indirect symbol.  We will have reported an error
2052          to the user in that case.  */
2053
2054       if (hi->root.type == bfd_link_hash_indirect)
2055         {
2056           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
2057           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
2058           hi->dynamic_def |= h->dynamic_def;
2059
2060           /* See if the new flags lead us to realize that the symbol
2061              must be dynamic.  */
2062           if (! *dynsym)
2063             {
2064               if (! dynamic)
2065                 {
2066                   if (! bfd_link_executable (info)
2067                       || hi->ref_dynamic)
2068                     *dynsym = TRUE;
2069                 }
2070               else
2071                 {
2072                   if (hi->ref_regular)
2073                     *dynsym = TRUE;
2074                 }
2075             }
2076         }
2077     }
2078
2079   return TRUE;
2080 }
2081 \f
2082 /* This routine is used to export all defined symbols into the dynamic
2083    symbol table.  It is called via elf_link_hash_traverse.  */
2084
2085 static bfd_boolean
2086 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
2087 {
2088   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2089
2090   /* Ignore indirect symbols.  These are added by the versioning code.  */
2091   if (h->root.type == bfd_link_hash_indirect)
2092     return TRUE;
2093
2094   /* Ignore this if we won't export it.  */
2095   if (!eif->info->export_dynamic && !h->dynamic)
2096     return TRUE;
2097
2098   if (h->dynindx == -1
2099       && (h->def_regular || h->ref_regular)
2100       && ! bfd_hide_sym_by_version (eif->info->version_info,
2101                                     h->root.root.string))
2102     {
2103       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2104         {
2105           eif->failed = TRUE;
2106           return FALSE;
2107         }
2108     }
2109
2110   return TRUE;
2111 }
2112 \f
2113 /* Look through the symbols which are defined in other shared
2114    libraries and referenced here.  Update the list of version
2115    dependencies.  This will be put into the .gnu.version_r section.
2116    This function is called via elf_link_hash_traverse.  */
2117
2118 static bfd_boolean
2119 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
2120                                          void *data)
2121 {
2122   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
2123   Elf_Internal_Verneed *t;
2124   Elf_Internal_Vernaux *a;
2125   bfd_size_type amt;
2126
2127   /* We only care about symbols defined in shared objects with version
2128      information.  */
2129   if (!h->def_dynamic
2130       || h->def_regular
2131       || h->dynindx == -1
2132       || h->verinfo.verdef == NULL
2133       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
2134           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
2135     return TRUE;
2136
2137   /* See if we already know about this version.  */
2138   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
2139        t != NULL;
2140        t = t->vn_nextref)
2141     {
2142       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
2143         continue;
2144
2145       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
2146         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
2147           return TRUE;
2148
2149       break;
2150     }
2151
2152   /* This is a new version.  Add it to tree we are building.  */
2153
2154   if (t == NULL)
2155     {
2156       amt = sizeof *t;
2157       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
2158       if (t == NULL)
2159         {
2160           rinfo->failed = TRUE;
2161           return FALSE;
2162         }
2163
2164       t->vn_bfd = h->verinfo.verdef->vd_bfd;
2165       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
2166       elf_tdata (rinfo->info->output_bfd)->verref = t;
2167     }
2168
2169   amt = sizeof *a;
2170   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
2171   if (a == NULL)
2172     {
2173       rinfo->failed = TRUE;
2174       return FALSE;
2175     }
2176
2177   /* Note that we are copying a string pointer here, and testing it
2178      above.  If bfd_elf_string_from_elf_section is ever changed to
2179      discard the string data when low in memory, this will have to be
2180      fixed.  */
2181   a->vna_nodename = h->verinfo.verdef->vd_nodename;
2182
2183   a->vna_flags = h->verinfo.verdef->vd_flags;
2184   a->vna_nextptr = t->vn_auxptr;
2185
2186   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
2187   ++rinfo->vers;
2188
2189   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
2190
2191   t->vn_auxptr = a;
2192
2193   return TRUE;
2194 }
2195
2196 /* Figure out appropriate versions for all the symbols.  We may not
2197    have the version number script until we have read all of the input
2198    files, so until that point we don't know which symbols should be
2199    local.  This function is called via elf_link_hash_traverse.  */
2200
2201 static bfd_boolean
2202 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2203 {
2204   struct elf_info_failed *sinfo;
2205   struct bfd_link_info *info;
2206   const struct elf_backend_data *bed;
2207   struct elf_info_failed eif;
2208   char *p;
2209
2210   sinfo = (struct elf_info_failed *) data;
2211   info = sinfo->info;
2212
2213   /* Fix the symbol flags.  */
2214   eif.failed = FALSE;
2215   eif.info = info;
2216   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2217     {
2218       if (eif.failed)
2219         sinfo->failed = TRUE;
2220       return FALSE;
2221     }
2222
2223   /* We only need version numbers for symbols defined in regular
2224      objects.  */
2225   if (!h->def_regular)
2226     return TRUE;
2227
2228   bed = get_elf_backend_data (info->output_bfd);
2229   p = strchr (h->root.root.string, ELF_VER_CHR);
2230   if (p != NULL && h->verinfo.vertree == NULL)
2231     {
2232       struct bfd_elf_version_tree *t;
2233
2234       ++p;
2235       if (*p == ELF_VER_CHR)
2236         ++p;
2237
2238       /* If there is no version string, we can just return out.  */
2239       if (*p == '\0')
2240         return TRUE;
2241
2242       /* Look for the version.  If we find it, it is no longer weak.  */
2243       for (t = sinfo->info->version_info; t != NULL; t = t->next)
2244         {
2245           if (strcmp (t->name, p) == 0)
2246             {
2247               size_t len;
2248               char *alc;
2249               struct bfd_elf_version_expr *d;
2250
2251               len = p - h->root.root.string;
2252               alc = (char *) bfd_malloc (len);
2253               if (alc == NULL)
2254                 {
2255                   sinfo->failed = TRUE;
2256                   return FALSE;
2257                 }
2258               memcpy (alc, h->root.root.string, len - 1);
2259               alc[len - 1] = '\0';
2260               if (alc[len - 2] == ELF_VER_CHR)
2261                 alc[len - 2] = '\0';
2262
2263               h->verinfo.vertree = t;
2264               t->used = TRUE;
2265               d = NULL;
2266
2267               if (t->globals.list != NULL)
2268                 d = (*t->match) (&t->globals, NULL, alc);
2269
2270               /* See if there is anything to force this symbol to
2271                  local scope.  */
2272               if (d == NULL && t->locals.list != NULL)
2273                 {
2274                   d = (*t->match) (&t->locals, NULL, alc);
2275                   if (d != NULL
2276                       && h->dynindx != -1
2277                       && ! info->export_dynamic)
2278                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2279                 }
2280
2281               free (alc);
2282               break;
2283             }
2284         }
2285
2286       /* If we are building an application, we need to create a
2287          version node for this version.  */
2288       if (t == NULL && bfd_link_executable (info))
2289         {
2290           struct bfd_elf_version_tree **pp;
2291           int version_index;
2292
2293           /* If we aren't going to export this symbol, we don't need
2294              to worry about it.  */
2295           if (h->dynindx == -1)
2296             return TRUE;
2297
2298           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd,
2299                                                           sizeof *t);
2300           if (t == NULL)
2301             {
2302               sinfo->failed = TRUE;
2303               return FALSE;
2304             }
2305
2306           t->name = p;
2307           t->name_indx = (unsigned int) -1;
2308           t->used = TRUE;
2309
2310           version_index = 1;
2311           /* Don't count anonymous version tag.  */
2312           if (sinfo->info->version_info != NULL
2313               && sinfo->info->version_info->vernum == 0)
2314             version_index = 0;
2315           for (pp = &sinfo->info->version_info;
2316                *pp != NULL;
2317                pp = &(*pp)->next)
2318             ++version_index;
2319           t->vernum = version_index;
2320
2321           *pp = t;
2322
2323           h->verinfo.vertree = t;
2324         }
2325       else if (t == NULL)
2326         {
2327           /* We could not find the version for a symbol when
2328              generating a shared archive.  Return an error.  */
2329           _bfd_error_handler
2330             /* xgettext:c-format */
2331             (_("%B: version node not found for symbol %s"),
2332              info->output_bfd, h->root.root.string);
2333           bfd_set_error (bfd_error_bad_value);
2334           sinfo->failed = TRUE;
2335           return FALSE;
2336         }
2337     }
2338
2339   /* If we don't have a version for this symbol, see if we can find
2340      something.  */
2341   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2342     {
2343       bfd_boolean hide;
2344
2345       h->verinfo.vertree
2346         = bfd_find_version_for_sym (sinfo->info->version_info,
2347                                     h->root.root.string, &hide);
2348       if (h->verinfo.vertree != NULL && hide)
2349         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2350     }
2351
2352   return TRUE;
2353 }
2354 \f
2355 /* Read and swap the relocs from the section indicated by SHDR.  This
2356    may be either a REL or a RELA section.  The relocations are
2357    translated into RELA relocations and stored in INTERNAL_RELOCS,
2358    which should have already been allocated to contain enough space.
2359    The EXTERNAL_RELOCS are a buffer where the external form of the
2360    relocations should be stored.
2361
2362    Returns FALSE if something goes wrong.  */
2363
2364 static bfd_boolean
2365 elf_link_read_relocs_from_section (bfd *abfd,
2366                                    asection *sec,
2367                                    Elf_Internal_Shdr *shdr,
2368                                    void *external_relocs,
2369                                    Elf_Internal_Rela *internal_relocs)
2370 {
2371   const struct elf_backend_data *bed;
2372   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2373   const bfd_byte *erela;
2374   const bfd_byte *erelaend;
2375   Elf_Internal_Rela *irela;
2376   Elf_Internal_Shdr *symtab_hdr;
2377   size_t nsyms;
2378
2379   /* Position ourselves at the start of the section.  */
2380   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2381     return FALSE;
2382
2383   /* Read the relocations.  */
2384   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2385     return FALSE;
2386
2387   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2388   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2389
2390   bed = get_elf_backend_data (abfd);
2391
2392   /* Convert the external relocations to the internal format.  */
2393   if (shdr->sh_entsize == bed->s->sizeof_rel)
2394     swap_in = bed->s->swap_reloc_in;
2395   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2396     swap_in = bed->s->swap_reloca_in;
2397   else
2398     {
2399       bfd_set_error (bfd_error_wrong_format);
2400       return FALSE;
2401     }
2402
2403   erela = (const bfd_byte *) external_relocs;
2404   erelaend = erela + shdr->sh_size;
2405   irela = internal_relocs;
2406   while (erela < erelaend)
2407     {
2408       bfd_vma r_symndx;
2409
2410       (*swap_in) (abfd, erela, irela);
2411       r_symndx = ELF32_R_SYM (irela->r_info);
2412       if (bed->s->arch_size == 64)
2413         r_symndx >>= 24;
2414       if (nsyms > 0)
2415         {
2416           if ((size_t) r_symndx >= nsyms)
2417             {
2418               _bfd_error_handler
2419                 /* xgettext:c-format */
2420                 (_("%B: bad reloc symbol index (%#Lx >= %#lx)"
2421                    " for offset %#Lx in section `%A'"),
2422                  abfd, r_symndx, (unsigned long) nsyms,
2423                  irela->r_offset, sec);
2424               bfd_set_error (bfd_error_bad_value);
2425               return FALSE;
2426             }
2427         }
2428       else if (r_symndx != STN_UNDEF)
2429         {
2430           _bfd_error_handler
2431             /* xgettext:c-format */
2432             (_("%B: non-zero symbol index (%#Lx)"
2433                " for offset %#Lx in section `%A'"
2434                " when the object file has no symbol table"),
2435              abfd, r_symndx,
2436              irela->r_offset, sec);
2437           bfd_set_error (bfd_error_bad_value);
2438           return FALSE;
2439         }
2440       irela += bed->s->int_rels_per_ext_rel;
2441       erela += shdr->sh_entsize;
2442     }
2443
2444   return TRUE;
2445 }
2446
2447 /* Read and swap the relocs for a section O.  They may have been
2448    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2449    not NULL, they are used as buffers to read into.  They are known to
2450    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2451    the return value is allocated using either malloc or bfd_alloc,
2452    according to the KEEP_MEMORY argument.  If O has two relocation
2453    sections (both REL and RELA relocations), then the REL_HDR
2454    relocations will appear first in INTERNAL_RELOCS, followed by the
2455    RELA_HDR relocations.  */
2456
2457 Elf_Internal_Rela *
2458 _bfd_elf_link_read_relocs (bfd *abfd,
2459                            asection *o,
2460                            void *external_relocs,
2461                            Elf_Internal_Rela *internal_relocs,
2462                            bfd_boolean keep_memory)
2463 {
2464   void *alloc1 = NULL;
2465   Elf_Internal_Rela *alloc2 = NULL;
2466   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2467   struct bfd_elf_section_data *esdo = elf_section_data (o);
2468   Elf_Internal_Rela *internal_rela_relocs;
2469
2470   if (esdo->relocs != NULL)
2471     return esdo->relocs;
2472
2473   if (o->reloc_count == 0)
2474     return NULL;
2475
2476   if (internal_relocs == NULL)
2477     {
2478       bfd_size_type size;
2479
2480       size = (bfd_size_type) o->reloc_count * sizeof (Elf_Internal_Rela);
2481       if (keep_memory)
2482         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2483       else
2484         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2485       if (internal_relocs == NULL)
2486         goto error_return;
2487     }
2488
2489   if (external_relocs == NULL)
2490     {
2491       bfd_size_type size = 0;
2492
2493       if (esdo->rel.hdr)
2494         size += esdo->rel.hdr->sh_size;
2495       if (esdo->rela.hdr)
2496         size += esdo->rela.hdr->sh_size;
2497
2498       alloc1 = bfd_malloc (size);
2499       if (alloc1 == NULL)
2500         goto error_return;
2501       external_relocs = alloc1;
2502     }
2503
2504   internal_rela_relocs = internal_relocs;
2505   if (esdo->rel.hdr)
2506     {
2507       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2508                                               external_relocs,
2509                                               internal_relocs))
2510         goto error_return;
2511       external_relocs = (((bfd_byte *) external_relocs)
2512                          + esdo->rel.hdr->sh_size);
2513       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2514                                * bed->s->int_rels_per_ext_rel);
2515     }
2516
2517   if (esdo->rela.hdr
2518       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2519                                               external_relocs,
2520                                               internal_rela_relocs)))
2521     goto error_return;
2522
2523   /* Cache the results for next time, if we can.  */
2524   if (keep_memory)
2525     esdo->relocs = internal_relocs;
2526
2527   if (alloc1 != NULL)
2528     free (alloc1);
2529
2530   /* Don't free alloc2, since if it was allocated we are passing it
2531      back (under the name of internal_relocs).  */
2532
2533   return internal_relocs;
2534
2535  error_return:
2536   if (alloc1 != NULL)
2537     free (alloc1);
2538   if (alloc2 != NULL)
2539     {
2540       if (keep_memory)
2541         bfd_release (abfd, alloc2);
2542       else
2543         free (alloc2);
2544     }
2545   return NULL;
2546 }
2547
2548 /* Compute the size of, and allocate space for, REL_HDR which is the
2549    section header for a section containing relocations for O.  */
2550
2551 static bfd_boolean
2552 _bfd_elf_link_size_reloc_section (bfd *abfd,
2553                                   struct bfd_elf_section_reloc_data *reldata)
2554 {
2555   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2556
2557   /* That allows us to calculate the size of the section.  */
2558   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2559
2560   /* The contents field must last into write_object_contents, so we
2561      allocate it with bfd_alloc rather than malloc.  Also since we
2562      cannot be sure that the contents will actually be filled in,
2563      we zero the allocated space.  */
2564   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2565   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2566     return FALSE;
2567
2568   if (reldata->hashes == NULL && reldata->count)
2569     {
2570       struct elf_link_hash_entry **p;
2571
2572       p = ((struct elf_link_hash_entry **)
2573            bfd_zmalloc (reldata->count * sizeof (*p)));
2574       if (p == NULL)
2575         return FALSE;
2576
2577       reldata->hashes = p;
2578     }
2579
2580   return TRUE;
2581 }
2582
2583 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2584    originated from the section given by INPUT_REL_HDR) to the
2585    OUTPUT_BFD.  */
2586
2587 bfd_boolean
2588 _bfd_elf_link_output_relocs (bfd *output_bfd,
2589                              asection *input_section,
2590                              Elf_Internal_Shdr *input_rel_hdr,
2591                              Elf_Internal_Rela *internal_relocs,
2592                              struct elf_link_hash_entry **rel_hash
2593                                ATTRIBUTE_UNUSED)
2594 {
2595   Elf_Internal_Rela *irela;
2596   Elf_Internal_Rela *irelaend;
2597   bfd_byte *erel;
2598   struct bfd_elf_section_reloc_data *output_reldata;
2599   asection *output_section;
2600   const struct elf_backend_data *bed;
2601   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2602   struct bfd_elf_section_data *esdo;
2603
2604   output_section = input_section->output_section;
2605
2606   bed = get_elf_backend_data (output_bfd);
2607   esdo = elf_section_data (output_section);
2608   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2609     {
2610       output_reldata = &esdo->rel;
2611       swap_out = bed->s->swap_reloc_out;
2612     }
2613   else if (esdo->rela.hdr
2614            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2615     {
2616       output_reldata = &esdo->rela;
2617       swap_out = bed->s->swap_reloca_out;
2618     }
2619   else
2620     {
2621       _bfd_error_handler
2622         /* xgettext:c-format */
2623         (_("%B: relocation size mismatch in %B section %A"),
2624          output_bfd, input_section->owner, input_section);
2625       bfd_set_error (bfd_error_wrong_format);
2626       return FALSE;
2627     }
2628
2629   erel = output_reldata->hdr->contents;
2630   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2631   irela = internal_relocs;
2632   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2633                       * bed->s->int_rels_per_ext_rel);
2634   while (irela < irelaend)
2635     {
2636       (*swap_out) (output_bfd, irela, erel);
2637       irela += bed->s->int_rels_per_ext_rel;
2638       erel += input_rel_hdr->sh_entsize;
2639     }
2640
2641   /* Bump the counter, so that we know where to add the next set of
2642      relocations.  */
2643   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2644
2645   return TRUE;
2646 }
2647 \f
2648 /* Make weak undefined symbols in PIE dynamic.  */
2649
2650 bfd_boolean
2651 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2652                                  struct elf_link_hash_entry *h)
2653 {
2654   if (bfd_link_pie (info)
2655       && h->dynindx == -1
2656       && h->root.type == bfd_link_hash_undefweak)
2657     return bfd_elf_link_record_dynamic_symbol (info, h);
2658
2659   return TRUE;
2660 }
2661
2662 /* Fix up the flags for a symbol.  This handles various cases which
2663    can only be fixed after all the input files are seen.  This is
2664    currently called by both adjust_dynamic_symbol and
2665    assign_sym_version, which is unnecessary but perhaps more robust in
2666    the face of future changes.  */
2667
2668 static bfd_boolean
2669 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2670                            struct elf_info_failed *eif)
2671 {
2672   const struct elf_backend_data *bed;
2673
2674   /* If this symbol was mentioned in a non-ELF file, try to set
2675      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2676      permit a non-ELF file to correctly refer to a symbol defined in
2677      an ELF dynamic object.  */
2678   if (h->non_elf)
2679     {
2680       while (h->root.type == bfd_link_hash_indirect)
2681         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2682
2683       if (h->root.type != bfd_link_hash_defined
2684           && h->root.type != bfd_link_hash_defweak)
2685         {
2686           h->ref_regular = 1;
2687           h->ref_regular_nonweak = 1;
2688         }
2689       else
2690         {
2691           if (h->root.u.def.section->owner != NULL
2692               && (bfd_get_flavour (h->root.u.def.section->owner)
2693                   == bfd_target_elf_flavour))
2694             {
2695               h->ref_regular = 1;
2696               h->ref_regular_nonweak = 1;
2697             }
2698           else
2699             h->def_regular = 1;
2700         }
2701
2702       if (h->dynindx == -1
2703           && (h->def_dynamic
2704               || h->ref_dynamic))
2705         {
2706           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2707             {
2708               eif->failed = TRUE;
2709               return FALSE;
2710             }
2711         }
2712     }
2713   else
2714     {
2715       /* Unfortunately, NON_ELF is only correct if the symbol
2716          was first seen in a non-ELF file.  Fortunately, if the symbol
2717          was first seen in an ELF file, we're probably OK unless the
2718          symbol was defined in a non-ELF file.  Catch that case here.
2719          FIXME: We're still in trouble if the symbol was first seen in
2720          a dynamic object, and then later in a non-ELF regular object.  */
2721       if ((h->root.type == bfd_link_hash_defined
2722            || h->root.type == bfd_link_hash_defweak)
2723           && !h->def_regular
2724           && (h->root.u.def.section->owner != NULL
2725               ? (bfd_get_flavour (h->root.u.def.section->owner)
2726                  != bfd_target_elf_flavour)
2727               : (bfd_is_abs_section (h->root.u.def.section)
2728                  && !h->def_dynamic)))
2729         h->def_regular = 1;
2730     }
2731
2732   /* Backend specific symbol fixup.  */
2733   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2734   if (bed->elf_backend_fixup_symbol
2735       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2736     return FALSE;
2737
2738   /* If this is a final link, and the symbol was defined as a common
2739      symbol in a regular object file, and there was no definition in
2740      any dynamic object, then the linker will have allocated space for
2741      the symbol in a common section but the DEF_REGULAR
2742      flag will not have been set.  */
2743   if (h->root.type == bfd_link_hash_defined
2744       && !h->def_regular
2745       && h->ref_regular
2746       && !h->def_dynamic
2747       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2748     h->def_regular = 1;
2749
2750   /* If a weak undefined symbol has non-default visibility, we also
2751      hide it from the dynamic linker.  */
2752   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2753       && h->root.type == bfd_link_hash_undefweak)
2754     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2755
2756   /* A hidden versioned symbol in executable should be forced local if
2757      it is is locally defined, not referenced by shared library and not
2758      exported.  */
2759   else if (bfd_link_executable (eif->info)
2760            && h->versioned == versioned_hidden
2761            && !eif->info->export_dynamic
2762            && !h->dynamic
2763            && !h->ref_dynamic
2764            && h->def_regular)
2765     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2766
2767   /* If -Bsymbolic was used (which means to bind references to global
2768      symbols to the definition within the shared object), and this
2769      symbol was defined in a regular object, then it actually doesn't
2770      need a PLT entry.  Likewise, if the symbol has non-default
2771      visibility.  If the symbol has hidden or internal visibility, we
2772      will force it local.  */
2773   else if (h->needs_plt
2774            && bfd_link_pic (eif->info)
2775            && is_elf_hash_table (eif->info->hash)
2776            && (SYMBOLIC_BIND (eif->info, h)
2777                || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2778            && h->def_regular)
2779     {
2780       bfd_boolean force_local;
2781
2782       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2783                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2784       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2785     }
2786
2787   /* If this is a weak defined symbol in a dynamic object, and we know
2788      the real definition in the dynamic object, copy interesting flags
2789      over to the real definition.  */
2790   if (h->is_weakalias)
2791     {
2792       struct elf_link_hash_entry *def = weakdef (h);
2793
2794       /* If the real definition is defined by a regular object file,
2795          don't do anything special.  See the longer description in
2796          _bfd_elf_adjust_dynamic_symbol, below.  */
2797       if (def->def_regular)
2798         {
2799           h = def;
2800           while ((h = h->u.alias) != def)
2801             h->is_weakalias = 0;
2802         }
2803       else
2804         {
2805           while (h->root.type == bfd_link_hash_indirect)
2806             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2807           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2808                       || h->root.type == bfd_link_hash_defweak);
2809           BFD_ASSERT (def->def_dynamic);
2810           BFD_ASSERT (def->root.type == bfd_link_hash_defined);
2811           (*bed->elf_backend_copy_indirect_symbol) (eif->info, def, h);
2812         }
2813     }
2814
2815   return TRUE;
2816 }
2817
2818 /* Make the backend pick a good value for a dynamic symbol.  This is
2819    called via elf_link_hash_traverse, and also calls itself
2820    recursively.  */
2821
2822 static bfd_boolean
2823 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2824 {
2825   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2826   struct elf_link_hash_table *htab;
2827   const struct elf_backend_data *bed;
2828
2829   if (! is_elf_hash_table (eif->info->hash))
2830     return FALSE;
2831
2832   /* Ignore indirect symbols.  These are added by the versioning code.  */
2833   if (h->root.type == bfd_link_hash_indirect)
2834     return TRUE;
2835
2836   /* Fix the symbol flags.  */
2837   if (! _bfd_elf_fix_symbol_flags (h, eif))
2838     return FALSE;
2839
2840   htab = elf_hash_table (eif->info);
2841   bed = get_elf_backend_data (htab->dynobj);
2842
2843   if (h->root.type == bfd_link_hash_undefweak)
2844     {
2845       if (eif->info->dynamic_undefined_weak == 0)
2846         (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2847       else if (eif->info->dynamic_undefined_weak > 0
2848                && h->ref_regular
2849                && ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2850                && !bfd_hide_sym_by_version (eif->info->version_info,
2851                                             h->root.root.string))
2852         {
2853           if (!bfd_elf_link_record_dynamic_symbol (eif->info, h))
2854             {
2855               eif->failed = TRUE;
2856               return FALSE;
2857             }
2858         }
2859     }
2860
2861   /* If this symbol does not require a PLT entry, and it is not
2862      defined by a dynamic object, or is not referenced by a regular
2863      object, ignore it.  We do have to handle a weak defined symbol,
2864      even if no regular object refers to it, if we decided to add it
2865      to the dynamic symbol table.  FIXME: Do we normally need to worry
2866      about symbols which are defined by one dynamic object and
2867      referenced by another one?  */
2868   if (!h->needs_plt
2869       && h->type != STT_GNU_IFUNC
2870       && (h->def_regular
2871           || !h->def_dynamic
2872           || (!h->ref_regular
2873               && (!h->is_weakalias || weakdef (h)->dynindx == -1))))
2874     {
2875       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2876       return TRUE;
2877     }
2878
2879   /* If we've already adjusted this symbol, don't do it again.  This
2880      can happen via a recursive call.  */
2881   if (h->dynamic_adjusted)
2882     return TRUE;
2883
2884   /* Don't look at this symbol again.  Note that we must set this
2885      after checking the above conditions, because we may look at a
2886      symbol once, decide not to do anything, and then get called
2887      recursively later after REF_REGULAR is set below.  */
2888   h->dynamic_adjusted = 1;
2889
2890   /* If this is a weak definition, and we know a real definition, and
2891      the real symbol is not itself defined by a regular object file,
2892      then get a good value for the real definition.  We handle the
2893      real symbol first, for the convenience of the backend routine.
2894
2895      Note that there is a confusing case here.  If the real definition
2896      is defined by a regular object file, we don't get the real symbol
2897      from the dynamic object, but we do get the weak symbol.  If the
2898      processor backend uses a COPY reloc, then if some routine in the
2899      dynamic object changes the real symbol, we will not see that
2900      change in the corresponding weak symbol.  This is the way other
2901      ELF linkers work as well, and seems to be a result of the shared
2902      library model.
2903
2904      I will clarify this issue.  Most SVR4 shared libraries define the
2905      variable _timezone and define timezone as a weak synonym.  The
2906      tzset call changes _timezone.  If you write
2907        extern int timezone;
2908        int _timezone = 5;
2909        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2910      you might expect that, since timezone is a synonym for _timezone,
2911      the same number will print both times.  However, if the processor
2912      backend uses a COPY reloc, then actually timezone will be copied
2913      into your process image, and, since you define _timezone
2914      yourself, _timezone will not.  Thus timezone and _timezone will
2915      wind up at different memory locations.  The tzset call will set
2916      _timezone, leaving timezone unchanged.  */
2917
2918   if (h->is_weakalias)
2919     {
2920       struct elf_link_hash_entry *def = weakdef (h);
2921
2922       /* If we get to this point, there is an implicit reference to
2923          the alias by a regular object file via the weak symbol H.  */
2924       def->ref_regular = 1;
2925
2926       /* Ensure that the backend adjust_dynamic_symbol function sees
2927          the strong alias before H by recursively calling ourselves.  */
2928       if (!_bfd_elf_adjust_dynamic_symbol (def, eif))
2929         return FALSE;
2930     }
2931
2932   /* If a symbol has no type and no size and does not require a PLT
2933      entry, then we are probably about to do the wrong thing here: we
2934      are probably going to create a COPY reloc for an empty object.
2935      This case can arise when a shared object is built with assembly
2936      code, and the assembly code fails to set the symbol type.  */
2937   if (h->size == 0
2938       && h->type == STT_NOTYPE
2939       && !h->needs_plt)
2940     _bfd_error_handler
2941       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2942        h->root.root.string);
2943
2944   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2945     {
2946       eif->failed = TRUE;
2947       return FALSE;
2948     }
2949
2950   return TRUE;
2951 }
2952
2953 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2954    DYNBSS.  */
2955
2956 bfd_boolean
2957 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
2958                               struct elf_link_hash_entry *h,
2959                               asection *dynbss)
2960 {
2961   unsigned int power_of_two;
2962   bfd_vma mask;
2963   asection *sec = h->root.u.def.section;
2964
2965   /* The section alignment of the definition is the maximum alignment
2966      requirement of symbols defined in the section.  Since we don't
2967      know the symbol alignment requirement, we start with the
2968      maximum alignment and check low bits of the symbol address
2969      for the minimum alignment.  */
2970   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2971   mask = ((bfd_vma) 1 << power_of_two) - 1;
2972   while ((h->root.u.def.value & mask) != 0)
2973     {
2974        mask >>= 1;
2975        --power_of_two;
2976     }
2977
2978   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
2979                                                 dynbss))
2980     {
2981       /* Adjust the section alignment if needed.  */
2982       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
2983                                        power_of_two))
2984         return FALSE;
2985     }
2986
2987   /* We make sure that the symbol will be aligned properly.  */
2988   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
2989
2990   /* Define the symbol as being at this point in DYNBSS.  */
2991   h->root.u.def.section = dynbss;
2992   h->root.u.def.value = dynbss->size;
2993
2994   /* Increment the size of DYNBSS to make room for the symbol.  */
2995   dynbss->size += h->size;
2996
2997   /* No error if extern_protected_data is true.  */
2998   if (h->protected_def
2999       && (!info->extern_protected_data
3000           || (info->extern_protected_data < 0
3001               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
3002     info->callbacks->einfo
3003       (_("%P: copy reloc against protected `%T' is dangerous\n"),
3004        h->root.root.string);
3005
3006   return TRUE;
3007 }
3008
3009 /* Adjust all external symbols pointing into SEC_MERGE sections
3010    to reflect the object merging within the sections.  */
3011
3012 static bfd_boolean
3013 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
3014 {
3015   asection *sec;
3016
3017   if ((h->root.type == bfd_link_hash_defined
3018        || h->root.type == bfd_link_hash_defweak)
3019       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
3020       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
3021     {
3022       bfd *output_bfd = (bfd *) data;
3023
3024       h->root.u.def.value =
3025         _bfd_merged_section_offset (output_bfd,
3026                                     &h->root.u.def.section,
3027                                     elf_section_data (sec)->sec_info,
3028                                     h->root.u.def.value);
3029     }
3030
3031   return TRUE;
3032 }
3033
3034 /* Returns false if the symbol referred to by H should be considered
3035    to resolve local to the current module, and true if it should be
3036    considered to bind dynamically.  */
3037
3038 bfd_boolean
3039 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
3040                            struct bfd_link_info *info,
3041                            bfd_boolean not_local_protected)
3042 {
3043   bfd_boolean binding_stays_local_p;
3044   const struct elf_backend_data *bed;
3045   struct elf_link_hash_table *hash_table;
3046
3047   if (h == NULL)
3048     return FALSE;
3049
3050   while (h->root.type == bfd_link_hash_indirect
3051          || h->root.type == bfd_link_hash_warning)
3052     h = (struct elf_link_hash_entry *) h->root.u.i.link;
3053
3054   /* If it was forced local, then clearly it's not dynamic.  */
3055   if (h->dynindx == -1)
3056     return FALSE;
3057   if (h->forced_local)
3058     return FALSE;
3059
3060   /* Identify the cases where name binding rules say that a
3061      visible symbol resolves locally.  */
3062   binding_stays_local_p = (bfd_link_executable (info)
3063                            || SYMBOLIC_BIND (info, h));
3064
3065   switch (ELF_ST_VISIBILITY (h->other))
3066     {
3067     case STV_INTERNAL:
3068     case STV_HIDDEN:
3069       return FALSE;
3070
3071     case STV_PROTECTED:
3072       hash_table = elf_hash_table (info);
3073       if (!is_elf_hash_table (hash_table))
3074         return FALSE;
3075
3076       bed = get_elf_backend_data (hash_table->dynobj);
3077
3078       /* Proper resolution for function pointer equality may require
3079          that these symbols perhaps be resolved dynamically, even though
3080          we should be resolving them to the current module.  */
3081       if (!not_local_protected || !bed->is_function_type (h->type))
3082         binding_stays_local_p = TRUE;
3083       break;
3084
3085     default:
3086       break;
3087     }
3088
3089   /* If it isn't defined locally, then clearly it's dynamic.  */
3090   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
3091     return TRUE;
3092
3093   /* Otherwise, the symbol is dynamic if binding rules don't tell
3094      us that it remains local.  */
3095   return !binding_stays_local_p;
3096 }
3097
3098 /* Return true if the symbol referred to by H should be considered
3099    to resolve local to the current module, and false otherwise.  Differs
3100    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
3101    undefined symbols.  The two functions are virtually identical except
3102    for the place where dynindx == -1 is tested.  If that test is true,
3103    _bfd_elf_dynamic_symbol_p will say the symbol is local, while
3104    _bfd_elf_symbol_refs_local_p will say the symbol is local only for
3105    defined symbols.
3106    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
3107    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
3108    treatment of undefined weak symbols.  For those that do not make
3109    undefined weak symbols dynamic, both functions may return false.  */
3110
3111 bfd_boolean
3112 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
3113                               struct bfd_link_info *info,
3114                               bfd_boolean local_protected)
3115 {
3116   const struct elf_backend_data *bed;
3117   struct elf_link_hash_table *hash_table;
3118
3119   /* If it's a local sym, of course we resolve locally.  */
3120   if (h == NULL)
3121     return TRUE;
3122
3123   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
3124   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
3125       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
3126     return TRUE;
3127
3128   /* Forced local symbols resolve locally.  */
3129   if (h->forced_local)
3130     return TRUE;
3131
3132   /* Common symbols that become definitions don't get the DEF_REGULAR
3133      flag set, so test it first, and don't bail out.  */
3134   if (ELF_COMMON_DEF_P (h))
3135     /* Do nothing.  */;
3136   /* If we don't have a definition in a regular file, then we can't
3137      resolve locally.  The sym is either undefined or dynamic.  */
3138   else if (!h->def_regular)
3139     return FALSE;
3140
3141   /* Non-dynamic symbols resolve locally.  */
3142   if (h->dynindx == -1)
3143     return TRUE;
3144
3145   /* At this point, we know the symbol is defined and dynamic.  In an
3146      executable it must resolve locally, likewise when building symbolic
3147      shared libraries.  */
3148   if (bfd_link_executable (info) || SYMBOLIC_BIND (info, h))
3149     return TRUE;
3150
3151   /* Now deal with defined dynamic symbols in shared libraries.  Ones
3152      with default visibility might not resolve locally.  */
3153   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
3154     return FALSE;
3155
3156   hash_table = elf_hash_table (info);
3157   if (!is_elf_hash_table (hash_table))
3158     return TRUE;
3159
3160   bed = get_elf_backend_data (hash_table->dynobj);
3161
3162   /* If extern_protected_data is false, STV_PROTECTED non-function
3163      symbols are local.  */
3164   if ((!info->extern_protected_data
3165        || (info->extern_protected_data < 0
3166            && !bed->extern_protected_data))
3167       && !bed->is_function_type (h->type))
3168     return TRUE;
3169
3170   /* Function pointer equality tests may require that STV_PROTECTED
3171      symbols be treated as dynamic symbols.  If the address of a
3172      function not defined in an executable is set to that function's
3173      plt entry in the executable, then the address of the function in
3174      a shared library must also be the plt entry in the executable.  */
3175   return local_protected;
3176 }
3177
3178 /* Caches some TLS segment info, and ensures that the TLS segment vma is
3179    aligned.  Returns the first TLS output section.  */
3180
3181 struct bfd_section *
3182 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
3183 {
3184   struct bfd_section *sec, *tls;
3185   unsigned int align = 0;
3186
3187   for (sec = obfd->sections; sec != NULL; sec = sec->next)
3188     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
3189       break;
3190   tls = sec;
3191
3192   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
3193     if (sec->alignment_power > align)
3194       align = sec->alignment_power;
3195
3196   elf_hash_table (info)->tls_sec = tls;
3197
3198   /* Ensure the alignment of the first section is the largest alignment,
3199      so that the tls segment starts aligned.  */
3200   if (tls != NULL)
3201     tls->alignment_power = align;
3202
3203   return tls;
3204 }
3205
3206 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
3207 static bfd_boolean
3208 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
3209                                   Elf_Internal_Sym *sym)
3210 {
3211   const struct elf_backend_data *bed;
3212
3213   /* Local symbols do not count, but target specific ones might.  */
3214   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
3215       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
3216     return FALSE;
3217
3218   bed = get_elf_backend_data (abfd);
3219   /* Function symbols do not count.  */
3220   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
3221     return FALSE;
3222
3223   /* If the section is undefined, then so is the symbol.  */
3224   if (sym->st_shndx == SHN_UNDEF)
3225     return FALSE;
3226
3227   /* If the symbol is defined in the common section, then
3228      it is a common definition and so does not count.  */
3229   if (bed->common_definition (sym))
3230     return FALSE;
3231
3232   /* If the symbol is in a target specific section then we
3233      must rely upon the backend to tell us what it is.  */
3234   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3235     /* FIXME - this function is not coded yet:
3236
3237        return _bfd_is_global_symbol_definition (abfd, sym);
3238
3239        Instead for now assume that the definition is not global,
3240        Even if this is wrong, at least the linker will behave
3241        in the same way that it used to do.  */
3242     return FALSE;
3243
3244   return TRUE;
3245 }
3246
3247 /* Search the symbol table of the archive element of the archive ABFD
3248    whose archive map contains a mention of SYMDEF, and determine if
3249    the symbol is defined in this element.  */
3250 static bfd_boolean
3251 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3252 {
3253   Elf_Internal_Shdr * hdr;
3254   size_t symcount;
3255   size_t extsymcount;
3256   size_t extsymoff;
3257   Elf_Internal_Sym *isymbuf;
3258   Elf_Internal_Sym *isym;
3259   Elf_Internal_Sym *isymend;
3260   bfd_boolean result;
3261
3262   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3263   if (abfd == NULL)
3264     return FALSE;
3265
3266   if (! bfd_check_format (abfd, bfd_object))
3267     return FALSE;
3268
3269   /* Select the appropriate symbol table.  If we don't know if the
3270      object file is an IR object, give linker LTO plugin a chance to
3271      get the correct symbol table.  */
3272   if (abfd->plugin_format == bfd_plugin_yes
3273 #if BFD_SUPPORTS_PLUGINS
3274       || (abfd->plugin_format == bfd_plugin_unknown
3275           && bfd_link_plugin_object_p (abfd))
3276 #endif
3277       )
3278     {
3279       /* Use the IR symbol table if the object has been claimed by
3280          plugin.  */
3281       abfd = abfd->plugin_dummy_bfd;
3282       hdr = &elf_tdata (abfd)->symtab_hdr;
3283     }
3284   else if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3285     hdr = &elf_tdata (abfd)->symtab_hdr;
3286   else
3287     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3288
3289   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3290
3291   /* The sh_info field of the symtab header tells us where the
3292      external symbols start.  We don't care about the local symbols.  */
3293   if (elf_bad_symtab (abfd))
3294     {
3295       extsymcount = symcount;
3296       extsymoff = 0;
3297     }
3298   else
3299     {
3300       extsymcount = symcount - hdr->sh_info;
3301       extsymoff = hdr->sh_info;
3302     }
3303
3304   if (extsymcount == 0)
3305     return FALSE;
3306
3307   /* Read in the symbol table.  */
3308   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3309                                   NULL, NULL, NULL);
3310   if (isymbuf == NULL)
3311     return FALSE;
3312
3313   /* Scan the symbol table looking for SYMDEF.  */
3314   result = FALSE;
3315   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3316     {
3317       const char *name;
3318
3319       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3320                                               isym->st_name);
3321       if (name == NULL)
3322         break;
3323
3324       if (strcmp (name, symdef->name) == 0)
3325         {
3326           result = is_global_data_symbol_definition (abfd, isym);
3327           break;
3328         }
3329     }
3330
3331   free (isymbuf);
3332
3333   return result;
3334 }
3335 \f
3336 /* Add an entry to the .dynamic table.  */
3337
3338 bfd_boolean
3339 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3340                             bfd_vma tag,
3341                             bfd_vma val)
3342 {
3343   struct elf_link_hash_table *hash_table;
3344   const struct elf_backend_data *bed;
3345   asection *s;
3346   bfd_size_type newsize;
3347   bfd_byte *newcontents;
3348   Elf_Internal_Dyn dyn;
3349
3350   hash_table = elf_hash_table (info);
3351   if (! is_elf_hash_table (hash_table))
3352     return FALSE;
3353
3354   bed = get_elf_backend_data (hash_table->dynobj);
3355   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3356   BFD_ASSERT (s != NULL);
3357
3358   newsize = s->size + bed->s->sizeof_dyn;
3359   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3360   if (newcontents == NULL)
3361     return FALSE;
3362
3363   dyn.d_tag = tag;
3364   dyn.d_un.d_val = val;
3365   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3366
3367   s->size = newsize;
3368   s->contents = newcontents;
3369
3370   return TRUE;
3371 }
3372
3373 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3374    otherwise just check whether one already exists.  Returns -1 on error,
3375    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3376
3377 static int
3378 elf_add_dt_needed_tag (bfd *abfd,
3379                        struct bfd_link_info *info,
3380                        const char *soname,
3381                        bfd_boolean do_it)
3382 {
3383   struct elf_link_hash_table *hash_table;
3384   size_t strindex;
3385
3386   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3387     return -1;
3388
3389   hash_table = elf_hash_table (info);
3390   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3391   if (strindex == (size_t) -1)
3392     return -1;
3393
3394   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3395     {
3396       asection *sdyn;
3397       const struct elf_backend_data *bed;
3398       bfd_byte *extdyn;
3399
3400       bed = get_elf_backend_data (hash_table->dynobj);
3401       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3402       if (sdyn != NULL)
3403         for (extdyn = sdyn->contents;
3404              extdyn < sdyn->contents + sdyn->size;
3405              extdyn += bed->s->sizeof_dyn)
3406           {
3407             Elf_Internal_Dyn dyn;
3408
3409             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3410             if (dyn.d_tag == DT_NEEDED
3411                 && dyn.d_un.d_val == strindex)
3412               {
3413                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3414                 return 1;
3415               }
3416           }
3417     }
3418
3419   if (do_it)
3420     {
3421       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3422         return -1;
3423
3424       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3425         return -1;
3426     }
3427   else
3428     /* We were just checking for existence of the tag.  */
3429     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3430
3431   return 0;
3432 }
3433
3434 /* Return true if SONAME is on the needed list between NEEDED and STOP
3435    (or the end of list if STOP is NULL), and needed by a library that
3436    will be loaded.  */
3437
3438 static bfd_boolean
3439 on_needed_list (const char *soname,
3440                 struct bfd_link_needed_list *needed,
3441                 struct bfd_link_needed_list *stop)
3442 {
3443   struct bfd_link_needed_list *look;
3444   for (look = needed; look != stop; look = look->next)
3445     if (strcmp (soname, look->name) == 0
3446         && ((elf_dyn_lib_class (look->by) & DYN_AS_NEEDED) == 0
3447             /* If needed by a library that itself is not directly
3448                needed, recursively check whether that library is
3449                indirectly needed.  Since we add DT_NEEDED entries to
3450                the end of the list, library dependencies appear after
3451                the library.  Therefore search prior to the current
3452                LOOK, preventing possible infinite recursion.  */
3453             || on_needed_list (elf_dt_name (look->by), needed, look)))
3454       return TRUE;
3455
3456   return FALSE;
3457 }
3458
3459 /* Sort symbol by value, section, and size.  */
3460 static int
3461 elf_sort_symbol (const void *arg1, const void *arg2)
3462 {
3463   const struct elf_link_hash_entry *h1;
3464   const struct elf_link_hash_entry *h2;
3465   bfd_signed_vma vdiff;
3466
3467   h1 = *(const struct elf_link_hash_entry **) arg1;
3468   h2 = *(const struct elf_link_hash_entry **) arg2;
3469   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3470   if (vdiff != 0)
3471     return vdiff > 0 ? 1 : -1;
3472   else
3473     {
3474       int sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3475       if (sdiff != 0)
3476         return sdiff > 0 ? 1 : -1;
3477     }
3478   vdiff = h1->size - h2->size;
3479   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3480 }
3481
3482 /* This function is used to adjust offsets into .dynstr for
3483    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3484
3485 static bfd_boolean
3486 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3487 {
3488   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3489
3490   if (h->dynindx != -1)
3491     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3492   return TRUE;
3493 }
3494
3495 /* Assign string offsets in .dynstr, update all structures referencing
3496    them.  */
3497
3498 static bfd_boolean
3499 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3500 {
3501   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3502   struct elf_link_local_dynamic_entry *entry;
3503   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3504   bfd *dynobj = hash_table->dynobj;
3505   asection *sdyn;
3506   bfd_size_type size;
3507   const struct elf_backend_data *bed;
3508   bfd_byte *extdyn;
3509
3510   _bfd_elf_strtab_finalize (dynstr);
3511   size = _bfd_elf_strtab_size (dynstr);
3512
3513   bed = get_elf_backend_data (dynobj);
3514   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3515   BFD_ASSERT (sdyn != NULL);
3516
3517   /* Update all .dynamic entries referencing .dynstr strings.  */
3518   for (extdyn = sdyn->contents;
3519        extdyn < sdyn->contents + sdyn->size;
3520        extdyn += bed->s->sizeof_dyn)
3521     {
3522       Elf_Internal_Dyn dyn;
3523
3524       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3525       switch (dyn.d_tag)
3526         {
3527         case DT_STRSZ:
3528           dyn.d_un.d_val = size;
3529           break;
3530         case DT_NEEDED:
3531         case DT_SONAME:
3532         case DT_RPATH:
3533         case DT_RUNPATH:
3534         case DT_FILTER:
3535         case DT_AUXILIARY:
3536         case DT_AUDIT:
3537         case DT_DEPAUDIT:
3538           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3539           break;
3540         default:
3541           continue;
3542         }
3543       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3544     }
3545
3546   /* Now update local dynamic symbols.  */
3547   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3548     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3549                                                   entry->isym.st_name);
3550
3551   /* And the rest of dynamic symbols.  */
3552   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3553
3554   /* Adjust version definitions.  */
3555   if (elf_tdata (output_bfd)->cverdefs)
3556     {
3557       asection *s;
3558       bfd_byte *p;
3559       size_t i;
3560       Elf_Internal_Verdef def;
3561       Elf_Internal_Verdaux defaux;
3562
3563       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3564       p = s->contents;
3565       do
3566         {
3567           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3568                                    &def);
3569           p += sizeof (Elf_External_Verdef);
3570           if (def.vd_aux != sizeof (Elf_External_Verdef))
3571             continue;
3572           for (i = 0; i < def.vd_cnt; ++i)
3573             {
3574               _bfd_elf_swap_verdaux_in (output_bfd,
3575                                         (Elf_External_Verdaux *) p, &defaux);
3576               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3577                                                         defaux.vda_name);
3578               _bfd_elf_swap_verdaux_out (output_bfd,
3579                                          &defaux, (Elf_External_Verdaux *) p);
3580               p += sizeof (Elf_External_Verdaux);
3581             }
3582         }
3583       while (def.vd_next);
3584     }
3585
3586   /* Adjust version references.  */
3587   if (elf_tdata (output_bfd)->verref)
3588     {
3589       asection *s;
3590       bfd_byte *p;
3591       size_t i;
3592       Elf_Internal_Verneed need;
3593       Elf_Internal_Vernaux needaux;
3594
3595       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3596       p = s->contents;
3597       do
3598         {
3599           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3600                                     &need);
3601           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3602           _bfd_elf_swap_verneed_out (output_bfd, &need,
3603                                      (Elf_External_Verneed *) p);
3604           p += sizeof (Elf_External_Verneed);
3605           for (i = 0; i < need.vn_cnt; ++i)
3606             {
3607               _bfd_elf_swap_vernaux_in (output_bfd,
3608                                         (Elf_External_Vernaux *) p, &needaux);
3609               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3610                                                          needaux.vna_name);
3611               _bfd_elf_swap_vernaux_out (output_bfd,
3612                                          &needaux,
3613                                          (Elf_External_Vernaux *) p);
3614               p += sizeof (Elf_External_Vernaux);
3615             }
3616         }
3617       while (need.vn_next);
3618     }
3619
3620   return TRUE;
3621 }
3622 \f
3623 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3624    The default is to only match when the INPUT and OUTPUT are exactly
3625    the same target.  */
3626
3627 bfd_boolean
3628 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3629                                     const bfd_target *output)
3630 {
3631   return input == output;
3632 }
3633
3634 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3635    This version is used when different targets for the same architecture
3636    are virtually identical.  */
3637
3638 bfd_boolean
3639 _bfd_elf_relocs_compatible (const bfd_target *input,
3640                             const bfd_target *output)
3641 {
3642   const struct elf_backend_data *obed, *ibed;
3643
3644   if (input == output)
3645     return TRUE;
3646
3647   ibed = xvec_get_elf_backend_data (input);
3648   obed = xvec_get_elf_backend_data (output);
3649
3650   if (ibed->arch != obed->arch)
3651     return FALSE;
3652
3653   /* If both backends are using this function, deem them compatible.  */
3654   return ibed->relocs_compatible == obed->relocs_compatible;
3655 }
3656
3657 /* Make a special call to the linker "notice" function to tell it that
3658    we are about to handle an as-needed lib, or have finished
3659    processing the lib.  */
3660
3661 bfd_boolean
3662 _bfd_elf_notice_as_needed (bfd *ibfd,
3663                            struct bfd_link_info *info,
3664                            enum notice_asneeded_action act)
3665 {
3666   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3667 }
3668
3669 /* Check relocations an ELF object file.  */
3670
3671 bfd_boolean
3672 _bfd_elf_link_check_relocs (bfd *abfd, struct bfd_link_info *info)
3673 {
3674   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3675   struct elf_link_hash_table *htab = elf_hash_table (info);
3676
3677   /* If this object is the same format as the output object, and it is
3678      not a shared library, then let the backend look through the
3679      relocs.
3680
3681      This is required to build global offset table entries and to
3682      arrange for dynamic relocs.  It is not required for the
3683      particular common case of linking non PIC code, even when linking
3684      against shared libraries, but unfortunately there is no way of
3685      knowing whether an object file has been compiled PIC or not.
3686      Looking through the relocs is not particularly time consuming.
3687      The problem is that we must either (1) keep the relocs in memory,
3688      which causes the linker to require additional runtime memory or
3689      (2) read the relocs twice from the input file, which wastes time.
3690      This would be a good case for using mmap.
3691
3692      I have no idea how to handle linking PIC code into a file of a
3693      different format.  It probably can't be done.  */
3694   if ((abfd->flags & DYNAMIC) == 0
3695       && is_elf_hash_table (htab)
3696       && bed->check_relocs != NULL
3697       && elf_object_id (abfd) == elf_hash_table_id (htab)
3698       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
3699     {
3700       asection *o;
3701
3702       for (o = abfd->sections; o != NULL; o = o->next)
3703         {
3704           Elf_Internal_Rela *internal_relocs;
3705           bfd_boolean ok;
3706
3707           /* Don't check relocations in excluded sections.  */
3708           if ((o->flags & SEC_RELOC) == 0
3709               || (o->flags & SEC_EXCLUDE) != 0
3710               || o->reloc_count == 0
3711               || ((info->strip == strip_all || info->strip == strip_debugger)
3712                   && (o->flags & SEC_DEBUGGING) != 0)
3713               || bfd_is_abs_section (o->output_section))
3714             continue;
3715
3716           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
3717                                                        info->keep_memory);
3718           if (internal_relocs == NULL)
3719             return FALSE;
3720
3721           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
3722
3723           if (elf_section_data (o)->relocs != internal_relocs)
3724             free (internal_relocs);
3725
3726           if (! ok)
3727             return FALSE;
3728         }
3729     }
3730
3731   return TRUE;
3732 }
3733
3734 /* Add symbols from an ELF object file to the linker hash table.  */
3735
3736 static bfd_boolean
3737 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3738 {
3739   Elf_Internal_Ehdr *ehdr;
3740   Elf_Internal_Shdr *hdr;
3741   size_t symcount;
3742   size_t extsymcount;
3743   size_t extsymoff;
3744   struct elf_link_hash_entry **sym_hash;
3745   bfd_boolean dynamic;
3746   Elf_External_Versym *extversym = NULL;
3747   Elf_External_Versym *ever;
3748   struct elf_link_hash_entry *weaks;
3749   struct elf_link_hash_entry **nondeflt_vers = NULL;
3750   size_t nondeflt_vers_cnt = 0;
3751   Elf_Internal_Sym *isymbuf = NULL;
3752   Elf_Internal_Sym *isym;
3753   Elf_Internal_Sym *isymend;
3754   const struct elf_backend_data *bed;
3755   bfd_boolean add_needed;
3756   struct elf_link_hash_table *htab;
3757   bfd_size_type amt;
3758   void *alloc_mark = NULL;
3759   struct bfd_hash_entry **old_table = NULL;
3760   unsigned int old_size = 0;
3761   unsigned int old_count = 0;
3762   void *old_tab = NULL;
3763   void *old_ent;
3764   struct bfd_link_hash_entry *old_undefs = NULL;
3765   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3766   void *old_strtab = NULL;
3767   size_t tabsize = 0;
3768   asection *s;
3769   bfd_boolean just_syms;
3770
3771   htab = elf_hash_table (info);
3772   bed = get_elf_backend_data (abfd);
3773
3774   if ((abfd->flags & DYNAMIC) == 0)
3775     dynamic = FALSE;
3776   else
3777     {
3778       dynamic = TRUE;
3779
3780       /* You can't use -r against a dynamic object.  Also, there's no
3781          hope of using a dynamic object which does not exactly match
3782          the format of the output file.  */
3783       if (bfd_link_relocatable (info)
3784           || !is_elf_hash_table (htab)
3785           || info->output_bfd->xvec != abfd->xvec)
3786         {
3787           if (bfd_link_relocatable (info))
3788             bfd_set_error (bfd_error_invalid_operation);
3789           else
3790             bfd_set_error (bfd_error_wrong_format);
3791           goto error_return;
3792         }
3793     }
3794
3795   ehdr = elf_elfheader (abfd);
3796   if (info->warn_alternate_em
3797       && bed->elf_machine_code != ehdr->e_machine
3798       && ((bed->elf_machine_alt1 != 0
3799            && ehdr->e_machine == bed->elf_machine_alt1)
3800           || (bed->elf_machine_alt2 != 0
3801               && ehdr->e_machine == bed->elf_machine_alt2)))
3802     info->callbacks->einfo
3803       /* xgettext:c-format */
3804       (_("%P: alternate ELF machine code found (%d) in %B, expecting %d\n"),
3805        ehdr->e_machine, abfd, bed->elf_machine_code);
3806
3807   /* As a GNU extension, any input sections which are named
3808      .gnu.warning.SYMBOL are treated as warning symbols for the given
3809      symbol.  This differs from .gnu.warning sections, which generate
3810      warnings when they are included in an output file.  */
3811   /* PR 12761: Also generate this warning when building shared libraries.  */
3812   for (s = abfd->sections; s != NULL; s = s->next)
3813     {
3814       const char *name;
3815
3816       name = bfd_get_section_name (abfd, s);
3817       if (CONST_STRNEQ (name, ".gnu.warning."))
3818         {
3819           char *msg;
3820           bfd_size_type sz;
3821
3822           name += sizeof ".gnu.warning." - 1;
3823
3824           /* If this is a shared object, then look up the symbol
3825              in the hash table.  If it is there, and it is already
3826              been defined, then we will not be using the entry
3827              from this shared object, so we don't need to warn.
3828              FIXME: If we see the definition in a regular object
3829              later on, we will warn, but we shouldn't.  The only
3830              fix is to keep track of what warnings we are supposed
3831              to emit, and then handle them all at the end of the
3832              link.  */
3833           if (dynamic)
3834             {
3835               struct elf_link_hash_entry *h;
3836
3837               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3838
3839               /* FIXME: What about bfd_link_hash_common?  */
3840               if (h != NULL
3841                   && (h->root.type == bfd_link_hash_defined
3842                       || h->root.type == bfd_link_hash_defweak))
3843                 continue;
3844             }
3845
3846           sz = s->size;
3847           msg = (char *) bfd_alloc (abfd, sz + 1);
3848           if (msg == NULL)
3849             goto error_return;
3850
3851           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3852             goto error_return;
3853
3854           msg[sz] = '\0';
3855
3856           if (! (_bfd_generic_link_add_one_symbol
3857                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3858                   FALSE, bed->collect, NULL)))
3859             goto error_return;
3860
3861           if (bfd_link_executable (info))
3862             {
3863               /* Clobber the section size so that the warning does
3864                  not get copied into the output file.  */
3865               s->size = 0;
3866
3867               /* Also set SEC_EXCLUDE, so that symbols defined in
3868                  the warning section don't get copied to the output.  */
3869               s->flags |= SEC_EXCLUDE;
3870             }
3871         }
3872     }
3873
3874   just_syms = ((s = abfd->sections) != NULL
3875                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3876
3877   add_needed = TRUE;
3878   if (! dynamic)
3879     {
3880       /* If we are creating a shared library, create all the dynamic
3881          sections immediately.  We need to attach them to something,
3882          so we attach them to this BFD, provided it is the right
3883          format and is not from ld --just-symbols.  Always create the
3884          dynamic sections for -E/--dynamic-list.  FIXME: If there
3885          are no input BFD's of the same format as the output, we can't
3886          make a shared library.  */
3887       if (!just_syms
3888           && (bfd_link_pic (info)
3889               || (!bfd_link_relocatable (info)
3890                   && info->nointerp
3891                   && (info->export_dynamic || info->dynamic)))
3892           && is_elf_hash_table (htab)
3893           && info->output_bfd->xvec == abfd->xvec
3894           && !htab->dynamic_sections_created)
3895         {
3896           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3897             goto error_return;
3898         }
3899     }
3900   else if (!is_elf_hash_table (htab))
3901     goto error_return;
3902   else
3903     {
3904       const char *soname = NULL;
3905       char *audit = NULL;
3906       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3907       const Elf_Internal_Phdr *phdr;
3908       int ret;
3909
3910       /* ld --just-symbols and dynamic objects don't mix very well.
3911          ld shouldn't allow it.  */
3912       if (just_syms)
3913         abort ();
3914
3915       /* If this dynamic lib was specified on the command line with
3916          --as-needed in effect, then we don't want to add a DT_NEEDED
3917          tag unless the lib is actually used.  Similary for libs brought
3918          in by another lib's DT_NEEDED.  When --no-add-needed is used
3919          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3920          any dynamic library in DT_NEEDED tags in the dynamic lib at
3921          all.  */
3922       add_needed = (elf_dyn_lib_class (abfd)
3923                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3924                        | DYN_NO_NEEDED)) == 0;
3925
3926       s = bfd_get_section_by_name (abfd, ".dynamic");
3927       if (s != NULL)
3928         {
3929           bfd_byte *dynbuf;
3930           bfd_byte *extdyn;
3931           unsigned int elfsec;
3932           unsigned long shlink;
3933
3934           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3935             {
3936 error_free_dyn:
3937               free (dynbuf);
3938               goto error_return;
3939             }
3940
3941           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3942           if (elfsec == SHN_BAD)
3943             goto error_free_dyn;
3944           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3945
3946           for (extdyn = dynbuf;
3947                extdyn < dynbuf + s->size;
3948                extdyn += bed->s->sizeof_dyn)
3949             {
3950               Elf_Internal_Dyn dyn;
3951
3952               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3953               if (dyn.d_tag == DT_SONAME)
3954                 {
3955                   unsigned int tagv = dyn.d_un.d_val;
3956                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3957                   if (soname == NULL)
3958                     goto error_free_dyn;
3959                 }
3960               if (dyn.d_tag == DT_NEEDED)
3961                 {
3962                   struct bfd_link_needed_list *n, **pn;
3963                   char *fnm, *anm;
3964                   unsigned int tagv = dyn.d_un.d_val;
3965
3966                   amt = sizeof (struct bfd_link_needed_list);
3967                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3968                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3969                   if (n == NULL || fnm == NULL)
3970                     goto error_free_dyn;
3971                   amt = strlen (fnm) + 1;
3972                   anm = (char *) bfd_alloc (abfd, amt);
3973                   if (anm == NULL)
3974                     goto error_free_dyn;
3975                   memcpy (anm, fnm, amt);
3976                   n->name = anm;
3977                   n->by = abfd;
3978                   n->next = NULL;
3979                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
3980                     ;
3981                   *pn = n;
3982                 }
3983               if (dyn.d_tag == DT_RUNPATH)
3984                 {
3985                   struct bfd_link_needed_list *n, **pn;
3986                   char *fnm, *anm;
3987                   unsigned int tagv = dyn.d_un.d_val;
3988
3989                   amt = sizeof (struct bfd_link_needed_list);
3990                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3991                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3992                   if (n == NULL || fnm == NULL)
3993                     goto error_free_dyn;
3994                   amt = strlen (fnm) + 1;
3995                   anm = (char *) bfd_alloc (abfd, amt);
3996                   if (anm == NULL)
3997                     goto error_free_dyn;
3998                   memcpy (anm, fnm, amt);
3999                   n->name = anm;
4000                   n->by = abfd;
4001                   n->next = NULL;
4002                   for (pn = & runpath;
4003                        *pn != NULL;
4004                        pn = &(*pn)->next)
4005                     ;
4006                   *pn = n;
4007                 }
4008               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
4009               if (!runpath && dyn.d_tag == DT_RPATH)
4010                 {
4011                   struct bfd_link_needed_list *n, **pn;
4012                   char *fnm, *anm;
4013                   unsigned int tagv = dyn.d_un.d_val;
4014
4015                   amt = sizeof (struct bfd_link_needed_list);
4016                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
4017                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4018                   if (n == NULL || fnm == NULL)
4019                     goto error_free_dyn;
4020                   amt = strlen (fnm) + 1;
4021                   anm = (char *) bfd_alloc (abfd, amt);
4022                   if (anm == NULL)
4023                     goto error_free_dyn;
4024                   memcpy (anm, fnm, amt);
4025                   n->name = anm;
4026                   n->by = abfd;
4027                   n->next = NULL;
4028                   for (pn = & rpath;
4029                        *pn != NULL;
4030                        pn = &(*pn)->next)
4031                     ;
4032                   *pn = n;
4033                 }
4034               if (dyn.d_tag == DT_AUDIT)
4035                 {
4036                   unsigned int tagv = dyn.d_un.d_val;
4037                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4038                 }
4039             }
4040
4041           free (dynbuf);
4042         }
4043
4044       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
4045          frees all more recently bfd_alloc'd blocks as well.  */
4046       if (runpath)
4047         rpath = runpath;
4048
4049       if (rpath)
4050         {
4051           struct bfd_link_needed_list **pn;
4052           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
4053             ;
4054           *pn = rpath;
4055         }
4056
4057       /* If we have a PT_GNU_RELRO program header, mark as read-only
4058          all sections contained fully therein.  This makes relro
4059          shared library sections appear as they will at run-time.  */
4060       phdr = elf_tdata (abfd)->phdr + elf_elfheader (abfd)->e_phnum;
4061       while (--phdr >= elf_tdata (abfd)->phdr)
4062         if (phdr->p_type == PT_GNU_RELRO)
4063           {
4064             for (s = abfd->sections; s != NULL; s = s->next)
4065               if ((s->flags & SEC_ALLOC) != 0
4066                   && s->vma >= phdr->p_vaddr
4067                   && s->vma + s->size <= phdr->p_vaddr + phdr->p_memsz)
4068                 s->flags |= SEC_READONLY;
4069             break;
4070           }
4071
4072       /* We do not want to include any of the sections in a dynamic
4073          object in the output file.  We hack by simply clobbering the
4074          list of sections in the BFD.  This could be handled more
4075          cleanly by, say, a new section flag; the existing
4076          SEC_NEVER_LOAD flag is not the one we want, because that one
4077          still implies that the section takes up space in the output
4078          file.  */
4079       bfd_section_list_clear (abfd);
4080
4081       /* Find the name to use in a DT_NEEDED entry that refers to this
4082          object.  If the object has a DT_SONAME entry, we use it.
4083          Otherwise, if the generic linker stuck something in
4084          elf_dt_name, we use that.  Otherwise, we just use the file
4085          name.  */
4086       if (soname == NULL || *soname == '\0')
4087         {
4088           soname = elf_dt_name (abfd);
4089           if (soname == NULL || *soname == '\0')
4090             soname = bfd_get_filename (abfd);
4091         }
4092
4093       /* Save the SONAME because sometimes the linker emulation code
4094          will need to know it.  */
4095       elf_dt_name (abfd) = soname;
4096
4097       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4098       if (ret < 0)
4099         goto error_return;
4100
4101       /* If we have already included this dynamic object in the
4102          link, just ignore it.  There is no reason to include a
4103          particular dynamic object more than once.  */
4104       if (ret > 0)
4105         return TRUE;
4106
4107       /* Save the DT_AUDIT entry for the linker emulation code. */
4108       elf_dt_audit (abfd) = audit;
4109     }
4110
4111   /* If this is a dynamic object, we always link against the .dynsym
4112      symbol table, not the .symtab symbol table.  The dynamic linker
4113      will only see the .dynsym symbol table, so there is no reason to
4114      look at .symtab for a dynamic object.  */
4115
4116   if (! dynamic || elf_dynsymtab (abfd) == 0)
4117     hdr = &elf_tdata (abfd)->symtab_hdr;
4118   else
4119     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
4120
4121   symcount = hdr->sh_size / bed->s->sizeof_sym;
4122
4123   /* The sh_info field of the symtab header tells us where the
4124      external symbols start.  We don't care about the local symbols at
4125      this point.  */
4126   if (elf_bad_symtab (abfd))
4127     {
4128       extsymcount = symcount;
4129       extsymoff = 0;
4130     }
4131   else
4132     {
4133       extsymcount = symcount - hdr->sh_info;
4134       extsymoff = hdr->sh_info;
4135     }
4136
4137   sym_hash = elf_sym_hashes (abfd);
4138   if (extsymcount != 0)
4139     {
4140       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
4141                                       NULL, NULL, NULL);
4142       if (isymbuf == NULL)
4143         goto error_return;
4144
4145       if (sym_hash == NULL)
4146         {
4147           /* We store a pointer to the hash table entry for each
4148              external symbol.  */
4149           amt = extsymcount;
4150           amt *= sizeof (struct elf_link_hash_entry *);
4151           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
4152           if (sym_hash == NULL)
4153             goto error_free_sym;
4154           elf_sym_hashes (abfd) = sym_hash;
4155         }
4156     }
4157
4158   if (dynamic)
4159     {
4160       /* Read in any version definitions.  */
4161       if (!_bfd_elf_slurp_version_tables (abfd,
4162                                           info->default_imported_symver))
4163         goto error_free_sym;
4164
4165       /* Read in the symbol versions, but don't bother to convert them
4166          to internal format.  */
4167       if (elf_dynversym (abfd) != 0)
4168         {
4169           Elf_Internal_Shdr *versymhdr;
4170
4171           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
4172           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
4173           if (extversym == NULL)
4174             goto error_free_sym;
4175           amt = versymhdr->sh_size;
4176           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
4177               || bfd_bread (extversym, amt, abfd) != amt)
4178             goto error_free_vers;
4179         }
4180     }
4181
4182   /* If we are loading an as-needed shared lib, save the symbol table
4183      state before we start adding symbols.  If the lib turns out
4184      to be unneeded, restore the state.  */
4185   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4186     {
4187       unsigned int i;
4188       size_t entsize;
4189
4190       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
4191         {
4192           struct bfd_hash_entry *p;
4193           struct elf_link_hash_entry *h;
4194
4195           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4196             {
4197               h = (struct elf_link_hash_entry *) p;
4198               entsize += htab->root.table.entsize;
4199               if (h->root.type == bfd_link_hash_warning)
4200                 entsize += htab->root.table.entsize;
4201             }
4202         }
4203
4204       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
4205       old_tab = bfd_malloc (tabsize + entsize);
4206       if (old_tab == NULL)
4207         goto error_free_vers;
4208
4209       /* Remember the current objalloc pointer, so that all mem for
4210          symbols added can later be reclaimed.  */
4211       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
4212       if (alloc_mark == NULL)
4213         goto error_free_vers;
4214
4215       /* Make a special call to the linker "notice" function to
4216          tell it that we are about to handle an as-needed lib.  */
4217       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
4218         goto error_free_vers;
4219
4220       /* Clone the symbol table.  Remember some pointers into the
4221          symbol table, and dynamic symbol count.  */
4222       old_ent = (char *) old_tab + tabsize;
4223       memcpy (old_tab, htab->root.table.table, tabsize);
4224       old_undefs = htab->root.undefs;
4225       old_undefs_tail = htab->root.undefs_tail;
4226       old_table = htab->root.table.table;
4227       old_size = htab->root.table.size;
4228       old_count = htab->root.table.count;
4229       old_strtab = _bfd_elf_strtab_save (htab->dynstr);
4230       if (old_strtab == NULL)
4231         goto error_free_vers;
4232
4233       for (i = 0; i < htab->root.table.size; i++)
4234         {
4235           struct bfd_hash_entry *p;
4236           struct elf_link_hash_entry *h;
4237
4238           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4239             {
4240               memcpy (old_ent, p, htab->root.table.entsize);
4241               old_ent = (char *) old_ent + htab->root.table.entsize;
4242               h = (struct elf_link_hash_entry *) p;
4243               if (h->root.type == bfd_link_hash_warning)
4244                 {
4245                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
4246                   old_ent = (char *) old_ent + htab->root.table.entsize;
4247                 }
4248             }
4249         }
4250     }
4251
4252   weaks = NULL;
4253   ever = extversym != NULL ? extversym + extsymoff : NULL;
4254   for (isym = isymbuf, isymend = isymbuf + extsymcount;
4255        isym < isymend;
4256        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
4257     {
4258       int bind;
4259       bfd_vma value;
4260       asection *sec, *new_sec;
4261       flagword flags;
4262       const char *name;
4263       struct elf_link_hash_entry *h;
4264       struct elf_link_hash_entry *hi;
4265       bfd_boolean definition;
4266       bfd_boolean size_change_ok;
4267       bfd_boolean type_change_ok;
4268       bfd_boolean new_weak;
4269       bfd_boolean old_weak;
4270       bfd_boolean override;
4271       bfd_boolean common;
4272       bfd_boolean discarded;
4273       unsigned int old_alignment;
4274       bfd *old_bfd;
4275       bfd_boolean matched;
4276
4277       override = FALSE;
4278
4279       flags = BSF_NO_FLAGS;
4280       sec = NULL;
4281       value = isym->st_value;
4282       common = bed->common_definition (isym);
4283       if (common && info->inhibit_common_definition)
4284         {
4285           /* Treat common symbol as undefined for --no-define-common.  */
4286           isym->st_shndx = SHN_UNDEF;
4287           common = FALSE;
4288         }
4289       discarded = FALSE;
4290
4291       bind = ELF_ST_BIND (isym->st_info);
4292       switch (bind)
4293         {
4294         case STB_LOCAL:
4295           /* This should be impossible, since ELF requires that all
4296              global symbols follow all local symbols, and that sh_info
4297              point to the first global symbol.  Unfortunately, Irix 5
4298              screws this up.  */
4299           continue;
4300
4301         case STB_GLOBAL:
4302           if (isym->st_shndx != SHN_UNDEF && !common)
4303             flags = BSF_GLOBAL;
4304           break;
4305
4306         case STB_WEAK:
4307           flags = BSF_WEAK;
4308           break;
4309
4310         case STB_GNU_UNIQUE:
4311           flags = BSF_GNU_UNIQUE;
4312           break;
4313
4314         default:
4315           /* Leave it up to the processor backend.  */
4316           break;
4317         }
4318
4319       if (isym->st_shndx == SHN_UNDEF)
4320         sec = bfd_und_section_ptr;
4321       else if (isym->st_shndx == SHN_ABS)
4322         sec = bfd_abs_section_ptr;
4323       else if (isym->st_shndx == SHN_COMMON)
4324         {
4325           sec = bfd_com_section_ptr;
4326           /* What ELF calls the size we call the value.  What ELF
4327              calls the value we call the alignment.  */
4328           value = isym->st_size;
4329         }
4330       else
4331         {
4332           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
4333           if (sec == NULL)
4334             sec = bfd_abs_section_ptr;
4335           else if (discarded_section (sec))
4336             {
4337               /* Symbols from discarded section are undefined.  We keep
4338                  its visibility.  */
4339               sec = bfd_und_section_ptr;
4340               discarded = TRUE;
4341               isym->st_shndx = SHN_UNDEF;
4342             }
4343           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
4344             value -= sec->vma;
4345         }
4346
4347       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4348                                               isym->st_name);
4349       if (name == NULL)
4350         goto error_free_vers;
4351
4352       if (isym->st_shndx == SHN_COMMON
4353           && (abfd->flags & BFD_PLUGIN) != 0)
4354         {
4355           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4356
4357           if (xc == NULL)
4358             {
4359               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4360                                  | SEC_EXCLUDE);
4361               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4362               if (xc == NULL)
4363                 goto error_free_vers;
4364             }
4365           sec = xc;
4366         }
4367       else if (isym->st_shndx == SHN_COMMON
4368                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4369                && !bfd_link_relocatable (info))
4370         {
4371           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4372
4373           if (tcomm == NULL)
4374             {
4375               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4376                                  | SEC_LINKER_CREATED);
4377               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4378               if (tcomm == NULL)
4379                 goto error_free_vers;
4380             }
4381           sec = tcomm;
4382         }
4383       else if (bed->elf_add_symbol_hook)
4384         {
4385           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4386                                              &sec, &value))
4387             goto error_free_vers;
4388
4389           /* The hook function sets the name to NULL if this symbol
4390              should be skipped for some reason.  */
4391           if (name == NULL)
4392             continue;
4393         }
4394
4395       /* Sanity check that all possibilities were handled.  */
4396       if (sec == NULL)
4397         {
4398           bfd_set_error (bfd_error_bad_value);
4399           goto error_free_vers;
4400         }
4401
4402       /* Silently discard TLS symbols from --just-syms.  There's
4403          no way to combine a static TLS block with a new TLS block
4404          for this executable.  */
4405       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4406           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4407         continue;
4408
4409       if (bfd_is_und_section (sec)
4410           || bfd_is_com_section (sec))
4411         definition = FALSE;
4412       else
4413         definition = TRUE;
4414
4415       size_change_ok = FALSE;
4416       type_change_ok = bed->type_change_ok;
4417       old_weak = FALSE;
4418       matched = FALSE;
4419       old_alignment = 0;
4420       old_bfd = NULL;
4421       new_sec = sec;
4422
4423       if (is_elf_hash_table (htab))
4424         {
4425           Elf_Internal_Versym iver;
4426           unsigned int vernum = 0;
4427           bfd_boolean skip;
4428
4429           if (ever == NULL)
4430             {
4431               if (info->default_imported_symver)
4432                 /* Use the default symbol version created earlier.  */
4433                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4434               else
4435                 iver.vs_vers = 0;
4436             }
4437           else
4438             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4439
4440           vernum = iver.vs_vers & VERSYM_VERSION;
4441
4442           /* If this is a hidden symbol, or if it is not version
4443              1, we append the version name to the symbol name.
4444              However, we do not modify a non-hidden absolute symbol
4445              if it is not a function, because it might be the version
4446              symbol itself.  FIXME: What if it isn't?  */
4447           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4448               || (vernum > 1
4449                   && (!bfd_is_abs_section (sec)
4450                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4451             {
4452               const char *verstr;
4453               size_t namelen, verlen, newlen;
4454               char *newname, *p;
4455
4456               if (isym->st_shndx != SHN_UNDEF)
4457                 {
4458                   if (vernum > elf_tdata (abfd)->cverdefs)
4459                     verstr = NULL;
4460                   else if (vernum > 1)
4461                     verstr =
4462                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4463                   else
4464                     verstr = "";
4465
4466                   if (verstr == NULL)
4467                     {
4468                       _bfd_error_handler
4469                         /* xgettext:c-format */
4470                         (_("%B: %s: invalid version %u (max %d)"),
4471                          abfd, name, vernum,
4472                          elf_tdata (abfd)->cverdefs);
4473                       bfd_set_error (bfd_error_bad_value);
4474                       goto error_free_vers;
4475                     }
4476                 }
4477               else
4478                 {
4479                   /* We cannot simply test for the number of
4480                      entries in the VERNEED section since the
4481                      numbers for the needed versions do not start
4482                      at 0.  */
4483                   Elf_Internal_Verneed *t;
4484
4485                   verstr = NULL;
4486                   for (t = elf_tdata (abfd)->verref;
4487                        t != NULL;
4488                        t = t->vn_nextref)
4489                     {
4490                       Elf_Internal_Vernaux *a;
4491
4492                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4493                         {
4494                           if (a->vna_other == vernum)
4495                             {
4496                               verstr = a->vna_nodename;
4497                               break;
4498                             }
4499                         }
4500                       if (a != NULL)
4501                         break;
4502                     }
4503                   if (verstr == NULL)
4504                     {
4505                       _bfd_error_handler
4506                         /* xgettext:c-format */
4507                         (_("%B: %s: invalid needed version %d"),
4508                          abfd, name, vernum);
4509                       bfd_set_error (bfd_error_bad_value);
4510                       goto error_free_vers;
4511                     }
4512                 }
4513
4514               namelen = strlen (name);
4515               verlen = strlen (verstr);
4516               newlen = namelen + verlen + 2;
4517               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4518                   && isym->st_shndx != SHN_UNDEF)
4519                 ++newlen;
4520
4521               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4522               if (newname == NULL)
4523                 goto error_free_vers;
4524               memcpy (newname, name, namelen);
4525               p = newname + namelen;
4526               *p++ = ELF_VER_CHR;
4527               /* If this is a defined non-hidden version symbol,
4528                  we add another @ to the name.  This indicates the
4529                  default version of the symbol.  */
4530               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4531                   && isym->st_shndx != SHN_UNDEF)
4532                 *p++ = ELF_VER_CHR;
4533               memcpy (p, verstr, verlen + 1);
4534
4535               name = newname;
4536             }
4537
4538           /* If this symbol has default visibility and the user has
4539              requested we not re-export it, then mark it as hidden.  */
4540           if (!bfd_is_und_section (sec)
4541               && !dynamic
4542               && abfd->no_export
4543               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4544             isym->st_other = (STV_HIDDEN
4545                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4546
4547           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4548                                       sym_hash, &old_bfd, &old_weak,
4549                                       &old_alignment, &skip, &override,
4550                                       &type_change_ok, &size_change_ok,
4551                                       &matched))
4552             goto error_free_vers;
4553
4554           if (skip)
4555             continue;
4556
4557           /* Override a definition only if the new symbol matches the
4558              existing one.  */
4559           if (override && matched)
4560             definition = FALSE;
4561
4562           h = *sym_hash;
4563           while (h->root.type == bfd_link_hash_indirect
4564                  || h->root.type == bfd_link_hash_warning)
4565             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4566
4567           if (elf_tdata (abfd)->verdef != NULL
4568               && vernum > 1
4569               && definition)
4570             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4571         }
4572
4573       if (! (_bfd_generic_link_add_one_symbol
4574              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4575               (struct bfd_link_hash_entry **) sym_hash)))
4576         goto error_free_vers;
4577
4578       if ((flags & BSF_GNU_UNIQUE)
4579           && (abfd->flags & DYNAMIC) == 0
4580           && bfd_get_flavour (info->output_bfd) == bfd_target_elf_flavour)
4581         elf_tdata (info->output_bfd)->has_gnu_symbols |= elf_gnu_symbol_unique;
4582
4583       h = *sym_hash;
4584       /* We need to make sure that indirect symbol dynamic flags are
4585          updated.  */
4586       hi = h;
4587       while (h->root.type == bfd_link_hash_indirect
4588              || h->root.type == bfd_link_hash_warning)
4589         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4590
4591       /* Setting the index to -3 tells elf_link_output_extsym that
4592          this symbol is defined in a discarded section.  */
4593       if (discarded)
4594         h->indx = -3;
4595
4596       *sym_hash = h;
4597
4598       new_weak = (flags & BSF_WEAK) != 0;
4599       if (dynamic
4600           && definition
4601           && new_weak
4602           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4603           && is_elf_hash_table (htab)
4604           && h->u.alias == NULL)
4605         {
4606           /* Keep a list of all weak defined non function symbols from
4607              a dynamic object, using the alias field.  Later in this
4608              function we will set the alias field to the correct
4609              value.  We only put non-function symbols from dynamic
4610              objects on this list, because that happens to be the only
4611              time we need to know the normal symbol corresponding to a
4612              weak symbol, and the information is time consuming to
4613              figure out.  If the alias field is not already NULL,
4614              then this symbol was already defined by some previous
4615              dynamic object, and we will be using that previous
4616              definition anyhow.  */
4617
4618           h->u.alias = weaks;
4619           weaks = h;
4620         }
4621
4622       /* Set the alignment of a common symbol.  */
4623       if ((common || bfd_is_com_section (sec))
4624           && h->root.type == bfd_link_hash_common)
4625         {
4626           unsigned int align;
4627
4628           if (common)
4629             align = bfd_log2 (isym->st_value);
4630           else
4631             {
4632               /* The new symbol is a common symbol in a shared object.
4633                  We need to get the alignment from the section.  */
4634               align = new_sec->alignment_power;
4635             }
4636           if (align > old_alignment)
4637             h->root.u.c.p->alignment_power = align;
4638           else
4639             h->root.u.c.p->alignment_power = old_alignment;
4640         }
4641
4642       if (is_elf_hash_table (htab))
4643         {
4644           /* Set a flag in the hash table entry indicating the type of
4645              reference or definition we just found.  A dynamic symbol
4646              is one which is referenced or defined by both a regular
4647              object and a shared object.  */
4648           bfd_boolean dynsym = FALSE;
4649
4650           /* Plugin symbols aren't normal.  Don't set def_regular or
4651              ref_regular for them, or make them dynamic.  */
4652           if ((abfd->flags & BFD_PLUGIN) != 0)
4653             ;
4654           else if (! dynamic)
4655             {
4656               if (! definition)
4657                 {
4658                   h->ref_regular = 1;
4659                   if (bind != STB_WEAK)
4660                     h->ref_regular_nonweak = 1;
4661                 }
4662               else
4663                 {
4664                   h->def_regular = 1;
4665                   if (h->def_dynamic)
4666                     {
4667                       h->def_dynamic = 0;
4668                       h->ref_dynamic = 1;
4669                     }
4670                 }
4671
4672               /* If the indirect symbol has been forced local, don't
4673                  make the real symbol dynamic.  */
4674               if ((h == hi || !hi->forced_local)
4675                   && (bfd_link_dll (info)
4676                       || h->def_dynamic
4677                       || h->ref_dynamic))
4678                 dynsym = TRUE;
4679             }
4680           else
4681             {
4682               if (! definition)
4683                 {
4684                   h->ref_dynamic = 1;
4685                   hi->ref_dynamic = 1;
4686                 }
4687               else
4688                 {
4689                   h->def_dynamic = 1;
4690                   hi->def_dynamic = 1;
4691                 }
4692
4693               /* If the indirect symbol has been forced local, don't
4694                  make the real symbol dynamic.  */
4695               if ((h == hi || !hi->forced_local)
4696                   && (h->def_regular
4697                       || h->ref_regular
4698                       || (h->is_weakalias
4699                           && weakdef (h)->dynindx != -1)))
4700                 dynsym = TRUE;
4701             }
4702
4703           /* Check to see if we need to add an indirect symbol for
4704              the default name.  */
4705           if (definition
4706               || (!override && h->root.type == bfd_link_hash_common))
4707             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4708                                               sec, value, &old_bfd, &dynsym))
4709               goto error_free_vers;
4710
4711           /* Check the alignment when a common symbol is involved. This
4712              can change when a common symbol is overridden by a normal
4713              definition or a common symbol is ignored due to the old
4714              normal definition. We need to make sure the maximum
4715              alignment is maintained.  */
4716           if ((old_alignment || common)
4717               && h->root.type != bfd_link_hash_common)
4718             {
4719               unsigned int common_align;
4720               unsigned int normal_align;
4721               unsigned int symbol_align;
4722               bfd *normal_bfd;
4723               bfd *common_bfd;
4724
4725               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4726                           || h->root.type == bfd_link_hash_defweak);
4727
4728               symbol_align = ffs (h->root.u.def.value) - 1;
4729               if (h->root.u.def.section->owner != NULL
4730                   && (h->root.u.def.section->owner->flags
4731                        & (DYNAMIC | BFD_PLUGIN)) == 0)
4732                 {
4733                   normal_align = h->root.u.def.section->alignment_power;
4734                   if (normal_align > symbol_align)
4735                     normal_align = symbol_align;
4736                 }
4737               else
4738                 normal_align = symbol_align;
4739
4740               if (old_alignment)
4741                 {
4742                   common_align = old_alignment;
4743                   common_bfd = old_bfd;
4744                   normal_bfd = abfd;
4745                 }
4746               else
4747                 {
4748                   common_align = bfd_log2 (isym->st_value);
4749                   common_bfd = abfd;
4750                   normal_bfd = old_bfd;
4751                 }
4752
4753               if (normal_align < common_align)
4754                 {
4755                   /* PR binutils/2735 */
4756                   if (normal_bfd == NULL)
4757                     _bfd_error_handler
4758                       /* xgettext:c-format */
4759                       (_("Warning: alignment %u of common symbol `%s' in %B is"
4760                          " greater than the alignment (%u) of its section %A"),
4761                        1 << common_align, name, common_bfd,
4762                        1 << normal_align, h->root.u.def.section);
4763                   else
4764                     _bfd_error_handler
4765                       /* xgettext:c-format */
4766                       (_("Warning: alignment %u of symbol `%s' in %B"
4767                          " is smaller than %u in %B"),
4768                        1 << normal_align, name, normal_bfd,
4769                        1 << common_align, common_bfd);
4770                 }
4771             }
4772
4773           /* Remember the symbol size if it isn't undefined.  */
4774           if (isym->st_size != 0
4775               && isym->st_shndx != SHN_UNDEF
4776               && (definition || h->size == 0))
4777             {
4778               if (h->size != 0
4779                   && h->size != isym->st_size
4780                   && ! size_change_ok)
4781                 _bfd_error_handler
4782                   /* xgettext:c-format */
4783                   (_("Warning: size of symbol `%s' changed"
4784                      " from %Lu in %B to %Lu in %B"),
4785                    name, h->size, old_bfd, isym->st_size, abfd);
4786
4787               h->size = isym->st_size;
4788             }
4789
4790           /* If this is a common symbol, then we always want H->SIZE
4791              to be the size of the common symbol.  The code just above
4792              won't fix the size if a common symbol becomes larger.  We
4793              don't warn about a size change here, because that is
4794              covered by --warn-common.  Allow changes between different
4795              function types.  */
4796           if (h->root.type == bfd_link_hash_common)
4797             h->size = h->root.u.c.size;
4798
4799           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4800               && ((definition && !new_weak)
4801                   || (old_weak && h->root.type == bfd_link_hash_common)
4802                   || h->type == STT_NOTYPE))
4803             {
4804               unsigned int type = ELF_ST_TYPE (isym->st_info);
4805
4806               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4807                  symbol.  */
4808               if (type == STT_GNU_IFUNC
4809                   && (abfd->flags & DYNAMIC) != 0)
4810                 type = STT_FUNC;
4811
4812               if (h->type != type)
4813                 {
4814                   if (h->type != STT_NOTYPE && ! type_change_ok)
4815                     /* xgettext:c-format */
4816                     _bfd_error_handler
4817                       (_("Warning: type of symbol `%s' changed"
4818                          " from %d to %d in %B"),
4819                        name, h->type, type, abfd);
4820
4821                   h->type = type;
4822                 }
4823             }
4824
4825           /* Merge st_other field.  */
4826           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4827
4828           /* We don't want to make debug symbol dynamic.  */
4829           if (definition
4830               && (sec->flags & SEC_DEBUGGING)
4831               && !bfd_link_relocatable (info))
4832             dynsym = FALSE;
4833
4834           /* Nor should we make plugin symbols dynamic.  */
4835           if ((abfd->flags & BFD_PLUGIN) != 0)
4836             dynsym = FALSE;
4837
4838           if (definition)
4839             {
4840               h->target_internal = isym->st_target_internal;
4841               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4842             }
4843
4844           if (definition && !dynamic)
4845             {
4846               char *p = strchr (name, ELF_VER_CHR);
4847               if (p != NULL && p[1] != ELF_VER_CHR)
4848                 {
4849                   /* Queue non-default versions so that .symver x, x@FOO
4850                      aliases can be checked.  */
4851                   if (!nondeflt_vers)
4852                     {
4853                       amt = ((isymend - isym + 1)
4854                              * sizeof (struct elf_link_hash_entry *));
4855                       nondeflt_vers
4856                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
4857                       if (!nondeflt_vers)
4858                         goto error_free_vers;
4859                     }
4860                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4861                 }
4862             }
4863
4864           if (dynsym && h->dynindx == -1)
4865             {
4866               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4867                 goto error_free_vers;
4868               if (h->is_weakalias
4869                   && weakdef (h)->dynindx == -1)
4870                 {
4871                   if (!bfd_elf_link_record_dynamic_symbol (info, weakdef (h)))
4872                     goto error_free_vers;
4873                 }
4874             }
4875           else if (h->dynindx != -1)
4876             /* If the symbol already has a dynamic index, but
4877                visibility says it should not be visible, turn it into
4878                a local symbol.  */
4879             switch (ELF_ST_VISIBILITY (h->other))
4880               {
4881               case STV_INTERNAL:
4882               case STV_HIDDEN:
4883                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4884                 dynsym = FALSE;
4885                 break;
4886               }
4887
4888           /* Don't add DT_NEEDED for references from the dummy bfd nor
4889              for unmatched symbol.  */
4890           if (!add_needed
4891               && matched
4892               && definition
4893               && ((dynsym
4894                    && h->ref_regular_nonweak
4895                    && (old_bfd == NULL
4896                        || (old_bfd->flags & BFD_PLUGIN) == 0))
4897                   || (h->ref_dynamic_nonweak
4898                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4899                       && !on_needed_list (elf_dt_name (abfd),
4900                                           htab->needed, NULL))))
4901             {
4902               int ret;
4903               const char *soname = elf_dt_name (abfd);
4904
4905               info->callbacks->minfo ("%!", soname, old_bfd,
4906                                       h->root.root.string);
4907
4908               /* A symbol from a library loaded via DT_NEEDED of some
4909                  other library is referenced by a regular object.
4910                  Add a DT_NEEDED entry for it.  Issue an error if
4911                  --no-add-needed is used and the reference was not
4912                  a weak one.  */
4913               if (old_bfd != NULL
4914                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4915                 {
4916                   _bfd_error_handler
4917                     /* xgettext:c-format */
4918                     (_("%B: undefined reference to symbol '%s'"),
4919                      old_bfd, name);
4920                   bfd_set_error (bfd_error_missing_dso);
4921                   goto error_free_vers;
4922                 }
4923
4924               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4925                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4926
4927               add_needed = TRUE;
4928               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4929               if (ret < 0)
4930                 goto error_free_vers;
4931
4932               BFD_ASSERT (ret == 0);
4933             }
4934         }
4935     }
4936
4937   if (info->lto_plugin_active
4938       && !bfd_link_relocatable (info)
4939       && (abfd->flags & BFD_PLUGIN) == 0
4940       && !just_syms
4941       && extsymcount)
4942     {
4943       int r_sym_shift;
4944
4945       if (bed->s->arch_size == 32)
4946         r_sym_shift = 8;
4947       else
4948         r_sym_shift = 32;
4949
4950       /* If linker plugin is enabled, set non_ir_ref_regular on symbols
4951          referenced in regular objects so that linker plugin will get
4952          the correct symbol resolution.  */
4953
4954       sym_hash = elf_sym_hashes (abfd);
4955       for (s = abfd->sections; s != NULL; s = s->next)
4956         {
4957           Elf_Internal_Rela *internal_relocs;
4958           Elf_Internal_Rela *rel, *relend;
4959
4960           /* Don't check relocations in excluded sections.  */
4961           if ((s->flags & SEC_RELOC) == 0
4962               || s->reloc_count == 0
4963               || (s->flags & SEC_EXCLUDE) != 0
4964               || ((info->strip == strip_all
4965                    || info->strip == strip_debugger)
4966                   && (s->flags & SEC_DEBUGGING) != 0))
4967             continue;
4968
4969           internal_relocs = _bfd_elf_link_read_relocs (abfd, s, NULL,
4970                                                        NULL,
4971                                                        info->keep_memory);
4972           if (internal_relocs == NULL)
4973             goto error_free_vers;
4974
4975           rel = internal_relocs;
4976           relend = rel + s->reloc_count;
4977           for ( ; rel < relend; rel++)
4978             {
4979               unsigned long r_symndx = rel->r_info >> r_sym_shift;
4980               struct elf_link_hash_entry *h;
4981
4982               /* Skip local symbols.  */
4983               if (r_symndx < extsymoff)
4984                 continue;
4985
4986               h = sym_hash[r_symndx - extsymoff];
4987               if (h != NULL)
4988                 h->root.non_ir_ref_regular = 1;
4989             }
4990
4991           if (elf_section_data (s)->relocs != internal_relocs)
4992             free (internal_relocs);
4993         }
4994     }
4995
4996   if (extversym != NULL)
4997     {
4998       free (extversym);
4999       extversym = NULL;
5000     }
5001
5002   if (isymbuf != NULL)
5003     {
5004       free (isymbuf);
5005       isymbuf = NULL;
5006     }
5007
5008   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
5009     {
5010       unsigned int i;
5011
5012       /* Restore the symbol table.  */
5013       old_ent = (char *) old_tab + tabsize;
5014       memset (elf_sym_hashes (abfd), 0,
5015               extsymcount * sizeof (struct elf_link_hash_entry *));
5016       htab->root.table.table = old_table;
5017       htab->root.table.size = old_size;
5018       htab->root.table.count = old_count;
5019       memcpy (htab->root.table.table, old_tab, tabsize);
5020       htab->root.undefs = old_undefs;
5021       htab->root.undefs_tail = old_undefs_tail;
5022       _bfd_elf_strtab_restore (htab->dynstr, old_strtab);
5023       free (old_strtab);
5024       old_strtab = NULL;
5025       for (i = 0; i < htab->root.table.size; i++)
5026         {
5027           struct bfd_hash_entry *p;
5028           struct elf_link_hash_entry *h;
5029           bfd_size_type size;
5030           unsigned int alignment_power;
5031           unsigned int non_ir_ref_dynamic;
5032
5033           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
5034             {
5035               h = (struct elf_link_hash_entry *) p;
5036               if (h->root.type == bfd_link_hash_warning)
5037                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
5038
5039               /* Preserve the maximum alignment and size for common
5040                  symbols even if this dynamic lib isn't on DT_NEEDED
5041                  since it can still be loaded at run time by another
5042                  dynamic lib.  */
5043               if (h->root.type == bfd_link_hash_common)
5044                 {
5045                   size = h->root.u.c.size;
5046                   alignment_power = h->root.u.c.p->alignment_power;
5047                 }
5048               else
5049                 {
5050                   size = 0;
5051                   alignment_power = 0;
5052                 }
5053               /* Preserve non_ir_ref_dynamic so that this symbol
5054                  will be exported when the dynamic lib becomes needed
5055                  in the second pass.  */
5056               non_ir_ref_dynamic = h->root.non_ir_ref_dynamic;
5057               memcpy (p, old_ent, htab->root.table.entsize);
5058               old_ent = (char *) old_ent + htab->root.table.entsize;
5059               h = (struct elf_link_hash_entry *) p;
5060               if (h->root.type == bfd_link_hash_warning)
5061                 {
5062                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
5063                   old_ent = (char *) old_ent + htab->root.table.entsize;
5064                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
5065                 }
5066               if (h->root.type == bfd_link_hash_common)
5067                 {
5068                   if (size > h->root.u.c.size)
5069                     h->root.u.c.size = size;
5070                   if (alignment_power > h->root.u.c.p->alignment_power)
5071                     h->root.u.c.p->alignment_power = alignment_power;
5072                 }
5073               h->root.non_ir_ref_dynamic = non_ir_ref_dynamic;
5074             }
5075         }
5076
5077       /* Make a special call to the linker "notice" function to
5078          tell it that symbols added for crefs may need to be removed.  */
5079       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
5080         goto error_free_vers;
5081
5082       free (old_tab);
5083       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
5084                            alloc_mark);
5085       if (nondeflt_vers != NULL)
5086         free (nondeflt_vers);
5087       return TRUE;
5088     }
5089
5090   if (old_tab != NULL)
5091     {
5092       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
5093         goto error_free_vers;
5094       free (old_tab);
5095       old_tab = NULL;
5096     }
5097
5098   /* Now that all the symbols from this input file are created, if
5099      not performing a relocatable link, handle .symver foo, foo@BAR
5100      such that any relocs against foo become foo@BAR.  */
5101   if (!bfd_link_relocatable (info) && nondeflt_vers != NULL)
5102     {
5103       size_t cnt, symidx;
5104
5105       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
5106         {
5107           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
5108           char *shortname, *p;
5109
5110           p = strchr (h->root.root.string, ELF_VER_CHR);
5111           if (p == NULL
5112               || (h->root.type != bfd_link_hash_defined
5113                   && h->root.type != bfd_link_hash_defweak))
5114             continue;
5115
5116           amt = p - h->root.root.string;
5117           shortname = (char *) bfd_malloc (amt + 1);
5118           if (!shortname)
5119             goto error_free_vers;
5120           memcpy (shortname, h->root.root.string, amt);
5121           shortname[amt] = '\0';
5122
5123           hi = (struct elf_link_hash_entry *)
5124                bfd_link_hash_lookup (&htab->root, shortname,
5125                                      FALSE, FALSE, FALSE);
5126           if (hi != NULL
5127               && hi->root.type == h->root.type
5128               && hi->root.u.def.value == h->root.u.def.value
5129               && hi->root.u.def.section == h->root.u.def.section)
5130             {
5131               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
5132               hi->root.type = bfd_link_hash_indirect;
5133               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
5134               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
5135               sym_hash = elf_sym_hashes (abfd);
5136               if (sym_hash)
5137                 for (symidx = 0; symidx < extsymcount; ++symidx)
5138                   if (sym_hash[symidx] == hi)
5139                     {
5140                       sym_hash[symidx] = h;
5141                       break;
5142                     }
5143             }
5144           free (shortname);
5145         }
5146       free (nondeflt_vers);
5147       nondeflt_vers = NULL;
5148     }
5149
5150   /* Now set the alias field correctly for all the weak defined
5151      symbols we found.  The only way to do this is to search all the
5152      symbols.  Since we only need the information for non functions in
5153      dynamic objects, that's the only time we actually put anything on
5154      the list WEAKS.  We need this information so that if a regular
5155      object refers to a symbol defined weakly in a dynamic object, the
5156      real symbol in the dynamic object is also put in the dynamic
5157      symbols; we also must arrange for both symbols to point to the
5158      same memory location.  We could handle the general case of symbol
5159      aliasing, but a general symbol alias can only be generated in
5160      assembler code, handling it correctly would be very time
5161      consuming, and other ELF linkers don't handle general aliasing
5162      either.  */
5163   if (weaks != NULL)
5164     {
5165       struct elf_link_hash_entry **hpp;
5166       struct elf_link_hash_entry **hppend;
5167       struct elf_link_hash_entry **sorted_sym_hash;
5168       struct elf_link_hash_entry *h;
5169       size_t sym_count;
5170
5171       /* Since we have to search the whole symbol list for each weak
5172          defined symbol, search time for N weak defined symbols will be
5173          O(N^2). Binary search will cut it down to O(NlogN).  */
5174       amt = extsymcount;
5175       amt *= sizeof (struct elf_link_hash_entry *);
5176       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
5177       if (sorted_sym_hash == NULL)
5178         goto error_return;
5179       sym_hash = sorted_sym_hash;
5180       hpp = elf_sym_hashes (abfd);
5181       hppend = hpp + extsymcount;
5182       sym_count = 0;
5183       for (; hpp < hppend; hpp++)
5184         {
5185           h = *hpp;
5186           if (h != NULL
5187               && h->root.type == bfd_link_hash_defined
5188               && !bed->is_function_type (h->type))
5189             {
5190               *sym_hash = h;
5191               sym_hash++;
5192               sym_count++;
5193             }
5194         }
5195
5196       qsort (sorted_sym_hash, sym_count,
5197              sizeof (struct elf_link_hash_entry *),
5198              elf_sort_symbol);
5199
5200       while (weaks != NULL)
5201         {
5202           struct elf_link_hash_entry *hlook;
5203           asection *slook;
5204           bfd_vma vlook;
5205           size_t i, j, idx = 0;
5206
5207           hlook = weaks;
5208           weaks = hlook->u.alias;
5209           hlook->u.alias = NULL;
5210
5211           if (hlook->root.type != bfd_link_hash_defined
5212               && hlook->root.type != bfd_link_hash_defweak)
5213             continue;
5214
5215           slook = hlook->root.u.def.section;
5216           vlook = hlook->root.u.def.value;
5217
5218           i = 0;
5219           j = sym_count;
5220           while (i != j)
5221             {
5222               bfd_signed_vma vdiff;
5223               idx = (i + j) / 2;
5224               h = sorted_sym_hash[idx];
5225               vdiff = vlook - h->root.u.def.value;
5226               if (vdiff < 0)
5227                 j = idx;
5228               else if (vdiff > 0)
5229                 i = idx + 1;
5230               else
5231                 {
5232                   int sdiff = slook->id - h->root.u.def.section->id;
5233                   if (sdiff < 0)
5234                     j = idx;
5235                   else if (sdiff > 0)
5236                     i = idx + 1;
5237                   else
5238                     break;
5239                 }
5240             }
5241
5242           /* We didn't find a value/section match.  */
5243           if (i == j)
5244             continue;
5245
5246           /* With multiple aliases, or when the weak symbol is already
5247              strongly defined, we have multiple matching symbols and
5248              the binary search above may land on any of them.  Step
5249              one past the matching symbol(s).  */
5250           while (++idx != j)
5251             {
5252               h = sorted_sym_hash[idx];
5253               if (h->root.u.def.section != slook
5254                   || h->root.u.def.value != vlook)
5255                 break;
5256             }
5257
5258           /* Now look back over the aliases.  Since we sorted by size
5259              as well as value and section, we'll choose the one with
5260              the largest size.  */
5261           while (idx-- != i)
5262             {
5263               h = sorted_sym_hash[idx];
5264
5265               /* Stop if value or section doesn't match.  */
5266               if (h->root.u.def.section != slook
5267                   || h->root.u.def.value != vlook)
5268                 break;
5269               else if (h != hlook)
5270                 {
5271                   struct elf_link_hash_entry *t;
5272
5273                   hlook->u.alias = h;
5274                   hlook->is_weakalias = 1;
5275                   t = h;
5276                   if (t->u.alias != NULL)
5277                     while (t->u.alias != h)
5278                       t = t->u.alias;
5279                   t->u.alias = hlook;
5280
5281                   /* If the weak definition is in the list of dynamic
5282                      symbols, make sure the real definition is put
5283                      there as well.  */
5284                   if (hlook->dynindx != -1 && h->dynindx == -1)
5285                     {
5286                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
5287                         {
5288                         err_free_sym_hash:
5289                           free (sorted_sym_hash);
5290                           goto error_return;
5291                         }
5292                     }
5293
5294                   /* If the real definition is in the list of dynamic
5295                      symbols, make sure the weak definition is put
5296                      there as well.  If we don't do this, then the
5297                      dynamic loader might not merge the entries for the
5298                      real definition and the weak definition.  */
5299                   if (h->dynindx != -1 && hlook->dynindx == -1)
5300                     {
5301                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
5302                         goto err_free_sym_hash;
5303                     }
5304                   break;
5305                 }
5306             }
5307         }
5308
5309       free (sorted_sym_hash);
5310     }
5311
5312   if (bed->check_directives
5313       && !(*bed->check_directives) (abfd, info))
5314     return FALSE;
5315
5316   /* If this is a non-traditional link, try to optimize the handling
5317      of the .stab/.stabstr sections.  */
5318   if (! dynamic
5319       && ! info->traditional_format
5320       && is_elf_hash_table (htab)
5321       && (info->strip != strip_all && info->strip != strip_debugger))
5322     {
5323       asection *stabstr;
5324
5325       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
5326       if (stabstr != NULL)
5327         {
5328           bfd_size_type string_offset = 0;
5329           asection *stab;
5330
5331           for (stab = abfd->sections; stab; stab = stab->next)
5332             if (CONST_STRNEQ (stab->name, ".stab")
5333                 && (!stab->name[5] ||
5334                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
5335                 && (stab->flags & SEC_MERGE) == 0
5336                 && !bfd_is_abs_section (stab->output_section))
5337               {
5338                 struct bfd_elf_section_data *secdata;
5339
5340                 secdata = elf_section_data (stab);
5341                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
5342                                                stabstr, &secdata->sec_info,
5343                                                &string_offset))
5344                   goto error_return;
5345                 if (secdata->sec_info)
5346                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
5347             }
5348         }
5349     }
5350
5351   if (is_elf_hash_table (htab) && add_needed)
5352     {
5353       /* Add this bfd to the loaded list.  */
5354       struct elf_link_loaded_list *n;
5355
5356       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
5357       if (n == NULL)
5358         goto error_return;
5359       n->abfd = abfd;
5360       n->next = htab->loaded;
5361       htab->loaded = n;
5362     }
5363
5364   return TRUE;
5365
5366  error_free_vers:
5367   if (old_tab != NULL)
5368     free (old_tab);
5369   if (old_strtab != NULL)
5370     free (old_strtab);
5371   if (nondeflt_vers != NULL)
5372     free (nondeflt_vers);
5373   if (extversym != NULL)
5374     free (extversym);
5375  error_free_sym:
5376   if (isymbuf != NULL)
5377     free (isymbuf);
5378  error_return:
5379   return FALSE;
5380 }
5381
5382 /* Return the linker hash table entry of a symbol that might be
5383    satisfied by an archive symbol.  Return -1 on error.  */
5384
5385 struct elf_link_hash_entry *
5386 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5387                                 struct bfd_link_info *info,
5388                                 const char *name)
5389 {
5390   struct elf_link_hash_entry *h;
5391   char *p, *copy;
5392   size_t len, first;
5393
5394   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5395   if (h != NULL)
5396     return h;
5397
5398   /* If this is a default version (the name contains @@), look up the
5399      symbol again with only one `@' as well as without the version.
5400      The effect is that references to the symbol with and without the
5401      version will be matched by the default symbol in the archive.  */
5402
5403   p = strchr (name, ELF_VER_CHR);
5404   if (p == NULL || p[1] != ELF_VER_CHR)
5405     return h;
5406
5407   /* First check with only one `@'.  */
5408   len = strlen (name);
5409   copy = (char *) bfd_alloc (abfd, len);
5410   if (copy == NULL)
5411     return (struct elf_link_hash_entry *) 0 - 1;
5412
5413   first = p - name + 1;
5414   memcpy (copy, name, first);
5415   memcpy (copy + first, name + first + 1, len - first);
5416
5417   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5418   if (h == NULL)
5419     {
5420       /* We also need to check references to the symbol without the
5421          version.  */
5422       copy[first - 1] = '\0';
5423       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5424                                 FALSE, FALSE, TRUE);
5425     }
5426
5427   bfd_release (abfd, copy);
5428   return h;
5429 }
5430
5431 /* Add symbols from an ELF archive file to the linker hash table.  We
5432    don't use _bfd_generic_link_add_archive_symbols because we need to
5433    handle versioned symbols.
5434
5435    Fortunately, ELF archive handling is simpler than that done by
5436    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5437    oddities.  In ELF, if we find a symbol in the archive map, and the
5438    symbol is currently undefined, we know that we must pull in that
5439    object file.
5440
5441    Unfortunately, we do have to make multiple passes over the symbol
5442    table until nothing further is resolved.  */
5443
5444 static bfd_boolean
5445 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5446 {
5447   symindex c;
5448   unsigned char *included = NULL;
5449   carsym *symdefs;
5450   bfd_boolean loop;
5451   bfd_size_type amt;
5452   const struct elf_backend_data *bed;
5453   struct elf_link_hash_entry * (*archive_symbol_lookup)
5454     (bfd *, struct bfd_link_info *, const char *);
5455
5456   if (! bfd_has_map (abfd))
5457     {
5458       /* An empty archive is a special case.  */
5459       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5460         return TRUE;
5461       bfd_set_error (bfd_error_no_armap);
5462       return FALSE;
5463     }
5464
5465   /* Keep track of all symbols we know to be already defined, and all
5466      files we know to be already included.  This is to speed up the
5467      second and subsequent passes.  */
5468   c = bfd_ardata (abfd)->symdef_count;
5469   if (c == 0)
5470     return TRUE;
5471   amt = c;
5472   amt *= sizeof (*included);
5473   included = (unsigned char *) bfd_zmalloc (amt);
5474   if (included == NULL)
5475     return FALSE;
5476
5477   symdefs = bfd_ardata (abfd)->symdefs;
5478   bed = get_elf_backend_data (abfd);
5479   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5480
5481   do
5482     {
5483       file_ptr last;
5484       symindex i;
5485       carsym *symdef;
5486       carsym *symdefend;
5487
5488       loop = FALSE;
5489       last = -1;
5490
5491       symdef = symdefs;
5492       symdefend = symdef + c;
5493       for (i = 0; symdef < symdefend; symdef++, i++)
5494         {
5495           struct elf_link_hash_entry *h;
5496           bfd *element;
5497           struct bfd_link_hash_entry *undefs_tail;
5498           symindex mark;
5499
5500           if (included[i])
5501             continue;
5502           if (symdef->file_offset == last)
5503             {
5504               included[i] = TRUE;
5505               continue;
5506             }
5507
5508           h = archive_symbol_lookup (abfd, info, symdef->name);
5509           if (h == (struct elf_link_hash_entry *) 0 - 1)
5510             goto error_return;
5511
5512           if (h == NULL)
5513             continue;
5514
5515           if (h->root.type == bfd_link_hash_common)
5516             {
5517               /* We currently have a common symbol.  The archive map contains
5518                  a reference to this symbol, so we may want to include it.  We
5519                  only want to include it however, if this archive element
5520                  contains a definition of the symbol, not just another common
5521                  declaration of it.
5522
5523                  Unfortunately some archivers (including GNU ar) will put
5524                  declarations of common symbols into their archive maps, as
5525                  well as real definitions, so we cannot just go by the archive
5526                  map alone.  Instead we must read in the element's symbol
5527                  table and check that to see what kind of symbol definition
5528                  this is.  */
5529               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5530                 continue;
5531             }
5532           else if (h->root.type != bfd_link_hash_undefined)
5533             {
5534               if (h->root.type != bfd_link_hash_undefweak)
5535                 /* Symbol must be defined.  Don't check it again.  */
5536                 included[i] = TRUE;
5537               continue;
5538             }
5539
5540           /* We need to include this archive member.  */
5541           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5542           if (element == NULL)
5543             goto error_return;
5544
5545           if (! bfd_check_format (element, bfd_object))
5546             goto error_return;
5547
5548           undefs_tail = info->hash->undefs_tail;
5549
5550           if (!(*info->callbacks
5551                 ->add_archive_element) (info, element, symdef->name, &element))
5552             continue;
5553           if (!bfd_link_add_symbols (element, info))
5554             goto error_return;
5555
5556           /* If there are any new undefined symbols, we need to make
5557              another pass through the archive in order to see whether
5558              they can be defined.  FIXME: This isn't perfect, because
5559              common symbols wind up on undefs_tail and because an
5560              undefined symbol which is defined later on in this pass
5561              does not require another pass.  This isn't a bug, but it
5562              does make the code less efficient than it could be.  */
5563           if (undefs_tail != info->hash->undefs_tail)
5564             loop = TRUE;
5565
5566           /* Look backward to mark all symbols from this object file
5567              which we have already seen in this pass.  */
5568           mark = i;
5569           do
5570             {
5571               included[mark] = TRUE;
5572               if (mark == 0)
5573                 break;
5574               --mark;
5575             }
5576           while (symdefs[mark].file_offset == symdef->file_offset);
5577
5578           /* We mark subsequent symbols from this object file as we go
5579              on through the loop.  */
5580           last = symdef->file_offset;
5581         }
5582     }
5583   while (loop);
5584
5585   free (included);
5586
5587   return TRUE;
5588
5589  error_return:
5590   if (included != NULL)
5591     free (included);
5592   return FALSE;
5593 }
5594
5595 /* Given an ELF BFD, add symbols to the global hash table as
5596    appropriate.  */
5597
5598 bfd_boolean
5599 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5600 {
5601   switch (bfd_get_format (abfd))
5602     {
5603     case bfd_object:
5604       return elf_link_add_object_symbols (abfd, info);
5605     case bfd_archive:
5606       return elf_link_add_archive_symbols (abfd, info);
5607     default:
5608       bfd_set_error (bfd_error_wrong_format);
5609       return FALSE;
5610     }
5611 }
5612 \f
5613 struct hash_codes_info
5614 {
5615   unsigned long *hashcodes;
5616   bfd_boolean error;
5617 };
5618
5619 /* This function will be called though elf_link_hash_traverse to store
5620    all hash value of the exported symbols in an array.  */
5621
5622 static bfd_boolean
5623 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5624 {
5625   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5626   const char *name;
5627   unsigned long ha;
5628   char *alc = NULL;
5629
5630   /* Ignore indirect symbols.  These are added by the versioning code.  */
5631   if (h->dynindx == -1)
5632     return TRUE;
5633
5634   name = h->root.root.string;
5635   if (h->versioned >= versioned)
5636     {
5637       char *p = strchr (name, ELF_VER_CHR);
5638       if (p != NULL)
5639         {
5640           alc = (char *) bfd_malloc (p - name + 1);
5641           if (alc == NULL)
5642             {
5643               inf->error = TRUE;
5644               return FALSE;
5645             }
5646           memcpy (alc, name, p - name);
5647           alc[p - name] = '\0';
5648           name = alc;
5649         }
5650     }
5651
5652   /* Compute the hash value.  */
5653   ha = bfd_elf_hash (name);
5654
5655   /* Store the found hash value in the array given as the argument.  */
5656   *(inf->hashcodes)++ = ha;
5657
5658   /* And store it in the struct so that we can put it in the hash table
5659      later.  */
5660   h->u.elf_hash_value = ha;
5661
5662   if (alc != NULL)
5663     free (alc);
5664
5665   return TRUE;
5666 }
5667
5668 struct collect_gnu_hash_codes
5669 {
5670   bfd *output_bfd;
5671   const struct elf_backend_data *bed;
5672   unsigned long int nsyms;
5673   unsigned long int maskbits;
5674   unsigned long int *hashcodes;
5675   unsigned long int *hashval;
5676   unsigned long int *indx;
5677   unsigned long int *counts;
5678   bfd_vma *bitmask;
5679   bfd_byte *contents;
5680   long int min_dynindx;
5681   unsigned long int bucketcount;
5682   unsigned long int symindx;
5683   long int local_indx;
5684   long int shift1, shift2;
5685   unsigned long int mask;
5686   bfd_boolean error;
5687 };
5688
5689 /* This function will be called though elf_link_hash_traverse to store
5690    all hash value of the exported symbols in an array.  */
5691
5692 static bfd_boolean
5693 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5694 {
5695   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5696   const char *name;
5697   unsigned long ha;
5698   char *alc = NULL;
5699
5700   /* Ignore indirect symbols.  These are added by the versioning code.  */
5701   if (h->dynindx == -1)
5702     return TRUE;
5703
5704   /* Ignore also local symbols and undefined symbols.  */
5705   if (! (*s->bed->elf_hash_symbol) (h))
5706     return TRUE;
5707
5708   name = h->root.root.string;
5709   if (h->versioned >= versioned)
5710     {
5711       char *p = strchr (name, ELF_VER_CHR);
5712       if (p != NULL)
5713         {
5714           alc = (char *) bfd_malloc (p - name + 1);
5715           if (alc == NULL)
5716             {
5717               s->error = TRUE;
5718               return FALSE;
5719             }
5720           memcpy (alc, name, p - name);
5721           alc[p - name] = '\0';
5722           name = alc;
5723         }
5724     }
5725
5726   /* Compute the hash value.  */
5727   ha = bfd_elf_gnu_hash (name);
5728
5729   /* Store the found hash value in the array for compute_bucket_count,
5730      and also for .dynsym reordering purposes.  */
5731   s->hashcodes[s->nsyms] = ha;
5732   s->hashval[h->dynindx] = ha;
5733   ++s->nsyms;
5734   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5735     s->min_dynindx = h->dynindx;
5736
5737   if (alc != NULL)
5738     free (alc);
5739
5740   return TRUE;
5741 }
5742
5743 /* This function will be called though elf_link_hash_traverse to do
5744    final dynaminc symbol renumbering.  */
5745
5746 static bfd_boolean
5747 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5748 {
5749   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5750   unsigned long int bucket;
5751   unsigned long int val;
5752
5753   /* Ignore indirect symbols.  */
5754   if (h->dynindx == -1)
5755     return TRUE;
5756
5757   /* Ignore also local symbols and undefined symbols.  */
5758   if (! (*s->bed->elf_hash_symbol) (h))
5759     {
5760       if (h->dynindx >= s->min_dynindx)
5761         h->dynindx = s->local_indx++;
5762       return TRUE;
5763     }
5764
5765   bucket = s->hashval[h->dynindx] % s->bucketcount;
5766   val = (s->hashval[h->dynindx] >> s->shift1)
5767         & ((s->maskbits >> s->shift1) - 1);
5768   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5769   s->bitmask[val]
5770     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5771   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5772   if (s->counts[bucket] == 1)
5773     /* Last element terminates the chain.  */
5774     val |= 1;
5775   bfd_put_32 (s->output_bfd, val,
5776               s->contents + (s->indx[bucket] - s->symindx) * 4);
5777   --s->counts[bucket];
5778   h->dynindx = s->indx[bucket]++;
5779   return TRUE;
5780 }
5781
5782 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5783
5784 bfd_boolean
5785 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5786 {
5787   return !(h->forced_local
5788            || h->root.type == bfd_link_hash_undefined
5789            || h->root.type == bfd_link_hash_undefweak
5790            || ((h->root.type == bfd_link_hash_defined
5791                 || h->root.type == bfd_link_hash_defweak)
5792                && h->root.u.def.section->output_section == NULL));
5793 }
5794
5795 /* Array used to determine the number of hash table buckets to use
5796    based on the number of symbols there are.  If there are fewer than
5797    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5798    fewer than 37 we use 17 buckets, and so forth.  We never use more
5799    than 32771 buckets.  */
5800
5801 static const size_t elf_buckets[] =
5802 {
5803   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5804   16411, 32771, 0
5805 };
5806
5807 /* Compute bucket count for hashing table.  We do not use a static set
5808    of possible tables sizes anymore.  Instead we determine for all
5809    possible reasonable sizes of the table the outcome (i.e., the
5810    number of collisions etc) and choose the best solution.  The
5811    weighting functions are not too simple to allow the table to grow
5812    without bounds.  Instead one of the weighting factors is the size.
5813    Therefore the result is always a good payoff between few collisions
5814    (= short chain lengths) and table size.  */
5815 static size_t
5816 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5817                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5818                       unsigned long int nsyms,
5819                       int gnu_hash)
5820 {
5821   size_t best_size = 0;
5822   unsigned long int i;
5823
5824   /* We have a problem here.  The following code to optimize the table
5825      size requires an integer type with more the 32 bits.  If
5826      BFD_HOST_U_64_BIT is set we know about such a type.  */
5827 #ifdef BFD_HOST_U_64_BIT
5828   if (info->optimize)
5829     {
5830       size_t minsize;
5831       size_t maxsize;
5832       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5833       bfd *dynobj = elf_hash_table (info)->dynobj;
5834       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5835       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5836       unsigned long int *counts;
5837       bfd_size_type amt;
5838       unsigned int no_improvement_count = 0;
5839
5840       /* Possible optimization parameters: if we have NSYMS symbols we say
5841          that the hashing table must at least have NSYMS/4 and at most
5842          2*NSYMS buckets.  */
5843       minsize = nsyms / 4;
5844       if (minsize == 0)
5845         minsize = 1;
5846       best_size = maxsize = nsyms * 2;
5847       if (gnu_hash)
5848         {
5849           if (minsize < 2)
5850             minsize = 2;
5851           if ((best_size & 31) == 0)
5852             ++best_size;
5853         }
5854
5855       /* Create array where we count the collisions in.  We must use bfd_malloc
5856          since the size could be large.  */
5857       amt = maxsize;
5858       amt *= sizeof (unsigned long int);
5859       counts = (unsigned long int *) bfd_malloc (amt);
5860       if (counts == NULL)
5861         return 0;
5862
5863       /* Compute the "optimal" size for the hash table.  The criteria is a
5864          minimal chain length.  The minor criteria is (of course) the size
5865          of the table.  */
5866       for (i = minsize; i < maxsize; ++i)
5867         {
5868           /* Walk through the array of hashcodes and count the collisions.  */
5869           BFD_HOST_U_64_BIT max;
5870           unsigned long int j;
5871           unsigned long int fact;
5872
5873           if (gnu_hash && (i & 31) == 0)
5874             continue;
5875
5876           memset (counts, '\0', i * sizeof (unsigned long int));
5877
5878           /* Determine how often each hash bucket is used.  */
5879           for (j = 0; j < nsyms; ++j)
5880             ++counts[hashcodes[j] % i];
5881
5882           /* For the weight function we need some information about the
5883              pagesize on the target.  This is information need not be 100%
5884              accurate.  Since this information is not available (so far) we
5885              define it here to a reasonable default value.  If it is crucial
5886              to have a better value some day simply define this value.  */
5887 # ifndef BFD_TARGET_PAGESIZE
5888 #  define BFD_TARGET_PAGESIZE   (4096)
5889 # endif
5890
5891           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5892              and the chains.  */
5893           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5894
5895 # if 1
5896           /* Variant 1: optimize for short chains.  We add the squares
5897              of all the chain lengths (which favors many small chain
5898              over a few long chains).  */
5899           for (j = 0; j < i; ++j)
5900             max += counts[j] * counts[j];
5901
5902           /* This adds penalties for the overall size of the table.  */
5903           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5904           max *= fact * fact;
5905 # else
5906           /* Variant 2: Optimize a lot more for small table.  Here we
5907              also add squares of the size but we also add penalties for
5908              empty slots (the +1 term).  */
5909           for (j = 0; j < i; ++j)
5910             max += (1 + counts[j]) * (1 + counts[j]);
5911
5912           /* The overall size of the table is considered, but not as
5913              strong as in variant 1, where it is squared.  */
5914           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5915           max *= fact;
5916 # endif
5917
5918           /* Compare with current best results.  */
5919           if (max < best_chlen)
5920             {
5921               best_chlen = max;
5922               best_size = i;
5923               no_improvement_count = 0;
5924             }
5925           /* PR 11843: Avoid futile long searches for the best bucket size
5926              when there are a large number of symbols.  */
5927           else if (++no_improvement_count == 100)
5928             break;
5929         }
5930
5931       free (counts);
5932     }
5933   else
5934 #endif /* defined (BFD_HOST_U_64_BIT) */
5935     {
5936       /* This is the fallback solution if no 64bit type is available or if we
5937          are not supposed to spend much time on optimizations.  We select the
5938          bucket count using a fixed set of numbers.  */
5939       for (i = 0; elf_buckets[i] != 0; i++)
5940         {
5941           best_size = elf_buckets[i];
5942           if (nsyms < elf_buckets[i + 1])
5943             break;
5944         }
5945       if (gnu_hash && best_size < 2)
5946         best_size = 2;
5947     }
5948
5949   return best_size;
5950 }
5951
5952 /* Size any SHT_GROUP section for ld -r.  */
5953
5954 bfd_boolean
5955 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5956 {
5957   bfd *ibfd;
5958   asection *s;
5959
5960   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5961     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5962         && (s = ibfd->sections) != NULL
5963         && s->sec_info_type != SEC_INFO_TYPE_JUST_SYMS
5964         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5965       return FALSE;
5966   return TRUE;
5967 }
5968
5969 /* Set a default stack segment size.  The value in INFO wins.  If it
5970    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
5971    undefined it is initialized.  */
5972
5973 bfd_boolean
5974 bfd_elf_stack_segment_size (bfd *output_bfd,
5975                             struct bfd_link_info *info,
5976                             const char *legacy_symbol,
5977                             bfd_vma default_size)
5978 {
5979   struct elf_link_hash_entry *h = NULL;
5980
5981   /* Look for legacy symbol.  */
5982   if (legacy_symbol)
5983     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
5984                               FALSE, FALSE, FALSE);
5985   if (h && (h->root.type == bfd_link_hash_defined
5986             || h->root.type == bfd_link_hash_defweak)
5987       && h->def_regular
5988       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
5989     {
5990       /* The symbol has no type if specified on the command line.  */
5991       h->type = STT_OBJECT;
5992       if (info->stacksize)
5993         /* xgettext:c-format */
5994         _bfd_error_handler (_("%B: stack size specified and %s set"),
5995                             output_bfd, legacy_symbol);
5996       else if (h->root.u.def.section != bfd_abs_section_ptr)
5997         /* xgettext:c-format */
5998         _bfd_error_handler (_("%B: %s not absolute"),
5999                             output_bfd, legacy_symbol);
6000       else
6001         info->stacksize = h->root.u.def.value;
6002     }
6003
6004   if (!info->stacksize)
6005     /* If the user didn't set a size, or explicitly inhibit the
6006        size, set it now.  */
6007     info->stacksize = default_size;
6008
6009   /* Provide the legacy symbol, if it is referenced.  */
6010   if (h && (h->root.type == bfd_link_hash_undefined
6011             || h->root.type == bfd_link_hash_undefweak))
6012     {
6013       struct bfd_link_hash_entry *bh = NULL;
6014
6015       if (!(_bfd_generic_link_add_one_symbol
6016             (info, output_bfd, legacy_symbol,
6017              BSF_GLOBAL, bfd_abs_section_ptr,
6018              info->stacksize >= 0 ? info->stacksize : 0,
6019              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
6020         return FALSE;
6021
6022       h = (struct elf_link_hash_entry *) bh;
6023       h->def_regular = 1;
6024       h->type = STT_OBJECT;
6025     }
6026
6027   return TRUE;
6028 }
6029
6030 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
6031
6032 struct elf_gc_sweep_symbol_info
6033 {
6034   struct bfd_link_info *info;
6035   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
6036                        bfd_boolean);
6037 };
6038
6039 static bfd_boolean
6040 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
6041 {
6042   if (!h->mark
6043       && (((h->root.type == bfd_link_hash_defined
6044             || h->root.type == bfd_link_hash_defweak)
6045            && !((h->def_regular || ELF_COMMON_DEF_P (h))
6046                 && h->root.u.def.section->gc_mark))
6047           || h->root.type == bfd_link_hash_undefined
6048           || h->root.type == bfd_link_hash_undefweak))
6049     {
6050       struct elf_gc_sweep_symbol_info *inf;
6051
6052       inf = (struct elf_gc_sweep_symbol_info *) data;
6053       (*inf->hide_symbol) (inf->info, h, TRUE);
6054       h->def_regular = 0;
6055       h->ref_regular = 0;
6056       h->ref_regular_nonweak = 0;
6057     }
6058
6059   return TRUE;
6060 }
6061
6062 /* Set up the sizes and contents of the ELF dynamic sections.  This is
6063    called by the ELF linker emulation before_allocation routine.  We
6064    must set the sizes of the sections before the linker sets the
6065    addresses of the various sections.  */
6066
6067 bfd_boolean
6068 bfd_elf_size_dynamic_sections (bfd *output_bfd,
6069                                const char *soname,
6070                                const char *rpath,
6071                                const char *filter_shlib,
6072                                const char *audit,
6073                                const char *depaudit,
6074                                const char * const *auxiliary_filters,
6075                                struct bfd_link_info *info,
6076                                asection **sinterpptr)
6077 {
6078   bfd *dynobj;
6079   const struct elf_backend_data *bed;
6080
6081   *sinterpptr = NULL;
6082
6083   if (!is_elf_hash_table (info->hash))
6084     return TRUE;
6085
6086   dynobj = elf_hash_table (info)->dynobj;
6087
6088   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6089     {
6090       struct bfd_elf_version_tree *verdefs;
6091       struct elf_info_failed asvinfo;
6092       struct bfd_elf_version_tree *t;
6093       struct bfd_elf_version_expr *d;
6094       asection *s;
6095       size_t soname_indx;
6096
6097       /* If we are supposed to export all symbols into the dynamic symbol
6098          table (this is not the normal case), then do so.  */
6099       if (info->export_dynamic
6100           || (bfd_link_executable (info) && info->dynamic))
6101         {
6102           struct elf_info_failed eif;
6103
6104           eif.info = info;
6105           eif.failed = FALSE;
6106           elf_link_hash_traverse (elf_hash_table (info),
6107                                   _bfd_elf_export_symbol,
6108                                   &eif);
6109           if (eif.failed)
6110             return FALSE;
6111         }
6112
6113       if (soname != NULL)
6114         {
6115           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6116                                              soname, TRUE);
6117           if (soname_indx == (size_t) -1
6118               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
6119             return FALSE;
6120         }
6121       else
6122         soname_indx = (size_t) -1;
6123
6124       /* Make all global versions with definition.  */
6125       for (t = info->version_info; t != NULL; t = t->next)
6126         for (d = t->globals.list; d != NULL; d = d->next)
6127           if (!d->symver && d->literal)
6128             {
6129               const char *verstr, *name;
6130               size_t namelen, verlen, newlen;
6131               char *newname, *p, leading_char;
6132               struct elf_link_hash_entry *newh;
6133
6134               leading_char = bfd_get_symbol_leading_char (output_bfd);
6135               name = d->pattern;
6136               namelen = strlen (name) + (leading_char != '\0');
6137               verstr = t->name;
6138               verlen = strlen (verstr);
6139               newlen = namelen + verlen + 3;
6140
6141               newname = (char *) bfd_malloc (newlen);
6142               if (newname == NULL)
6143                 return FALSE;
6144               newname[0] = leading_char;
6145               memcpy (newname + (leading_char != '\0'), name, namelen);
6146
6147               /* Check the hidden versioned definition.  */
6148               p = newname + namelen;
6149               *p++ = ELF_VER_CHR;
6150               memcpy (p, verstr, verlen + 1);
6151               newh = elf_link_hash_lookup (elf_hash_table (info),
6152                                            newname, FALSE, FALSE,
6153                                            FALSE);
6154               if (newh == NULL
6155                   || (newh->root.type != bfd_link_hash_defined
6156                       && newh->root.type != bfd_link_hash_defweak))
6157                 {
6158                   /* Check the default versioned definition.  */
6159                   *p++ = ELF_VER_CHR;
6160                   memcpy (p, verstr, verlen + 1);
6161                   newh = elf_link_hash_lookup (elf_hash_table (info),
6162                                                newname, FALSE, FALSE,
6163                                                FALSE);
6164                 }
6165               free (newname);
6166
6167               /* Mark this version if there is a definition and it is
6168                  not defined in a shared object.  */
6169               if (newh != NULL
6170                   && !newh->def_dynamic
6171                   && (newh->root.type == bfd_link_hash_defined
6172                       || newh->root.type == bfd_link_hash_defweak))
6173                 d->symver = 1;
6174             }
6175
6176       /* Attach all the symbols to their version information.  */
6177       asvinfo.info = info;
6178       asvinfo.failed = FALSE;
6179
6180       elf_link_hash_traverse (elf_hash_table (info),
6181                               _bfd_elf_link_assign_sym_version,
6182                               &asvinfo);
6183       if (asvinfo.failed)
6184         return FALSE;
6185
6186       if (!info->allow_undefined_version)
6187         {
6188           /* Check if all global versions have a definition.  */
6189           bfd_boolean all_defined = TRUE;
6190           for (t = info->version_info; t != NULL; t = t->next)
6191             for (d = t->globals.list; d != NULL; d = d->next)
6192               if (d->literal && !d->symver && !d->script)
6193                 {
6194                   _bfd_error_handler
6195                     (_("%s: undefined version: %s"),
6196                      d->pattern, t->name);
6197                   all_defined = FALSE;
6198                 }
6199
6200           if (!all_defined)
6201             {
6202               bfd_set_error (bfd_error_bad_value);
6203               return FALSE;
6204             }
6205         }
6206
6207       /* Set up the version definition section.  */
6208       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6209       BFD_ASSERT (s != NULL);
6210
6211       /* We may have created additional version definitions if we are
6212          just linking a regular application.  */
6213       verdefs = info->version_info;
6214
6215       /* Skip anonymous version tag.  */
6216       if (verdefs != NULL && verdefs->vernum == 0)
6217         verdefs = verdefs->next;
6218
6219       if (verdefs == NULL && !info->create_default_symver)
6220         s->flags |= SEC_EXCLUDE;
6221       else
6222         {
6223           unsigned int cdefs;
6224           bfd_size_type size;
6225           bfd_byte *p;
6226           Elf_Internal_Verdef def;
6227           Elf_Internal_Verdaux defaux;
6228           struct bfd_link_hash_entry *bh;
6229           struct elf_link_hash_entry *h;
6230           const char *name;
6231
6232           cdefs = 0;
6233           size = 0;
6234
6235           /* Make space for the base version.  */
6236           size += sizeof (Elf_External_Verdef);
6237           size += sizeof (Elf_External_Verdaux);
6238           ++cdefs;
6239
6240           /* Make space for the default version.  */
6241           if (info->create_default_symver)
6242             {
6243               size += sizeof (Elf_External_Verdef);
6244               ++cdefs;
6245             }
6246
6247           for (t = verdefs; t != NULL; t = t->next)
6248             {
6249               struct bfd_elf_version_deps *n;
6250
6251               /* Don't emit base version twice.  */
6252               if (t->vernum == 0)
6253                 continue;
6254
6255               size += sizeof (Elf_External_Verdef);
6256               size += sizeof (Elf_External_Verdaux);
6257               ++cdefs;
6258
6259               for (n = t->deps; n != NULL; n = n->next)
6260                 size += sizeof (Elf_External_Verdaux);
6261             }
6262
6263           s->size = size;
6264           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6265           if (s->contents == NULL && s->size != 0)
6266             return FALSE;
6267
6268           /* Fill in the version definition section.  */
6269
6270           p = s->contents;
6271
6272           def.vd_version = VER_DEF_CURRENT;
6273           def.vd_flags = VER_FLG_BASE;
6274           def.vd_ndx = 1;
6275           def.vd_cnt = 1;
6276           if (info->create_default_symver)
6277             {
6278               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6279               def.vd_next = sizeof (Elf_External_Verdef);
6280             }
6281           else
6282             {
6283               def.vd_aux = sizeof (Elf_External_Verdef);
6284               def.vd_next = (sizeof (Elf_External_Verdef)
6285                              + sizeof (Elf_External_Verdaux));
6286             }
6287
6288           if (soname_indx != (size_t) -1)
6289             {
6290               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6291                                       soname_indx);
6292               def.vd_hash = bfd_elf_hash (soname);
6293               defaux.vda_name = soname_indx;
6294               name = soname;
6295             }
6296           else
6297             {
6298               size_t indx;
6299
6300               name = lbasename (output_bfd->filename);
6301               def.vd_hash = bfd_elf_hash (name);
6302               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6303                                           name, FALSE);
6304               if (indx == (size_t) -1)
6305                 return FALSE;
6306               defaux.vda_name = indx;
6307             }
6308           defaux.vda_next = 0;
6309
6310           _bfd_elf_swap_verdef_out (output_bfd, &def,
6311                                     (Elf_External_Verdef *) p);
6312           p += sizeof (Elf_External_Verdef);
6313           if (info->create_default_symver)
6314             {
6315               /* Add a symbol representing this version.  */
6316               bh = NULL;
6317               if (! (_bfd_generic_link_add_one_symbol
6318                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6319                       0, NULL, FALSE,
6320                       get_elf_backend_data (dynobj)->collect, &bh)))
6321                 return FALSE;
6322               h = (struct elf_link_hash_entry *) bh;
6323               h->non_elf = 0;
6324               h->def_regular = 1;
6325               h->type = STT_OBJECT;
6326               h->verinfo.vertree = NULL;
6327
6328               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6329                 return FALSE;
6330
6331               /* Create a duplicate of the base version with the same
6332                  aux block, but different flags.  */
6333               def.vd_flags = 0;
6334               def.vd_ndx = 2;
6335               def.vd_aux = sizeof (Elf_External_Verdef);
6336               if (verdefs)
6337                 def.vd_next = (sizeof (Elf_External_Verdef)
6338                                + sizeof (Elf_External_Verdaux));
6339               else
6340                 def.vd_next = 0;
6341               _bfd_elf_swap_verdef_out (output_bfd, &def,
6342                                         (Elf_External_Verdef *) p);
6343               p += sizeof (Elf_External_Verdef);
6344             }
6345           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6346                                      (Elf_External_Verdaux *) p);
6347           p += sizeof (Elf_External_Verdaux);
6348
6349           for (t = verdefs; t != NULL; t = t->next)
6350             {
6351               unsigned int cdeps;
6352               struct bfd_elf_version_deps *n;
6353
6354               /* Don't emit the base version twice.  */
6355               if (t->vernum == 0)
6356                 continue;
6357
6358               cdeps = 0;
6359               for (n = t->deps; n != NULL; n = n->next)
6360                 ++cdeps;
6361
6362               /* Add a symbol representing this version.  */
6363               bh = NULL;
6364               if (! (_bfd_generic_link_add_one_symbol
6365                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6366                       0, NULL, FALSE,
6367                       get_elf_backend_data (dynobj)->collect, &bh)))
6368                 return FALSE;
6369               h = (struct elf_link_hash_entry *) bh;
6370               h->non_elf = 0;
6371               h->def_regular = 1;
6372               h->type = STT_OBJECT;
6373               h->verinfo.vertree = t;
6374
6375               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6376                 return FALSE;
6377
6378               def.vd_version = VER_DEF_CURRENT;
6379               def.vd_flags = 0;
6380               if (t->globals.list == NULL
6381                   && t->locals.list == NULL
6382                   && ! t->used)
6383                 def.vd_flags |= VER_FLG_WEAK;
6384               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6385               def.vd_cnt = cdeps + 1;
6386               def.vd_hash = bfd_elf_hash (t->name);
6387               def.vd_aux = sizeof (Elf_External_Verdef);
6388               def.vd_next = 0;
6389
6390               /* If a basever node is next, it *must* be the last node in
6391                  the chain, otherwise Verdef construction breaks.  */
6392               if (t->next != NULL && t->next->vernum == 0)
6393                 BFD_ASSERT (t->next->next == NULL);
6394
6395               if (t->next != NULL && t->next->vernum != 0)
6396                 def.vd_next = (sizeof (Elf_External_Verdef)
6397                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6398
6399               _bfd_elf_swap_verdef_out (output_bfd, &def,
6400                                         (Elf_External_Verdef *) p);
6401               p += sizeof (Elf_External_Verdef);
6402
6403               defaux.vda_name = h->dynstr_index;
6404               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6405                                       h->dynstr_index);
6406               defaux.vda_next = 0;
6407               if (t->deps != NULL)
6408                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6409               t->name_indx = defaux.vda_name;
6410
6411               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6412                                          (Elf_External_Verdaux *) p);
6413               p += sizeof (Elf_External_Verdaux);
6414
6415               for (n = t->deps; n != NULL; n = n->next)
6416                 {
6417                   if (n->version_needed == NULL)
6418                     {
6419                       /* This can happen if there was an error in the
6420                          version script.  */
6421                       defaux.vda_name = 0;
6422                     }
6423                   else
6424                     {
6425                       defaux.vda_name = n->version_needed->name_indx;
6426                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6427                                               defaux.vda_name);
6428                     }
6429                   if (n->next == NULL)
6430                     defaux.vda_next = 0;
6431                   else
6432                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6433
6434                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6435                                              (Elf_External_Verdaux *) p);
6436                   p += sizeof (Elf_External_Verdaux);
6437                 }
6438             }
6439
6440           elf_tdata (output_bfd)->cverdefs = cdefs;
6441         }
6442     }
6443
6444   bed = get_elf_backend_data (output_bfd);
6445
6446   if (info->gc_sections && bed->can_gc_sections)
6447     {
6448       struct elf_gc_sweep_symbol_info sweep_info;
6449
6450       /* Remove the symbols that were in the swept sections from the
6451          dynamic symbol table.  */
6452       sweep_info.info = info;
6453       sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
6454       elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
6455                               &sweep_info);
6456     }
6457
6458   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6459     {
6460       asection *s;
6461       struct elf_find_verdep_info sinfo;
6462
6463       /* Work out the size of the version reference section.  */
6464
6465       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6466       BFD_ASSERT (s != NULL);
6467
6468       sinfo.info = info;
6469       sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6470       if (sinfo.vers == 0)
6471         sinfo.vers = 1;
6472       sinfo.failed = FALSE;
6473
6474       elf_link_hash_traverse (elf_hash_table (info),
6475                               _bfd_elf_link_find_version_dependencies,
6476                               &sinfo);
6477       if (sinfo.failed)
6478         return FALSE;
6479
6480       if (elf_tdata (output_bfd)->verref == NULL)
6481         s->flags |= SEC_EXCLUDE;
6482       else
6483         {
6484           Elf_Internal_Verneed *vn;
6485           unsigned int size;
6486           unsigned int crefs;
6487           bfd_byte *p;
6488
6489           /* Build the version dependency section.  */
6490           size = 0;
6491           crefs = 0;
6492           for (vn = elf_tdata (output_bfd)->verref;
6493                vn != NULL;
6494                vn = vn->vn_nextref)
6495             {
6496               Elf_Internal_Vernaux *a;
6497
6498               size += sizeof (Elf_External_Verneed);
6499               ++crefs;
6500               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6501                 size += sizeof (Elf_External_Vernaux);
6502             }
6503
6504           s->size = size;
6505           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6506           if (s->contents == NULL)
6507             return FALSE;
6508
6509           p = s->contents;
6510           for (vn = elf_tdata (output_bfd)->verref;
6511                vn != NULL;
6512                vn = vn->vn_nextref)
6513             {
6514               unsigned int caux;
6515               Elf_Internal_Vernaux *a;
6516               size_t indx;
6517
6518               caux = 0;
6519               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6520                 ++caux;
6521
6522               vn->vn_version = VER_NEED_CURRENT;
6523               vn->vn_cnt = caux;
6524               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6525                                           elf_dt_name (vn->vn_bfd) != NULL
6526                                           ? elf_dt_name (vn->vn_bfd)
6527                                           : lbasename (vn->vn_bfd->filename),
6528                                           FALSE);
6529               if (indx == (size_t) -1)
6530                 return FALSE;
6531               vn->vn_file = indx;
6532               vn->vn_aux = sizeof (Elf_External_Verneed);
6533               if (vn->vn_nextref == NULL)
6534                 vn->vn_next = 0;
6535               else
6536                 vn->vn_next = (sizeof (Elf_External_Verneed)
6537                                + caux * sizeof (Elf_External_Vernaux));
6538
6539               _bfd_elf_swap_verneed_out (output_bfd, vn,
6540                                          (Elf_External_Verneed *) p);
6541               p += sizeof (Elf_External_Verneed);
6542
6543               for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6544                 {
6545                   a->vna_hash = bfd_elf_hash (a->vna_nodename);
6546                   indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6547                                               a->vna_nodename, FALSE);
6548                   if (indx == (size_t) -1)
6549                     return FALSE;
6550                   a->vna_name = indx;
6551                   if (a->vna_nextptr == NULL)
6552                     a->vna_next = 0;
6553                   else
6554                     a->vna_next = sizeof (Elf_External_Vernaux);
6555
6556                   _bfd_elf_swap_vernaux_out (output_bfd, a,
6557                                              (Elf_External_Vernaux *) p);
6558                   p += sizeof (Elf_External_Vernaux);
6559                 }
6560             }
6561
6562           elf_tdata (output_bfd)->cverrefs = crefs;
6563         }
6564     }
6565
6566   /* Any syms created from now on start with -1 in
6567      got.refcount/offset and plt.refcount/offset.  */
6568   elf_hash_table (info)->init_got_refcount
6569     = elf_hash_table (info)->init_got_offset;
6570   elf_hash_table (info)->init_plt_refcount
6571     = elf_hash_table (info)->init_plt_offset;
6572
6573   if (bfd_link_relocatable (info)
6574       && !_bfd_elf_size_group_sections (info))
6575     return FALSE;
6576
6577   /* The backend may have to create some sections regardless of whether
6578      we're dynamic or not.  */
6579   if (bed->elf_backend_always_size_sections
6580       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
6581     return FALSE;
6582
6583   /* Determine any GNU_STACK segment requirements, after the backend
6584      has had a chance to set a default segment size.  */
6585   if (info->execstack)
6586     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
6587   else if (info->noexecstack)
6588     elf_stack_flags (output_bfd) = PF_R | PF_W;
6589   else
6590     {
6591       bfd *inputobj;
6592       asection *notesec = NULL;
6593       int exec = 0;
6594
6595       for (inputobj = info->input_bfds;
6596            inputobj;
6597            inputobj = inputobj->link.next)
6598         {
6599           asection *s;
6600
6601           if (inputobj->flags
6602               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
6603             continue;
6604           s = inputobj->sections;
6605           if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
6606             continue;
6607
6608           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
6609           if (s)
6610             {
6611               if (s->flags & SEC_CODE)
6612                 exec = PF_X;
6613               notesec = s;
6614             }
6615           else if (bed->default_execstack)
6616             exec = PF_X;
6617         }
6618       if (notesec || info->stacksize > 0)
6619         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
6620       if (notesec && exec && bfd_link_relocatable (info)
6621           && notesec->output_section != bfd_abs_section_ptr)
6622         notesec->output_section->flags |= SEC_CODE;
6623     }
6624
6625   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6626     {
6627       struct elf_info_failed eif;
6628       struct elf_link_hash_entry *h;
6629       asection *dynstr;
6630       asection *s;
6631
6632       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
6633       BFD_ASSERT (*sinterpptr != NULL || !bfd_link_executable (info) || info->nointerp);
6634
6635       if (info->symbolic)
6636         {
6637           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
6638             return FALSE;
6639           info->flags |= DF_SYMBOLIC;
6640         }
6641
6642       if (rpath != NULL)
6643         {
6644           size_t indx;
6645           bfd_vma tag;
6646
6647           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
6648                                       TRUE);
6649           if (indx == (size_t) -1)
6650             return FALSE;
6651
6652           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
6653           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
6654             return FALSE;
6655         }
6656
6657       if (filter_shlib != NULL)
6658         {
6659           size_t indx;
6660
6661           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6662                                       filter_shlib, TRUE);
6663           if (indx == (size_t) -1
6664               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
6665             return FALSE;
6666         }
6667
6668       if (auxiliary_filters != NULL)
6669         {
6670           const char * const *p;
6671
6672           for (p = auxiliary_filters; *p != NULL; p++)
6673             {
6674               size_t indx;
6675
6676               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6677                                           *p, TRUE);
6678               if (indx == (size_t) -1
6679                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
6680                 return FALSE;
6681             }
6682         }
6683
6684       if (audit != NULL)
6685         {
6686           size_t indx;
6687
6688           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
6689                                       TRUE);
6690           if (indx == (size_t) -1
6691               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
6692             return FALSE;
6693         }
6694
6695       if (depaudit != NULL)
6696         {
6697           size_t indx;
6698
6699           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
6700                                       TRUE);
6701           if (indx == (size_t) -1
6702               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
6703             return FALSE;
6704         }
6705
6706       eif.info = info;
6707       eif.failed = FALSE;
6708
6709       /* Find all symbols which were defined in a dynamic object and make
6710          the backend pick a reasonable value for them.  */
6711       elf_link_hash_traverse (elf_hash_table (info),
6712                               _bfd_elf_adjust_dynamic_symbol,
6713                               &eif);
6714       if (eif.failed)
6715         return FALSE;
6716
6717       /* Add some entries to the .dynamic section.  We fill in some of the
6718          values later, in bfd_elf_final_link, but we must add the entries
6719          now so that we know the final size of the .dynamic section.  */
6720
6721       /* If there are initialization and/or finalization functions to
6722          call then add the corresponding DT_INIT/DT_FINI entries.  */
6723       h = (info->init_function
6724            ? elf_link_hash_lookup (elf_hash_table (info),
6725                                    info->init_function, FALSE,
6726                                    FALSE, FALSE)
6727            : NULL);
6728       if (h != NULL
6729           && (h->ref_regular
6730               || h->def_regular))
6731         {
6732           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
6733             return FALSE;
6734         }
6735       h = (info->fini_function
6736            ? elf_link_hash_lookup (elf_hash_table (info),
6737                                    info->fini_function, FALSE,
6738                                    FALSE, FALSE)
6739            : NULL);
6740       if (h != NULL
6741           && (h->ref_regular
6742               || h->def_regular))
6743         {
6744           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
6745             return FALSE;
6746         }
6747
6748       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
6749       if (s != NULL && s->linker_has_input)
6750         {
6751           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
6752           if (! bfd_link_executable (info))
6753             {
6754               bfd *sub;
6755               asection *o;
6756
6757               for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
6758                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour
6759                     && (o = sub->sections) != NULL
6760                     && o->sec_info_type != SEC_INFO_TYPE_JUST_SYMS)
6761                   for (o = sub->sections; o != NULL; o = o->next)
6762                     if (elf_section_data (o)->this_hdr.sh_type
6763                         == SHT_PREINIT_ARRAY)
6764                       {
6765                         _bfd_error_handler
6766                           (_("%B: .preinit_array section is not allowed in DSO"),
6767                            sub);
6768                         break;
6769                       }
6770
6771               bfd_set_error (bfd_error_nonrepresentable_section);
6772               return FALSE;
6773             }
6774
6775           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6776               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6777             return FALSE;
6778         }
6779       s = bfd_get_section_by_name (output_bfd, ".init_array");
6780       if (s != NULL && s->linker_has_input)
6781         {
6782           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6783               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6784             return FALSE;
6785         }
6786       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6787       if (s != NULL && s->linker_has_input)
6788         {
6789           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6790               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6791             return FALSE;
6792         }
6793
6794       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6795       /* If .dynstr is excluded from the link, we don't want any of
6796          these tags.  Strictly, we should be checking each section
6797          individually;  This quick check covers for the case where
6798          someone does a /DISCARD/ : { *(*) }.  */
6799       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6800         {
6801           bfd_size_type strsize;
6802
6803           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6804           if ((info->emit_hash
6805                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6806               || (info->emit_gnu_hash
6807                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6808               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6809               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6810               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6811               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6812                                               bed->s->sizeof_sym))
6813             return FALSE;
6814         }
6815     }
6816
6817   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6818     return FALSE;
6819
6820   /* The backend must work out the sizes of all the other dynamic
6821      sections.  */
6822   if (dynobj != NULL
6823       && bed->elf_backend_size_dynamic_sections != NULL
6824       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6825     return FALSE;
6826
6827   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6828     {
6829       unsigned long section_sym_count;
6830
6831       if (elf_tdata (output_bfd)->cverdefs)
6832         {
6833           unsigned int crefs = elf_tdata (output_bfd)->cverdefs;
6834
6835           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6836               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, crefs))
6837             return FALSE;
6838         }
6839
6840       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6841         {
6842           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6843             return FALSE;
6844         }
6845       else if (info->flags & DF_BIND_NOW)
6846         {
6847           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6848             return FALSE;
6849         }
6850
6851       if (info->flags_1)
6852         {
6853           if (bfd_link_executable (info))
6854             info->flags_1 &= ~ (DF_1_INITFIRST
6855                                 | DF_1_NODELETE
6856                                 | DF_1_NOOPEN);
6857           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6858             return FALSE;
6859         }
6860
6861       if (elf_tdata (output_bfd)->cverrefs)
6862         {
6863           unsigned int crefs = elf_tdata (output_bfd)->cverrefs;
6864
6865           if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6866               || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6867             return FALSE;
6868         }
6869
6870       if ((elf_tdata (output_bfd)->cverrefs == 0
6871            && elf_tdata (output_bfd)->cverdefs == 0)
6872           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6873                                              &section_sym_count) <= 1)
6874         {
6875           asection *s;
6876
6877           s = bfd_get_linker_section (dynobj, ".gnu.version");
6878           s->flags |= SEC_EXCLUDE;
6879         }
6880     }
6881   return TRUE;
6882 }
6883
6884 /* Find the first non-excluded output section.  We'll use its
6885    section symbol for some emitted relocs.  */
6886 void
6887 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6888 {
6889   asection *s;
6890
6891   for (s = output_bfd->sections; s != NULL; s = s->next)
6892     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6893         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6894       {
6895         elf_hash_table (info)->text_index_section = s;
6896         break;
6897       }
6898 }
6899
6900 /* Find two non-excluded output sections, one for code, one for data.
6901    We'll use their section symbols for some emitted relocs.  */
6902 void
6903 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6904 {
6905   asection *s;
6906
6907   /* Data first, since setting text_index_section changes
6908      _bfd_elf_link_omit_section_dynsym.  */
6909   for (s = output_bfd->sections; s != NULL; s = s->next)
6910     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6911         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6912       {
6913         elf_hash_table (info)->data_index_section = s;
6914         break;
6915       }
6916
6917   for (s = output_bfd->sections; s != NULL; s = s->next)
6918     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6919          == (SEC_ALLOC | SEC_READONLY))
6920         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6921       {
6922         elf_hash_table (info)->text_index_section = s;
6923         break;
6924       }
6925
6926   if (elf_hash_table (info)->text_index_section == NULL)
6927     elf_hash_table (info)->text_index_section
6928       = elf_hash_table (info)->data_index_section;
6929 }
6930
6931 bfd_boolean
6932 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6933 {
6934   const struct elf_backend_data *bed;
6935   unsigned long section_sym_count;
6936   bfd_size_type dynsymcount = 0;
6937
6938   if (!is_elf_hash_table (info->hash))
6939     return TRUE;
6940
6941   bed = get_elf_backend_data (output_bfd);
6942   (*bed->elf_backend_init_index_section) (output_bfd, info);
6943
6944   /* Assign dynsym indices.  In a shared library we generate a section
6945      symbol for each output section, which come first.  Next come all
6946      of the back-end allocated local dynamic syms, followed by the rest
6947      of the global symbols.
6948
6949      This is usually not needed for static binaries, however backends
6950      can request to always do it, e.g. the MIPS backend uses dynamic
6951      symbol counts to lay out GOT, which will be produced in the
6952      presence of GOT relocations even in static binaries (holding fixed
6953      data in that case, to satisfy those relocations).  */
6954
6955   if (elf_hash_table (info)->dynamic_sections_created
6956       || bed->always_renumber_dynsyms)
6957     dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6958                                                   &section_sym_count);
6959
6960   if (elf_hash_table (info)->dynamic_sections_created)
6961     {
6962       bfd *dynobj;
6963       asection *s;
6964       unsigned int dtagcount;
6965
6966       dynobj = elf_hash_table (info)->dynobj;
6967
6968       /* Work out the size of the symbol version section.  */
6969       s = bfd_get_linker_section (dynobj, ".gnu.version");
6970       BFD_ASSERT (s != NULL);
6971       if ((s->flags & SEC_EXCLUDE) == 0)
6972         {
6973           s->size = dynsymcount * sizeof (Elf_External_Versym);
6974           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6975           if (s->contents == NULL)
6976             return FALSE;
6977
6978           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6979             return FALSE;
6980         }
6981
6982       /* Set the size of the .dynsym and .hash sections.  We counted
6983          the number of dynamic symbols in elf_link_add_object_symbols.
6984          We will build the contents of .dynsym and .hash when we build
6985          the final symbol table, because until then we do not know the
6986          correct value to give the symbols.  We built the .dynstr
6987          section as we went along in elf_link_add_object_symbols.  */
6988       s = elf_hash_table (info)->dynsym;
6989       BFD_ASSERT (s != NULL);
6990       s->size = dynsymcount * bed->s->sizeof_sym;
6991
6992       s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6993       if (s->contents == NULL)
6994         return FALSE;
6995
6996       /* The first entry in .dynsym is a dummy symbol.  Clear all the
6997          section syms, in case we don't output them all.  */
6998       ++section_sym_count;
6999       memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
7000
7001       elf_hash_table (info)->bucketcount = 0;
7002
7003       /* Compute the size of the hashing table.  As a side effect this
7004          computes the hash values for all the names we export.  */
7005       if (info->emit_hash)
7006         {
7007           unsigned long int *hashcodes;
7008           struct hash_codes_info hashinf;
7009           bfd_size_type amt;
7010           unsigned long int nsyms;
7011           size_t bucketcount;
7012           size_t hash_entry_size;
7013
7014           /* Compute the hash values for all exported symbols.  At the same
7015              time store the values in an array so that we could use them for
7016              optimizations.  */
7017           amt = dynsymcount * sizeof (unsigned long int);
7018           hashcodes = (unsigned long int *) bfd_malloc (amt);
7019           if (hashcodes == NULL)
7020             return FALSE;
7021           hashinf.hashcodes = hashcodes;
7022           hashinf.error = FALSE;
7023
7024           /* Put all hash values in HASHCODES.  */
7025           elf_link_hash_traverse (elf_hash_table (info),
7026                                   elf_collect_hash_codes, &hashinf);
7027           if (hashinf.error)
7028             {
7029               free (hashcodes);
7030               return FALSE;
7031             }
7032
7033           nsyms = hashinf.hashcodes - hashcodes;
7034           bucketcount
7035             = compute_bucket_count (info, hashcodes, nsyms, 0);
7036           free (hashcodes);
7037
7038           if (bucketcount == 0 && nsyms > 0)
7039             return FALSE;
7040
7041           elf_hash_table (info)->bucketcount = bucketcount;
7042
7043           s = bfd_get_linker_section (dynobj, ".hash");
7044           BFD_ASSERT (s != NULL);
7045           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
7046           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
7047           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7048           if (s->contents == NULL)
7049             return FALSE;
7050
7051           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
7052           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
7053                    s->contents + hash_entry_size);
7054         }
7055
7056       if (info->emit_gnu_hash)
7057         {
7058           size_t i, cnt;
7059           unsigned char *contents;
7060           struct collect_gnu_hash_codes cinfo;
7061           bfd_size_type amt;
7062           size_t bucketcount;
7063
7064           memset (&cinfo, 0, sizeof (cinfo));
7065
7066           /* Compute the hash values for all exported symbols.  At the same
7067              time store the values in an array so that we could use them for
7068              optimizations.  */
7069           amt = dynsymcount * 2 * sizeof (unsigned long int);
7070           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
7071           if (cinfo.hashcodes == NULL)
7072             return FALSE;
7073
7074           cinfo.hashval = cinfo.hashcodes + dynsymcount;
7075           cinfo.min_dynindx = -1;
7076           cinfo.output_bfd = output_bfd;
7077           cinfo.bed = bed;
7078
7079           /* Put all hash values in HASHCODES.  */
7080           elf_link_hash_traverse (elf_hash_table (info),
7081                                   elf_collect_gnu_hash_codes, &cinfo);
7082           if (cinfo.error)
7083             {
7084               free (cinfo.hashcodes);
7085               return FALSE;
7086             }
7087
7088           bucketcount
7089             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
7090
7091           if (bucketcount == 0)
7092             {
7093               free (cinfo.hashcodes);
7094               return FALSE;
7095             }
7096
7097           s = bfd_get_linker_section (dynobj, ".gnu.hash");
7098           BFD_ASSERT (s != NULL);
7099
7100           if (cinfo.nsyms == 0)
7101             {
7102               /* Empty .gnu.hash section is special.  */
7103               BFD_ASSERT (cinfo.min_dynindx == -1);
7104               free (cinfo.hashcodes);
7105               s->size = 5 * 4 + bed->s->arch_size / 8;
7106               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7107               if (contents == NULL)
7108                 return FALSE;
7109               s->contents = contents;
7110               /* 1 empty bucket.  */
7111               bfd_put_32 (output_bfd, 1, contents);
7112               /* SYMIDX above the special symbol 0.  */
7113               bfd_put_32 (output_bfd, 1, contents + 4);
7114               /* Just one word for bitmask.  */
7115               bfd_put_32 (output_bfd, 1, contents + 8);
7116               /* Only hash fn bloom filter.  */
7117               bfd_put_32 (output_bfd, 0, contents + 12);
7118               /* No hashes are valid - empty bitmask.  */
7119               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
7120               /* No hashes in the only bucket.  */
7121               bfd_put_32 (output_bfd, 0,
7122                           contents + 16 + bed->s->arch_size / 8);
7123             }
7124           else
7125             {
7126               unsigned long int maskwords, maskbitslog2, x;
7127               BFD_ASSERT (cinfo.min_dynindx != -1);
7128
7129               x = cinfo.nsyms;
7130               maskbitslog2 = 1;
7131               while ((x >>= 1) != 0)
7132                 ++maskbitslog2;
7133               if (maskbitslog2 < 3)
7134                 maskbitslog2 = 5;
7135               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
7136                 maskbitslog2 = maskbitslog2 + 3;
7137               else
7138                 maskbitslog2 = maskbitslog2 + 2;
7139               if (bed->s->arch_size == 64)
7140                 {
7141                   if (maskbitslog2 == 5)
7142                     maskbitslog2 = 6;
7143                   cinfo.shift1 = 6;
7144                 }
7145               else
7146                 cinfo.shift1 = 5;
7147               cinfo.mask = (1 << cinfo.shift1) - 1;
7148               cinfo.shift2 = maskbitslog2;
7149               cinfo.maskbits = 1 << maskbitslog2;
7150               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
7151               amt = bucketcount * sizeof (unsigned long int) * 2;
7152               amt += maskwords * sizeof (bfd_vma);
7153               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
7154               if (cinfo.bitmask == NULL)
7155                 {
7156                   free (cinfo.hashcodes);
7157                   return FALSE;
7158                 }
7159
7160               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
7161               cinfo.indx = cinfo.counts + bucketcount;
7162               cinfo.symindx = dynsymcount - cinfo.nsyms;
7163               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
7164
7165               /* Determine how often each hash bucket is used.  */
7166               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
7167               for (i = 0; i < cinfo.nsyms; ++i)
7168                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
7169
7170               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
7171                 if (cinfo.counts[i] != 0)
7172                   {
7173                     cinfo.indx[i] = cnt;
7174                     cnt += cinfo.counts[i];
7175                   }
7176               BFD_ASSERT (cnt == dynsymcount);
7177               cinfo.bucketcount = bucketcount;
7178               cinfo.local_indx = cinfo.min_dynindx;
7179
7180               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
7181               s->size += cinfo.maskbits / 8;
7182               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7183               if (contents == NULL)
7184                 {
7185                   free (cinfo.bitmask);
7186                   free (cinfo.hashcodes);
7187                   return FALSE;
7188                 }
7189
7190               s->contents = contents;
7191               bfd_put_32 (output_bfd, bucketcount, contents);
7192               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
7193               bfd_put_32 (output_bfd, maskwords, contents + 8);
7194               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
7195               contents += 16 + cinfo.maskbits / 8;
7196
7197               for (i = 0; i < bucketcount; ++i)
7198                 {
7199                   if (cinfo.counts[i] == 0)
7200                     bfd_put_32 (output_bfd, 0, contents);
7201                   else
7202                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
7203                   contents += 4;
7204                 }
7205
7206               cinfo.contents = contents;
7207
7208               /* Renumber dynamic symbols, populate .gnu.hash section.  */
7209               elf_link_hash_traverse (elf_hash_table (info),
7210                                       elf_renumber_gnu_hash_syms, &cinfo);
7211
7212               contents = s->contents + 16;
7213               for (i = 0; i < maskwords; ++i)
7214                 {
7215                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
7216                            contents);
7217                   contents += bed->s->arch_size / 8;
7218                 }
7219
7220               free (cinfo.bitmask);
7221               free (cinfo.hashcodes);
7222             }
7223         }
7224
7225       s = bfd_get_linker_section (dynobj, ".dynstr");
7226       BFD_ASSERT (s != NULL);
7227
7228       elf_finalize_dynstr (output_bfd, info);
7229
7230       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
7231
7232       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
7233         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
7234           return FALSE;
7235     }
7236
7237   return TRUE;
7238 }
7239 \f
7240 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
7241
7242 static void
7243 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
7244                             asection *sec)
7245 {
7246   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
7247   sec->sec_info_type = SEC_INFO_TYPE_NONE;
7248 }
7249
7250 /* Finish SHF_MERGE section merging.  */
7251
7252 bfd_boolean
7253 _bfd_elf_merge_sections (bfd *obfd, struct bfd_link_info *info)
7254 {
7255   bfd *ibfd;
7256   asection *sec;
7257
7258   if (!is_elf_hash_table (info->hash))
7259     return FALSE;
7260
7261   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
7262     if ((ibfd->flags & DYNAMIC) == 0
7263         && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
7264         && (elf_elfheader (ibfd)->e_ident[EI_CLASS]
7265             == get_elf_backend_data (obfd)->s->elfclass))
7266       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
7267         if ((sec->flags & SEC_MERGE) != 0
7268             && !bfd_is_abs_section (sec->output_section))
7269           {
7270             struct bfd_elf_section_data *secdata;
7271
7272             secdata = elf_section_data (sec);
7273             if (! _bfd_add_merge_section (obfd,
7274                                           &elf_hash_table (info)->merge_info,
7275                                           sec, &secdata->sec_info))
7276               return FALSE;
7277             else if (secdata->sec_info)
7278               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
7279           }
7280
7281   if (elf_hash_table (info)->merge_info != NULL)
7282     _bfd_merge_sections (obfd, info, elf_hash_table (info)->merge_info,
7283                          merge_sections_remove_hook);
7284   return TRUE;
7285 }
7286
7287 /* Create an entry in an ELF linker hash table.  */
7288
7289 struct bfd_hash_entry *
7290 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
7291                             struct bfd_hash_table *table,
7292                             const char *string)
7293 {
7294   /* Allocate the structure if it has not already been allocated by a
7295      subclass.  */
7296   if (entry == NULL)
7297     {
7298       entry = (struct bfd_hash_entry *)
7299         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
7300       if (entry == NULL)
7301         return entry;
7302     }
7303
7304   /* Call the allocation method of the superclass.  */
7305   entry = _bfd_link_hash_newfunc (entry, table, string);
7306   if (entry != NULL)
7307     {
7308       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
7309       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
7310
7311       /* Set local fields.  */
7312       ret->indx = -1;
7313       ret->dynindx = -1;
7314       ret->got = htab->init_got_refcount;
7315       ret->plt = htab->init_plt_refcount;
7316       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
7317                               - offsetof (struct elf_link_hash_entry, size)));
7318       /* Assume that we have been called by a non-ELF symbol reader.
7319          This flag is then reset by the code which reads an ELF input
7320          file.  This ensures that a symbol created by a non-ELF symbol
7321          reader will have the flag set correctly.  */
7322       ret->non_elf = 1;
7323     }
7324
7325   return entry;
7326 }
7327
7328 /* Copy data from an indirect symbol to its direct symbol, hiding the
7329    old indirect symbol.  Also used for copying flags to a weakdef.  */
7330
7331 void
7332 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
7333                                   struct elf_link_hash_entry *dir,
7334                                   struct elf_link_hash_entry *ind)
7335 {
7336   struct elf_link_hash_table *htab;
7337
7338   /* Copy down any references that we may have already seen to the
7339      symbol which just became indirect.  */
7340
7341   if (dir->versioned != versioned_hidden)
7342     dir->ref_dynamic |= ind->ref_dynamic;
7343   dir->ref_regular |= ind->ref_regular;
7344   dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
7345   dir->non_got_ref |= ind->non_got_ref;
7346   dir->needs_plt |= ind->needs_plt;
7347   dir->pointer_equality_needed |= ind->pointer_equality_needed;
7348
7349   if (ind->root.type != bfd_link_hash_indirect)
7350     return;
7351
7352   /* Copy over the global and procedure linkage table refcount entries.
7353      These may have been already set up by a check_relocs routine.  */
7354   htab = elf_hash_table (info);
7355   if (ind->got.refcount > htab->init_got_refcount.refcount)
7356     {
7357       if (dir->got.refcount < 0)
7358         dir->got.refcount = 0;
7359       dir->got.refcount += ind->got.refcount;
7360       ind->got.refcount = htab->init_got_refcount.refcount;
7361     }
7362
7363   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
7364     {
7365       if (dir->plt.refcount < 0)
7366         dir->plt.refcount = 0;
7367       dir->plt.refcount += ind->plt.refcount;
7368       ind->plt.refcount = htab->init_plt_refcount.refcount;
7369     }
7370
7371   if (ind->dynindx != -1)
7372     {
7373       if (dir->dynindx != -1)
7374         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
7375       dir->dynindx = ind->dynindx;
7376       dir->dynstr_index = ind->dynstr_index;
7377       ind->dynindx = -1;
7378       ind->dynstr_index = 0;
7379     }
7380 }
7381
7382 void
7383 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
7384                                 struct elf_link_hash_entry *h,
7385                                 bfd_boolean force_local)
7386 {
7387   /* STT_GNU_IFUNC symbol must go through PLT.  */
7388   if (h->type != STT_GNU_IFUNC)
7389     {
7390       h->plt = elf_hash_table (info)->init_plt_offset;
7391       h->needs_plt = 0;
7392     }
7393   if (force_local)
7394     {
7395       h->forced_local = 1;
7396       if (h->dynindx != -1)
7397         {
7398           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
7399                                   h->dynstr_index);
7400           h->dynindx = -1;
7401           h->dynstr_index = 0;
7402         }
7403     }
7404 }
7405
7406 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
7407    caller.  */
7408
7409 bfd_boolean
7410 _bfd_elf_link_hash_table_init
7411   (struct elf_link_hash_table *table,
7412    bfd *abfd,
7413    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
7414                                       struct bfd_hash_table *,
7415                                       const char *),
7416    unsigned int entsize,
7417    enum elf_target_id target_id)
7418 {
7419   bfd_boolean ret;
7420   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
7421
7422   table->init_got_refcount.refcount = can_refcount - 1;
7423   table->init_plt_refcount.refcount = can_refcount - 1;
7424   table->init_got_offset.offset = -(bfd_vma) 1;
7425   table->init_plt_offset.offset = -(bfd_vma) 1;
7426   /* The first dynamic symbol is a dummy.  */
7427   table->dynsymcount = 1;
7428
7429   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
7430
7431   table->root.type = bfd_link_elf_hash_table;
7432   table->hash_table_id = target_id;
7433
7434   return ret;
7435 }
7436
7437 /* Create an ELF linker hash table.  */
7438
7439 struct bfd_link_hash_table *
7440 _bfd_elf_link_hash_table_create (bfd *abfd)
7441 {
7442   struct elf_link_hash_table *ret;
7443   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7444
7445   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7446   if (ret == NULL)
7447     return NULL;
7448
7449   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7450                                        sizeof (struct elf_link_hash_entry),
7451                                        GENERIC_ELF_DATA))
7452     {
7453       free (ret);
7454       return NULL;
7455     }
7456   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7457
7458   return &ret->root;
7459 }
7460
7461 /* Destroy an ELF linker hash table.  */
7462
7463 void
7464 _bfd_elf_link_hash_table_free (bfd *obfd)
7465 {
7466   struct elf_link_hash_table *htab;
7467
7468   htab = (struct elf_link_hash_table *) obfd->link.hash;
7469   if (htab->dynstr != NULL)
7470     _bfd_elf_strtab_free (htab->dynstr);
7471   _bfd_merge_sections_free (htab->merge_info);
7472   _bfd_generic_link_hash_table_free (obfd);
7473 }
7474
7475 /* This is a hook for the ELF emulation code in the generic linker to
7476    tell the backend linker what file name to use for the DT_NEEDED
7477    entry for a dynamic object.  */
7478
7479 void
7480 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7481 {
7482   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7483       && bfd_get_format (abfd) == bfd_object)
7484     elf_dt_name (abfd) = name;
7485 }
7486
7487 int
7488 bfd_elf_get_dyn_lib_class (bfd *abfd)
7489 {
7490   int lib_class;
7491   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7492       && bfd_get_format (abfd) == bfd_object)
7493     lib_class = elf_dyn_lib_class (abfd);
7494   else
7495     lib_class = 0;
7496   return lib_class;
7497 }
7498
7499 void
7500 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7501 {
7502   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7503       && bfd_get_format (abfd) == bfd_object)
7504     elf_dyn_lib_class (abfd) = lib_class;
7505 }
7506
7507 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7508    the linker ELF emulation code.  */
7509
7510 struct bfd_link_needed_list *
7511 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7512                          struct bfd_link_info *info)
7513 {
7514   if (! is_elf_hash_table (info->hash))
7515     return NULL;
7516   return elf_hash_table (info)->needed;
7517 }
7518
7519 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7520    hook for the linker ELF emulation code.  */
7521
7522 struct bfd_link_needed_list *
7523 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7524                           struct bfd_link_info *info)
7525 {
7526   if (! is_elf_hash_table (info->hash))
7527     return NULL;
7528   return elf_hash_table (info)->runpath;
7529 }
7530
7531 /* Get the name actually used for a dynamic object for a link.  This
7532    is the SONAME entry if there is one.  Otherwise, it is the string
7533    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7534
7535 const char *
7536 bfd_elf_get_dt_soname (bfd *abfd)
7537 {
7538   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7539       && bfd_get_format (abfd) == bfd_object)
7540     return elf_dt_name (abfd);
7541   return NULL;
7542 }
7543
7544 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7545    the ELF linker emulation code.  */
7546
7547 bfd_boolean
7548 bfd_elf_get_bfd_needed_list (bfd *abfd,
7549                              struct bfd_link_needed_list **pneeded)
7550 {
7551   asection *s;
7552   bfd_byte *dynbuf = NULL;
7553   unsigned int elfsec;
7554   unsigned long shlink;
7555   bfd_byte *extdyn, *extdynend;
7556   size_t extdynsize;
7557   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7558
7559   *pneeded = NULL;
7560
7561   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7562       || bfd_get_format (abfd) != bfd_object)
7563     return TRUE;
7564
7565   s = bfd_get_section_by_name (abfd, ".dynamic");
7566   if (s == NULL || s->size == 0)
7567     return TRUE;
7568
7569   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7570     goto error_return;
7571
7572   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7573   if (elfsec == SHN_BAD)
7574     goto error_return;
7575
7576   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7577
7578   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7579   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7580
7581   extdyn = dynbuf;
7582   extdynend = extdyn + s->size;
7583   for (; extdyn < extdynend; extdyn += extdynsize)
7584     {
7585       Elf_Internal_Dyn dyn;
7586
7587       (*swap_dyn_in) (abfd, extdyn, &dyn);
7588
7589       if (dyn.d_tag == DT_NULL)
7590         break;
7591
7592       if (dyn.d_tag == DT_NEEDED)
7593         {
7594           const char *string;
7595           struct bfd_link_needed_list *l;
7596           unsigned int tagv = dyn.d_un.d_val;
7597           bfd_size_type amt;
7598
7599           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7600           if (string == NULL)
7601             goto error_return;
7602
7603           amt = sizeof *l;
7604           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7605           if (l == NULL)
7606             goto error_return;
7607
7608           l->by = abfd;
7609           l->name = string;
7610           l->next = *pneeded;
7611           *pneeded = l;
7612         }
7613     }
7614
7615   free (dynbuf);
7616
7617   return TRUE;
7618
7619  error_return:
7620   if (dynbuf != NULL)
7621     free (dynbuf);
7622   return FALSE;
7623 }
7624
7625 struct elf_symbuf_symbol
7626 {
7627   unsigned long st_name;        /* Symbol name, index in string tbl */
7628   unsigned char st_info;        /* Type and binding attributes */
7629   unsigned char st_other;       /* Visibilty, and target specific */
7630 };
7631
7632 struct elf_symbuf_head
7633 {
7634   struct elf_symbuf_symbol *ssym;
7635   size_t count;
7636   unsigned int st_shndx;
7637 };
7638
7639 struct elf_symbol
7640 {
7641   union
7642     {
7643       Elf_Internal_Sym *isym;
7644       struct elf_symbuf_symbol *ssym;
7645     } u;
7646   const char *name;
7647 };
7648
7649 /* Sort references to symbols by ascending section number.  */
7650
7651 static int
7652 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7653 {
7654   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7655   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7656
7657   return s1->st_shndx - s2->st_shndx;
7658 }
7659
7660 static int
7661 elf_sym_name_compare (const void *arg1, const void *arg2)
7662 {
7663   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7664   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7665   return strcmp (s1->name, s2->name);
7666 }
7667
7668 static struct elf_symbuf_head *
7669 elf_create_symbuf (size_t symcount, Elf_Internal_Sym *isymbuf)
7670 {
7671   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7672   struct elf_symbuf_symbol *ssym;
7673   struct elf_symbuf_head *ssymbuf, *ssymhead;
7674   size_t i, shndx_count, total_size;
7675
7676   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7677   if (indbuf == NULL)
7678     return NULL;
7679
7680   for (ind = indbuf, i = 0; i < symcount; i++)
7681     if (isymbuf[i].st_shndx != SHN_UNDEF)
7682       *ind++ = &isymbuf[i];
7683   indbufend = ind;
7684
7685   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7686          elf_sort_elf_symbol);
7687
7688   shndx_count = 0;
7689   if (indbufend > indbuf)
7690     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7691       if (ind[0]->st_shndx != ind[1]->st_shndx)
7692         shndx_count++;
7693
7694   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7695                 + (indbufend - indbuf) * sizeof (*ssym));
7696   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7697   if (ssymbuf == NULL)
7698     {
7699       free (indbuf);
7700       return NULL;
7701     }
7702
7703   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7704   ssymbuf->ssym = NULL;
7705   ssymbuf->count = shndx_count;
7706   ssymbuf->st_shndx = 0;
7707   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7708     {
7709       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7710         {
7711           ssymhead++;
7712           ssymhead->ssym = ssym;
7713           ssymhead->count = 0;
7714           ssymhead->st_shndx = (*ind)->st_shndx;
7715         }
7716       ssym->st_name = (*ind)->st_name;
7717       ssym->st_info = (*ind)->st_info;
7718       ssym->st_other = (*ind)->st_other;
7719       ssymhead->count++;
7720     }
7721   BFD_ASSERT ((size_t) (ssymhead - ssymbuf) == shndx_count
7722               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7723                   == total_size));
7724
7725   free (indbuf);
7726   return ssymbuf;
7727 }
7728
7729 /* Check if 2 sections define the same set of local and global
7730    symbols.  */
7731
7732 static bfd_boolean
7733 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7734                                    struct bfd_link_info *info)
7735 {
7736   bfd *bfd1, *bfd2;
7737   const struct elf_backend_data *bed1, *bed2;
7738   Elf_Internal_Shdr *hdr1, *hdr2;
7739   size_t symcount1, symcount2;
7740   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7741   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7742   Elf_Internal_Sym *isym, *isymend;
7743   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7744   size_t count1, count2, i;
7745   unsigned int shndx1, shndx2;
7746   bfd_boolean result;
7747
7748   bfd1 = sec1->owner;
7749   bfd2 = sec2->owner;
7750
7751   /* Both sections have to be in ELF.  */
7752   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7753       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7754     return FALSE;
7755
7756   if (elf_section_type (sec1) != elf_section_type (sec2))
7757     return FALSE;
7758
7759   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7760   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7761   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7762     return FALSE;
7763
7764   bed1 = get_elf_backend_data (bfd1);
7765   bed2 = get_elf_backend_data (bfd2);
7766   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7767   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7768   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7769   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7770
7771   if (symcount1 == 0 || symcount2 == 0)
7772     return FALSE;
7773
7774   result = FALSE;
7775   isymbuf1 = NULL;
7776   isymbuf2 = NULL;
7777   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7778   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7779
7780   if (ssymbuf1 == NULL)
7781     {
7782       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7783                                        NULL, NULL, NULL);
7784       if (isymbuf1 == NULL)
7785         goto done;
7786
7787       if (!info->reduce_memory_overheads)
7788         elf_tdata (bfd1)->symbuf = ssymbuf1
7789           = elf_create_symbuf (symcount1, isymbuf1);
7790     }
7791
7792   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7793     {
7794       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7795                                        NULL, NULL, NULL);
7796       if (isymbuf2 == NULL)
7797         goto done;
7798
7799       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7800         elf_tdata (bfd2)->symbuf = ssymbuf2
7801           = elf_create_symbuf (symcount2, isymbuf2);
7802     }
7803
7804   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7805     {
7806       /* Optimized faster version.  */
7807       size_t lo, hi, mid;
7808       struct elf_symbol *symp;
7809       struct elf_symbuf_symbol *ssym, *ssymend;
7810
7811       lo = 0;
7812       hi = ssymbuf1->count;
7813       ssymbuf1++;
7814       count1 = 0;
7815       while (lo < hi)
7816         {
7817           mid = (lo + hi) / 2;
7818           if (shndx1 < ssymbuf1[mid].st_shndx)
7819             hi = mid;
7820           else if (shndx1 > ssymbuf1[mid].st_shndx)
7821             lo = mid + 1;
7822           else
7823             {
7824               count1 = ssymbuf1[mid].count;
7825               ssymbuf1 += mid;
7826               break;
7827             }
7828         }
7829
7830       lo = 0;
7831       hi = ssymbuf2->count;
7832       ssymbuf2++;
7833       count2 = 0;
7834       while (lo < hi)
7835         {
7836           mid = (lo + hi) / 2;
7837           if (shndx2 < ssymbuf2[mid].st_shndx)
7838             hi = mid;
7839           else if (shndx2 > ssymbuf2[mid].st_shndx)
7840             lo = mid + 1;
7841           else
7842             {
7843               count2 = ssymbuf2[mid].count;
7844               ssymbuf2 += mid;
7845               break;
7846             }
7847         }
7848
7849       if (count1 == 0 || count2 == 0 || count1 != count2)
7850         goto done;
7851
7852       symtable1
7853         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
7854       symtable2
7855         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
7856       if (symtable1 == NULL || symtable2 == NULL)
7857         goto done;
7858
7859       symp = symtable1;
7860       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7861            ssym < ssymend; ssym++, symp++)
7862         {
7863           symp->u.ssym = ssym;
7864           symp->name = bfd_elf_string_from_elf_section (bfd1,
7865                                                         hdr1->sh_link,
7866                                                         ssym->st_name);
7867         }
7868
7869       symp = symtable2;
7870       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7871            ssym < ssymend; ssym++, symp++)
7872         {
7873           symp->u.ssym = ssym;
7874           symp->name = bfd_elf_string_from_elf_section (bfd2,
7875                                                         hdr2->sh_link,
7876                                                         ssym->st_name);
7877         }
7878
7879       /* Sort symbol by name.  */
7880       qsort (symtable1, count1, sizeof (struct elf_symbol),
7881              elf_sym_name_compare);
7882       qsort (symtable2, count1, sizeof (struct elf_symbol),
7883              elf_sym_name_compare);
7884
7885       for (i = 0; i < count1; i++)
7886         /* Two symbols must have the same binding, type and name.  */
7887         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7888             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7889             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7890           goto done;
7891
7892       result = TRUE;
7893       goto done;
7894     }
7895
7896   symtable1 = (struct elf_symbol *)
7897       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7898   symtable2 = (struct elf_symbol *)
7899       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7900   if (symtable1 == NULL || symtable2 == NULL)
7901     goto done;
7902
7903   /* Count definitions in the section.  */
7904   count1 = 0;
7905   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7906     if (isym->st_shndx == shndx1)
7907       symtable1[count1++].u.isym = isym;
7908
7909   count2 = 0;
7910   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7911     if (isym->st_shndx == shndx2)
7912       symtable2[count2++].u.isym = isym;
7913
7914   if (count1 == 0 || count2 == 0 || count1 != count2)
7915     goto done;
7916
7917   for (i = 0; i < count1; i++)
7918     symtable1[i].name
7919       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7920                                          symtable1[i].u.isym->st_name);
7921
7922   for (i = 0; i < count2; i++)
7923     symtable2[i].name
7924       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7925                                          symtable2[i].u.isym->st_name);
7926
7927   /* Sort symbol by name.  */
7928   qsort (symtable1, count1, sizeof (struct elf_symbol),
7929          elf_sym_name_compare);
7930   qsort (symtable2, count1, sizeof (struct elf_symbol),
7931          elf_sym_name_compare);
7932
7933   for (i = 0; i < count1; i++)
7934     /* Two symbols must have the same binding, type and name.  */
7935     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7936         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7937         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7938       goto done;
7939
7940   result = TRUE;
7941
7942 done:
7943   if (symtable1)
7944     free (symtable1);
7945   if (symtable2)
7946     free (symtable2);
7947   if (isymbuf1)
7948     free (isymbuf1);
7949   if (isymbuf2)
7950     free (isymbuf2);
7951
7952   return result;
7953 }
7954
7955 /* Return TRUE if 2 section types are compatible.  */
7956
7957 bfd_boolean
7958 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7959                                  bfd *bbfd, const asection *bsec)
7960 {
7961   if (asec == NULL
7962       || bsec == NULL
7963       || abfd->xvec->flavour != bfd_target_elf_flavour
7964       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7965     return TRUE;
7966
7967   return elf_section_type (asec) == elf_section_type (bsec);
7968 }
7969 \f
7970 /* Final phase of ELF linker.  */
7971
7972 /* A structure we use to avoid passing large numbers of arguments.  */
7973
7974 struct elf_final_link_info
7975 {
7976   /* General link information.  */
7977   struct bfd_link_info *info;
7978   /* Output BFD.  */
7979   bfd *output_bfd;
7980   /* Symbol string table.  */
7981   struct elf_strtab_hash *symstrtab;
7982   /* .hash section.  */
7983   asection *hash_sec;
7984   /* symbol version section (.gnu.version).  */
7985   asection *symver_sec;
7986   /* Buffer large enough to hold contents of any section.  */
7987   bfd_byte *contents;
7988   /* Buffer large enough to hold external relocs of any section.  */
7989   void *external_relocs;
7990   /* Buffer large enough to hold internal relocs of any section.  */
7991   Elf_Internal_Rela *internal_relocs;
7992   /* Buffer large enough to hold external local symbols of any input
7993      BFD.  */
7994   bfd_byte *external_syms;
7995   /* And a buffer for symbol section indices.  */
7996   Elf_External_Sym_Shndx *locsym_shndx;
7997   /* Buffer large enough to hold internal local symbols of any input
7998      BFD.  */
7999   Elf_Internal_Sym *internal_syms;
8000   /* Array large enough to hold a symbol index for each local symbol
8001      of any input BFD.  */
8002   long *indices;
8003   /* Array large enough to hold a section pointer for each local
8004      symbol of any input BFD.  */
8005   asection **sections;
8006   /* Buffer for SHT_SYMTAB_SHNDX section.  */
8007   Elf_External_Sym_Shndx *symshndxbuf;
8008   /* Number of STT_FILE syms seen.  */
8009   size_t filesym_count;
8010 };
8011
8012 /* This struct is used to pass information to elf_link_output_extsym.  */
8013
8014 struct elf_outext_info
8015 {
8016   bfd_boolean failed;
8017   bfd_boolean localsyms;
8018   bfd_boolean file_sym_done;
8019   struct elf_final_link_info *flinfo;
8020 };
8021
8022
8023 /* Support for evaluating a complex relocation.
8024
8025    Complex relocations are generalized, self-describing relocations.  The
8026    implementation of them consists of two parts: complex symbols, and the
8027    relocations themselves.
8028
8029    The relocations are use a reserved elf-wide relocation type code (R_RELC
8030    external / BFD_RELOC_RELC internal) and an encoding of relocation field
8031    information (start bit, end bit, word width, etc) into the addend.  This
8032    information is extracted from CGEN-generated operand tables within gas.
8033
8034    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
8035    internal) representing prefix-notation expressions, including but not
8036    limited to those sorts of expressions normally encoded as addends in the
8037    addend field.  The symbol mangling format is:
8038
8039    <node> := <literal>
8040           |  <unary-operator> ':' <node>
8041           |  <binary-operator> ':' <node> ':' <node>
8042           ;
8043
8044    <literal> := 's' <digits=N> ':' <N character symbol name>
8045              |  'S' <digits=N> ':' <N character section name>
8046              |  '#' <hexdigits>
8047              ;
8048
8049    <binary-operator> := as in C
8050    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
8051
8052 static void
8053 set_symbol_value (bfd *bfd_with_globals,
8054                   Elf_Internal_Sym *isymbuf,
8055                   size_t locsymcount,
8056                   size_t symidx,
8057                   bfd_vma val)
8058 {
8059   struct elf_link_hash_entry **sym_hashes;
8060   struct elf_link_hash_entry *h;
8061   size_t extsymoff = locsymcount;
8062
8063   if (symidx < locsymcount)
8064     {
8065       Elf_Internal_Sym *sym;
8066
8067       sym = isymbuf + symidx;
8068       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
8069         {
8070           /* It is a local symbol: move it to the
8071              "absolute" section and give it a value.  */
8072           sym->st_shndx = SHN_ABS;
8073           sym->st_value = val;
8074           return;
8075         }
8076       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
8077       extsymoff = 0;
8078     }
8079
8080   /* It is a global symbol: set its link type
8081      to "defined" and give it a value.  */
8082
8083   sym_hashes = elf_sym_hashes (bfd_with_globals);
8084   h = sym_hashes [symidx - extsymoff];
8085   while (h->root.type == bfd_link_hash_indirect
8086          || h->root.type == bfd_link_hash_warning)
8087     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8088   h->root.type = bfd_link_hash_defined;
8089   h->root.u.def.value = val;
8090   h->root.u.def.section = bfd_abs_section_ptr;
8091 }
8092
8093 static bfd_boolean
8094 resolve_symbol (const char *name,
8095                 bfd *input_bfd,
8096                 struct elf_final_link_info *flinfo,
8097                 bfd_vma *result,
8098                 Elf_Internal_Sym *isymbuf,
8099                 size_t locsymcount)
8100 {
8101   Elf_Internal_Sym *sym;
8102   struct bfd_link_hash_entry *global_entry;
8103   const char *candidate = NULL;
8104   Elf_Internal_Shdr *symtab_hdr;
8105   size_t i;
8106
8107   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
8108
8109   for (i = 0; i < locsymcount; ++ i)
8110     {
8111       sym = isymbuf + i;
8112
8113       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
8114         continue;
8115
8116       candidate = bfd_elf_string_from_elf_section (input_bfd,
8117                                                    symtab_hdr->sh_link,
8118                                                    sym->st_name);
8119 #ifdef DEBUG
8120       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
8121               name, candidate, (unsigned long) sym->st_value);
8122 #endif
8123       if (candidate && strcmp (candidate, name) == 0)
8124         {
8125           asection *sec = flinfo->sections [i];
8126
8127           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
8128           *result += sec->output_offset + sec->output_section->vma;
8129 #ifdef DEBUG
8130           printf ("Found symbol with value %8.8lx\n",
8131                   (unsigned long) *result);
8132 #endif
8133           return TRUE;
8134         }
8135     }
8136
8137   /* Hmm, haven't found it yet. perhaps it is a global.  */
8138   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
8139                                        FALSE, FALSE, TRUE);
8140   if (!global_entry)
8141     return FALSE;
8142
8143   if (global_entry->type == bfd_link_hash_defined
8144       || global_entry->type == bfd_link_hash_defweak)
8145     {
8146       *result = (global_entry->u.def.value
8147                  + global_entry->u.def.section->output_section->vma
8148                  + global_entry->u.def.section->output_offset);
8149 #ifdef DEBUG
8150       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
8151               global_entry->root.string, (unsigned long) *result);
8152 #endif
8153       return TRUE;
8154     }
8155
8156   return FALSE;
8157 }
8158
8159 /* Looks up NAME in SECTIONS.  If found sets RESULT to NAME's address (in
8160    bytes) and returns TRUE, otherwise returns FALSE.  Accepts pseudo-section
8161    names like "foo.end" which is the end address of section "foo".  */
8162    
8163 static bfd_boolean
8164 resolve_section (const char *name,
8165                  asection *sections,
8166                  bfd_vma *result,
8167                  bfd * abfd)
8168 {
8169   asection *curr;
8170   unsigned int len;
8171
8172   for (curr = sections; curr; curr = curr->next)
8173     if (strcmp (curr->name, name) == 0)
8174       {
8175         *result = curr->vma;
8176         return TRUE;
8177       }
8178
8179   /* Hmm. still haven't found it. try pseudo-section names.  */
8180   /* FIXME: This could be coded more efficiently...  */
8181   for (curr = sections; curr; curr = curr->next)
8182     {
8183       len = strlen (curr->name);
8184       if (len > strlen (name))
8185         continue;
8186
8187       if (strncmp (curr->name, name, len) == 0)
8188         {
8189           if (strncmp (".end", name + len, 4) == 0)
8190             {
8191               *result = curr->vma + curr->size / bfd_octets_per_byte (abfd);
8192               return TRUE;
8193             }
8194
8195           /* Insert more pseudo-section names here, if you like.  */
8196         }
8197     }
8198
8199   return FALSE;
8200 }
8201
8202 static void
8203 undefined_reference (const char *reftype, const char *name)
8204 {
8205   /* xgettext:c-format */
8206   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
8207                       reftype, name);
8208 }
8209
8210 static bfd_boolean
8211 eval_symbol (bfd_vma *result,
8212              const char **symp,
8213              bfd *input_bfd,
8214              struct elf_final_link_info *flinfo,
8215              bfd_vma dot,
8216              Elf_Internal_Sym *isymbuf,
8217              size_t locsymcount,
8218              int signed_p)
8219 {
8220   size_t len;
8221   size_t symlen;
8222   bfd_vma a;
8223   bfd_vma b;
8224   char symbuf[4096];
8225   const char *sym = *symp;
8226   const char *symend;
8227   bfd_boolean symbol_is_section = FALSE;
8228
8229   len = strlen (sym);
8230   symend = sym + len;
8231
8232   if (len < 1 || len > sizeof (symbuf))
8233     {
8234       bfd_set_error (bfd_error_invalid_operation);
8235       return FALSE;
8236     }
8237
8238   switch (* sym)
8239     {
8240     case '.':
8241       *result = dot;
8242       *symp = sym + 1;
8243       return TRUE;
8244
8245     case '#':
8246       ++sym;
8247       *result = strtoul (sym, (char **) symp, 16);
8248       return TRUE;
8249
8250     case 'S':
8251       symbol_is_section = TRUE;
8252       /* Fall through.  */
8253     case 's':
8254       ++sym;
8255       symlen = strtol (sym, (char **) symp, 10);
8256       sym = *symp + 1; /* Skip the trailing ':'.  */
8257
8258       if (symend < sym || symlen + 1 > sizeof (symbuf))
8259         {
8260           bfd_set_error (bfd_error_invalid_operation);
8261           return FALSE;
8262         }
8263
8264       memcpy (symbuf, sym, symlen);
8265       symbuf[symlen] = '\0';
8266       *symp = sym + symlen;
8267
8268       /* Is it always possible, with complex symbols, that gas "mis-guessed"
8269          the symbol as a section, or vice-versa. so we're pretty liberal in our
8270          interpretation here; section means "try section first", not "must be a
8271          section", and likewise with symbol.  */
8272
8273       if (symbol_is_section)
8274         {
8275           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result, input_bfd)
8276               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
8277                                   isymbuf, locsymcount))
8278             {
8279               undefined_reference ("section", symbuf);
8280               return FALSE;
8281             }
8282         }
8283       else
8284         {
8285           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
8286                                isymbuf, locsymcount)
8287               && !resolve_section (symbuf, flinfo->output_bfd->sections,
8288                                    result, input_bfd))
8289             {
8290               undefined_reference ("symbol", symbuf);
8291               return FALSE;
8292             }
8293         }
8294
8295       return TRUE;
8296
8297       /* All that remains are operators.  */
8298
8299 #define UNARY_OP(op)                                            \
8300   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8301     {                                                           \
8302       sym += strlen (#op);                                      \
8303       if (*sym == ':')                                          \
8304         ++sym;                                                  \
8305       *symp = sym;                                              \
8306       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8307                         isymbuf, locsymcount, signed_p))        \
8308         return FALSE;                                           \
8309       if (signed_p)                                             \
8310         *result = op ((bfd_signed_vma) a);                      \
8311       else                                                      \
8312         *result = op a;                                         \
8313       return TRUE;                                              \
8314     }
8315
8316 #define BINARY_OP(op)                                           \
8317   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8318     {                                                           \
8319       sym += strlen (#op);                                      \
8320       if (*sym == ':')                                          \
8321         ++sym;                                                  \
8322       *symp = sym;                                              \
8323       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8324                         isymbuf, locsymcount, signed_p))        \
8325         return FALSE;                                           \
8326       ++*symp;                                                  \
8327       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
8328                         isymbuf, locsymcount, signed_p))        \
8329         return FALSE;                                           \
8330       if (signed_p)                                             \
8331         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
8332       else                                                      \
8333         *result = a op b;                                       \
8334       return TRUE;                                              \
8335     }
8336
8337     default:
8338       UNARY_OP  (0-);
8339       BINARY_OP (<<);
8340       BINARY_OP (>>);
8341       BINARY_OP (==);
8342       BINARY_OP (!=);
8343       BINARY_OP (<=);
8344       BINARY_OP (>=);
8345       BINARY_OP (&&);
8346       BINARY_OP (||);
8347       UNARY_OP  (~);
8348       UNARY_OP  (!);
8349       BINARY_OP (*);
8350       BINARY_OP (/);
8351       BINARY_OP (%);
8352       BINARY_OP (^);
8353       BINARY_OP (|);
8354       BINARY_OP (&);
8355       BINARY_OP (+);
8356       BINARY_OP (-);
8357       BINARY_OP (<);
8358       BINARY_OP (>);
8359 #undef UNARY_OP
8360 #undef BINARY_OP
8361       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
8362       bfd_set_error (bfd_error_invalid_operation);
8363       return FALSE;
8364     }
8365 }
8366
8367 static void
8368 put_value (bfd_vma size,
8369            unsigned long chunksz,
8370            bfd *input_bfd,
8371            bfd_vma x,
8372            bfd_byte *location)
8373 {
8374   location += (size - chunksz);
8375
8376   for (; size; size -= chunksz, location -= chunksz)
8377     {
8378       switch (chunksz)
8379         {
8380         case 1:
8381           bfd_put_8 (input_bfd, x, location);
8382           x >>= 8;
8383           break;
8384         case 2:
8385           bfd_put_16 (input_bfd, x, location);
8386           x >>= 16;
8387           break;
8388         case 4:
8389           bfd_put_32 (input_bfd, x, location);
8390           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
8391           x >>= 16;
8392           x >>= 16;
8393           break;
8394 #ifdef BFD64
8395         case 8:
8396           bfd_put_64 (input_bfd, x, location);
8397           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
8398           x >>= 32;
8399           x >>= 32;
8400           break;
8401 #endif
8402         default:
8403           abort ();
8404           break;
8405         }
8406     }
8407 }
8408
8409 static bfd_vma
8410 get_value (bfd_vma size,
8411            unsigned long chunksz,
8412            bfd *input_bfd,
8413            bfd_byte *location)
8414 {
8415   int shift;
8416   bfd_vma x = 0;
8417
8418   /* Sanity checks.  */
8419   BFD_ASSERT (chunksz <= sizeof (x)
8420               && size >= chunksz
8421               && chunksz != 0
8422               && (size % chunksz) == 0
8423               && input_bfd != NULL
8424               && location != NULL);
8425
8426   if (chunksz == sizeof (x))
8427     {
8428       BFD_ASSERT (size == chunksz);
8429
8430       /* Make sure that we do not perform an undefined shift operation.
8431          We know that size == chunksz so there will only be one iteration
8432          of the loop below.  */
8433       shift = 0;
8434     }
8435   else
8436     shift = 8 * chunksz;
8437
8438   for (; size; size -= chunksz, location += chunksz)
8439     {
8440       switch (chunksz)
8441         {
8442         case 1:
8443           x = (x << shift) | bfd_get_8 (input_bfd, location);
8444           break;
8445         case 2:
8446           x = (x << shift) | bfd_get_16 (input_bfd, location);
8447           break;
8448         case 4:
8449           x = (x << shift) | bfd_get_32 (input_bfd, location);
8450           break;
8451 #ifdef BFD64
8452         case 8:
8453           x = (x << shift) | bfd_get_64 (input_bfd, location);
8454           break;
8455 #endif
8456         default:
8457           abort ();
8458         }
8459     }
8460   return x;
8461 }
8462
8463 static void
8464 decode_complex_addend (unsigned long *start,   /* in bits */
8465                        unsigned long *oplen,   /* in bits */
8466                        unsigned long *len,     /* in bits */
8467                        unsigned long *wordsz,  /* in bytes */
8468                        unsigned long *chunksz, /* in bytes */
8469                        unsigned long *lsb0_p,
8470                        unsigned long *signed_p,
8471                        unsigned long *trunc_p,
8472                        unsigned long encoded)
8473 {
8474   * start     =  encoded        & 0x3F;
8475   * len       = (encoded >>  6) & 0x3F;
8476   * oplen     = (encoded >> 12) & 0x3F;
8477   * wordsz    = (encoded >> 18) & 0xF;
8478   * chunksz   = (encoded >> 22) & 0xF;
8479   * lsb0_p    = (encoded >> 27) & 1;
8480   * signed_p  = (encoded >> 28) & 1;
8481   * trunc_p   = (encoded >> 29) & 1;
8482 }
8483
8484 bfd_reloc_status_type
8485 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8486                                     asection *input_section ATTRIBUTE_UNUSED,
8487                                     bfd_byte *contents,
8488                                     Elf_Internal_Rela *rel,
8489                                     bfd_vma relocation)
8490 {
8491   bfd_vma shift, x, mask;
8492   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8493   bfd_reloc_status_type r;
8494
8495   /*  Perform this reloc, since it is complex.
8496       (this is not to say that it necessarily refers to a complex
8497       symbol; merely that it is a self-describing CGEN based reloc.
8498       i.e. the addend has the complete reloc information (bit start, end,
8499       word size, etc) encoded within it.).  */
8500
8501   decode_complex_addend (&start, &oplen, &len, &wordsz,
8502                          &chunksz, &lsb0_p, &signed_p,
8503                          &trunc_p, rel->r_addend);
8504
8505   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8506
8507   if (lsb0_p)
8508     shift = (start + 1) - len;
8509   else
8510     shift = (8 * wordsz) - (start + len);
8511
8512   x = get_value (wordsz, chunksz, input_bfd,
8513                  contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8514
8515 #ifdef DEBUG
8516   printf ("Doing complex reloc: "
8517           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8518           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8519           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8520           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8521           oplen, (unsigned long) x, (unsigned long) mask,
8522           (unsigned long) relocation);
8523 #endif
8524
8525   r = bfd_reloc_ok;
8526   if (! trunc_p)
8527     /* Now do an overflow check.  */
8528     r = bfd_check_overflow ((signed_p
8529                              ? complain_overflow_signed
8530                              : complain_overflow_unsigned),
8531                             len, 0, (8 * wordsz),
8532                             relocation);
8533
8534   /* Do the deed.  */
8535   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8536
8537 #ifdef DEBUG
8538   printf ("           relocation: %8.8lx\n"
8539           "         shifted mask: %8.8lx\n"
8540           " shifted/masked reloc: %8.8lx\n"
8541           "               result: %8.8lx\n",
8542           (unsigned long) relocation, (unsigned long) (mask << shift),
8543           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8544 #endif
8545   put_value (wordsz, chunksz, input_bfd, x,
8546              contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8547   return r;
8548 }
8549
8550 /* Functions to read r_offset from external (target order) reloc
8551    entry.  Faster than bfd_getl32 et al, because we let the compiler
8552    know the value is aligned.  */
8553
8554 static bfd_vma
8555 ext32l_r_offset (const void *p)
8556 {
8557   union aligned32
8558   {
8559     uint32_t v;
8560     unsigned char c[4];
8561   };
8562   const union aligned32 *a
8563     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8564
8565   uint32_t aval = (  (uint32_t) a->c[0]
8566                    | (uint32_t) a->c[1] << 8
8567                    | (uint32_t) a->c[2] << 16
8568                    | (uint32_t) a->c[3] << 24);
8569   return aval;
8570 }
8571
8572 static bfd_vma
8573 ext32b_r_offset (const void *p)
8574 {
8575   union aligned32
8576   {
8577     uint32_t v;
8578     unsigned char c[4];
8579   };
8580   const union aligned32 *a
8581     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8582
8583   uint32_t aval = (  (uint32_t) a->c[0] << 24
8584                    | (uint32_t) a->c[1] << 16
8585                    | (uint32_t) a->c[2] << 8
8586                    | (uint32_t) a->c[3]);
8587   return aval;
8588 }
8589
8590 #ifdef BFD_HOST_64_BIT
8591 static bfd_vma
8592 ext64l_r_offset (const void *p)
8593 {
8594   union aligned64
8595   {
8596     uint64_t v;
8597     unsigned char c[8];
8598   };
8599   const union aligned64 *a
8600     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8601
8602   uint64_t aval = (  (uint64_t) a->c[0]
8603                    | (uint64_t) a->c[1] << 8
8604                    | (uint64_t) a->c[2] << 16
8605                    | (uint64_t) a->c[3] << 24
8606                    | (uint64_t) a->c[4] << 32
8607                    | (uint64_t) a->c[5] << 40
8608                    | (uint64_t) a->c[6] << 48
8609                    | (uint64_t) a->c[7] << 56);
8610   return aval;
8611 }
8612
8613 static bfd_vma
8614 ext64b_r_offset (const void *p)
8615 {
8616   union aligned64
8617   {
8618     uint64_t v;
8619     unsigned char c[8];
8620   };
8621   const union aligned64 *a
8622     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8623
8624   uint64_t aval = (  (uint64_t) a->c[0] << 56
8625                    | (uint64_t) a->c[1] << 48
8626                    | (uint64_t) a->c[2] << 40
8627                    | (uint64_t) a->c[3] << 32
8628                    | (uint64_t) a->c[4] << 24
8629                    | (uint64_t) a->c[5] << 16
8630                    | (uint64_t) a->c[6] << 8
8631                    | (uint64_t) a->c[7]);
8632   return aval;
8633 }
8634 #endif
8635
8636 /* When performing a relocatable link, the input relocations are
8637    preserved.  But, if they reference global symbols, the indices
8638    referenced must be updated.  Update all the relocations found in
8639    RELDATA.  */
8640
8641 static bfd_boolean
8642 elf_link_adjust_relocs (bfd *abfd,
8643                         asection *sec,
8644                         struct bfd_elf_section_reloc_data *reldata,
8645                         bfd_boolean sort,
8646                         struct bfd_link_info *info)
8647 {
8648   unsigned int i;
8649   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8650   bfd_byte *erela;
8651   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8652   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8653   bfd_vma r_type_mask;
8654   int r_sym_shift;
8655   unsigned int count = reldata->count;
8656   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8657
8658   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8659     {
8660       swap_in = bed->s->swap_reloc_in;
8661       swap_out = bed->s->swap_reloc_out;
8662     }
8663   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8664     {
8665       swap_in = bed->s->swap_reloca_in;
8666       swap_out = bed->s->swap_reloca_out;
8667     }
8668   else
8669     abort ();
8670
8671   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8672     abort ();
8673
8674   if (bed->s->arch_size == 32)
8675     {
8676       r_type_mask = 0xff;
8677       r_sym_shift = 8;
8678     }
8679   else
8680     {
8681       r_type_mask = 0xffffffff;
8682       r_sym_shift = 32;
8683     }
8684
8685   erela = reldata->hdr->contents;
8686   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8687     {
8688       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8689       unsigned int j;
8690
8691       if (*rel_hash == NULL)
8692         continue;
8693
8694       if ((*rel_hash)->indx == -2
8695           && info->gc_sections
8696           && ! info->gc_keep_exported)
8697         {
8698           /* PR 21524: Let the user know if a symbol was removed by garbage collection.  */
8699           _bfd_error_handler (_("%B:%A: error: relocation references symbol %s which was removed by garbage collection."),
8700                               abfd, sec,
8701                               (*rel_hash)->root.root.string);
8702           _bfd_error_handler (_("%B:%A: error: try relinking with --gc-keep-exported enabled."),
8703                               abfd, sec);
8704           bfd_set_error (bfd_error_invalid_operation);
8705           return FALSE;
8706         }
8707       BFD_ASSERT ((*rel_hash)->indx >= 0);
8708
8709       (*swap_in) (abfd, erela, irela);
8710       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8711         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8712                            | (irela[j].r_info & r_type_mask));
8713       (*swap_out) (abfd, irela, erela);
8714     }
8715
8716   if (bed->elf_backend_update_relocs)
8717     (*bed->elf_backend_update_relocs) (sec, reldata);
8718
8719   if (sort && count != 0)
8720     {
8721       bfd_vma (*ext_r_off) (const void *);
8722       bfd_vma r_off;
8723       size_t elt_size;
8724       bfd_byte *base, *end, *p, *loc;
8725       bfd_byte *buf = NULL;
8726
8727       if (bed->s->arch_size == 32)
8728         {
8729           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8730             ext_r_off = ext32l_r_offset;
8731           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8732             ext_r_off = ext32b_r_offset;
8733           else
8734             abort ();
8735         }
8736       else
8737         {
8738 #ifdef BFD_HOST_64_BIT
8739           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8740             ext_r_off = ext64l_r_offset;
8741           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8742             ext_r_off = ext64b_r_offset;
8743           else
8744 #endif
8745             abort ();
8746         }
8747
8748       /*  Must use a stable sort here.  A modified insertion sort,
8749           since the relocs are mostly sorted already.  */
8750       elt_size = reldata->hdr->sh_entsize;
8751       base = reldata->hdr->contents;
8752       end = base + count * elt_size;
8753       if (elt_size > sizeof (Elf64_External_Rela))
8754         abort ();
8755
8756       /* Ensure the first element is lowest.  This acts as a sentinel,
8757          speeding the main loop below.  */
8758       r_off = (*ext_r_off) (base);
8759       for (p = loc = base; (p += elt_size) < end; )
8760         {
8761           bfd_vma r_off2 = (*ext_r_off) (p);
8762           if (r_off > r_off2)
8763             {
8764               r_off = r_off2;
8765               loc = p;
8766             }
8767         }
8768       if (loc != base)
8769         {
8770           /* Don't just swap *base and *loc as that changes the order
8771              of the original base[0] and base[1] if they happen to
8772              have the same r_offset.  */
8773           bfd_byte onebuf[sizeof (Elf64_External_Rela)];
8774           memcpy (onebuf, loc, elt_size);
8775           memmove (base + elt_size, base, loc - base);
8776           memcpy (base, onebuf, elt_size);
8777         }
8778
8779       for (p = base + elt_size; (p += elt_size) < end; )
8780         {
8781           /* base to p is sorted, *p is next to insert.  */
8782           r_off = (*ext_r_off) (p);
8783           /* Search the sorted region for location to insert.  */
8784           loc = p - elt_size;
8785           while (r_off < (*ext_r_off) (loc))
8786             loc -= elt_size;
8787           loc += elt_size;
8788           if (loc != p)
8789             {
8790               /* Chances are there is a run of relocs to insert here,
8791                  from one of more input files.  Files are not always
8792                  linked in order due to the way elf_link_input_bfd is
8793                  called.  See pr17666.  */
8794               size_t sortlen = p - loc;
8795               bfd_vma r_off2 = (*ext_r_off) (loc);
8796               size_t runlen = elt_size;
8797               size_t buf_size = 96 * 1024;
8798               while (p + runlen < end
8799                      && (sortlen <= buf_size
8800                          || runlen + elt_size <= buf_size)
8801                      && r_off2 > (*ext_r_off) (p + runlen))
8802                 runlen += elt_size;
8803               if (buf == NULL)
8804                 {
8805                   buf = bfd_malloc (buf_size);
8806                   if (buf == NULL)
8807                     return FALSE;
8808                 }
8809               if (runlen < sortlen)
8810                 {
8811                   memcpy (buf, p, runlen);
8812                   memmove (loc + runlen, loc, sortlen);
8813                   memcpy (loc, buf, runlen);
8814                 }
8815               else
8816                 {
8817                   memcpy (buf, loc, sortlen);
8818                   memmove (loc, p, runlen);
8819                   memcpy (loc + runlen, buf, sortlen);
8820                 }
8821               p += runlen - elt_size;
8822             }
8823         }
8824       /* Hashes are no longer valid.  */
8825       free (reldata->hashes);
8826       reldata->hashes = NULL;
8827       free (buf);
8828     }
8829   return TRUE;
8830 }
8831
8832 struct elf_link_sort_rela
8833 {
8834   union {
8835     bfd_vma offset;
8836     bfd_vma sym_mask;
8837   } u;
8838   enum elf_reloc_type_class type;
8839   /* We use this as an array of size int_rels_per_ext_rel.  */
8840   Elf_Internal_Rela rela[1];
8841 };
8842
8843 static int
8844 elf_link_sort_cmp1 (const void *A, const void *B)
8845 {
8846   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8847   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8848   int relativea, relativeb;
8849
8850   relativea = a->type == reloc_class_relative;
8851   relativeb = b->type == reloc_class_relative;
8852
8853   if (relativea < relativeb)
8854     return 1;
8855   if (relativea > relativeb)
8856     return -1;
8857   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8858     return -1;
8859   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8860     return 1;
8861   if (a->rela->r_offset < b->rela->r_offset)
8862     return -1;
8863   if (a->rela->r_offset > b->rela->r_offset)
8864     return 1;
8865   return 0;
8866 }
8867
8868 static int
8869 elf_link_sort_cmp2 (const void *A, const void *B)
8870 {
8871   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8872   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8873
8874   if (a->type < b->type)
8875     return -1;
8876   if (a->type > b->type)
8877     return 1;
8878   if (a->u.offset < b->u.offset)
8879     return -1;
8880   if (a->u.offset > b->u.offset)
8881     return 1;
8882   if (a->rela->r_offset < b->rela->r_offset)
8883     return -1;
8884   if (a->rela->r_offset > b->rela->r_offset)
8885     return 1;
8886   return 0;
8887 }
8888
8889 static size_t
8890 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8891 {
8892   asection *dynamic_relocs;
8893   asection *rela_dyn;
8894   asection *rel_dyn;
8895   bfd_size_type count, size;
8896   size_t i, ret, sort_elt, ext_size;
8897   bfd_byte *sort, *s_non_relative, *p;
8898   struct elf_link_sort_rela *sq;
8899   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8900   int i2e = bed->s->int_rels_per_ext_rel;
8901   unsigned int opb = bfd_octets_per_byte (abfd);
8902   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8903   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8904   struct bfd_link_order *lo;
8905   bfd_vma r_sym_mask;
8906   bfd_boolean use_rela;
8907
8908   /* Find a dynamic reloc section.  */
8909   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8910   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8911   if (rela_dyn != NULL && rela_dyn->size > 0
8912       && rel_dyn != NULL && rel_dyn->size > 0)
8913     {
8914       bfd_boolean use_rela_initialised = FALSE;
8915
8916       /* This is just here to stop gcc from complaining.
8917          Its initialization checking code is not perfect.  */
8918       use_rela = TRUE;
8919
8920       /* Both sections are present.  Examine the sizes
8921          of the indirect sections to help us choose.  */
8922       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8923         if (lo->type == bfd_indirect_link_order)
8924           {
8925             asection *o = lo->u.indirect.section;
8926
8927             if ((o->size % bed->s->sizeof_rela) == 0)
8928               {
8929                 if ((o->size % bed->s->sizeof_rel) == 0)
8930                   /* Section size is divisible by both rel and rela sizes.
8931                      It is of no help to us.  */
8932                   ;
8933                 else
8934                   {
8935                     /* Section size is only divisible by rela.  */
8936                     if (use_rela_initialised && !use_rela)
8937                       {
8938                         _bfd_error_handler (_("%B: Unable to sort relocs - "
8939                                               "they are in more than one size"),
8940                                             abfd);
8941                         bfd_set_error (bfd_error_invalid_operation);
8942                         return 0;
8943                       }
8944                     else
8945                       {
8946                         use_rela = TRUE;
8947                         use_rela_initialised = TRUE;
8948                       }
8949                   }
8950               }
8951             else if ((o->size % bed->s->sizeof_rel) == 0)
8952               {
8953                 /* Section size is only divisible by rel.  */
8954                 if (use_rela_initialised && use_rela)
8955                   {
8956                     _bfd_error_handler (_("%B: Unable to sort relocs - "
8957                                           "they are in more than one size"),
8958                                         abfd);
8959                     bfd_set_error (bfd_error_invalid_operation);
8960                     return 0;
8961                   }
8962                 else
8963                   {
8964                     use_rela = FALSE;
8965                     use_rela_initialised = TRUE;
8966                   }
8967               }
8968             else
8969               {
8970                 /* The section size is not divisible by either -
8971                    something is wrong.  */
8972                 _bfd_error_handler (_("%B: Unable to sort relocs - "
8973                                       "they are of an unknown size"), abfd);
8974                 bfd_set_error (bfd_error_invalid_operation);
8975                 return 0;
8976               }
8977           }
8978
8979       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8980         if (lo->type == bfd_indirect_link_order)
8981           {
8982             asection *o = lo->u.indirect.section;
8983
8984             if ((o->size % bed->s->sizeof_rela) == 0)
8985               {
8986                 if ((o->size % bed->s->sizeof_rel) == 0)
8987                   /* Section size is divisible by both rel and rela sizes.
8988                      It is of no help to us.  */
8989                   ;
8990                 else
8991                   {
8992                     /* Section size is only divisible by rela.  */
8993                     if (use_rela_initialised && !use_rela)
8994                       {
8995                         _bfd_error_handler (_("%B: Unable to sort relocs - "
8996                                               "they are in more than one size"),
8997                                             abfd);
8998                         bfd_set_error (bfd_error_invalid_operation);
8999                         return 0;
9000                       }
9001                     else
9002                       {
9003                         use_rela = TRUE;
9004                         use_rela_initialised = TRUE;
9005                       }
9006                   }
9007               }
9008             else if ((o->size % bed->s->sizeof_rel) == 0)
9009               {
9010                 /* Section size is only divisible by rel.  */
9011                 if (use_rela_initialised && use_rela)
9012                   {
9013                     _bfd_error_handler (_("%B: Unable to sort relocs - "
9014                                           "they are in more than one size"),
9015                                         abfd);
9016                     bfd_set_error (bfd_error_invalid_operation);
9017                     return 0;
9018                   }
9019                 else
9020                   {
9021                     use_rela = FALSE;
9022                     use_rela_initialised = TRUE;
9023                   }
9024               }
9025             else
9026               {
9027                 /* The section size is not divisible by either -
9028                    something is wrong.  */
9029                 _bfd_error_handler (_("%B: Unable to sort relocs - "
9030                                       "they are of an unknown size"), abfd);
9031                 bfd_set_error (bfd_error_invalid_operation);
9032                 return 0;
9033               }
9034           }
9035
9036       if (! use_rela_initialised)
9037         /* Make a guess.  */
9038         use_rela = TRUE;
9039     }
9040   else if (rela_dyn != NULL && rela_dyn->size > 0)
9041     use_rela = TRUE;
9042   else if (rel_dyn != NULL && rel_dyn->size > 0)
9043     use_rela = FALSE;
9044   else
9045     return 0;
9046
9047   if (use_rela)
9048     {
9049       dynamic_relocs = rela_dyn;
9050       ext_size = bed->s->sizeof_rela;
9051       swap_in = bed->s->swap_reloca_in;
9052       swap_out = bed->s->swap_reloca_out;
9053     }
9054   else
9055     {
9056       dynamic_relocs = rel_dyn;
9057       ext_size = bed->s->sizeof_rel;
9058       swap_in = bed->s->swap_reloc_in;
9059       swap_out = bed->s->swap_reloc_out;
9060     }
9061
9062   size = 0;
9063   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9064     if (lo->type == bfd_indirect_link_order)
9065       size += lo->u.indirect.section->size;
9066
9067   if (size != dynamic_relocs->size)
9068     return 0;
9069
9070   sort_elt = (sizeof (struct elf_link_sort_rela)
9071               + (i2e - 1) * sizeof (Elf_Internal_Rela));
9072
9073   count = dynamic_relocs->size / ext_size;
9074   if (count == 0)
9075     return 0;
9076   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
9077
9078   if (sort == NULL)
9079     {
9080       (*info->callbacks->warning)
9081         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
9082       return 0;
9083     }
9084
9085   if (bed->s->arch_size == 32)
9086     r_sym_mask = ~(bfd_vma) 0xff;
9087   else
9088     r_sym_mask = ~(bfd_vma) 0xffffffff;
9089
9090   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9091     if (lo->type == bfd_indirect_link_order)
9092       {
9093         bfd_byte *erel, *erelend;
9094         asection *o = lo->u.indirect.section;
9095
9096         if (o->contents == NULL && o->size != 0)
9097           {
9098             /* This is a reloc section that is being handled as a normal
9099                section.  See bfd_section_from_shdr.  We can't combine
9100                relocs in this case.  */
9101             free (sort);
9102             return 0;
9103           }
9104         erel = o->contents;
9105         erelend = o->contents + o->size;
9106         p = sort + o->output_offset * opb / ext_size * sort_elt;
9107
9108         while (erel < erelend)
9109           {
9110             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9111
9112             (*swap_in) (abfd, erel, s->rela);
9113             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
9114             s->u.sym_mask = r_sym_mask;
9115             p += sort_elt;
9116             erel += ext_size;
9117           }
9118       }
9119
9120   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
9121
9122   for (i = 0, p = sort; i < count; i++, p += sort_elt)
9123     {
9124       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9125       if (s->type != reloc_class_relative)
9126         break;
9127     }
9128   ret = i;
9129   s_non_relative = p;
9130
9131   sq = (struct elf_link_sort_rela *) s_non_relative;
9132   for (; i < count; i++, p += sort_elt)
9133     {
9134       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
9135       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
9136         sq = sp;
9137       sp->u.offset = sq->rela->r_offset;
9138     }
9139
9140   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
9141
9142   struct elf_link_hash_table *htab = elf_hash_table (info);
9143   if (htab->srelplt && htab->srelplt->output_section == dynamic_relocs)
9144     {
9145       /* We have plt relocs in .rela.dyn.  */
9146       sq = (struct elf_link_sort_rela *) sort;
9147       for (i = 0; i < count; i++)
9148         if (sq[count - i - 1].type != reloc_class_plt)
9149           break;
9150       if (i != 0 && htab->srelplt->size == i * ext_size)
9151         {
9152           struct bfd_link_order **plo;
9153           /* Put srelplt link_order last.  This is so the output_offset
9154              set in the next loop is correct for DT_JMPREL.  */
9155           for (plo = &dynamic_relocs->map_head.link_order; *plo != NULL; )
9156             if ((*plo)->type == bfd_indirect_link_order
9157                 && (*plo)->u.indirect.section == htab->srelplt)
9158               {
9159                 lo = *plo;
9160                 *plo = lo->next;
9161               }
9162             else
9163               plo = &(*plo)->next;
9164           *plo = lo;
9165           lo->next = NULL;
9166           dynamic_relocs->map_tail.link_order = lo;
9167         }
9168     }
9169
9170   p = sort;
9171   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9172     if (lo->type == bfd_indirect_link_order)
9173       {
9174         bfd_byte *erel, *erelend;
9175         asection *o = lo->u.indirect.section;
9176
9177         erel = o->contents;
9178         erelend = o->contents + o->size;
9179         o->output_offset = (p - sort) / sort_elt * ext_size / opb;
9180         while (erel < erelend)
9181           {
9182             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9183             (*swap_out) (abfd, s->rela, erel);
9184             p += sort_elt;
9185             erel += ext_size;
9186           }
9187       }
9188
9189   free (sort);
9190   *psec = dynamic_relocs;
9191   return ret;
9192 }
9193
9194 /* Add a symbol to the output symbol string table.  */
9195
9196 static int
9197 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
9198                            const char *name,
9199                            Elf_Internal_Sym *elfsym,
9200                            asection *input_sec,
9201                            struct elf_link_hash_entry *h)
9202 {
9203   int (*output_symbol_hook)
9204     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
9205      struct elf_link_hash_entry *);
9206   struct elf_link_hash_table *hash_table;
9207   const struct elf_backend_data *bed;
9208   bfd_size_type strtabsize;
9209
9210   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9211
9212   bed = get_elf_backend_data (flinfo->output_bfd);
9213   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
9214   if (output_symbol_hook != NULL)
9215     {
9216       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
9217       if (ret != 1)
9218         return ret;
9219     }
9220
9221   if (name == NULL
9222       || *name == '\0'
9223       || (input_sec->flags & SEC_EXCLUDE))
9224     elfsym->st_name = (unsigned long) -1;
9225   else
9226     {
9227       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
9228          to get the final offset for st_name.  */
9229       elfsym->st_name
9230         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
9231                                                name, FALSE);
9232       if (elfsym->st_name == (unsigned long) -1)
9233         return 0;
9234     }
9235
9236   hash_table = elf_hash_table (flinfo->info);
9237   strtabsize = hash_table->strtabsize;
9238   if (strtabsize <= hash_table->strtabcount)
9239     {
9240       strtabsize += strtabsize;
9241       hash_table->strtabsize = strtabsize;
9242       strtabsize *= sizeof (*hash_table->strtab);
9243       hash_table->strtab
9244         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
9245                                                  strtabsize);
9246       if (hash_table->strtab == NULL)
9247         return 0;
9248     }
9249   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
9250   hash_table->strtab[hash_table->strtabcount].dest_index
9251     = hash_table->strtabcount;
9252   hash_table->strtab[hash_table->strtabcount].destshndx_index
9253     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
9254
9255   bfd_get_symcount (flinfo->output_bfd) += 1;
9256   hash_table->strtabcount += 1;
9257
9258   return 1;
9259 }
9260
9261 /* Swap symbols out to the symbol table and flush the output symbols to
9262    the file.  */
9263
9264 static bfd_boolean
9265 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
9266 {
9267   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
9268   bfd_size_type amt;
9269   size_t i;
9270   const struct elf_backend_data *bed;
9271   bfd_byte *symbuf;
9272   Elf_Internal_Shdr *hdr;
9273   file_ptr pos;
9274   bfd_boolean ret;
9275
9276   if (!hash_table->strtabcount)
9277     return TRUE;
9278
9279   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9280
9281   bed = get_elf_backend_data (flinfo->output_bfd);
9282
9283   amt = bed->s->sizeof_sym * hash_table->strtabcount;
9284   symbuf = (bfd_byte *) bfd_malloc (amt);
9285   if (symbuf == NULL)
9286     return FALSE;
9287
9288   if (flinfo->symshndxbuf)
9289     {
9290       amt = sizeof (Elf_External_Sym_Shndx);
9291       amt *= bfd_get_symcount (flinfo->output_bfd);
9292       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
9293       if (flinfo->symshndxbuf == NULL)
9294         {
9295           free (symbuf);
9296           return FALSE;
9297         }
9298     }
9299
9300   for (i = 0; i < hash_table->strtabcount; i++)
9301     {
9302       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
9303       if (elfsym->sym.st_name == (unsigned long) -1)
9304         elfsym->sym.st_name = 0;
9305       else
9306         elfsym->sym.st_name
9307           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
9308                                                     elfsym->sym.st_name);
9309       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
9310                                ((bfd_byte *) symbuf
9311                                 + (elfsym->dest_index
9312                                    * bed->s->sizeof_sym)),
9313                                (flinfo->symshndxbuf
9314                                 + elfsym->destshndx_index));
9315     }
9316
9317   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
9318   pos = hdr->sh_offset + hdr->sh_size;
9319   amt = hash_table->strtabcount * bed->s->sizeof_sym;
9320   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
9321       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
9322     {
9323       hdr->sh_size += amt;
9324       ret = TRUE;
9325     }
9326   else
9327     ret = FALSE;
9328
9329   free (symbuf);
9330
9331   free (hash_table->strtab);
9332   hash_table->strtab = NULL;
9333
9334   return ret;
9335 }
9336
9337 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
9338
9339 static bfd_boolean
9340 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
9341 {
9342   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
9343       && sym->st_shndx < SHN_LORESERVE)
9344     {
9345       /* The gABI doesn't support dynamic symbols in output sections
9346          beyond 64k.  */
9347       _bfd_error_handler
9348         /* xgettext:c-format */
9349         (_("%B: Too many sections: %d (>= %d)"),
9350          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
9351       bfd_set_error (bfd_error_nonrepresentable_section);
9352       return FALSE;
9353     }
9354   return TRUE;
9355 }
9356
9357 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
9358    allowing an unsatisfied unversioned symbol in the DSO to match a
9359    versioned symbol that would normally require an explicit version.
9360    We also handle the case that a DSO references a hidden symbol
9361    which may be satisfied by a versioned symbol in another DSO.  */
9362
9363 static bfd_boolean
9364 elf_link_check_versioned_symbol (struct bfd_link_info *info,
9365                                  const struct elf_backend_data *bed,
9366                                  struct elf_link_hash_entry *h)
9367 {
9368   bfd *abfd;
9369   struct elf_link_loaded_list *loaded;
9370
9371   if (!is_elf_hash_table (info->hash))
9372     return FALSE;
9373
9374   /* Check indirect symbol.  */
9375   while (h->root.type == bfd_link_hash_indirect)
9376     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9377
9378   switch (h->root.type)
9379     {
9380     default:
9381       abfd = NULL;
9382       break;
9383
9384     case bfd_link_hash_undefined:
9385     case bfd_link_hash_undefweak:
9386       abfd = h->root.u.undef.abfd;
9387       if (abfd == NULL
9388           || (abfd->flags & DYNAMIC) == 0
9389           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
9390         return FALSE;
9391       break;
9392
9393     case bfd_link_hash_defined:
9394     case bfd_link_hash_defweak:
9395       abfd = h->root.u.def.section->owner;
9396       break;
9397
9398     case bfd_link_hash_common:
9399       abfd = h->root.u.c.p->section->owner;
9400       break;
9401     }
9402   BFD_ASSERT (abfd != NULL);
9403
9404   for (loaded = elf_hash_table (info)->loaded;
9405        loaded != NULL;
9406        loaded = loaded->next)
9407     {
9408       bfd *input;
9409       Elf_Internal_Shdr *hdr;
9410       size_t symcount;
9411       size_t extsymcount;
9412       size_t extsymoff;
9413       Elf_Internal_Shdr *versymhdr;
9414       Elf_Internal_Sym *isym;
9415       Elf_Internal_Sym *isymend;
9416       Elf_Internal_Sym *isymbuf;
9417       Elf_External_Versym *ever;
9418       Elf_External_Versym *extversym;
9419
9420       input = loaded->abfd;
9421
9422       /* We check each DSO for a possible hidden versioned definition.  */
9423       if (input == abfd
9424           || (input->flags & DYNAMIC) == 0
9425           || elf_dynversym (input) == 0)
9426         continue;
9427
9428       hdr = &elf_tdata (input)->dynsymtab_hdr;
9429
9430       symcount = hdr->sh_size / bed->s->sizeof_sym;
9431       if (elf_bad_symtab (input))
9432         {
9433           extsymcount = symcount;
9434           extsymoff = 0;
9435         }
9436       else
9437         {
9438           extsymcount = symcount - hdr->sh_info;
9439           extsymoff = hdr->sh_info;
9440         }
9441
9442       if (extsymcount == 0)
9443         continue;
9444
9445       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
9446                                       NULL, NULL, NULL);
9447       if (isymbuf == NULL)
9448         return FALSE;
9449
9450       /* Read in any version definitions.  */
9451       versymhdr = &elf_tdata (input)->dynversym_hdr;
9452       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
9453       if (extversym == NULL)
9454         goto error_ret;
9455
9456       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
9457           || (bfd_bread (extversym, versymhdr->sh_size, input)
9458               != versymhdr->sh_size))
9459         {
9460           free (extversym);
9461         error_ret:
9462           free (isymbuf);
9463           return FALSE;
9464         }
9465
9466       ever = extversym + extsymoff;
9467       isymend = isymbuf + extsymcount;
9468       for (isym = isymbuf; isym < isymend; isym++, ever++)
9469         {
9470           const char *name;
9471           Elf_Internal_Versym iver;
9472           unsigned short version_index;
9473
9474           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
9475               || isym->st_shndx == SHN_UNDEF)
9476             continue;
9477
9478           name = bfd_elf_string_from_elf_section (input,
9479                                                   hdr->sh_link,
9480                                                   isym->st_name);
9481           if (strcmp (name, h->root.root.string) != 0)
9482             continue;
9483
9484           _bfd_elf_swap_versym_in (input, ever, &iver);
9485
9486           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
9487               && !(h->def_regular
9488                    && h->forced_local))
9489             {
9490               /* If we have a non-hidden versioned sym, then it should
9491                  have provided a definition for the undefined sym unless
9492                  it is defined in a non-shared object and forced local.
9493                */
9494               abort ();
9495             }
9496
9497           version_index = iver.vs_vers & VERSYM_VERSION;
9498           if (version_index == 1 || version_index == 2)
9499             {
9500               /* This is the base or first version.  We can use it.  */
9501               free (extversym);
9502               free (isymbuf);
9503               return TRUE;
9504             }
9505         }
9506
9507       free (extversym);
9508       free (isymbuf);
9509     }
9510
9511   return FALSE;
9512 }
9513
9514 /* Convert ELF common symbol TYPE.  */
9515
9516 static int
9517 elf_link_convert_common_type (struct bfd_link_info *info, int type)
9518 {
9519   /* Commom symbol can only appear in relocatable link.  */
9520   if (!bfd_link_relocatable (info))
9521     abort ();
9522   switch (info->elf_stt_common)
9523     {
9524     case unchanged:
9525       break;
9526     case elf_stt_common:
9527       type = STT_COMMON;
9528       break;
9529     case no_elf_stt_common:
9530       type = STT_OBJECT;
9531       break;
9532     }
9533   return type;
9534 }
9535
9536 /* Add an external symbol to the symbol table.  This is called from
9537    the hash table traversal routine.  When generating a shared object,
9538    we go through the symbol table twice.  The first time we output
9539    anything that might have been forced to local scope in a version
9540    script.  The second time we output the symbols that are still
9541    global symbols.  */
9542
9543 static bfd_boolean
9544 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
9545 {
9546   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
9547   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
9548   struct elf_final_link_info *flinfo = eoinfo->flinfo;
9549   bfd_boolean strip;
9550   Elf_Internal_Sym sym;
9551   asection *input_sec;
9552   const struct elf_backend_data *bed;
9553   long indx;
9554   int ret;
9555   unsigned int type;
9556
9557   if (h->root.type == bfd_link_hash_warning)
9558     {
9559       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9560       if (h->root.type == bfd_link_hash_new)
9561         return TRUE;
9562     }
9563
9564   /* Decide whether to output this symbol in this pass.  */
9565   if (eoinfo->localsyms)
9566     {
9567       if (!h->forced_local)
9568         return TRUE;
9569     }
9570   else
9571     {
9572       if (h->forced_local)
9573         return TRUE;
9574     }
9575
9576   bed = get_elf_backend_data (flinfo->output_bfd);
9577
9578   if (h->root.type == bfd_link_hash_undefined)
9579     {
9580       /* If we have an undefined symbol reference here then it must have
9581          come from a shared library that is being linked in.  (Undefined
9582          references in regular files have already been handled unless
9583          they are in unreferenced sections which are removed by garbage
9584          collection).  */
9585       bfd_boolean ignore_undef = FALSE;
9586
9587       /* Some symbols may be special in that the fact that they're
9588          undefined can be safely ignored - let backend determine that.  */
9589       if (bed->elf_backend_ignore_undef_symbol)
9590         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9591
9592       /* If we are reporting errors for this situation then do so now.  */
9593       if (!ignore_undef
9594           && h->ref_dynamic
9595           && (!h->ref_regular || flinfo->info->gc_sections)
9596           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9597           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9598         (*flinfo->info->callbacks->undefined_symbol)
9599           (flinfo->info, h->root.root.string,
9600            h->ref_regular ? NULL : h->root.u.undef.abfd,
9601            NULL, 0,
9602            flinfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR);
9603
9604       /* Strip a global symbol defined in a discarded section.  */
9605       if (h->indx == -3)
9606         return TRUE;
9607     }
9608
9609   /* We should also warn if a forced local symbol is referenced from
9610      shared libraries.  */
9611   if (bfd_link_executable (flinfo->info)
9612       && h->forced_local
9613       && h->ref_dynamic
9614       && h->def_regular
9615       && !h->dynamic_def
9616       && h->ref_dynamic_nonweak
9617       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9618     {
9619       bfd *def_bfd;
9620       const char *msg;
9621       struct elf_link_hash_entry *hi = h;
9622
9623       /* Check indirect symbol.  */
9624       while (hi->root.type == bfd_link_hash_indirect)
9625         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9626
9627       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9628         /* xgettext:c-format */
9629         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
9630       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9631         /* xgettext:c-format */
9632         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
9633       else
9634         /* xgettext:c-format */
9635         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
9636       def_bfd = flinfo->output_bfd;
9637       if (hi->root.u.def.section != bfd_abs_section_ptr)
9638         def_bfd = hi->root.u.def.section->owner;
9639       _bfd_error_handler (msg, flinfo->output_bfd,
9640                           h->root.root.string, def_bfd);
9641       bfd_set_error (bfd_error_bad_value);
9642       eoinfo->failed = TRUE;
9643       return FALSE;
9644     }
9645
9646   /* We don't want to output symbols that have never been mentioned by
9647      a regular file, or that we have been told to strip.  However, if
9648      h->indx is set to -2, the symbol is used by a reloc and we must
9649      output it.  */
9650   strip = FALSE;
9651   if (h->indx == -2)
9652     ;
9653   else if ((h->def_dynamic
9654             || h->ref_dynamic
9655             || h->root.type == bfd_link_hash_new)
9656            && !h->def_regular
9657            && !h->ref_regular)
9658     strip = TRUE;
9659   else if (flinfo->info->strip == strip_all)
9660     strip = TRUE;
9661   else if (flinfo->info->strip == strip_some
9662            && bfd_hash_lookup (flinfo->info->keep_hash,
9663                                h->root.root.string, FALSE, FALSE) == NULL)
9664     strip = TRUE;
9665   else if ((h->root.type == bfd_link_hash_defined
9666             || h->root.type == bfd_link_hash_defweak)
9667            && ((flinfo->info->strip_discarded
9668                 && discarded_section (h->root.u.def.section))
9669                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9670                    && h->root.u.def.section->owner != NULL
9671                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9672     strip = TRUE;
9673   else if ((h->root.type == bfd_link_hash_undefined
9674             || h->root.type == bfd_link_hash_undefweak)
9675            && h->root.u.undef.abfd != NULL
9676            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9677     strip = TRUE;
9678
9679   type = h->type;
9680
9681   /* If we're stripping it, and it's not a dynamic symbol, there's
9682      nothing else to do.   However, if it is a forced local symbol or
9683      an ifunc symbol we need to give the backend finish_dynamic_symbol
9684      function a chance to make it dynamic.  */
9685   if (strip
9686       && h->dynindx == -1
9687       && type != STT_GNU_IFUNC
9688       && !h->forced_local)
9689     return TRUE;
9690
9691   sym.st_value = 0;
9692   sym.st_size = h->size;
9693   sym.st_other = h->other;
9694   switch (h->root.type)
9695     {
9696     default:
9697     case bfd_link_hash_new:
9698     case bfd_link_hash_warning:
9699       abort ();
9700       return FALSE;
9701
9702     case bfd_link_hash_undefined:
9703     case bfd_link_hash_undefweak:
9704       input_sec = bfd_und_section_ptr;
9705       sym.st_shndx = SHN_UNDEF;
9706       break;
9707
9708     case bfd_link_hash_defined:
9709     case bfd_link_hash_defweak:
9710       {
9711         input_sec = h->root.u.def.section;
9712         if (input_sec->output_section != NULL)
9713           {
9714             sym.st_shndx =
9715               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9716                                                  input_sec->output_section);
9717             if (sym.st_shndx == SHN_BAD)
9718               {
9719                 _bfd_error_handler
9720                   /* xgettext:c-format */
9721                   (_("%B: could not find output section %A for input section %A"),
9722                    flinfo->output_bfd, input_sec->output_section, input_sec);
9723                 bfd_set_error (bfd_error_nonrepresentable_section);
9724                 eoinfo->failed = TRUE;
9725                 return FALSE;
9726               }
9727
9728             /* ELF symbols in relocatable files are section relative,
9729                but in nonrelocatable files they are virtual
9730                addresses.  */
9731             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9732             if (!bfd_link_relocatable (flinfo->info))
9733               {
9734                 sym.st_value += input_sec->output_section->vma;
9735                 if (h->type == STT_TLS)
9736                   {
9737                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9738                     if (tls_sec != NULL)
9739                       sym.st_value -= tls_sec->vma;
9740                   }
9741               }
9742           }
9743         else
9744           {
9745             BFD_ASSERT (input_sec->owner == NULL
9746                         || (input_sec->owner->flags & DYNAMIC) != 0);
9747             sym.st_shndx = SHN_UNDEF;
9748             input_sec = bfd_und_section_ptr;
9749           }
9750       }
9751       break;
9752
9753     case bfd_link_hash_common:
9754       input_sec = h->root.u.c.p->section;
9755       sym.st_shndx = bed->common_section_index (input_sec);
9756       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9757       break;
9758
9759     case bfd_link_hash_indirect:
9760       /* These symbols are created by symbol versioning.  They point
9761          to the decorated version of the name.  For example, if the
9762          symbol foo@@GNU_1.2 is the default, which should be used when
9763          foo is used with no version, then we add an indirect symbol
9764          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9765          since the indirected symbol is already in the hash table.  */
9766       return TRUE;
9767     }
9768
9769   if (type == STT_COMMON || type == STT_OBJECT)
9770     switch (h->root.type)
9771       {
9772       case bfd_link_hash_common:
9773         type = elf_link_convert_common_type (flinfo->info, type);
9774         break;
9775       case bfd_link_hash_defined:
9776       case bfd_link_hash_defweak:
9777         if (bed->common_definition (&sym))
9778           type = elf_link_convert_common_type (flinfo->info, type);
9779         else
9780           type = STT_OBJECT;
9781         break;
9782       case bfd_link_hash_undefined:
9783       case bfd_link_hash_undefweak:
9784         break;
9785       default:
9786         abort ();
9787       }
9788
9789   if (h->forced_local)
9790     {
9791       sym.st_info = ELF_ST_INFO (STB_LOCAL, type);
9792       /* Turn off visibility on local symbol.  */
9793       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9794     }
9795   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9796   else if (h->unique_global && h->def_regular)
9797     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, type);
9798   else if (h->root.type == bfd_link_hash_undefweak
9799            || h->root.type == bfd_link_hash_defweak)
9800     sym.st_info = ELF_ST_INFO (STB_WEAK, type);
9801   else
9802     sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9803   sym.st_target_internal = h->target_internal;
9804
9805   /* Give the processor backend a chance to tweak the symbol value,
9806      and also to finish up anything that needs to be done for this
9807      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9808      forced local syms when non-shared is due to a historical quirk.
9809      STT_GNU_IFUNC symbol must go through PLT.  */
9810   if ((h->type == STT_GNU_IFUNC
9811        && h->def_regular
9812        && !bfd_link_relocatable (flinfo->info))
9813       || ((h->dynindx != -1
9814            || h->forced_local)
9815           && ((bfd_link_pic (flinfo->info)
9816                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9817                    || h->root.type != bfd_link_hash_undefweak))
9818               || !h->forced_local)
9819           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9820     {
9821       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9822              (flinfo->output_bfd, flinfo->info, h, &sym)))
9823         {
9824           eoinfo->failed = TRUE;
9825           return FALSE;
9826         }
9827     }
9828
9829   /* If we are marking the symbol as undefined, and there are no
9830      non-weak references to this symbol from a regular object, then
9831      mark the symbol as weak undefined; if there are non-weak
9832      references, mark the symbol as strong.  We can't do this earlier,
9833      because it might not be marked as undefined until the
9834      finish_dynamic_symbol routine gets through with it.  */
9835   if (sym.st_shndx == SHN_UNDEF
9836       && h->ref_regular
9837       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9838           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9839     {
9840       int bindtype;
9841       type = ELF_ST_TYPE (sym.st_info);
9842
9843       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9844       if (type == STT_GNU_IFUNC)
9845         type = STT_FUNC;
9846
9847       if (h->ref_regular_nonweak)
9848         bindtype = STB_GLOBAL;
9849       else
9850         bindtype = STB_WEAK;
9851       sym.st_info = ELF_ST_INFO (bindtype, type);
9852     }
9853
9854   /* If this is a symbol defined in a dynamic library, don't use the
9855      symbol size from the dynamic library.  Relinking an executable
9856      against a new library may introduce gratuitous changes in the
9857      executable's symbols if we keep the size.  */
9858   if (sym.st_shndx == SHN_UNDEF
9859       && !h->def_regular
9860       && h->def_dynamic)
9861     sym.st_size = 0;
9862
9863   /* If a non-weak symbol with non-default visibility is not defined
9864      locally, it is a fatal error.  */
9865   if (!bfd_link_relocatable (flinfo->info)
9866       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9867       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9868       && h->root.type == bfd_link_hash_undefined
9869       && !h->def_regular)
9870     {
9871       const char *msg;
9872
9873       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9874         /* xgettext:c-format */
9875         msg = _("%B: protected symbol `%s' isn't defined");
9876       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9877         /* xgettext:c-format */
9878         msg = _("%B: internal symbol `%s' isn't defined");
9879       else
9880         /* xgettext:c-format */
9881         msg = _("%B: hidden symbol `%s' isn't defined");
9882       _bfd_error_handler (msg, flinfo->output_bfd, h->root.root.string);
9883       bfd_set_error (bfd_error_bad_value);
9884       eoinfo->failed = TRUE;
9885       return FALSE;
9886     }
9887
9888   /* If this symbol should be put in the .dynsym section, then put it
9889      there now.  We already know the symbol index.  We also fill in
9890      the entry in the .hash section.  */
9891   if (elf_hash_table (flinfo->info)->dynsym != NULL
9892       && h->dynindx != -1
9893       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9894     {
9895       bfd_byte *esym;
9896
9897       /* Since there is no version information in the dynamic string,
9898          if there is no version info in symbol version section, we will
9899          have a run-time problem if not linking executable, referenced
9900          by shared library, or not bound locally.  */
9901       if (h->verinfo.verdef == NULL
9902           && (!bfd_link_executable (flinfo->info)
9903               || h->ref_dynamic
9904               || !h->def_regular))
9905         {
9906           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9907
9908           if (p && p [1] != '\0')
9909             {
9910               _bfd_error_handler
9911                 /* xgettext:c-format */
9912                 (_("%B: No symbol version section for versioned symbol `%s'"),
9913                  flinfo->output_bfd, h->root.root.string);
9914               eoinfo->failed = TRUE;
9915               return FALSE;
9916             }
9917         }
9918
9919       sym.st_name = h->dynstr_index;
9920       esym = (elf_hash_table (flinfo->info)->dynsym->contents
9921               + h->dynindx * bed->s->sizeof_sym);
9922       if (!check_dynsym (flinfo->output_bfd, &sym))
9923         {
9924           eoinfo->failed = TRUE;
9925           return FALSE;
9926         }
9927       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9928
9929       if (flinfo->hash_sec != NULL)
9930         {
9931           size_t hash_entry_size;
9932           bfd_byte *bucketpos;
9933           bfd_vma chain;
9934           size_t bucketcount;
9935           size_t bucket;
9936
9937           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9938           bucket = h->u.elf_hash_value % bucketcount;
9939
9940           hash_entry_size
9941             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9942           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9943                        + (bucket + 2) * hash_entry_size);
9944           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9945           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9946                    bucketpos);
9947           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9948                    ((bfd_byte *) flinfo->hash_sec->contents
9949                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9950         }
9951
9952       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9953         {
9954           Elf_Internal_Versym iversym;
9955           Elf_External_Versym *eversym;
9956
9957           if (!h->def_regular)
9958             {
9959               if (h->verinfo.verdef == NULL
9960                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9961                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9962                 iversym.vs_vers = 0;
9963               else
9964                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9965             }
9966           else
9967             {
9968               if (h->verinfo.vertree == NULL)
9969                 iversym.vs_vers = 1;
9970               else
9971                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9972               if (flinfo->info->create_default_symver)
9973                 iversym.vs_vers++;
9974             }
9975
9976           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
9977              defined locally.  */
9978           if (h->versioned == versioned_hidden && h->def_regular)
9979             iversym.vs_vers |= VERSYM_HIDDEN;
9980
9981           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
9982           eversym += h->dynindx;
9983           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
9984         }
9985     }
9986
9987   /* If the symbol is undefined, and we didn't output it to .dynsym,
9988      strip it from .symtab too.  Obviously we can't do this for
9989      relocatable output or when needed for --emit-relocs.  */
9990   else if (input_sec == bfd_und_section_ptr
9991            && h->indx != -2
9992            /* PR 22319 Do not strip global undefined symbols marked as being needed.  */
9993            && (h->mark != 1 || ELF_ST_BIND (sym.st_info) != STB_GLOBAL)
9994            && !bfd_link_relocatable (flinfo->info))
9995     return TRUE;
9996
9997   /* Also strip others that we couldn't earlier due to dynamic symbol
9998      processing.  */
9999   if (strip)
10000     return TRUE;
10001   if ((input_sec->flags & SEC_EXCLUDE) != 0)
10002     return TRUE;
10003
10004   /* Output a FILE symbol so that following locals are not associated
10005      with the wrong input file.  We need one for forced local symbols
10006      if we've seen more than one FILE symbol or when we have exactly
10007      one FILE symbol but global symbols are present in a file other
10008      than the one with the FILE symbol.  We also need one if linker
10009      defined symbols are present.  In practice these conditions are
10010      always met, so just emit the FILE symbol unconditionally.  */
10011   if (eoinfo->localsyms
10012       && !eoinfo->file_sym_done
10013       && eoinfo->flinfo->filesym_count != 0)
10014     {
10015       Elf_Internal_Sym fsym;
10016
10017       memset (&fsym, 0, sizeof (fsym));
10018       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10019       fsym.st_shndx = SHN_ABS;
10020       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
10021                                       bfd_und_section_ptr, NULL))
10022         return FALSE;
10023
10024       eoinfo->file_sym_done = TRUE;
10025     }
10026
10027   indx = bfd_get_symcount (flinfo->output_bfd);
10028   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
10029                                    input_sec, h);
10030   if (ret == 0)
10031     {
10032       eoinfo->failed = TRUE;
10033       return FALSE;
10034     }
10035   else if (ret == 1)
10036     h->indx = indx;
10037   else if (h->indx == -2)
10038     abort();
10039
10040   return TRUE;
10041 }
10042
10043 /* Return TRUE if special handling is done for relocs in SEC against
10044    symbols defined in discarded sections.  */
10045
10046 static bfd_boolean
10047 elf_section_ignore_discarded_relocs (asection *sec)
10048 {
10049   const struct elf_backend_data *bed;
10050
10051   switch (sec->sec_info_type)
10052     {
10053     case SEC_INFO_TYPE_STABS:
10054     case SEC_INFO_TYPE_EH_FRAME:
10055     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10056       return TRUE;
10057     default:
10058       break;
10059     }
10060
10061   bed = get_elf_backend_data (sec->owner);
10062   if (bed->elf_backend_ignore_discarded_relocs != NULL
10063       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
10064     return TRUE;
10065
10066   return FALSE;
10067 }
10068
10069 /* Return a mask saying how ld should treat relocations in SEC against
10070    symbols defined in discarded sections.  If this function returns
10071    COMPLAIN set, ld will issue a warning message.  If this function
10072    returns PRETEND set, and the discarded section was link-once and the
10073    same size as the kept link-once section, ld will pretend that the
10074    symbol was actually defined in the kept section.  Otherwise ld will
10075    zero the reloc (at least that is the intent, but some cooperation by
10076    the target dependent code is needed, particularly for REL targets).  */
10077
10078 unsigned int
10079 _bfd_elf_default_action_discarded (asection *sec)
10080 {
10081   if (sec->flags & SEC_DEBUGGING)
10082     return PRETEND;
10083
10084   if (strcmp (".eh_frame", sec->name) == 0)
10085     return 0;
10086
10087   if (strcmp (".gcc_except_table", sec->name) == 0)
10088     return 0;
10089
10090   return COMPLAIN | PRETEND;
10091 }
10092
10093 /* Find a match between a section and a member of a section group.  */
10094
10095 static asection *
10096 match_group_member (asection *sec, asection *group,
10097                     struct bfd_link_info *info)
10098 {
10099   asection *first = elf_next_in_group (group);
10100   asection *s = first;
10101
10102   while (s != NULL)
10103     {
10104       if (bfd_elf_match_symbols_in_sections (s, sec, info))
10105         return s;
10106
10107       s = elf_next_in_group (s);
10108       if (s == first)
10109         break;
10110     }
10111
10112   return NULL;
10113 }
10114
10115 /* Check if the kept section of a discarded section SEC can be used
10116    to replace it.  Return the replacement if it is OK.  Otherwise return
10117    NULL.  */
10118
10119 asection *
10120 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
10121 {
10122   asection *kept;
10123
10124   kept = sec->kept_section;
10125   if (kept != NULL)
10126     {
10127       if ((kept->flags & SEC_GROUP) != 0)
10128         kept = match_group_member (sec, kept, info);
10129       if (kept != NULL
10130           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
10131               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
10132         kept = NULL;
10133       sec->kept_section = kept;
10134     }
10135   return kept;
10136 }
10137
10138 /* Link an input file into the linker output file.  This function
10139    handles all the sections and relocations of the input file at once.
10140    This is so that we only have to read the local symbols once, and
10141    don't have to keep them in memory.  */
10142
10143 static bfd_boolean
10144 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
10145 {
10146   int (*relocate_section)
10147     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
10148      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
10149   bfd *output_bfd;
10150   Elf_Internal_Shdr *symtab_hdr;
10151   size_t locsymcount;
10152   size_t extsymoff;
10153   Elf_Internal_Sym *isymbuf;
10154   Elf_Internal_Sym *isym;
10155   Elf_Internal_Sym *isymend;
10156   long *pindex;
10157   asection **ppsection;
10158   asection *o;
10159   const struct elf_backend_data *bed;
10160   struct elf_link_hash_entry **sym_hashes;
10161   bfd_size_type address_size;
10162   bfd_vma r_type_mask;
10163   int r_sym_shift;
10164   bfd_boolean have_file_sym = FALSE;
10165
10166   output_bfd = flinfo->output_bfd;
10167   bed = get_elf_backend_data (output_bfd);
10168   relocate_section = bed->elf_backend_relocate_section;
10169
10170   /* If this is a dynamic object, we don't want to do anything here:
10171      we don't want the local symbols, and we don't want the section
10172      contents.  */
10173   if ((input_bfd->flags & DYNAMIC) != 0)
10174     return TRUE;
10175
10176   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
10177   if (elf_bad_symtab (input_bfd))
10178     {
10179       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
10180       extsymoff = 0;
10181     }
10182   else
10183     {
10184       locsymcount = symtab_hdr->sh_info;
10185       extsymoff = symtab_hdr->sh_info;
10186     }
10187
10188   /* Read the local symbols.  */
10189   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
10190   if (isymbuf == NULL && locsymcount != 0)
10191     {
10192       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
10193                                       flinfo->internal_syms,
10194                                       flinfo->external_syms,
10195                                       flinfo->locsym_shndx);
10196       if (isymbuf == NULL)
10197         return FALSE;
10198     }
10199
10200   /* Find local symbol sections and adjust values of symbols in
10201      SEC_MERGE sections.  Write out those local symbols we know are
10202      going into the output file.  */
10203   isymend = isymbuf + locsymcount;
10204   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
10205        isym < isymend;
10206        isym++, pindex++, ppsection++)
10207     {
10208       asection *isec;
10209       const char *name;
10210       Elf_Internal_Sym osym;
10211       long indx;
10212       int ret;
10213
10214       *pindex = -1;
10215
10216       if (elf_bad_symtab (input_bfd))
10217         {
10218           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
10219             {
10220               *ppsection = NULL;
10221               continue;
10222             }
10223         }
10224
10225       if (isym->st_shndx == SHN_UNDEF)
10226         isec = bfd_und_section_ptr;
10227       else if (isym->st_shndx == SHN_ABS)
10228         isec = bfd_abs_section_ptr;
10229       else if (isym->st_shndx == SHN_COMMON)
10230         isec = bfd_com_section_ptr;
10231       else
10232         {
10233           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
10234           if (isec == NULL)
10235             {
10236               /* Don't attempt to output symbols with st_shnx in the
10237                  reserved range other than SHN_ABS and SHN_COMMON.  */
10238               *ppsection = NULL;
10239               continue;
10240             }
10241           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
10242                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
10243             isym->st_value =
10244               _bfd_merged_section_offset (output_bfd, &isec,
10245                                           elf_section_data (isec)->sec_info,
10246                                           isym->st_value);
10247         }
10248
10249       *ppsection = isec;
10250
10251       /* Don't output the first, undefined, symbol.  In fact, don't
10252          output any undefined local symbol.  */
10253       if (isec == bfd_und_section_ptr)
10254         continue;
10255
10256       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
10257         {
10258           /* We never output section symbols.  Instead, we use the
10259              section symbol of the corresponding section in the output
10260              file.  */
10261           continue;
10262         }
10263
10264       /* If we are stripping all symbols, we don't want to output this
10265          one.  */
10266       if (flinfo->info->strip == strip_all)
10267         continue;
10268
10269       /* If we are discarding all local symbols, we don't want to
10270          output this one.  If we are generating a relocatable output
10271          file, then some of the local symbols may be required by
10272          relocs; we output them below as we discover that they are
10273          needed.  */
10274       if (flinfo->info->discard == discard_all)
10275         continue;
10276
10277       /* If this symbol is defined in a section which we are
10278          discarding, we don't need to keep it.  */
10279       if (isym->st_shndx != SHN_UNDEF
10280           && isym->st_shndx < SHN_LORESERVE
10281           && bfd_section_removed_from_list (output_bfd,
10282                                             isec->output_section))
10283         continue;
10284
10285       /* Get the name of the symbol.  */
10286       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
10287                                               isym->st_name);
10288       if (name == NULL)
10289         return FALSE;
10290
10291       /* See if we are discarding symbols with this name.  */
10292       if ((flinfo->info->strip == strip_some
10293            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
10294                == NULL))
10295           || (((flinfo->info->discard == discard_sec_merge
10296                 && (isec->flags & SEC_MERGE)
10297                 && !bfd_link_relocatable (flinfo->info))
10298                || flinfo->info->discard == discard_l)
10299               && bfd_is_local_label_name (input_bfd, name)))
10300         continue;
10301
10302       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
10303         {
10304           if (input_bfd->lto_output)
10305             /* -flto puts a temp file name here.  This means builds
10306                are not reproducible.  Discard the symbol.  */
10307             continue;
10308           have_file_sym = TRUE;
10309           flinfo->filesym_count += 1;
10310         }
10311       if (!have_file_sym)
10312         {
10313           /* In the absence of debug info, bfd_find_nearest_line uses
10314              FILE symbols to determine the source file for local
10315              function symbols.  Provide a FILE symbol here if input
10316              files lack such, so that their symbols won't be
10317              associated with a previous input file.  It's not the
10318              source file, but the best we can do.  */
10319           have_file_sym = TRUE;
10320           flinfo->filesym_count += 1;
10321           memset (&osym, 0, sizeof (osym));
10322           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10323           osym.st_shndx = SHN_ABS;
10324           if (!elf_link_output_symstrtab (flinfo,
10325                                           (input_bfd->lto_output ? NULL
10326                                            : input_bfd->filename),
10327                                           &osym, bfd_abs_section_ptr,
10328                                           NULL))
10329             return FALSE;
10330         }
10331
10332       osym = *isym;
10333
10334       /* Adjust the section index for the output file.  */
10335       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10336                                                          isec->output_section);
10337       if (osym.st_shndx == SHN_BAD)
10338         return FALSE;
10339
10340       /* ELF symbols in relocatable files are section relative, but
10341          in executable files they are virtual addresses.  Note that
10342          this code assumes that all ELF sections have an associated
10343          BFD section with a reasonable value for output_offset; below
10344          we assume that they also have a reasonable value for
10345          output_section.  Any special sections must be set up to meet
10346          these requirements.  */
10347       osym.st_value += isec->output_offset;
10348       if (!bfd_link_relocatable (flinfo->info))
10349         {
10350           osym.st_value += isec->output_section->vma;
10351           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
10352             {
10353               /* STT_TLS symbols are relative to PT_TLS segment base.  */
10354               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
10355               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
10356             }
10357         }
10358
10359       indx = bfd_get_symcount (output_bfd);
10360       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
10361       if (ret == 0)
10362         return FALSE;
10363       else if (ret == 1)
10364         *pindex = indx;
10365     }
10366
10367   if (bed->s->arch_size == 32)
10368     {
10369       r_type_mask = 0xff;
10370       r_sym_shift = 8;
10371       address_size = 4;
10372     }
10373   else
10374     {
10375       r_type_mask = 0xffffffff;
10376       r_sym_shift = 32;
10377       address_size = 8;
10378     }
10379
10380   /* Relocate the contents of each section.  */
10381   sym_hashes = elf_sym_hashes (input_bfd);
10382   for (o = input_bfd->sections; o != NULL; o = o->next)
10383     {
10384       bfd_byte *contents;
10385
10386       if (! o->linker_mark)
10387         {
10388           /* This section was omitted from the link.  */
10389           continue;
10390         }
10391
10392       if (!flinfo->info->resolve_section_groups
10393           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
10394         {
10395           /* Deal with the group signature symbol.  */
10396           struct bfd_elf_section_data *sec_data = elf_section_data (o);
10397           unsigned long symndx = sec_data->this_hdr.sh_info;
10398           asection *osec = o->output_section;
10399
10400           BFD_ASSERT (bfd_link_relocatable (flinfo->info));
10401           if (symndx >= locsymcount
10402               || (elf_bad_symtab (input_bfd)
10403                   && flinfo->sections[symndx] == NULL))
10404             {
10405               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
10406               while (h->root.type == bfd_link_hash_indirect
10407                      || h->root.type == bfd_link_hash_warning)
10408                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
10409               /* Arrange for symbol to be output.  */
10410               h->indx = -2;
10411               elf_section_data (osec)->this_hdr.sh_info = -2;
10412             }
10413           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
10414             {
10415               /* We'll use the output section target_index.  */
10416               asection *sec = flinfo->sections[symndx]->output_section;
10417               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
10418             }
10419           else
10420             {
10421               if (flinfo->indices[symndx] == -1)
10422                 {
10423                   /* Otherwise output the local symbol now.  */
10424                   Elf_Internal_Sym sym = isymbuf[symndx];
10425                   asection *sec = flinfo->sections[symndx]->output_section;
10426                   const char *name;
10427                   long indx;
10428                   int ret;
10429
10430                   name = bfd_elf_string_from_elf_section (input_bfd,
10431                                                           symtab_hdr->sh_link,
10432                                                           sym.st_name);
10433                   if (name == NULL)
10434                     return FALSE;
10435
10436                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10437                                                                     sec);
10438                   if (sym.st_shndx == SHN_BAD)
10439                     return FALSE;
10440
10441                   sym.st_value += o->output_offset;
10442
10443                   indx = bfd_get_symcount (output_bfd);
10444                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
10445                                                    NULL);
10446                   if (ret == 0)
10447                     return FALSE;
10448                   else if (ret == 1)
10449                     flinfo->indices[symndx] = indx;
10450                   else
10451                     abort ();
10452                 }
10453               elf_section_data (osec)->this_hdr.sh_info
10454                 = flinfo->indices[symndx];
10455             }
10456         }
10457
10458       if ((o->flags & SEC_HAS_CONTENTS) == 0
10459           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
10460         continue;
10461
10462       if ((o->flags & SEC_LINKER_CREATED) != 0)
10463         {
10464           /* Section was created by _bfd_elf_link_create_dynamic_sections
10465              or somesuch.  */
10466           continue;
10467         }
10468
10469       /* Get the contents of the section.  They have been cached by a
10470          relaxation routine.  Note that o is a section in an input
10471          file, so the contents field will not have been set by any of
10472          the routines which work on output files.  */
10473       if (elf_section_data (o)->this_hdr.contents != NULL)
10474         {
10475           contents = elf_section_data (o)->this_hdr.contents;
10476           if (bed->caches_rawsize
10477               && o->rawsize != 0
10478               && o->rawsize < o->size)
10479             {
10480               memcpy (flinfo->contents, contents, o->rawsize);
10481               contents = flinfo->contents;
10482             }
10483         }
10484       else
10485         {
10486           contents = flinfo->contents;
10487           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
10488             return FALSE;
10489         }
10490
10491       if ((o->flags & SEC_RELOC) != 0)
10492         {
10493           Elf_Internal_Rela *internal_relocs;
10494           Elf_Internal_Rela *rel, *relend;
10495           int action_discarded;
10496           int ret;
10497
10498           /* Get the swapped relocs.  */
10499           internal_relocs
10500             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
10501                                          flinfo->internal_relocs, FALSE);
10502           if (internal_relocs == NULL
10503               && o->reloc_count > 0)
10504             return FALSE;
10505
10506           /* We need to reverse-copy input .ctors/.dtors sections if
10507              they are placed in .init_array/.finit_array for output.  */
10508           if (o->size > address_size
10509               && ((strncmp (o->name, ".ctors", 6) == 0
10510                    && strcmp (o->output_section->name,
10511                               ".init_array") == 0)
10512                   || (strncmp (o->name, ".dtors", 6) == 0
10513                       && strcmp (o->output_section->name,
10514                                  ".fini_array") == 0))
10515               && (o->name[6] == 0 || o->name[6] == '.'))
10516             {
10517               if (o->size * bed->s->int_rels_per_ext_rel
10518                   != o->reloc_count * address_size)
10519                 {
10520                   _bfd_error_handler
10521                     /* xgettext:c-format */
10522                     (_("error: %B: size of section %A is not "
10523                        "multiple of address size"),
10524                      input_bfd, o);
10525                   bfd_set_error (bfd_error_bad_value);
10526                   return FALSE;
10527                 }
10528               o->flags |= SEC_ELF_REVERSE_COPY;
10529             }
10530
10531           action_discarded = -1;
10532           if (!elf_section_ignore_discarded_relocs (o))
10533             action_discarded = (*bed->action_discarded) (o);
10534
10535           /* Run through the relocs evaluating complex reloc symbols and
10536              looking for relocs against symbols from discarded sections
10537              or section symbols from removed link-once sections.
10538              Complain about relocs against discarded sections.  Zero
10539              relocs against removed link-once sections.  */
10540
10541           rel = internal_relocs;
10542           relend = rel + o->reloc_count;
10543           for ( ; rel < relend; rel++)
10544             {
10545               unsigned long r_symndx = rel->r_info >> r_sym_shift;
10546               unsigned int s_type;
10547               asection **ps, *sec;
10548               struct elf_link_hash_entry *h = NULL;
10549               const char *sym_name;
10550
10551               if (r_symndx == STN_UNDEF)
10552                 continue;
10553
10554               if (r_symndx >= locsymcount
10555                   || (elf_bad_symtab (input_bfd)
10556                       && flinfo->sections[r_symndx] == NULL))
10557                 {
10558                   h = sym_hashes[r_symndx - extsymoff];
10559
10560                   /* Badly formatted input files can contain relocs that
10561                      reference non-existant symbols.  Check here so that
10562                      we do not seg fault.  */
10563                   if (h == NULL)
10564                     {
10565                       _bfd_error_handler
10566                         /* xgettext:c-format */
10567                         (_("error: %B contains a reloc (%#Lx) for section %A "
10568                            "that references a non-existent global symbol"),
10569                          input_bfd, rel->r_info, o);
10570                       bfd_set_error (bfd_error_bad_value);
10571                       return FALSE;
10572                     }
10573
10574                   while (h->root.type == bfd_link_hash_indirect
10575                          || h->root.type == bfd_link_hash_warning)
10576                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10577
10578                   s_type = h->type;
10579
10580                   /* If a plugin symbol is referenced from a non-IR file,
10581                      mark the symbol as undefined.  Note that the
10582                      linker may attach linker created dynamic sections
10583                      to the plugin bfd.  Symbols defined in linker
10584                      created sections are not plugin symbols.  */
10585                   if ((h->root.non_ir_ref_regular
10586                        || h->root.non_ir_ref_dynamic)
10587                       && (h->root.type == bfd_link_hash_defined
10588                           || h->root.type == bfd_link_hash_defweak)
10589                       && (h->root.u.def.section->flags
10590                           & SEC_LINKER_CREATED) == 0
10591                       && h->root.u.def.section->owner != NULL
10592                       && (h->root.u.def.section->owner->flags
10593                           & BFD_PLUGIN) != 0)
10594                     {
10595                       h->root.type = bfd_link_hash_undefined;
10596                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10597                     }
10598
10599                   ps = NULL;
10600                   if (h->root.type == bfd_link_hash_defined
10601                       || h->root.type == bfd_link_hash_defweak)
10602                     ps = &h->root.u.def.section;
10603
10604                   sym_name = h->root.root.string;
10605                 }
10606               else
10607                 {
10608                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10609
10610                   s_type = ELF_ST_TYPE (sym->st_info);
10611                   ps = &flinfo->sections[r_symndx];
10612                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10613                                                sym, *ps);
10614                 }
10615
10616               if ((s_type == STT_RELC || s_type == STT_SRELC)
10617                   && !bfd_link_relocatable (flinfo->info))
10618                 {
10619                   bfd_vma val;
10620                   bfd_vma dot = (rel->r_offset
10621                                  + o->output_offset + o->output_section->vma);
10622 #ifdef DEBUG
10623                   printf ("Encountered a complex symbol!");
10624                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10625                           input_bfd->filename, o->name,
10626                           (long) (rel - internal_relocs));
10627                   printf (" symbol: idx  %8.8lx, name %s\n",
10628                           r_symndx, sym_name);
10629                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10630                           (unsigned long) rel->r_info,
10631                           (unsigned long) rel->r_offset);
10632 #endif
10633                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10634                                     isymbuf, locsymcount, s_type == STT_SRELC))
10635                     return FALSE;
10636
10637                   /* Symbol evaluated OK.  Update to absolute value.  */
10638                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10639                                     r_symndx, val);
10640                   continue;
10641                 }
10642
10643               if (action_discarded != -1 && ps != NULL)
10644                 {
10645                   /* Complain if the definition comes from a
10646                      discarded section.  */
10647                   if ((sec = *ps) != NULL && discarded_section (sec))
10648                     {
10649                       BFD_ASSERT (r_symndx != STN_UNDEF);
10650                       if (action_discarded & COMPLAIN)
10651                         (*flinfo->info->callbacks->einfo)
10652                           /* xgettext:c-format */
10653                           (_("%X`%s' referenced in section `%A' of %B: "
10654                              "defined in discarded section `%A' of %B\n"),
10655                            sym_name, o, input_bfd, sec, sec->owner);
10656
10657                       /* Try to do the best we can to support buggy old
10658                          versions of gcc.  Pretend that the symbol is
10659                          really defined in the kept linkonce section.
10660                          FIXME: This is quite broken.  Modifying the
10661                          symbol here means we will be changing all later
10662                          uses of the symbol, not just in this section.  */
10663                       if (action_discarded & PRETEND)
10664                         {
10665                           asection *kept;
10666
10667                           kept = _bfd_elf_check_kept_section (sec,
10668                                                               flinfo->info);
10669                           if (kept != NULL)
10670                             {
10671                               *ps = kept;
10672                               continue;
10673                             }
10674                         }
10675                     }
10676                 }
10677             }
10678
10679           /* Relocate the section by invoking a back end routine.
10680
10681              The back end routine is responsible for adjusting the
10682              section contents as necessary, and (if using Rela relocs
10683              and generating a relocatable output file) adjusting the
10684              reloc addend as necessary.
10685
10686              The back end routine does not have to worry about setting
10687              the reloc address or the reloc symbol index.
10688
10689              The back end routine is given a pointer to the swapped in
10690              internal symbols, and can access the hash table entries
10691              for the external symbols via elf_sym_hashes (input_bfd).
10692
10693              When generating relocatable output, the back end routine
10694              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10695              output symbol is going to be a section symbol
10696              corresponding to the output section, which will require
10697              the addend to be adjusted.  */
10698
10699           ret = (*relocate_section) (output_bfd, flinfo->info,
10700                                      input_bfd, o, contents,
10701                                      internal_relocs,
10702                                      isymbuf,
10703                                      flinfo->sections);
10704           if (!ret)
10705             return FALSE;
10706
10707           if (ret == 2
10708               || bfd_link_relocatable (flinfo->info)
10709               || flinfo->info->emitrelocations)
10710             {
10711               Elf_Internal_Rela *irela;
10712               Elf_Internal_Rela *irelaend, *irelamid;
10713               bfd_vma last_offset;
10714               struct elf_link_hash_entry **rel_hash;
10715               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10716               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10717               unsigned int next_erel;
10718               bfd_boolean rela_normal;
10719               struct bfd_elf_section_data *esdi, *esdo;
10720
10721               esdi = elf_section_data (o);
10722               esdo = elf_section_data (o->output_section);
10723               rela_normal = FALSE;
10724
10725               /* Adjust the reloc addresses and symbol indices.  */
10726
10727               irela = internal_relocs;
10728               irelaend = irela + o->reloc_count;
10729               rel_hash = esdo->rel.hashes + esdo->rel.count;
10730               /* We start processing the REL relocs, if any.  When we reach
10731                  IRELAMID in the loop, we switch to the RELA relocs.  */
10732               irelamid = irela;
10733               if (esdi->rel.hdr != NULL)
10734                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10735                              * bed->s->int_rels_per_ext_rel);
10736               rel_hash_list = rel_hash;
10737               rela_hash_list = NULL;
10738               last_offset = o->output_offset;
10739               if (!bfd_link_relocatable (flinfo->info))
10740                 last_offset += o->output_section->vma;
10741               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10742                 {
10743                   unsigned long r_symndx;
10744                   asection *sec;
10745                   Elf_Internal_Sym sym;
10746
10747                   if (next_erel == bed->s->int_rels_per_ext_rel)
10748                     {
10749                       rel_hash++;
10750                       next_erel = 0;
10751                     }
10752
10753                   if (irela == irelamid)
10754                     {
10755                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10756                       rela_hash_list = rel_hash;
10757                       rela_normal = bed->rela_normal;
10758                     }
10759
10760                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10761                                                              flinfo->info, o,
10762                                                              irela->r_offset);
10763                   if (irela->r_offset >= (bfd_vma) -2)
10764                     {
10765                       /* This is a reloc for a deleted entry or somesuch.
10766                          Turn it into an R_*_NONE reloc, at the same
10767                          offset as the last reloc.  elf_eh_frame.c and
10768                          bfd_elf_discard_info rely on reloc offsets
10769                          being ordered.  */
10770                       irela->r_offset = last_offset;
10771                       irela->r_info = 0;
10772                       irela->r_addend = 0;
10773                       continue;
10774                     }
10775
10776                   irela->r_offset += o->output_offset;
10777
10778                   /* Relocs in an executable have to be virtual addresses.  */
10779                   if (!bfd_link_relocatable (flinfo->info))
10780                     irela->r_offset += o->output_section->vma;
10781
10782                   last_offset = irela->r_offset;
10783
10784                   r_symndx = irela->r_info >> r_sym_shift;
10785                   if (r_symndx == STN_UNDEF)
10786                     continue;
10787
10788                   if (r_symndx >= locsymcount
10789                       || (elf_bad_symtab (input_bfd)
10790                           && flinfo->sections[r_symndx] == NULL))
10791                     {
10792                       struct elf_link_hash_entry *rh;
10793                       unsigned long indx;
10794
10795                       /* This is a reloc against a global symbol.  We
10796                          have not yet output all the local symbols, so
10797                          we do not know the symbol index of any global
10798                          symbol.  We set the rel_hash entry for this
10799                          reloc to point to the global hash table entry
10800                          for this symbol.  The symbol index is then
10801                          set at the end of bfd_elf_final_link.  */
10802                       indx = r_symndx - extsymoff;
10803                       rh = elf_sym_hashes (input_bfd)[indx];
10804                       while (rh->root.type == bfd_link_hash_indirect
10805                              || rh->root.type == bfd_link_hash_warning)
10806                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10807
10808                       /* Setting the index to -2 tells
10809                          elf_link_output_extsym that this symbol is
10810                          used by a reloc.  */
10811                       BFD_ASSERT (rh->indx < 0);
10812                       rh->indx = -2;
10813                       *rel_hash = rh;
10814
10815                       continue;
10816                     }
10817
10818                   /* This is a reloc against a local symbol.  */
10819
10820                   *rel_hash = NULL;
10821                   sym = isymbuf[r_symndx];
10822                   sec = flinfo->sections[r_symndx];
10823                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10824                     {
10825                       /* I suppose the backend ought to fill in the
10826                          section of any STT_SECTION symbol against a
10827                          processor specific section.  */
10828                       r_symndx = STN_UNDEF;
10829                       if (bfd_is_abs_section (sec))
10830                         ;
10831                       else if (sec == NULL || sec->owner == NULL)
10832                         {
10833                           bfd_set_error (bfd_error_bad_value);
10834                           return FALSE;
10835                         }
10836                       else
10837                         {
10838                           asection *osec = sec->output_section;
10839
10840                           /* If we have discarded a section, the output
10841                              section will be the absolute section.  In
10842                              case of discarded SEC_MERGE sections, use
10843                              the kept section.  relocate_section should
10844                              have already handled discarded linkonce
10845                              sections.  */
10846                           if (bfd_is_abs_section (osec)
10847                               && sec->kept_section != NULL
10848                               && sec->kept_section->output_section != NULL)
10849                             {
10850                               osec = sec->kept_section->output_section;
10851                               irela->r_addend -= osec->vma;
10852                             }
10853
10854                           if (!bfd_is_abs_section (osec))
10855                             {
10856                               r_symndx = osec->target_index;
10857                               if (r_symndx == STN_UNDEF)
10858                                 {
10859                                   irela->r_addend += osec->vma;
10860                                   osec = _bfd_nearby_section (output_bfd, osec,
10861                                                               osec->vma);
10862                                   irela->r_addend -= osec->vma;
10863                                   r_symndx = osec->target_index;
10864                                 }
10865                             }
10866                         }
10867
10868                       /* Adjust the addend according to where the
10869                          section winds up in the output section.  */
10870                       if (rela_normal)
10871                         irela->r_addend += sec->output_offset;
10872                     }
10873                   else
10874                     {
10875                       if (flinfo->indices[r_symndx] == -1)
10876                         {
10877                           unsigned long shlink;
10878                           const char *name;
10879                           asection *osec;
10880                           long indx;
10881
10882                           if (flinfo->info->strip == strip_all)
10883                             {
10884                               /* You can't do ld -r -s.  */
10885                               bfd_set_error (bfd_error_invalid_operation);
10886                               return FALSE;
10887                             }
10888
10889                           /* This symbol was skipped earlier, but
10890                              since it is needed by a reloc, we
10891                              must output it now.  */
10892                           shlink = symtab_hdr->sh_link;
10893                           name = (bfd_elf_string_from_elf_section
10894                                   (input_bfd, shlink, sym.st_name));
10895                           if (name == NULL)
10896                             return FALSE;
10897
10898                           osec = sec->output_section;
10899                           sym.st_shndx =
10900                             _bfd_elf_section_from_bfd_section (output_bfd,
10901                                                                osec);
10902                           if (sym.st_shndx == SHN_BAD)
10903                             return FALSE;
10904
10905                           sym.st_value += sec->output_offset;
10906                           if (!bfd_link_relocatable (flinfo->info))
10907                             {
10908                               sym.st_value += osec->vma;
10909                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10910                                 {
10911                                   /* STT_TLS symbols are relative to PT_TLS
10912                                      segment base.  */
10913                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10914                                               ->tls_sec != NULL);
10915                                   sym.st_value -= (elf_hash_table (flinfo->info)
10916                                                    ->tls_sec->vma);
10917                                 }
10918                             }
10919
10920                           indx = bfd_get_symcount (output_bfd);
10921                           ret = elf_link_output_symstrtab (flinfo, name,
10922                                                            &sym, sec,
10923                                                            NULL);
10924                           if (ret == 0)
10925                             return FALSE;
10926                           else if (ret == 1)
10927                             flinfo->indices[r_symndx] = indx;
10928                           else
10929                             abort ();
10930                         }
10931
10932                       r_symndx = flinfo->indices[r_symndx];
10933                     }
10934
10935                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10936                                    | (irela->r_info & r_type_mask));
10937                 }
10938
10939               /* Swap out the relocs.  */
10940               input_rel_hdr = esdi->rel.hdr;
10941               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10942                 {
10943                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10944                                                      input_rel_hdr,
10945                                                      internal_relocs,
10946                                                      rel_hash_list))
10947                     return FALSE;
10948                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10949                                       * bed->s->int_rels_per_ext_rel);
10950                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10951                 }
10952
10953               input_rela_hdr = esdi->rela.hdr;
10954               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10955                 {
10956                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10957                                                      input_rela_hdr,
10958                                                      internal_relocs,
10959                                                      rela_hash_list))
10960                     return FALSE;
10961                 }
10962             }
10963         }
10964
10965       /* Write out the modified section contents.  */
10966       if (bed->elf_backend_write_section
10967           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10968                                                 contents))
10969         {
10970           /* Section written out.  */
10971         }
10972       else switch (o->sec_info_type)
10973         {
10974         case SEC_INFO_TYPE_STABS:
10975           if (! (_bfd_write_section_stabs
10976                  (output_bfd,
10977                   &elf_hash_table (flinfo->info)->stab_info,
10978                   o, &elf_section_data (o)->sec_info, contents)))
10979             return FALSE;
10980           break;
10981         case SEC_INFO_TYPE_MERGE:
10982           if (! _bfd_write_merged_section (output_bfd, o,
10983                                            elf_section_data (o)->sec_info))
10984             return FALSE;
10985           break;
10986         case SEC_INFO_TYPE_EH_FRAME:
10987           {
10988             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
10989                                                    o, contents))
10990               return FALSE;
10991           }
10992           break;
10993         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10994           {
10995             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
10996                                                          flinfo->info,
10997                                                          o, contents))
10998               return FALSE;
10999           }
11000           break;
11001         default:
11002           {
11003             if (! (o->flags & SEC_EXCLUDE))
11004               {
11005                 file_ptr offset = (file_ptr) o->output_offset;
11006                 bfd_size_type todo = o->size;
11007
11008                 offset *= bfd_octets_per_byte (output_bfd);
11009
11010                 if ((o->flags & SEC_ELF_REVERSE_COPY))
11011                   {
11012                     /* Reverse-copy input section to output.  */
11013                     do
11014                       {
11015                         todo -= address_size;
11016                         if (! bfd_set_section_contents (output_bfd,
11017                                                         o->output_section,
11018                                                         contents + todo,
11019                                                         offset,
11020                                                         address_size))
11021                           return FALSE;
11022                         if (todo == 0)
11023                           break;
11024                         offset += address_size;
11025                       }
11026                     while (1);
11027                   }
11028                 else if (! bfd_set_section_contents (output_bfd,
11029                                                      o->output_section,
11030                                                      contents,
11031                                                      offset, todo))
11032                   return FALSE;
11033               }
11034           }
11035           break;
11036         }
11037     }
11038
11039   return TRUE;
11040 }
11041
11042 /* Generate a reloc when linking an ELF file.  This is a reloc
11043    requested by the linker, and does not come from any input file.  This
11044    is used to build constructor and destructor tables when linking
11045    with -Ur.  */
11046
11047 static bfd_boolean
11048 elf_reloc_link_order (bfd *output_bfd,
11049                       struct bfd_link_info *info,
11050                       asection *output_section,
11051                       struct bfd_link_order *link_order)
11052 {
11053   reloc_howto_type *howto;
11054   long indx;
11055   bfd_vma offset;
11056   bfd_vma addend;
11057   struct bfd_elf_section_reloc_data *reldata;
11058   struct elf_link_hash_entry **rel_hash_ptr;
11059   Elf_Internal_Shdr *rel_hdr;
11060   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
11061   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
11062   bfd_byte *erel;
11063   unsigned int i;
11064   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
11065
11066   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
11067   if (howto == NULL)
11068     {
11069       bfd_set_error (bfd_error_bad_value);
11070       return FALSE;
11071     }
11072
11073   addend = link_order->u.reloc.p->addend;
11074
11075   if (esdo->rel.hdr)
11076     reldata = &esdo->rel;
11077   else if (esdo->rela.hdr)
11078     reldata = &esdo->rela;
11079   else
11080     {
11081       reldata = NULL;
11082       BFD_ASSERT (0);
11083     }
11084
11085   /* Figure out the symbol index.  */
11086   rel_hash_ptr = reldata->hashes + reldata->count;
11087   if (link_order->type == bfd_section_reloc_link_order)
11088     {
11089       indx = link_order->u.reloc.p->u.section->target_index;
11090       BFD_ASSERT (indx != 0);
11091       *rel_hash_ptr = NULL;
11092     }
11093   else
11094     {
11095       struct elf_link_hash_entry *h;
11096
11097       /* Treat a reloc against a defined symbol as though it were
11098          actually against the section.  */
11099       h = ((struct elf_link_hash_entry *)
11100            bfd_wrapped_link_hash_lookup (output_bfd, info,
11101                                          link_order->u.reloc.p->u.name,
11102                                          FALSE, FALSE, TRUE));
11103       if (h != NULL
11104           && (h->root.type == bfd_link_hash_defined
11105               || h->root.type == bfd_link_hash_defweak))
11106         {
11107           asection *section;
11108
11109           section = h->root.u.def.section;
11110           indx = section->output_section->target_index;
11111           *rel_hash_ptr = NULL;
11112           /* It seems that we ought to add the symbol value to the
11113              addend here, but in practice it has already been added
11114              because it was passed to constructor_callback.  */
11115           addend += section->output_section->vma + section->output_offset;
11116         }
11117       else if (h != NULL)
11118         {
11119           /* Setting the index to -2 tells elf_link_output_extsym that
11120              this symbol is used by a reloc.  */
11121           h->indx = -2;
11122           *rel_hash_ptr = h;
11123           indx = 0;
11124         }
11125       else
11126         {
11127           (*info->callbacks->unattached_reloc)
11128             (info, link_order->u.reloc.p->u.name, NULL, NULL, 0);
11129           indx = 0;
11130         }
11131     }
11132
11133   /* If this is an inplace reloc, we must write the addend into the
11134      object file.  */
11135   if (howto->partial_inplace && addend != 0)
11136     {
11137       bfd_size_type size;
11138       bfd_reloc_status_type rstat;
11139       bfd_byte *buf;
11140       bfd_boolean ok;
11141       const char *sym_name;
11142
11143       size = (bfd_size_type) bfd_get_reloc_size (howto);
11144       buf = (bfd_byte *) bfd_zmalloc (size);
11145       if (buf == NULL && size != 0)
11146         return FALSE;
11147       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
11148       switch (rstat)
11149         {
11150         case bfd_reloc_ok:
11151           break;
11152
11153         default:
11154         case bfd_reloc_outofrange:
11155           abort ();
11156
11157         case bfd_reloc_overflow:
11158           if (link_order->type == bfd_section_reloc_link_order)
11159             sym_name = bfd_section_name (output_bfd,
11160                                          link_order->u.reloc.p->u.section);
11161           else
11162             sym_name = link_order->u.reloc.p->u.name;
11163           (*info->callbacks->reloc_overflow) (info, NULL, sym_name,
11164                                               howto->name, addend, NULL, NULL,
11165                                               (bfd_vma) 0);
11166           break;
11167         }
11168
11169       ok = bfd_set_section_contents (output_bfd, output_section, buf,
11170                                      link_order->offset
11171                                      * bfd_octets_per_byte (output_bfd),
11172                                      size);
11173       free (buf);
11174       if (! ok)
11175         return FALSE;
11176     }
11177
11178   /* The address of a reloc is relative to the section in a
11179      relocatable file, and is a virtual address in an executable
11180      file.  */
11181   offset = link_order->offset;
11182   if (! bfd_link_relocatable (info))
11183     offset += output_section->vma;
11184
11185   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
11186     {
11187       irel[i].r_offset = offset;
11188       irel[i].r_info = 0;
11189       irel[i].r_addend = 0;
11190     }
11191   if (bed->s->arch_size == 32)
11192     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
11193   else
11194     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
11195
11196   rel_hdr = reldata->hdr;
11197   erel = rel_hdr->contents;
11198   if (rel_hdr->sh_type == SHT_REL)
11199     {
11200       erel += reldata->count * bed->s->sizeof_rel;
11201       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
11202     }
11203   else
11204     {
11205       irel[0].r_addend = addend;
11206       erel += reldata->count * bed->s->sizeof_rela;
11207       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
11208     }
11209
11210   ++reldata->count;
11211
11212   return TRUE;
11213 }
11214
11215
11216 /* Get the output vma of the section pointed to by the sh_link field.  */
11217
11218 static bfd_vma
11219 elf_get_linked_section_vma (struct bfd_link_order *p)
11220 {
11221   Elf_Internal_Shdr **elf_shdrp;
11222   asection *s;
11223   int elfsec;
11224
11225   s = p->u.indirect.section;
11226   elf_shdrp = elf_elfsections (s->owner);
11227   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
11228   elfsec = elf_shdrp[elfsec]->sh_link;
11229   /* PR 290:
11230      The Intel C compiler generates SHT_IA_64_UNWIND with
11231      SHF_LINK_ORDER.  But it doesn't set the sh_link or
11232      sh_info fields.  Hence we could get the situation
11233      where elfsec is 0.  */
11234   if (elfsec == 0)
11235     {
11236       const struct elf_backend_data *bed
11237         = get_elf_backend_data (s->owner);
11238       if (bed->link_order_error_handler)
11239         bed->link_order_error_handler
11240           /* xgettext:c-format */
11241           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
11242       return 0;
11243     }
11244   else
11245     {
11246       s = elf_shdrp[elfsec]->bfd_section;
11247       return s->output_section->vma + s->output_offset;
11248     }
11249 }
11250
11251
11252 /* Compare two sections based on the locations of the sections they are
11253    linked to.  Used by elf_fixup_link_order.  */
11254
11255 static int
11256 compare_link_order (const void * a, const void * b)
11257 {
11258   bfd_vma apos;
11259   bfd_vma bpos;
11260
11261   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
11262   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
11263   if (apos < bpos)
11264     return -1;
11265   return apos > bpos;
11266 }
11267
11268
11269 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
11270    order as their linked sections.  Returns false if this could not be done
11271    because an output section includes both ordered and unordered
11272    sections.  Ideally we'd do this in the linker proper.  */
11273
11274 static bfd_boolean
11275 elf_fixup_link_order (bfd *abfd, asection *o)
11276 {
11277   int seen_linkorder;
11278   int seen_other;
11279   int n;
11280   struct bfd_link_order *p;
11281   bfd *sub;
11282   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11283   unsigned elfsec;
11284   struct bfd_link_order **sections;
11285   asection *s, *other_sec, *linkorder_sec;
11286   bfd_vma offset;
11287
11288   other_sec = NULL;
11289   linkorder_sec = NULL;
11290   seen_other = 0;
11291   seen_linkorder = 0;
11292   for (p = o->map_head.link_order; p != NULL; p = p->next)
11293     {
11294       if (p->type == bfd_indirect_link_order)
11295         {
11296           s = p->u.indirect.section;
11297           sub = s->owner;
11298           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11299               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
11300               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
11301               && elfsec < elf_numsections (sub)
11302               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
11303               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
11304             {
11305               seen_linkorder++;
11306               linkorder_sec = s;
11307             }
11308           else
11309             {
11310               seen_other++;
11311               other_sec = s;
11312             }
11313         }
11314       else
11315         seen_other++;
11316
11317       if (seen_other && seen_linkorder)
11318         {
11319           if (other_sec && linkorder_sec)
11320             _bfd_error_handler
11321               /* xgettext:c-format */
11322               (_("%A has both ordered [`%A' in %B] "
11323                  "and unordered [`%A' in %B] sections"),
11324                o, linkorder_sec, linkorder_sec->owner,
11325                other_sec, other_sec->owner);
11326           else
11327             _bfd_error_handler
11328               (_("%A has both ordered and unordered sections"), o);
11329           bfd_set_error (bfd_error_bad_value);
11330           return FALSE;
11331         }
11332     }
11333
11334   if (!seen_linkorder)
11335     return TRUE;
11336
11337   sections = (struct bfd_link_order **)
11338     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
11339   if (sections == NULL)
11340     return FALSE;
11341   seen_linkorder = 0;
11342
11343   for (p = o->map_head.link_order; p != NULL; p = p->next)
11344     {
11345       sections[seen_linkorder++] = p;
11346     }
11347   /* Sort the input sections in the order of their linked section.  */
11348   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
11349          compare_link_order);
11350
11351   /* Change the offsets of the sections.  */
11352   offset = 0;
11353   for (n = 0; n < seen_linkorder; n++)
11354     {
11355       s = sections[n]->u.indirect.section;
11356       offset &= ~(bfd_vma) 0 << s->alignment_power;
11357       s->output_offset = offset / bfd_octets_per_byte (abfd);
11358       sections[n]->offset = offset;
11359       offset += sections[n]->size;
11360     }
11361
11362   free (sections);
11363   return TRUE;
11364 }
11365
11366 /* Generate an import library in INFO->implib_bfd from symbols in ABFD.
11367    Returns TRUE upon success, FALSE otherwise.  */
11368
11369 static bfd_boolean
11370 elf_output_implib (bfd *abfd, struct bfd_link_info *info)
11371 {
11372   bfd_boolean ret = FALSE;
11373   bfd *implib_bfd;
11374   const struct elf_backend_data *bed;
11375   flagword flags;
11376   enum bfd_architecture arch;
11377   unsigned int mach;
11378   asymbol **sympp = NULL;
11379   long symsize;
11380   long symcount;
11381   long src_count;
11382   elf_symbol_type *osymbuf;
11383
11384   implib_bfd = info->out_implib_bfd;
11385   bed = get_elf_backend_data (abfd);
11386
11387   if (!bfd_set_format (implib_bfd, bfd_object))
11388     return FALSE;
11389
11390   /* Use flag from executable but make it a relocatable object.  */
11391   flags = bfd_get_file_flags (abfd);
11392   flags &= ~HAS_RELOC;
11393   if (!bfd_set_start_address (implib_bfd, 0)
11394       || !bfd_set_file_flags (implib_bfd, flags & ~EXEC_P))
11395     return FALSE;
11396
11397   /* Copy architecture of output file to import library file.  */
11398   arch = bfd_get_arch (abfd);
11399   mach = bfd_get_mach (abfd);
11400   if (!bfd_set_arch_mach (implib_bfd, arch, mach)
11401       && (abfd->target_defaulted
11402           || bfd_get_arch (abfd) != bfd_get_arch (implib_bfd)))
11403     return FALSE;
11404
11405   /* Get symbol table size.  */
11406   symsize = bfd_get_symtab_upper_bound (abfd);
11407   if (symsize < 0)
11408     return FALSE;
11409
11410   /* Read in the symbol table.  */
11411   sympp = (asymbol **) xmalloc (symsize);
11412   symcount = bfd_canonicalize_symtab (abfd, sympp);
11413   if (symcount < 0)
11414     goto free_sym_buf;
11415
11416   /* Allow the BFD backend to copy any private header data it
11417      understands from the output BFD to the import library BFD.  */
11418   if (! bfd_copy_private_header_data (abfd, implib_bfd))
11419     goto free_sym_buf;
11420
11421   /* Filter symbols to appear in the import library.  */
11422   if (bed->elf_backend_filter_implib_symbols)
11423     symcount = bed->elf_backend_filter_implib_symbols (abfd, info, sympp,
11424                                                        symcount);
11425   else
11426     symcount = _bfd_elf_filter_global_symbols (abfd, info, sympp, symcount);
11427   if (symcount == 0)
11428     {
11429       bfd_set_error (bfd_error_no_symbols);
11430       _bfd_error_handler (_("%B: no symbol found for import library"),
11431                           implib_bfd);
11432       goto free_sym_buf;
11433     }
11434
11435
11436   /* Make symbols absolute.  */
11437   osymbuf = (elf_symbol_type *) bfd_alloc2 (implib_bfd, symcount,
11438                                             sizeof (*osymbuf));
11439   for (src_count = 0; src_count < symcount; src_count++)
11440     {
11441       memcpy (&osymbuf[src_count], (elf_symbol_type *) sympp[src_count],
11442               sizeof (*osymbuf));
11443       osymbuf[src_count].symbol.section = bfd_abs_section_ptr;
11444       osymbuf[src_count].internal_elf_sym.st_shndx = SHN_ABS;
11445       osymbuf[src_count].symbol.value += sympp[src_count]->section->vma;
11446       osymbuf[src_count].internal_elf_sym.st_value =
11447         osymbuf[src_count].symbol.value;
11448       sympp[src_count] = &osymbuf[src_count].symbol;
11449     }
11450
11451   bfd_set_symtab (implib_bfd, sympp, symcount);
11452
11453   /* Allow the BFD backend to copy any private data it understands
11454      from the output BFD to the import library BFD.  This is done last
11455      to permit the routine to look at the filtered symbol table.  */
11456   if (! bfd_copy_private_bfd_data (abfd, implib_bfd))
11457     goto free_sym_buf;
11458
11459   if (!bfd_close (implib_bfd))
11460     goto free_sym_buf;
11461
11462   ret = TRUE;
11463
11464 free_sym_buf:
11465   free (sympp);
11466   return ret;
11467 }
11468
11469 static void
11470 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
11471 {
11472   asection *o;
11473
11474   if (flinfo->symstrtab != NULL)
11475     _bfd_elf_strtab_free (flinfo->symstrtab);
11476   if (flinfo->contents != NULL)
11477     free (flinfo->contents);
11478   if (flinfo->external_relocs != NULL)
11479     free (flinfo->external_relocs);
11480   if (flinfo->internal_relocs != NULL)
11481     free (flinfo->internal_relocs);
11482   if (flinfo->external_syms != NULL)
11483     free (flinfo->external_syms);
11484   if (flinfo->locsym_shndx != NULL)
11485     free (flinfo->locsym_shndx);
11486   if (flinfo->internal_syms != NULL)
11487     free (flinfo->internal_syms);
11488   if (flinfo->indices != NULL)
11489     free (flinfo->indices);
11490   if (flinfo->sections != NULL)
11491     free (flinfo->sections);
11492   if (flinfo->symshndxbuf != NULL)
11493     free (flinfo->symshndxbuf);
11494   for (o = obfd->sections; o != NULL; o = o->next)
11495     {
11496       struct bfd_elf_section_data *esdo = elf_section_data (o);
11497       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11498         free (esdo->rel.hashes);
11499       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11500         free (esdo->rela.hashes);
11501     }
11502 }
11503
11504 /* Do the final step of an ELF link.  */
11505
11506 bfd_boolean
11507 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
11508 {
11509   bfd_boolean dynamic;
11510   bfd_boolean emit_relocs;
11511   bfd *dynobj;
11512   struct elf_final_link_info flinfo;
11513   asection *o;
11514   struct bfd_link_order *p;
11515   bfd *sub;
11516   bfd_size_type max_contents_size;
11517   bfd_size_type max_external_reloc_size;
11518   bfd_size_type max_internal_reloc_count;
11519   bfd_size_type max_sym_count;
11520   bfd_size_type max_sym_shndx_count;
11521   Elf_Internal_Sym elfsym;
11522   unsigned int i;
11523   Elf_Internal_Shdr *symtab_hdr;
11524   Elf_Internal_Shdr *symtab_shndx_hdr;
11525   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11526   struct elf_outext_info eoinfo;
11527   bfd_boolean merged;
11528   size_t relativecount = 0;
11529   asection *reldyn = 0;
11530   bfd_size_type amt;
11531   asection *attr_section = NULL;
11532   bfd_vma attr_size = 0;
11533   const char *std_attrs_section;
11534   struct elf_link_hash_table *htab = elf_hash_table (info);
11535
11536   if (!is_elf_hash_table (htab))
11537     return FALSE;
11538
11539   if (bfd_link_pic (info))
11540     abfd->flags |= DYNAMIC;
11541
11542   dynamic = htab->dynamic_sections_created;
11543   dynobj = htab->dynobj;
11544
11545   emit_relocs = (bfd_link_relocatable (info)
11546                  || info->emitrelocations);
11547
11548   flinfo.info = info;
11549   flinfo.output_bfd = abfd;
11550   flinfo.symstrtab = _bfd_elf_strtab_init ();
11551   if (flinfo.symstrtab == NULL)
11552     return FALSE;
11553
11554   if (! dynamic)
11555     {
11556       flinfo.hash_sec = NULL;
11557       flinfo.symver_sec = NULL;
11558     }
11559   else
11560     {
11561       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
11562       /* Note that dynsym_sec can be NULL (on VMS).  */
11563       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
11564       /* Note that it is OK if symver_sec is NULL.  */
11565     }
11566
11567   flinfo.contents = NULL;
11568   flinfo.external_relocs = NULL;
11569   flinfo.internal_relocs = NULL;
11570   flinfo.external_syms = NULL;
11571   flinfo.locsym_shndx = NULL;
11572   flinfo.internal_syms = NULL;
11573   flinfo.indices = NULL;
11574   flinfo.sections = NULL;
11575   flinfo.symshndxbuf = NULL;
11576   flinfo.filesym_count = 0;
11577
11578   /* The object attributes have been merged.  Remove the input
11579      sections from the link, and set the contents of the output
11580      secton.  */
11581   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
11582   for (o = abfd->sections; o != NULL; o = o->next)
11583     {
11584       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
11585           || strcmp (o->name, ".gnu.attributes") == 0)
11586         {
11587           for (p = o->map_head.link_order; p != NULL; p = p->next)
11588             {
11589               asection *input_section;
11590
11591               if (p->type != bfd_indirect_link_order)
11592                 continue;
11593               input_section = p->u.indirect.section;
11594               /* Hack: reset the SEC_HAS_CONTENTS flag so that
11595                  elf_link_input_bfd ignores this section.  */
11596               input_section->flags &= ~SEC_HAS_CONTENTS;
11597             }
11598
11599           attr_size = bfd_elf_obj_attr_size (abfd);
11600           if (attr_size)
11601             {
11602               bfd_set_section_size (abfd, o, attr_size);
11603               attr_section = o;
11604               /* Skip this section later on.  */
11605               o->map_head.link_order = NULL;
11606             }
11607           else
11608             o->flags |= SEC_EXCLUDE;
11609         }
11610     }
11611
11612   /* Count up the number of relocations we will output for each output
11613      section, so that we know the sizes of the reloc sections.  We
11614      also figure out some maximum sizes.  */
11615   max_contents_size = 0;
11616   max_external_reloc_size = 0;
11617   max_internal_reloc_count = 0;
11618   max_sym_count = 0;
11619   max_sym_shndx_count = 0;
11620   merged = FALSE;
11621   for (o = abfd->sections; o != NULL; o = o->next)
11622     {
11623       struct bfd_elf_section_data *esdo = elf_section_data (o);
11624       o->reloc_count = 0;
11625
11626       for (p = o->map_head.link_order; p != NULL; p = p->next)
11627         {
11628           unsigned int reloc_count = 0;
11629           unsigned int additional_reloc_count = 0;
11630           struct bfd_elf_section_data *esdi = NULL;
11631
11632           if (p->type == bfd_section_reloc_link_order
11633               || p->type == bfd_symbol_reloc_link_order)
11634             reloc_count = 1;
11635           else if (p->type == bfd_indirect_link_order)
11636             {
11637               asection *sec;
11638
11639               sec = p->u.indirect.section;
11640
11641               /* Mark all sections which are to be included in the
11642                  link.  This will normally be every section.  We need
11643                  to do this so that we can identify any sections which
11644                  the linker has decided to not include.  */
11645               sec->linker_mark = TRUE;
11646
11647               if (sec->flags & SEC_MERGE)
11648                 merged = TRUE;
11649
11650               if (sec->rawsize > max_contents_size)
11651                 max_contents_size = sec->rawsize;
11652               if (sec->size > max_contents_size)
11653                 max_contents_size = sec->size;
11654
11655               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
11656                   && (sec->owner->flags & DYNAMIC) == 0)
11657                 {
11658                   size_t sym_count;
11659
11660                   /* We are interested in just local symbols, not all
11661                      symbols.  */
11662                   if (elf_bad_symtab (sec->owner))
11663                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
11664                                  / bed->s->sizeof_sym);
11665                   else
11666                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
11667
11668                   if (sym_count > max_sym_count)
11669                     max_sym_count = sym_count;
11670
11671                   if (sym_count > max_sym_shndx_count
11672                       && elf_symtab_shndx_list (sec->owner) != NULL)
11673                     max_sym_shndx_count = sym_count;
11674
11675                   if (esdo->this_hdr.sh_type == SHT_REL
11676                       || esdo->this_hdr.sh_type == SHT_RELA)
11677                     /* Some backends use reloc_count in relocation sections
11678                        to count particular types of relocs.  Of course,
11679                        reloc sections themselves can't have relocations.  */
11680                     ;
11681                   else if (emit_relocs)
11682                     {
11683                       reloc_count = sec->reloc_count;
11684                       if (bed->elf_backend_count_additional_relocs)
11685                         {
11686                           int c;
11687                           c = (*bed->elf_backend_count_additional_relocs) (sec);
11688                           additional_reloc_count += c;
11689                         }
11690                     }
11691                   else if (bed->elf_backend_count_relocs)
11692                     reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
11693
11694                   esdi = elf_section_data (sec);
11695
11696                   if ((sec->flags & SEC_RELOC) != 0)
11697                     {
11698                       size_t ext_size = 0;
11699
11700                       if (esdi->rel.hdr != NULL)
11701                         ext_size = esdi->rel.hdr->sh_size;
11702                       if (esdi->rela.hdr != NULL)
11703                         ext_size += esdi->rela.hdr->sh_size;
11704
11705                       if (ext_size > max_external_reloc_size)
11706                         max_external_reloc_size = ext_size;
11707                       if (sec->reloc_count > max_internal_reloc_count)
11708                         max_internal_reloc_count = sec->reloc_count;
11709                     }
11710                 }
11711             }
11712
11713           if (reloc_count == 0)
11714             continue;
11715
11716           reloc_count += additional_reloc_count;
11717           o->reloc_count += reloc_count;
11718
11719           if (p->type == bfd_indirect_link_order && emit_relocs)
11720             {
11721               if (esdi->rel.hdr)
11722                 {
11723                   esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11724                   esdo->rel.count += additional_reloc_count;
11725                 }
11726               if (esdi->rela.hdr)
11727                 {
11728                   esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11729                   esdo->rela.count += additional_reloc_count;
11730                 }
11731             }
11732           else
11733             {
11734               if (o->use_rela_p)
11735                 esdo->rela.count += reloc_count;
11736               else
11737                 esdo->rel.count += reloc_count;
11738             }
11739         }
11740
11741       if (o->reloc_count > 0)
11742         o->flags |= SEC_RELOC;
11743       else
11744         {
11745           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11746              set it (this is probably a bug) and if it is set
11747              assign_section_numbers will create a reloc section.  */
11748           o->flags &=~ SEC_RELOC;
11749         }
11750
11751       /* If the SEC_ALLOC flag is not set, force the section VMA to
11752          zero.  This is done in elf_fake_sections as well, but forcing
11753          the VMA to 0 here will ensure that relocs against these
11754          sections are handled correctly.  */
11755       if ((o->flags & SEC_ALLOC) == 0
11756           && ! o->user_set_vma)
11757         o->vma = 0;
11758     }
11759
11760   if (! bfd_link_relocatable (info) && merged)
11761     elf_link_hash_traverse (htab, _bfd_elf_link_sec_merge_syms, abfd);
11762
11763   /* Figure out the file positions for everything but the symbol table
11764      and the relocs.  We set symcount to force assign_section_numbers
11765      to create a symbol table.  */
11766   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11767   BFD_ASSERT (! abfd->output_has_begun);
11768   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11769     goto error_return;
11770
11771   /* Set sizes, and assign file positions for reloc sections.  */
11772   for (o = abfd->sections; o != NULL; o = o->next)
11773     {
11774       struct bfd_elf_section_data *esdo = elf_section_data (o);
11775       if ((o->flags & SEC_RELOC) != 0)
11776         {
11777           if (esdo->rel.hdr
11778               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11779             goto error_return;
11780
11781           if (esdo->rela.hdr
11782               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11783             goto error_return;
11784         }
11785
11786       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
11787          to count upwards while actually outputting the relocations.  */
11788       esdo->rel.count = 0;
11789       esdo->rela.count = 0;
11790
11791       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
11792         {
11793           /* Cache the section contents so that they can be compressed
11794              later.  Use bfd_malloc since it will be freed by
11795              bfd_compress_section_contents.  */
11796           unsigned char *contents = esdo->this_hdr.contents;
11797           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
11798             abort ();
11799           contents
11800             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
11801           if (contents == NULL)
11802             goto error_return;
11803           esdo->this_hdr.contents = contents;
11804         }
11805     }
11806
11807   /* We have now assigned file positions for all the sections except
11808      .symtab, .strtab, and non-loaded reloc sections.  We start the
11809      .symtab section at the current file position, and write directly
11810      to it.  We build the .strtab section in memory.  */
11811   bfd_get_symcount (abfd) = 0;
11812   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11813   /* sh_name is set in prep_headers.  */
11814   symtab_hdr->sh_type = SHT_SYMTAB;
11815   /* sh_flags, sh_addr and sh_size all start off zero.  */
11816   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
11817   /* sh_link is set in assign_section_numbers.  */
11818   /* sh_info is set below.  */
11819   /* sh_offset is set just below.  */
11820   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
11821
11822   if (max_sym_count < 20)
11823     max_sym_count = 20;
11824   htab->strtabsize = max_sym_count;
11825   amt = max_sym_count * sizeof (struct elf_sym_strtab);
11826   htab->strtab = (struct elf_sym_strtab *) bfd_malloc (amt);
11827   if (htab->strtab == NULL)
11828     goto error_return;
11829   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
11830   flinfo.symshndxbuf
11831     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
11832        ? (Elf_External_Sym_Shndx *) -1 : NULL);
11833
11834   if (info->strip != strip_all || emit_relocs)
11835     {
11836       file_ptr off = elf_next_file_pos (abfd);
11837
11838       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
11839
11840       /* Note that at this point elf_next_file_pos (abfd) is
11841          incorrect.  We do not yet know the size of the .symtab section.
11842          We correct next_file_pos below, after we do know the size.  */
11843
11844       /* Start writing out the symbol table.  The first symbol is always a
11845          dummy symbol.  */
11846       elfsym.st_value = 0;
11847       elfsym.st_size = 0;
11848       elfsym.st_info = 0;
11849       elfsym.st_other = 0;
11850       elfsym.st_shndx = SHN_UNDEF;
11851       elfsym.st_target_internal = 0;
11852       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
11853                                      bfd_und_section_ptr, NULL) != 1)
11854         goto error_return;
11855
11856       /* Output a symbol for each section.  We output these even if we are
11857          discarding local symbols, since they are used for relocs.  These
11858          symbols have no names.  We store the index of each one in the
11859          index field of the section, so that we can find it again when
11860          outputting relocs.  */
11861
11862       elfsym.st_size = 0;
11863       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11864       elfsym.st_other = 0;
11865       elfsym.st_value = 0;
11866       elfsym.st_target_internal = 0;
11867       for (i = 1; i < elf_numsections (abfd); i++)
11868         {
11869           o = bfd_section_from_elf_index (abfd, i);
11870           if (o != NULL)
11871             {
11872               o->target_index = bfd_get_symcount (abfd);
11873               elfsym.st_shndx = i;
11874               if (!bfd_link_relocatable (info))
11875                 elfsym.st_value = o->vma;
11876               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
11877                                              NULL) != 1)
11878                 goto error_return;
11879             }
11880         }
11881     }
11882
11883   /* Allocate some memory to hold information read in from the input
11884      files.  */
11885   if (max_contents_size != 0)
11886     {
11887       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
11888       if (flinfo.contents == NULL)
11889         goto error_return;
11890     }
11891
11892   if (max_external_reloc_size != 0)
11893     {
11894       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
11895       if (flinfo.external_relocs == NULL)
11896         goto error_return;
11897     }
11898
11899   if (max_internal_reloc_count != 0)
11900     {
11901       amt = max_internal_reloc_count * sizeof (Elf_Internal_Rela);
11902       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
11903       if (flinfo.internal_relocs == NULL)
11904         goto error_return;
11905     }
11906
11907   if (max_sym_count != 0)
11908     {
11909       amt = max_sym_count * bed->s->sizeof_sym;
11910       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
11911       if (flinfo.external_syms == NULL)
11912         goto error_return;
11913
11914       amt = max_sym_count * sizeof (Elf_Internal_Sym);
11915       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
11916       if (flinfo.internal_syms == NULL)
11917         goto error_return;
11918
11919       amt = max_sym_count * sizeof (long);
11920       flinfo.indices = (long int *) bfd_malloc (amt);
11921       if (flinfo.indices == NULL)
11922         goto error_return;
11923
11924       amt = max_sym_count * sizeof (asection *);
11925       flinfo.sections = (asection **) bfd_malloc (amt);
11926       if (flinfo.sections == NULL)
11927         goto error_return;
11928     }
11929
11930   if (max_sym_shndx_count != 0)
11931     {
11932       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
11933       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
11934       if (flinfo.locsym_shndx == NULL)
11935         goto error_return;
11936     }
11937
11938   if (htab->tls_sec)
11939     {
11940       bfd_vma base, end = 0;
11941       asection *sec;
11942
11943       for (sec = htab->tls_sec;
11944            sec && (sec->flags & SEC_THREAD_LOCAL);
11945            sec = sec->next)
11946         {
11947           bfd_size_type size = sec->size;
11948
11949           if (size == 0
11950               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11951             {
11952               struct bfd_link_order *ord = sec->map_tail.link_order;
11953
11954               if (ord != NULL)
11955                 size = ord->offset + ord->size;
11956             }
11957           end = sec->vma + size;
11958         }
11959       base = htab->tls_sec->vma;
11960       /* Only align end of TLS section if static TLS doesn't have special
11961          alignment requirements.  */
11962       if (bed->static_tls_alignment == 1)
11963         end = align_power (end, htab->tls_sec->alignment_power);
11964       htab->tls_size = end - base;
11965     }
11966
11967   /* Reorder SHF_LINK_ORDER sections.  */
11968   for (o = abfd->sections; o != NULL; o = o->next)
11969     {
11970       if (!elf_fixup_link_order (abfd, o))
11971         return FALSE;
11972     }
11973
11974   if (!_bfd_elf_fixup_eh_frame_hdr (info))
11975     return FALSE;
11976
11977   /* Since ELF permits relocations to be against local symbols, we
11978      must have the local symbols available when we do the relocations.
11979      Since we would rather only read the local symbols once, and we
11980      would rather not keep them in memory, we handle all the
11981      relocations for a single input file at the same time.
11982
11983      Unfortunately, there is no way to know the total number of local
11984      symbols until we have seen all of them, and the local symbol
11985      indices precede the global symbol indices.  This means that when
11986      we are generating relocatable output, and we see a reloc against
11987      a global symbol, we can not know the symbol index until we have
11988      finished examining all the local symbols to see which ones we are
11989      going to output.  To deal with this, we keep the relocations in
11990      memory, and don't output them until the end of the link.  This is
11991      an unfortunate waste of memory, but I don't see a good way around
11992      it.  Fortunately, it only happens when performing a relocatable
11993      link, which is not the common case.  FIXME: If keep_memory is set
11994      we could write the relocs out and then read them again; I don't
11995      know how bad the memory loss will be.  */
11996
11997   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11998     sub->output_has_begun = FALSE;
11999   for (o = abfd->sections; o != NULL; o = o->next)
12000     {
12001       for (p = o->map_head.link_order; p != NULL; p = p->next)
12002         {
12003           if (p->type == bfd_indirect_link_order
12004               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
12005                   == bfd_target_elf_flavour)
12006               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
12007             {
12008               if (! sub->output_has_begun)
12009                 {
12010                   if (! elf_link_input_bfd (&flinfo, sub))
12011                     goto error_return;
12012                   sub->output_has_begun = TRUE;
12013                 }
12014             }
12015           else if (p->type == bfd_section_reloc_link_order
12016                    || p->type == bfd_symbol_reloc_link_order)
12017             {
12018               if (! elf_reloc_link_order (abfd, info, o, p))
12019                 goto error_return;
12020             }
12021           else
12022             {
12023               if (! _bfd_default_link_order (abfd, info, o, p))
12024                 {
12025                   if (p->type == bfd_indirect_link_order
12026                       && (bfd_get_flavour (sub)
12027                           == bfd_target_elf_flavour)
12028                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
12029                           != bed->s->elfclass))
12030                     {
12031                       const char *iclass, *oclass;
12032
12033                       switch (bed->s->elfclass)
12034                         {
12035                         case ELFCLASS64: oclass = "ELFCLASS64"; break;
12036                         case ELFCLASS32: oclass = "ELFCLASS32"; break;
12037                         case ELFCLASSNONE: oclass = "ELFCLASSNONE"; break;
12038                         default: abort ();
12039                         }
12040
12041                       switch (elf_elfheader (sub)->e_ident[EI_CLASS])
12042                         {
12043                         case ELFCLASS64: iclass = "ELFCLASS64"; break;
12044                         case ELFCLASS32: iclass = "ELFCLASS32"; break;
12045                         case ELFCLASSNONE: iclass = "ELFCLASSNONE"; break;
12046                         default: abort ();
12047                         }
12048
12049                       bfd_set_error (bfd_error_wrong_format);
12050                       _bfd_error_handler
12051                         /* xgettext:c-format */
12052                         (_("%B: file class %s incompatible with %s"),
12053                          sub, iclass, oclass);
12054                     }
12055
12056                   goto error_return;
12057                 }
12058             }
12059         }
12060     }
12061
12062   /* Free symbol buffer if needed.  */
12063   if (!info->reduce_memory_overheads)
12064     {
12065       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12066         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
12067             && elf_tdata (sub)->symbuf)
12068           {
12069             free (elf_tdata (sub)->symbuf);
12070             elf_tdata (sub)->symbuf = NULL;
12071           }
12072     }
12073
12074   /* Output any global symbols that got converted to local in a
12075      version script or due to symbol visibility.  We do this in a
12076      separate step since ELF requires all local symbols to appear
12077      prior to any global symbols.  FIXME: We should only do this if
12078      some global symbols were, in fact, converted to become local.
12079      FIXME: Will this work correctly with the Irix 5 linker?  */
12080   eoinfo.failed = FALSE;
12081   eoinfo.flinfo = &flinfo;
12082   eoinfo.localsyms = TRUE;
12083   eoinfo.file_sym_done = FALSE;
12084   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12085   if (eoinfo.failed)
12086     return FALSE;
12087
12088   /* If backend needs to output some local symbols not present in the hash
12089      table, do it now.  */
12090   if (bed->elf_backend_output_arch_local_syms
12091       && (info->strip != strip_all || emit_relocs))
12092     {
12093       typedef int (*out_sym_func)
12094         (void *, const char *, Elf_Internal_Sym *, asection *,
12095          struct elf_link_hash_entry *);
12096
12097       if (! ((*bed->elf_backend_output_arch_local_syms)
12098              (abfd, info, &flinfo,
12099               (out_sym_func) elf_link_output_symstrtab)))
12100         return FALSE;
12101     }
12102
12103   /* That wrote out all the local symbols.  Finish up the symbol table
12104      with the global symbols. Even if we want to strip everything we
12105      can, we still need to deal with those global symbols that got
12106      converted to local in a version script.  */
12107
12108   /* The sh_info field records the index of the first non local symbol.  */
12109   symtab_hdr->sh_info = bfd_get_symcount (abfd);
12110
12111   if (dynamic
12112       && htab->dynsym != NULL
12113       && htab->dynsym->output_section != bfd_abs_section_ptr)
12114     {
12115       Elf_Internal_Sym sym;
12116       bfd_byte *dynsym = htab->dynsym->contents;
12117
12118       o = htab->dynsym->output_section;
12119       elf_section_data (o)->this_hdr.sh_info = htab->local_dynsymcount + 1;
12120
12121       /* Write out the section symbols for the output sections.  */
12122       if (bfd_link_pic (info)
12123           || htab->is_relocatable_executable)
12124         {
12125           asection *s;
12126
12127           sym.st_size = 0;
12128           sym.st_name = 0;
12129           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
12130           sym.st_other = 0;
12131           sym.st_target_internal = 0;
12132
12133           for (s = abfd->sections; s != NULL; s = s->next)
12134             {
12135               int indx;
12136               bfd_byte *dest;
12137               long dynindx;
12138
12139               dynindx = elf_section_data (s)->dynindx;
12140               if (dynindx <= 0)
12141                 continue;
12142               indx = elf_section_data (s)->this_idx;
12143               BFD_ASSERT (indx > 0);
12144               sym.st_shndx = indx;
12145               if (! check_dynsym (abfd, &sym))
12146                 return FALSE;
12147               sym.st_value = s->vma;
12148               dest = dynsym + dynindx * bed->s->sizeof_sym;
12149               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12150             }
12151         }
12152
12153       /* Write out the local dynsyms.  */
12154       if (htab->dynlocal)
12155         {
12156           struct elf_link_local_dynamic_entry *e;
12157           for (e = htab->dynlocal; e ; e = e->next)
12158             {
12159               asection *s;
12160               bfd_byte *dest;
12161
12162               /* Copy the internal symbol and turn off visibility.
12163                  Note that we saved a word of storage and overwrote
12164                  the original st_name with the dynstr_index.  */
12165               sym = e->isym;
12166               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
12167
12168               s = bfd_section_from_elf_index (e->input_bfd,
12169                                               e->isym.st_shndx);
12170               if (s != NULL)
12171                 {
12172                   sym.st_shndx =
12173                     elf_section_data (s->output_section)->this_idx;
12174                   if (! check_dynsym (abfd, &sym))
12175                     return FALSE;
12176                   sym.st_value = (s->output_section->vma
12177                                   + s->output_offset
12178                                   + e->isym.st_value);
12179                 }
12180
12181               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
12182               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12183             }
12184         }
12185     }
12186
12187   /* We get the global symbols from the hash table.  */
12188   eoinfo.failed = FALSE;
12189   eoinfo.localsyms = FALSE;
12190   eoinfo.flinfo = &flinfo;
12191   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12192   if (eoinfo.failed)
12193     return FALSE;
12194
12195   /* If backend needs to output some symbols not present in the hash
12196      table, do it now.  */
12197   if (bed->elf_backend_output_arch_syms
12198       && (info->strip != strip_all || emit_relocs))
12199     {
12200       typedef int (*out_sym_func)
12201         (void *, const char *, Elf_Internal_Sym *, asection *,
12202          struct elf_link_hash_entry *);
12203
12204       if (! ((*bed->elf_backend_output_arch_syms)
12205              (abfd, info, &flinfo,
12206               (out_sym_func) elf_link_output_symstrtab)))
12207         return FALSE;
12208     }
12209
12210   /* Finalize the .strtab section.  */
12211   _bfd_elf_strtab_finalize (flinfo.symstrtab);
12212
12213   /* Swap out the .strtab section. */
12214   if (!elf_link_swap_symbols_out (&flinfo))
12215     return FALSE;
12216
12217   /* Now we know the size of the symtab section.  */
12218   if (bfd_get_symcount (abfd) > 0)
12219     {
12220       /* Finish up and write out the symbol string table (.strtab)
12221          section.  */
12222       Elf_Internal_Shdr *symstrtab_hdr = NULL;
12223       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
12224
12225       if (elf_symtab_shndx_list (abfd))
12226         {
12227           symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
12228
12229           if (symtab_shndx_hdr != NULL && symtab_shndx_hdr->sh_name != 0)
12230             {
12231               symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
12232               symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
12233               symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
12234               amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
12235               symtab_shndx_hdr->sh_size = amt;
12236
12237               off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
12238                                                                off, TRUE);
12239
12240               if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
12241                   || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
12242                 return FALSE;
12243             }
12244         }
12245
12246       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
12247       /* sh_name was set in prep_headers.  */
12248       symstrtab_hdr->sh_type = SHT_STRTAB;
12249       symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
12250       symstrtab_hdr->sh_addr = 0;
12251       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
12252       symstrtab_hdr->sh_entsize = 0;
12253       symstrtab_hdr->sh_link = 0;
12254       symstrtab_hdr->sh_info = 0;
12255       /* sh_offset is set just below.  */
12256       symstrtab_hdr->sh_addralign = 1;
12257
12258       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
12259                                                        off, TRUE);
12260       elf_next_file_pos (abfd) = off;
12261
12262       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
12263           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
12264         return FALSE;
12265     }
12266
12267   if (info->out_implib_bfd && !elf_output_implib (abfd, info))
12268     {
12269       _bfd_error_handler (_("%B: failed to generate import library"),
12270                           info->out_implib_bfd);
12271       return FALSE;
12272     }
12273
12274   /* Adjust the relocs to have the correct symbol indices.  */
12275   for (o = abfd->sections; o != NULL; o = o->next)
12276     {
12277       struct bfd_elf_section_data *esdo = elf_section_data (o);
12278       bfd_boolean sort;
12279
12280       if ((o->flags & SEC_RELOC) == 0)
12281         continue;
12282
12283       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
12284       if (esdo->rel.hdr != NULL
12285           && !elf_link_adjust_relocs (abfd, o, &esdo->rel, sort, info))
12286         return FALSE;
12287       if (esdo->rela.hdr != NULL
12288           && !elf_link_adjust_relocs (abfd, o, &esdo->rela, sort, info))
12289         return FALSE;
12290
12291       /* Set the reloc_count field to 0 to prevent write_relocs from
12292          trying to swap the relocs out itself.  */
12293       o->reloc_count = 0;
12294     }
12295
12296   if (dynamic && info->combreloc && dynobj != NULL)
12297     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
12298
12299   /* If we are linking against a dynamic object, or generating a
12300      shared library, finish up the dynamic linking information.  */
12301   if (dynamic)
12302     {
12303       bfd_byte *dyncon, *dynconend;
12304
12305       /* Fix up .dynamic entries.  */
12306       o = bfd_get_linker_section (dynobj, ".dynamic");
12307       BFD_ASSERT (o != NULL);
12308
12309       dyncon = o->contents;
12310       dynconend = o->contents + o->size;
12311       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12312         {
12313           Elf_Internal_Dyn dyn;
12314           const char *name;
12315           unsigned int type;
12316           bfd_size_type sh_size;
12317           bfd_vma sh_addr;
12318
12319           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12320
12321           switch (dyn.d_tag)
12322             {
12323             default:
12324               continue;
12325             case DT_NULL:
12326               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
12327                 {
12328                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
12329                     {
12330                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
12331                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
12332                     default: continue;
12333                     }
12334                   dyn.d_un.d_val = relativecount;
12335                   relativecount = 0;
12336                   break;
12337                 }
12338               continue;
12339
12340             case DT_INIT:
12341               name = info->init_function;
12342               goto get_sym;
12343             case DT_FINI:
12344               name = info->fini_function;
12345             get_sym:
12346               {
12347                 struct elf_link_hash_entry *h;
12348
12349                 h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
12350                 if (h != NULL
12351                     && (h->root.type == bfd_link_hash_defined
12352                         || h->root.type == bfd_link_hash_defweak))
12353                   {
12354                     dyn.d_un.d_ptr = h->root.u.def.value;
12355                     o = h->root.u.def.section;
12356                     if (o->output_section != NULL)
12357                       dyn.d_un.d_ptr += (o->output_section->vma
12358                                          + o->output_offset);
12359                     else
12360                       {
12361                         /* The symbol is imported from another shared
12362                            library and does not apply to this one.  */
12363                         dyn.d_un.d_ptr = 0;
12364                       }
12365                     break;
12366                   }
12367               }
12368               continue;
12369
12370             case DT_PREINIT_ARRAYSZ:
12371               name = ".preinit_array";
12372               goto get_out_size;
12373             case DT_INIT_ARRAYSZ:
12374               name = ".init_array";
12375               goto get_out_size;
12376             case DT_FINI_ARRAYSZ:
12377               name = ".fini_array";
12378             get_out_size:
12379               o = bfd_get_section_by_name (abfd, name);
12380               if (o == NULL)
12381                 {
12382                   _bfd_error_handler
12383                     (_("could not find section %s"), name);
12384                   goto error_return;
12385                 }
12386               if (o->size == 0)
12387                 _bfd_error_handler
12388                   (_("warning: %s section has zero size"), name);
12389               dyn.d_un.d_val = o->size;
12390               break;
12391
12392             case DT_PREINIT_ARRAY:
12393               name = ".preinit_array";
12394               goto get_out_vma;
12395             case DT_INIT_ARRAY:
12396               name = ".init_array";
12397               goto get_out_vma;
12398             case DT_FINI_ARRAY:
12399               name = ".fini_array";
12400             get_out_vma:
12401               o = bfd_get_section_by_name (abfd, name);
12402               goto do_vma;
12403
12404             case DT_HASH:
12405               name = ".hash";
12406               goto get_vma;
12407             case DT_GNU_HASH:
12408               name = ".gnu.hash";
12409               goto get_vma;
12410             case DT_STRTAB:
12411               name = ".dynstr";
12412               goto get_vma;
12413             case DT_SYMTAB:
12414               name = ".dynsym";
12415               goto get_vma;
12416             case DT_VERDEF:
12417               name = ".gnu.version_d";
12418               goto get_vma;
12419             case DT_VERNEED:
12420               name = ".gnu.version_r";
12421               goto get_vma;
12422             case DT_VERSYM:
12423               name = ".gnu.version";
12424             get_vma:
12425               o = bfd_get_linker_section (dynobj, name);
12426             do_vma:
12427               if (o == NULL || bfd_is_abs_section (o->output_section))
12428                 {
12429                   _bfd_error_handler
12430                     (_("could not find section %s"), name);
12431                   goto error_return;
12432                 }
12433               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
12434                 {
12435                   _bfd_error_handler
12436                     (_("warning: section '%s' is being made into a note"), name);
12437                   bfd_set_error (bfd_error_nonrepresentable_section);
12438                   goto error_return;
12439                 }
12440               dyn.d_un.d_ptr = o->output_section->vma + o->output_offset;
12441               break;
12442
12443             case DT_REL:
12444             case DT_RELA:
12445             case DT_RELSZ:
12446             case DT_RELASZ:
12447               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
12448                 type = SHT_REL;
12449               else
12450                 type = SHT_RELA;
12451               sh_size = 0;
12452               sh_addr = 0;
12453               for (i = 1; i < elf_numsections (abfd); i++)
12454                 {
12455                   Elf_Internal_Shdr *hdr;
12456
12457                   hdr = elf_elfsections (abfd)[i];
12458                   if (hdr->sh_type == type
12459                       && (hdr->sh_flags & SHF_ALLOC) != 0)
12460                     {
12461                       sh_size += hdr->sh_size;
12462                       if (sh_addr == 0
12463                           || sh_addr > hdr->sh_addr)
12464                         sh_addr = hdr->sh_addr;
12465                     }
12466                 }
12467
12468               if (bed->dtrel_excludes_plt && htab->srelplt != NULL)
12469                 {
12470                   /* Don't count procedure linkage table relocs in the
12471                      overall reloc count.  */
12472                   sh_size -= htab->srelplt->size;
12473                   if (sh_size == 0)
12474                     /* If the size is zero, make the address zero too.
12475                        This is to avoid a glibc bug.  If the backend
12476                        emits DT_RELA/DT_RELASZ even when DT_RELASZ is
12477                        zero, then we'll put DT_RELA at the end of
12478                        DT_JMPREL.  glibc will interpret the end of
12479                        DT_RELA matching the end of DT_JMPREL as the
12480                        case where DT_RELA includes DT_JMPREL, and for
12481                        LD_BIND_NOW will decide that processing DT_RELA
12482                        will process the PLT relocs too.  Net result:
12483                        No PLT relocs applied.  */
12484                     sh_addr = 0;
12485
12486                   /* If .rela.plt is the first .rela section, exclude
12487                      it from DT_RELA.  */
12488                   else if (sh_addr == (htab->srelplt->output_section->vma
12489                                        + htab->srelplt->output_offset))
12490                     sh_addr += htab->srelplt->size;
12491                 }
12492
12493               if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
12494                 dyn.d_un.d_val = sh_size;
12495               else
12496                 dyn.d_un.d_ptr = sh_addr;
12497               break;
12498             }
12499           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
12500         }
12501     }
12502
12503   /* If we have created any dynamic sections, then output them.  */
12504   if (dynobj != NULL)
12505     {
12506       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
12507         goto error_return;
12508
12509       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
12510       if (((info->warn_shared_textrel && bfd_link_pic (info))
12511            || info->error_textrel)
12512           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
12513         {
12514           bfd_byte *dyncon, *dynconend;
12515
12516           dyncon = o->contents;
12517           dynconend = o->contents + o->size;
12518           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12519             {
12520               Elf_Internal_Dyn dyn;
12521
12522               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12523
12524               if (dyn.d_tag == DT_TEXTREL)
12525                 {
12526                   if (info->error_textrel)
12527                     info->callbacks->einfo
12528                       (_("%P%X: read-only segment has dynamic relocations.\n"));
12529                   else
12530                     info->callbacks->einfo
12531                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
12532                   break;
12533                 }
12534             }
12535         }
12536
12537       for (o = dynobj->sections; o != NULL; o = o->next)
12538         {
12539           if ((o->flags & SEC_HAS_CONTENTS) == 0
12540               || o->size == 0
12541               || o->output_section == bfd_abs_section_ptr)
12542             continue;
12543           if ((o->flags & SEC_LINKER_CREATED) == 0)
12544             {
12545               /* At this point, we are only interested in sections
12546                  created by _bfd_elf_link_create_dynamic_sections.  */
12547               continue;
12548             }
12549           if (htab->stab_info.stabstr == o)
12550             continue;
12551           if (htab->eh_info.hdr_sec == o)
12552             continue;
12553           if (strcmp (o->name, ".dynstr") != 0)
12554             {
12555               if (! bfd_set_section_contents (abfd, o->output_section,
12556                                               o->contents,
12557                                               (file_ptr) o->output_offset
12558                                               * bfd_octets_per_byte (abfd),
12559                                               o->size))
12560                 goto error_return;
12561             }
12562           else
12563             {
12564               /* The contents of the .dynstr section are actually in a
12565                  stringtab.  */
12566               file_ptr off;
12567
12568               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
12569               if (bfd_seek (abfd, off, SEEK_SET) != 0
12570                   || !_bfd_elf_strtab_emit (abfd, htab->dynstr))
12571                 goto error_return;
12572             }
12573         }
12574     }
12575
12576   if (!info->resolve_section_groups)
12577     {
12578       bfd_boolean failed = FALSE;
12579
12580       BFD_ASSERT (bfd_link_relocatable (info));
12581       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
12582       if (failed)
12583         goto error_return;
12584     }
12585
12586   /* If we have optimized stabs strings, output them.  */
12587   if (htab->stab_info.stabstr != NULL)
12588     {
12589       if (!_bfd_write_stab_strings (abfd, &htab->stab_info))
12590         goto error_return;
12591     }
12592
12593   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
12594     goto error_return;
12595
12596   elf_final_link_free (abfd, &flinfo);
12597
12598   elf_linker (abfd) = TRUE;
12599
12600   if (attr_section)
12601     {
12602       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
12603       if (contents == NULL)
12604         return FALSE;   /* Bail out and fail.  */
12605       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
12606       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
12607       free (contents);
12608     }
12609
12610   return TRUE;
12611
12612  error_return:
12613   elf_final_link_free (abfd, &flinfo);
12614   return FALSE;
12615 }
12616 \f
12617 /* Initialize COOKIE for input bfd ABFD.  */
12618
12619 static bfd_boolean
12620 init_reloc_cookie (struct elf_reloc_cookie *cookie,
12621                    struct bfd_link_info *info, bfd *abfd)
12622 {
12623   Elf_Internal_Shdr *symtab_hdr;
12624   const struct elf_backend_data *bed;
12625
12626   bed = get_elf_backend_data (abfd);
12627   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12628
12629   cookie->abfd = abfd;
12630   cookie->sym_hashes = elf_sym_hashes (abfd);
12631   cookie->bad_symtab = elf_bad_symtab (abfd);
12632   if (cookie->bad_symtab)
12633     {
12634       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12635       cookie->extsymoff = 0;
12636     }
12637   else
12638     {
12639       cookie->locsymcount = symtab_hdr->sh_info;
12640       cookie->extsymoff = symtab_hdr->sh_info;
12641     }
12642
12643   if (bed->s->arch_size == 32)
12644     cookie->r_sym_shift = 8;
12645   else
12646     cookie->r_sym_shift = 32;
12647
12648   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
12649   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
12650     {
12651       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12652                                               cookie->locsymcount, 0,
12653                                               NULL, NULL, NULL);
12654       if (cookie->locsyms == NULL)
12655         {
12656           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
12657           return FALSE;
12658         }
12659       if (info->keep_memory)
12660         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
12661     }
12662   return TRUE;
12663 }
12664
12665 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
12666
12667 static void
12668 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
12669 {
12670   Elf_Internal_Shdr *symtab_hdr;
12671
12672   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12673   if (cookie->locsyms != NULL
12674       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
12675     free (cookie->locsyms);
12676 }
12677
12678 /* Initialize the relocation information in COOKIE for input section SEC
12679    of input bfd ABFD.  */
12680
12681 static bfd_boolean
12682 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12683                         struct bfd_link_info *info, bfd *abfd,
12684                         asection *sec)
12685 {
12686   if (sec->reloc_count == 0)
12687     {
12688       cookie->rels = NULL;
12689       cookie->relend = NULL;
12690     }
12691   else
12692     {
12693       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
12694                                                 info->keep_memory);
12695       if (cookie->rels == NULL)
12696         return FALSE;
12697       cookie->rel = cookie->rels;
12698       cookie->relend = cookie->rels + sec->reloc_count;
12699     }
12700   cookie->rel = cookie->rels;
12701   return TRUE;
12702 }
12703
12704 /* Free the memory allocated by init_reloc_cookie_rels,
12705    if appropriate.  */
12706
12707 static void
12708 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12709                         asection *sec)
12710 {
12711   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
12712     free (cookie->rels);
12713 }
12714
12715 /* Initialize the whole of COOKIE for input section SEC.  */
12716
12717 static bfd_boolean
12718 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12719                                struct bfd_link_info *info,
12720                                asection *sec)
12721 {
12722   if (!init_reloc_cookie (cookie, info, sec->owner))
12723     goto error1;
12724   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
12725     goto error2;
12726   return TRUE;
12727
12728  error2:
12729   fini_reloc_cookie (cookie, sec->owner);
12730  error1:
12731   return FALSE;
12732 }
12733
12734 /* Free the memory allocated by init_reloc_cookie_for_section,
12735    if appropriate.  */
12736
12737 static void
12738 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12739                                asection *sec)
12740 {
12741   fini_reloc_cookie_rels (cookie, sec);
12742   fini_reloc_cookie (cookie, sec->owner);
12743 }
12744 \f
12745 /* Garbage collect unused sections.  */
12746
12747 /* Default gc_mark_hook.  */
12748
12749 asection *
12750 _bfd_elf_gc_mark_hook (asection *sec,
12751                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12752                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12753                        struct elf_link_hash_entry *h,
12754                        Elf_Internal_Sym *sym)
12755 {
12756   if (h != NULL)
12757     {
12758       switch (h->root.type)
12759         {
12760         case bfd_link_hash_defined:
12761         case bfd_link_hash_defweak:
12762           return h->root.u.def.section;
12763
12764         case bfd_link_hash_common:
12765           return h->root.u.c.p->section;
12766
12767         default:
12768           break;
12769         }
12770     }
12771   else
12772     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12773
12774   return NULL;
12775 }
12776
12777 /* Return the global debug definition section.  */
12778
12779 static asection *
12780 elf_gc_mark_debug_section (asection *sec ATTRIBUTE_UNUSED,
12781                            struct bfd_link_info *info ATTRIBUTE_UNUSED,
12782                            Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12783                            struct elf_link_hash_entry *h,
12784                            Elf_Internal_Sym *sym ATTRIBUTE_UNUSED)
12785 {
12786   if (h != NULL
12787       && (h->root.type == bfd_link_hash_defined
12788           || h->root.type == bfd_link_hash_defweak)
12789       && (h->root.u.def.section->flags & SEC_DEBUGGING) != 0)
12790     return h->root.u.def.section;
12791
12792   return NULL;
12793 }
12794
12795 /* COOKIE->rel describes a relocation against section SEC, which is
12796    a section we've decided to keep.  Return the section that contains
12797    the relocation symbol, or NULL if no section contains it.  */
12798
12799 asection *
12800 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
12801                        elf_gc_mark_hook_fn gc_mark_hook,
12802                        struct elf_reloc_cookie *cookie,
12803                        bfd_boolean *start_stop)
12804 {
12805   unsigned long r_symndx;
12806   struct elf_link_hash_entry *h;
12807
12808   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
12809   if (r_symndx == STN_UNDEF)
12810     return NULL;
12811
12812   if (r_symndx >= cookie->locsymcount
12813       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12814     {
12815       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
12816       if (h == NULL)
12817         {
12818           info->callbacks->einfo (_("%F%P: corrupt input: %B\n"),
12819                                   sec->owner);
12820           return NULL;
12821         }
12822       while (h->root.type == bfd_link_hash_indirect
12823              || h->root.type == bfd_link_hash_warning)
12824         h = (struct elf_link_hash_entry *) h->root.u.i.link;
12825       h->mark = 1;
12826       /* If this symbol is weak and there is a non-weak definition, we
12827          keep the non-weak definition because many backends put
12828          dynamic reloc info on the non-weak definition for code
12829          handling copy relocs.  */
12830       if (h->is_weakalias)
12831         weakdef (h)->mark = 1;
12832
12833       if (start_stop != NULL)
12834         {
12835           /* To work around a glibc bug, mark XXX input sections
12836              when there is a reference to __start_XXX or __stop_XXX
12837              symbols.  */
12838           if (h->start_stop)
12839             {
12840               asection *s = h->u2.start_stop_section;
12841               *start_stop = !s->gc_mark;
12842               return s;
12843             }
12844         }
12845
12846       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
12847     }
12848
12849   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
12850                           &cookie->locsyms[r_symndx]);
12851 }
12852
12853 /* COOKIE->rel describes a relocation against section SEC, which is
12854    a section we've decided to keep.  Mark the section that contains
12855    the relocation symbol.  */
12856
12857 bfd_boolean
12858 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
12859                         asection *sec,
12860                         elf_gc_mark_hook_fn gc_mark_hook,
12861                         struct elf_reloc_cookie *cookie)
12862 {
12863   asection *rsec;
12864   bfd_boolean start_stop = FALSE;
12865
12866   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie, &start_stop);
12867   while (rsec != NULL)
12868     {
12869       if (!rsec->gc_mark)
12870         {
12871           if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
12872               || (rsec->owner->flags & DYNAMIC) != 0)
12873             rsec->gc_mark = 1;
12874           else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
12875             return FALSE;
12876         }
12877       if (!start_stop)
12878         break;
12879       rsec = bfd_get_next_section_by_name (rsec->owner, rsec);
12880     }
12881   return TRUE;
12882 }
12883
12884 /* The mark phase of garbage collection.  For a given section, mark
12885    it and any sections in this section's group, and all the sections
12886    which define symbols to which it refers.  */
12887
12888 bfd_boolean
12889 _bfd_elf_gc_mark (struct bfd_link_info *info,
12890                   asection *sec,
12891                   elf_gc_mark_hook_fn gc_mark_hook)
12892 {
12893   bfd_boolean ret;
12894   asection *group_sec, *eh_frame;
12895
12896   sec->gc_mark = 1;
12897
12898   /* Mark all the sections in the group.  */
12899   group_sec = elf_section_data (sec)->next_in_group;
12900   if (group_sec && !group_sec->gc_mark)
12901     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
12902       return FALSE;
12903
12904   /* Look through the section relocs.  */
12905   ret = TRUE;
12906   eh_frame = elf_eh_frame_section (sec->owner);
12907   if ((sec->flags & SEC_RELOC) != 0
12908       && sec->reloc_count > 0
12909       && sec != eh_frame)
12910     {
12911       struct elf_reloc_cookie cookie;
12912
12913       if (!init_reloc_cookie_for_section (&cookie, info, sec))
12914         ret = FALSE;
12915       else
12916         {
12917           for (; cookie.rel < cookie.relend; cookie.rel++)
12918             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
12919               {
12920                 ret = FALSE;
12921                 break;
12922               }
12923           fini_reloc_cookie_for_section (&cookie, sec);
12924         }
12925     }
12926
12927   if (ret && eh_frame && elf_fde_list (sec))
12928     {
12929       struct elf_reloc_cookie cookie;
12930
12931       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
12932         ret = FALSE;
12933       else
12934         {
12935           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
12936                                       gc_mark_hook, &cookie))
12937             ret = FALSE;
12938           fini_reloc_cookie_for_section (&cookie, eh_frame);
12939         }
12940     }
12941
12942   eh_frame = elf_section_eh_frame_entry (sec);
12943   if (ret && eh_frame && !eh_frame->gc_mark)
12944     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
12945       ret = FALSE;
12946
12947   return ret;
12948 }
12949
12950 /* Scan and mark sections in a special or debug section group.  */
12951
12952 static void
12953 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
12954 {
12955   /* Point to first section of section group.  */
12956   asection *ssec;
12957   /* Used to iterate the section group.  */
12958   asection *msec;
12959
12960   bfd_boolean is_special_grp = TRUE;
12961   bfd_boolean is_debug_grp = TRUE;
12962
12963   /* First scan to see if group contains any section other than debug
12964      and special section.  */
12965   ssec = msec = elf_next_in_group (grp);
12966   do
12967     {
12968       if ((msec->flags & SEC_DEBUGGING) == 0)
12969         is_debug_grp = FALSE;
12970
12971       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
12972         is_special_grp = FALSE;
12973
12974       msec = elf_next_in_group (msec);
12975     }
12976   while (msec != ssec);
12977
12978   /* If this is a pure debug section group or pure special section group,
12979      keep all sections in this group.  */
12980   if (is_debug_grp || is_special_grp)
12981     {
12982       do
12983         {
12984           msec->gc_mark = 1;
12985           msec = elf_next_in_group (msec);
12986         }
12987       while (msec != ssec);
12988     }
12989 }
12990
12991 /* Keep debug and special sections.  */
12992
12993 bfd_boolean
12994 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
12995                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
12996 {
12997   bfd *ibfd;
12998
12999   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13000     {
13001       asection *isec;
13002       bfd_boolean some_kept;
13003       bfd_boolean debug_frag_seen;
13004       bfd_boolean has_kept_debug_info;
13005
13006       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13007         continue;
13008       isec = ibfd->sections;
13009       if (isec == NULL || isec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13010         continue;
13011
13012       /* Ensure all linker created sections are kept,
13013          see if any other section is already marked,
13014          and note if we have any fragmented debug sections.  */
13015       debug_frag_seen = some_kept = has_kept_debug_info = FALSE;
13016       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13017         {
13018           if ((isec->flags & SEC_LINKER_CREATED) != 0)
13019             isec->gc_mark = 1;
13020           else if (isec->gc_mark
13021                    && (isec->flags & SEC_ALLOC) != 0
13022                    && elf_section_type (isec) != SHT_NOTE)
13023             some_kept = TRUE;
13024
13025           if (!debug_frag_seen
13026               && (isec->flags & SEC_DEBUGGING)
13027               && CONST_STRNEQ (isec->name, ".debug_line."))
13028             debug_frag_seen = TRUE;
13029         }
13030
13031       /* If no non-note alloc section in this file will be kept, then
13032          we can toss out the debug and special sections.  */
13033       if (!some_kept)
13034         continue;
13035
13036       /* Keep debug and special sections like .comment when they are
13037          not part of a group.  Also keep section groups that contain
13038          just debug sections or special sections.  */
13039       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13040         {
13041           if ((isec->flags & SEC_GROUP) != 0)
13042             _bfd_elf_gc_mark_debug_special_section_group (isec);
13043           else if (((isec->flags & SEC_DEBUGGING) != 0
13044                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
13045                    && elf_next_in_group (isec) == NULL)
13046             isec->gc_mark = 1;
13047           if (isec->gc_mark && (isec->flags & SEC_DEBUGGING) != 0)
13048             has_kept_debug_info = TRUE;
13049         }
13050
13051       /* Look for CODE sections which are going to be discarded,
13052          and find and discard any fragmented debug sections which
13053          are associated with that code section.  */
13054       if (debug_frag_seen)
13055         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13056           if ((isec->flags & SEC_CODE) != 0
13057               && isec->gc_mark == 0)
13058             {
13059               unsigned int ilen;
13060               asection *dsec;
13061
13062               ilen = strlen (isec->name);
13063
13064               /* Association is determined by the name of the debug
13065                  section containing the name of the code section as
13066                  a suffix.  For example .debug_line.text.foo is a
13067                  debug section associated with .text.foo.  */
13068               for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
13069                 {
13070                   unsigned int dlen;
13071
13072                   if (dsec->gc_mark == 0
13073                       || (dsec->flags & SEC_DEBUGGING) == 0)
13074                     continue;
13075
13076                   dlen = strlen (dsec->name);
13077
13078                   if (dlen > ilen
13079                       && strncmp (dsec->name + (dlen - ilen),
13080                                   isec->name, ilen) == 0)
13081                     dsec->gc_mark = 0;
13082                 }
13083           }
13084
13085       /* Mark debug sections referenced by kept debug sections.  */
13086       if (has_kept_debug_info)
13087         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13088           if (isec->gc_mark
13089               && (isec->flags & SEC_DEBUGGING) != 0)
13090             if (!_bfd_elf_gc_mark (info, isec,
13091                                    elf_gc_mark_debug_section))
13092               return FALSE;
13093     }
13094   return TRUE;
13095 }
13096
13097 static bfd_boolean
13098 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
13099 {
13100   bfd *sub;
13101   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13102
13103   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13104     {
13105       asection *o;
13106
13107       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13108           || elf_object_id (sub) != elf_hash_table_id (elf_hash_table (info))
13109           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13110         continue;
13111       o = sub->sections;
13112       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13113         continue;
13114
13115       for (o = sub->sections; o != NULL; o = o->next)
13116         {
13117           /* When any section in a section group is kept, we keep all
13118              sections in the section group.  If the first member of
13119              the section group is excluded, we will also exclude the
13120              group section.  */
13121           if (o->flags & SEC_GROUP)
13122             {
13123               asection *first = elf_next_in_group (o);
13124               o->gc_mark = first->gc_mark;
13125             }
13126
13127           if (o->gc_mark)
13128             continue;
13129
13130           /* Skip sweeping sections already excluded.  */
13131           if (o->flags & SEC_EXCLUDE)
13132             continue;
13133
13134           /* Since this is early in the link process, it is simple
13135              to remove a section from the output.  */
13136           o->flags |= SEC_EXCLUDE;
13137
13138           if (info->print_gc_sections && o->size != 0)
13139             /* xgettext:c-format */
13140             _bfd_error_handler (_("Removing unused section '%A' in file '%B'"),
13141                                 o, sub);
13142         }
13143     }
13144
13145   return TRUE;
13146 }
13147
13148 /* Propagate collected vtable information.  This is called through
13149    elf_link_hash_traverse.  */
13150
13151 static bfd_boolean
13152 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
13153 {
13154   /* Those that are not vtables.  */
13155   if (h->start_stop
13156       || h->u2.vtable == NULL
13157       || h->u2.vtable->parent == NULL)
13158     return TRUE;
13159
13160   /* Those vtables that do not have parents, we cannot merge.  */
13161   if (h->u2.vtable->parent == (struct elf_link_hash_entry *) -1)
13162     return TRUE;
13163
13164   /* If we've already been done, exit.  */
13165   if (h->u2.vtable->used && h->u2.vtable->used[-1])
13166     return TRUE;
13167
13168   /* Make sure the parent's table is up to date.  */
13169   elf_gc_propagate_vtable_entries_used (h->u2.vtable->parent, okp);
13170
13171   if (h->u2.vtable->used == NULL)
13172     {
13173       /* None of this table's entries were referenced.  Re-use the
13174          parent's table.  */
13175       h->u2.vtable->used = h->u2.vtable->parent->u2.vtable->used;
13176       h->u2.vtable->size = h->u2.vtable->parent->u2.vtable->size;
13177     }
13178   else
13179     {
13180       size_t n;
13181       bfd_boolean *cu, *pu;
13182
13183       /* Or the parent's entries into ours.  */
13184       cu = h->u2.vtable->used;
13185       cu[-1] = TRUE;
13186       pu = h->u2.vtable->parent->u2.vtable->used;
13187       if (pu != NULL)
13188         {
13189           const struct elf_backend_data *bed;
13190           unsigned int log_file_align;
13191
13192           bed = get_elf_backend_data (h->root.u.def.section->owner);
13193           log_file_align = bed->s->log_file_align;
13194           n = h->u2.vtable->parent->u2.vtable->size >> log_file_align;
13195           while (n--)
13196             {
13197               if (*pu)
13198                 *cu = TRUE;
13199               pu++;
13200               cu++;
13201             }
13202         }
13203     }
13204
13205   return TRUE;
13206 }
13207
13208 static bfd_boolean
13209 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
13210 {
13211   asection *sec;
13212   bfd_vma hstart, hend;
13213   Elf_Internal_Rela *relstart, *relend, *rel;
13214   const struct elf_backend_data *bed;
13215   unsigned int log_file_align;
13216
13217   /* Take care of both those symbols that do not describe vtables as
13218      well as those that are not loaded.  */
13219   if (h->start_stop
13220       || h->u2.vtable == NULL
13221       || h->u2.vtable->parent == NULL)
13222     return TRUE;
13223
13224   BFD_ASSERT (h->root.type == bfd_link_hash_defined
13225               || h->root.type == bfd_link_hash_defweak);
13226
13227   sec = h->root.u.def.section;
13228   hstart = h->root.u.def.value;
13229   hend = hstart + h->size;
13230
13231   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
13232   if (!relstart)
13233     return *(bfd_boolean *) okp = FALSE;
13234   bed = get_elf_backend_data (sec->owner);
13235   log_file_align = bed->s->log_file_align;
13236
13237   relend = relstart + sec->reloc_count;
13238
13239   for (rel = relstart; rel < relend; ++rel)
13240     if (rel->r_offset >= hstart && rel->r_offset < hend)
13241       {
13242         /* If the entry is in use, do nothing.  */
13243         if (h->u2.vtable->used
13244             && (rel->r_offset - hstart) < h->u2.vtable->size)
13245           {
13246             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
13247             if (h->u2.vtable->used[entry])
13248               continue;
13249           }
13250         /* Otherwise, kill it.  */
13251         rel->r_offset = rel->r_info = rel->r_addend = 0;
13252       }
13253
13254   return TRUE;
13255 }
13256
13257 /* Mark sections containing dynamically referenced symbols.  When
13258    building shared libraries, we must assume that any visible symbol is
13259    referenced.  */
13260
13261 bfd_boolean
13262 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
13263 {
13264   struct bfd_link_info *info = (struct bfd_link_info *) inf;
13265   struct bfd_elf_dynamic_list *d = info->dynamic_list;
13266
13267   if ((h->root.type == bfd_link_hash_defined
13268        || h->root.type == bfd_link_hash_defweak)
13269       && (h->ref_dynamic
13270           || ((h->def_regular || ELF_COMMON_DEF_P (h))
13271               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
13272               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
13273               && (!bfd_link_executable (info)
13274                   || info->gc_keep_exported
13275                   || info->export_dynamic
13276                   || (h->dynamic
13277                       && d != NULL
13278                       && (*d->match) (&d->head, NULL, h->root.root.string)))
13279               && (h->versioned >= versioned
13280                   || !bfd_hide_sym_by_version (info->version_info,
13281                                                h->root.root.string)))))
13282     h->root.u.def.section->flags |= SEC_KEEP;
13283
13284   return TRUE;
13285 }
13286
13287 /* Keep all sections containing symbols undefined on the command-line,
13288    and the section containing the entry symbol.  */
13289
13290 void
13291 _bfd_elf_gc_keep (struct bfd_link_info *info)
13292 {
13293   struct bfd_sym_chain *sym;
13294
13295   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
13296     {
13297       struct elf_link_hash_entry *h;
13298
13299       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
13300                                 FALSE, FALSE, FALSE);
13301
13302       if (h != NULL
13303           && (h->root.type == bfd_link_hash_defined
13304               || h->root.type == bfd_link_hash_defweak)
13305           && !bfd_is_abs_section (h->root.u.def.section)
13306           && !bfd_is_und_section (h->root.u.def.section))
13307         h->root.u.def.section->flags |= SEC_KEEP;
13308     }
13309 }
13310
13311 bfd_boolean
13312 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
13313                                 struct bfd_link_info *info)
13314 {
13315   bfd *ibfd = info->input_bfds;
13316
13317   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13318     {
13319       asection *sec;
13320       struct elf_reloc_cookie cookie;
13321
13322       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13323         continue;
13324       sec = ibfd->sections;
13325       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13326         continue;
13327
13328       if (!init_reloc_cookie (&cookie, info, ibfd))
13329         return FALSE;
13330
13331       for (sec = ibfd->sections; sec; sec = sec->next)
13332         {
13333           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
13334               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
13335             {
13336               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
13337               fini_reloc_cookie_rels (&cookie, sec);
13338             }
13339         }
13340     }
13341   return TRUE;
13342 }
13343
13344 /* Do mark and sweep of unused sections.  */
13345
13346 bfd_boolean
13347 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
13348 {
13349   bfd_boolean ok = TRUE;
13350   bfd *sub;
13351   elf_gc_mark_hook_fn gc_mark_hook;
13352   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13353   struct elf_link_hash_table *htab;
13354
13355   if (!bed->can_gc_sections
13356       || !is_elf_hash_table (info->hash))
13357     {
13358       _bfd_error_handler(_("Warning: gc-sections option ignored"));
13359       return TRUE;
13360     }
13361
13362   bed->gc_keep (info);
13363   htab = elf_hash_table (info);
13364
13365   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
13366      at the .eh_frame section if we can mark the FDEs individually.  */
13367   for (sub = info->input_bfds;
13368        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
13369        sub = sub->link.next)
13370     {
13371       asection *sec;
13372       struct elf_reloc_cookie cookie;
13373
13374       sec = sub->sections;
13375       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13376         continue;
13377       sec = bfd_get_section_by_name (sub, ".eh_frame");
13378       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
13379         {
13380           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
13381           if (elf_section_data (sec)->sec_info
13382               && (sec->flags & SEC_LINKER_CREATED) == 0)
13383             elf_eh_frame_section (sub) = sec;
13384           fini_reloc_cookie_for_section (&cookie, sec);
13385           sec = bfd_get_next_section_by_name (NULL, sec);
13386         }
13387     }
13388
13389   /* Apply transitive closure to the vtable entry usage info.  */
13390   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
13391   if (!ok)
13392     return FALSE;
13393
13394   /* Kill the vtable relocations that were not used.  */
13395   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
13396   if (!ok)
13397     return FALSE;
13398
13399   /* Mark dynamically referenced symbols.  */
13400   if (htab->dynamic_sections_created || info->gc_keep_exported)
13401     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
13402
13403   /* Grovel through relocs to find out who stays ...  */
13404   gc_mark_hook = bed->gc_mark_hook;
13405   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13406     {
13407       asection *o;
13408
13409       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13410           || elf_object_id (sub) != elf_hash_table_id (htab)
13411           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13412         continue;
13413
13414       o = sub->sections;
13415       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13416         continue;
13417
13418       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
13419          Also treat note sections as a root, if the section is not part
13420          of a group.  */
13421       for (o = sub->sections; o != NULL; o = o->next)
13422         if (!o->gc_mark
13423             && (o->flags & SEC_EXCLUDE) == 0
13424             && ((o->flags & SEC_KEEP) != 0
13425                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
13426                     && elf_next_in_group (o) == NULL )))
13427           {
13428             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
13429               return FALSE;
13430           }
13431     }
13432
13433   /* Allow the backend to mark additional target specific sections.  */
13434   bed->gc_mark_extra_sections (info, gc_mark_hook);
13435
13436   /* ... and mark SEC_EXCLUDE for those that go.  */
13437   return elf_gc_sweep (abfd, info);
13438 }
13439 \f
13440 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
13441
13442 bfd_boolean
13443 bfd_elf_gc_record_vtinherit (bfd *abfd,
13444                              asection *sec,
13445                              struct elf_link_hash_entry *h,
13446                              bfd_vma offset)
13447 {
13448   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
13449   struct elf_link_hash_entry **search, *child;
13450   size_t extsymcount;
13451   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13452
13453   /* The sh_info field of the symtab header tells us where the
13454      external symbols start.  We don't care about the local symbols at
13455      this point.  */
13456   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
13457   if (!elf_bad_symtab (abfd))
13458     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
13459
13460   sym_hashes = elf_sym_hashes (abfd);
13461   sym_hashes_end = sym_hashes + extsymcount;
13462
13463   /* Hunt down the child symbol, which is in this section at the same
13464      offset as the relocation.  */
13465   for (search = sym_hashes; search != sym_hashes_end; ++search)
13466     {
13467       if ((child = *search) != NULL
13468           && (child->root.type == bfd_link_hash_defined
13469               || child->root.type == bfd_link_hash_defweak)
13470           && child->root.u.def.section == sec
13471           && child->root.u.def.value == offset)
13472         goto win;
13473     }
13474
13475   /* xgettext:c-format */
13476   _bfd_error_handler (_("%B: %A+%#Lx: No symbol found for INHERIT"),
13477                       abfd, sec, offset);
13478   bfd_set_error (bfd_error_invalid_operation);
13479   return FALSE;
13480
13481  win:
13482   if (!child->u2.vtable)
13483     {
13484       child->u2.vtable = ((struct elf_link_virtual_table_entry *)
13485                           bfd_zalloc (abfd, sizeof (*child->u2.vtable)));
13486       if (!child->u2.vtable)
13487         return FALSE;
13488     }
13489   if (!h)
13490     {
13491       /* This *should* only be the absolute section.  It could potentially
13492          be that someone has defined a non-global vtable though, which
13493          would be bad.  It isn't worth paging in the local symbols to be
13494          sure though; that case should simply be handled by the assembler.  */
13495
13496       child->u2.vtable->parent = (struct elf_link_hash_entry *) -1;
13497     }
13498   else
13499     child->u2.vtable->parent = h;
13500
13501   return TRUE;
13502 }
13503
13504 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
13505
13506 bfd_boolean
13507 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
13508                            asection *sec ATTRIBUTE_UNUSED,
13509                            struct elf_link_hash_entry *h,
13510                            bfd_vma addend)
13511 {
13512   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13513   unsigned int log_file_align = bed->s->log_file_align;
13514
13515   if (!h->u2.vtable)
13516     {
13517       h->u2.vtable = ((struct elf_link_virtual_table_entry *)
13518                       bfd_zalloc (abfd, sizeof (*h->u2.vtable)));
13519       if (!h->u2.vtable)
13520         return FALSE;
13521     }
13522
13523   if (addend >= h->u2.vtable->size)
13524     {
13525       size_t size, bytes, file_align;
13526       bfd_boolean *ptr = h->u2.vtable->used;
13527
13528       /* While the symbol is undefined, we have to be prepared to handle
13529          a zero size.  */
13530       file_align = 1 << log_file_align;
13531       if (h->root.type == bfd_link_hash_undefined)
13532         size = addend + file_align;
13533       else
13534         {
13535           size = h->size;
13536           if (addend >= size)
13537             {
13538               /* Oops!  We've got a reference past the defined end of
13539                  the table.  This is probably a bug -- shall we warn?  */
13540               size = addend + file_align;
13541             }
13542         }
13543       size = (size + file_align - 1) & -file_align;
13544
13545       /* Allocate one extra entry for use as a "done" flag for the
13546          consolidation pass.  */
13547       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
13548
13549       if (ptr)
13550         {
13551           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
13552
13553           if (ptr != NULL)
13554             {
13555               size_t oldbytes;
13556
13557               oldbytes = (((h->u2.vtable->size >> log_file_align) + 1)
13558                           * sizeof (bfd_boolean));
13559               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
13560             }
13561         }
13562       else
13563         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
13564
13565       if (ptr == NULL)
13566         return FALSE;
13567
13568       /* And arrange for that done flag to be at index -1.  */
13569       h->u2.vtable->used = ptr + 1;
13570       h->u2.vtable->size = size;
13571     }
13572
13573   h->u2.vtable->used[addend >> log_file_align] = TRUE;
13574
13575   return TRUE;
13576 }
13577
13578 /* Map an ELF section header flag to its corresponding string.  */
13579 typedef struct
13580 {
13581   char *flag_name;
13582   flagword flag_value;
13583 } elf_flags_to_name_table;
13584
13585 static elf_flags_to_name_table elf_flags_to_names [] =
13586 {
13587   { "SHF_WRITE", SHF_WRITE },
13588   { "SHF_ALLOC", SHF_ALLOC },
13589   { "SHF_EXECINSTR", SHF_EXECINSTR },
13590   { "SHF_MERGE", SHF_MERGE },
13591   { "SHF_STRINGS", SHF_STRINGS },
13592   { "SHF_INFO_LINK", SHF_INFO_LINK},
13593   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
13594   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
13595   { "SHF_GROUP", SHF_GROUP },
13596   { "SHF_TLS", SHF_TLS },
13597   { "SHF_MASKOS", SHF_MASKOS },
13598   { "SHF_EXCLUDE", SHF_EXCLUDE },
13599 };
13600
13601 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
13602 bfd_boolean
13603 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
13604                               struct flag_info *flaginfo,
13605                               asection *section)
13606 {
13607   const bfd_vma sh_flags = elf_section_flags (section);
13608
13609   if (!flaginfo->flags_initialized)
13610     {
13611       bfd *obfd = info->output_bfd;
13612       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13613       struct flag_info_list *tf = flaginfo->flag_list;
13614       int with_hex = 0;
13615       int without_hex = 0;
13616
13617       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
13618         {
13619           unsigned i;
13620           flagword (*lookup) (char *);
13621
13622           lookup = bed->elf_backend_lookup_section_flags_hook;
13623           if (lookup != NULL)
13624             {
13625               flagword hexval = (*lookup) ((char *) tf->name);
13626
13627               if (hexval != 0)
13628                 {
13629                   if (tf->with == with_flags)
13630                     with_hex |= hexval;
13631                   else if (tf->with == without_flags)
13632                     without_hex |= hexval;
13633                   tf->valid = TRUE;
13634                   continue;
13635                 }
13636             }
13637           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
13638             {
13639               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
13640                 {
13641                   if (tf->with == with_flags)
13642                     with_hex |= elf_flags_to_names[i].flag_value;
13643                   else if (tf->with == without_flags)
13644                     without_hex |= elf_flags_to_names[i].flag_value;
13645                   tf->valid = TRUE;
13646                   break;
13647                 }
13648             }
13649           if (!tf->valid)
13650             {
13651               info->callbacks->einfo
13652                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
13653               return FALSE;
13654             }
13655         }
13656       flaginfo->flags_initialized = TRUE;
13657       flaginfo->only_with_flags |= with_hex;
13658       flaginfo->not_with_flags |= without_hex;
13659     }
13660
13661   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
13662     return FALSE;
13663
13664   if ((flaginfo->not_with_flags & sh_flags) != 0)
13665     return FALSE;
13666
13667   return TRUE;
13668 }
13669
13670 struct alloc_got_off_arg {
13671   bfd_vma gotoff;
13672   struct bfd_link_info *info;
13673 };
13674
13675 /* We need a special top-level link routine to convert got reference counts
13676    to real got offsets.  */
13677
13678 static bfd_boolean
13679 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
13680 {
13681   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
13682   bfd *obfd = gofarg->info->output_bfd;
13683   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13684
13685   if (h->got.refcount > 0)
13686     {
13687       h->got.offset = gofarg->gotoff;
13688       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
13689     }
13690   else
13691     h->got.offset = (bfd_vma) -1;
13692
13693   return TRUE;
13694 }
13695
13696 /* And an accompanying bit to work out final got entry offsets once
13697    we're done.  Should be called from final_link.  */
13698
13699 bfd_boolean
13700 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
13701                                         struct bfd_link_info *info)
13702 {
13703   bfd *i;
13704   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13705   bfd_vma gotoff;
13706   struct alloc_got_off_arg gofarg;
13707
13708   BFD_ASSERT (abfd == info->output_bfd);
13709
13710   if (! is_elf_hash_table (info->hash))
13711     return FALSE;
13712
13713   /* The GOT offset is relative to the .got section, but the GOT header is
13714      put into the .got.plt section, if the backend uses it.  */
13715   if (bed->want_got_plt)
13716     gotoff = 0;
13717   else
13718     gotoff = bed->got_header_size;
13719
13720   /* Do the local .got entries first.  */
13721   for (i = info->input_bfds; i; i = i->link.next)
13722     {
13723       bfd_signed_vma *local_got;
13724       size_t j, locsymcount;
13725       Elf_Internal_Shdr *symtab_hdr;
13726
13727       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13728         continue;
13729
13730       local_got = elf_local_got_refcounts (i);
13731       if (!local_got)
13732         continue;
13733
13734       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13735       if (elf_bad_symtab (i))
13736         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13737       else
13738         locsymcount = symtab_hdr->sh_info;
13739
13740       for (j = 0; j < locsymcount; ++j)
13741         {
13742           if (local_got[j] > 0)
13743             {
13744               local_got[j] = gotoff;
13745               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13746             }
13747           else
13748             local_got[j] = (bfd_vma) -1;
13749         }
13750     }
13751
13752   /* Then the global .got entries.  .plt refcounts are handled by
13753      adjust_dynamic_symbol  */
13754   gofarg.gotoff = gotoff;
13755   gofarg.info = info;
13756   elf_link_hash_traverse (elf_hash_table (info),
13757                           elf_gc_allocate_got_offsets,
13758                           &gofarg);
13759   return TRUE;
13760 }
13761
13762 /* Many folk need no more in the way of final link than this, once
13763    got entry reference counting is enabled.  */
13764
13765 bfd_boolean
13766 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
13767 {
13768   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
13769     return FALSE;
13770
13771   /* Invoke the regular ELF backend linker to do all the work.  */
13772   return bfd_elf_final_link (abfd, info);
13773 }
13774
13775 bfd_boolean
13776 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
13777 {
13778   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
13779
13780   if (rcookie->bad_symtab)
13781     rcookie->rel = rcookie->rels;
13782
13783   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
13784     {
13785       unsigned long r_symndx;
13786
13787       if (! rcookie->bad_symtab)
13788         if (rcookie->rel->r_offset > offset)
13789           return FALSE;
13790       if (rcookie->rel->r_offset != offset)
13791         continue;
13792
13793       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
13794       if (r_symndx == STN_UNDEF)
13795         return TRUE;
13796
13797       if (r_symndx >= rcookie->locsymcount
13798           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13799         {
13800           struct elf_link_hash_entry *h;
13801
13802           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
13803
13804           while (h->root.type == bfd_link_hash_indirect
13805                  || h->root.type == bfd_link_hash_warning)
13806             h = (struct elf_link_hash_entry *) h->root.u.i.link;
13807
13808           if ((h->root.type == bfd_link_hash_defined
13809                || h->root.type == bfd_link_hash_defweak)
13810               && (h->root.u.def.section->owner != rcookie->abfd
13811                   || h->root.u.def.section->kept_section != NULL
13812                   || discarded_section (h->root.u.def.section)))
13813             return TRUE;
13814         }
13815       else
13816         {
13817           /* It's not a relocation against a global symbol,
13818              but it could be a relocation against a local
13819              symbol for a discarded section.  */
13820           asection *isec;
13821           Elf_Internal_Sym *isym;
13822
13823           /* Need to: get the symbol; get the section.  */
13824           isym = &rcookie->locsyms[r_symndx];
13825           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
13826           if (isec != NULL
13827               && (isec->kept_section != NULL
13828                   || discarded_section (isec)))
13829             return TRUE;
13830         }
13831       return FALSE;
13832     }
13833   return FALSE;
13834 }
13835
13836 /* Discard unneeded references to discarded sections.
13837    Returns -1 on error, 1 if any section's size was changed, 0 if
13838    nothing changed.  This function assumes that the relocations are in
13839    sorted order, which is true for all known assemblers.  */
13840
13841 int
13842 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
13843 {
13844   struct elf_reloc_cookie cookie;
13845   asection *o;
13846   bfd *abfd;
13847   int changed = 0;
13848
13849   if (info->traditional_format
13850       || !is_elf_hash_table (info->hash))
13851     return 0;
13852
13853   o = bfd_get_section_by_name (output_bfd, ".stab");
13854   if (o != NULL)
13855     {
13856       asection *i;
13857
13858       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13859         {
13860           if (i->size == 0
13861               || i->reloc_count == 0
13862               || i->sec_info_type != SEC_INFO_TYPE_STABS)
13863             continue;
13864
13865           abfd = i->owner;
13866           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13867             continue;
13868
13869           if (!init_reloc_cookie_for_section (&cookie, info, i))
13870             return -1;
13871
13872           if (_bfd_discard_section_stabs (abfd, i,
13873                                           elf_section_data (i)->sec_info,
13874                                           bfd_elf_reloc_symbol_deleted_p,
13875                                           &cookie))
13876             changed = 1;
13877
13878           fini_reloc_cookie_for_section (&cookie, i);
13879         }
13880     }
13881
13882   o = NULL;
13883   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
13884     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
13885   if (o != NULL)
13886     {
13887       asection *i;
13888       int eh_changed = 0;
13889       unsigned int eh_alignment;
13890
13891       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13892         {
13893           if (i->size == 0)
13894             continue;
13895
13896           abfd = i->owner;
13897           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13898             continue;
13899
13900           if (!init_reloc_cookie_for_section (&cookie, info, i))
13901             return -1;
13902
13903           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
13904           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
13905                                                  bfd_elf_reloc_symbol_deleted_p,
13906                                                  &cookie))
13907             {
13908               eh_changed = 1;
13909               if (i->size != i->rawsize)
13910                 changed = 1;
13911             }
13912
13913           fini_reloc_cookie_for_section (&cookie, i);
13914         }
13915
13916       eh_alignment = 1 << o->alignment_power;
13917       /* Skip over zero terminator, and prevent empty sections from
13918          adding alignment padding at the end.  */
13919       for (i = o->map_tail.s; i != NULL; i = i->map_tail.s)
13920         if (i->size == 0)
13921           i->flags |= SEC_EXCLUDE;
13922         else if (i->size > 4)
13923           break;
13924       /* The last non-empty eh_frame section doesn't need padding.  */
13925       if (i != NULL)
13926         i = i->map_tail.s;
13927       /* Any prior sections must pad the last FDE out to the output
13928          section alignment.  Otherwise we might have zero padding
13929          between sections, which would be seen as a terminator.  */
13930       for (; i != NULL; i = i->map_tail.s)
13931         if (i->size == 4)
13932           /* All but the last zero terminator should have been removed.  */
13933           BFD_FAIL ();
13934         else
13935           {
13936             bfd_size_type size
13937               = (i->size + eh_alignment - 1) & -eh_alignment;
13938             if (i->size != size)
13939               {
13940                 i->size = size;
13941                 changed = 1;
13942                 eh_changed = 1;
13943               }
13944           }
13945       if (eh_changed)
13946         elf_link_hash_traverse (elf_hash_table (info),
13947                                 _bfd_elf_adjust_eh_frame_global_symbol, NULL);
13948     }
13949
13950   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
13951     {
13952       const struct elf_backend_data *bed;
13953       asection *s;
13954
13955       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13956         continue;
13957       s = abfd->sections;
13958       if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13959         continue;
13960
13961       bed = get_elf_backend_data (abfd);
13962
13963       if (bed->elf_backend_discard_info != NULL)
13964         {
13965           if (!init_reloc_cookie (&cookie, info, abfd))
13966             return -1;
13967
13968           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
13969             changed = 1;
13970
13971           fini_reloc_cookie (&cookie, abfd);
13972         }
13973     }
13974
13975   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
13976     _bfd_elf_end_eh_frame_parsing (info);
13977
13978   if (info->eh_frame_hdr_type
13979       && !bfd_link_relocatable (info)
13980       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
13981     changed = 1;
13982
13983   return changed;
13984 }
13985
13986 bfd_boolean
13987 _bfd_elf_section_already_linked (bfd *abfd,
13988                                  asection *sec,
13989                                  struct bfd_link_info *info)
13990 {
13991   flagword flags;
13992   const char *name, *key;
13993   struct bfd_section_already_linked *l;
13994   struct bfd_section_already_linked_hash_entry *already_linked_list;
13995
13996   if (sec->output_section == bfd_abs_section_ptr)
13997     return FALSE;
13998
13999   flags = sec->flags;
14000
14001   /* Return if it isn't a linkonce section.  A comdat group section
14002      also has SEC_LINK_ONCE set.  */
14003   if ((flags & SEC_LINK_ONCE) == 0)
14004     return FALSE;
14005
14006   /* Don't put group member sections on our list of already linked
14007      sections.  They are handled as a group via their group section.  */
14008   if (elf_sec_group (sec) != NULL)
14009     return FALSE;
14010
14011   /* For a SHT_GROUP section, use the group signature as the key.  */
14012   name = sec->name;
14013   if ((flags & SEC_GROUP) != 0
14014       && elf_next_in_group (sec) != NULL
14015       && elf_group_name (elf_next_in_group (sec)) != NULL)
14016     key = elf_group_name (elf_next_in_group (sec));
14017   else
14018     {
14019       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
14020       if (CONST_STRNEQ (name, ".gnu.linkonce.")
14021           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
14022         key++;
14023       else
14024         /* Must be a user linkonce section that doesn't follow gcc's
14025            naming convention.  In this case we won't be matching
14026            single member groups.  */
14027         key = name;
14028     }
14029
14030   already_linked_list = bfd_section_already_linked_table_lookup (key);
14031
14032   for (l = already_linked_list->entry; l != NULL; l = l->next)
14033     {
14034       /* We may have 2 different types of sections on the list: group
14035          sections with a signature of <key> (<key> is some string),
14036          and linkonce sections named .gnu.linkonce.<type>.<key>.
14037          Match like sections.  LTO plugin sections are an exception.
14038          They are always named .gnu.linkonce.t.<key> and match either
14039          type of section.  */
14040       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
14041            && ((flags & SEC_GROUP) != 0
14042                || strcmp (name, l->sec->name) == 0))
14043           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
14044         {
14045           /* The section has already been linked.  See if we should
14046              issue a warning.  */
14047           if (!_bfd_handle_already_linked (sec, l, info))
14048             return FALSE;
14049
14050           if (flags & SEC_GROUP)
14051             {
14052               asection *first = elf_next_in_group (sec);
14053               asection *s = first;
14054
14055               while (s != NULL)
14056                 {
14057                   s->output_section = bfd_abs_section_ptr;
14058                   /* Record which group discards it.  */
14059                   s->kept_section = l->sec;
14060                   s = elf_next_in_group (s);
14061                   /* These lists are circular.  */
14062                   if (s == first)
14063                     break;
14064                 }
14065             }
14066
14067           return TRUE;
14068         }
14069     }
14070
14071   /* A single member comdat group section may be discarded by a
14072      linkonce section and vice versa.  */
14073   if ((flags & SEC_GROUP) != 0)
14074     {
14075       asection *first = elf_next_in_group (sec);
14076
14077       if (first != NULL && elf_next_in_group (first) == first)
14078         /* Check this single member group against linkonce sections.  */
14079         for (l = already_linked_list->entry; l != NULL; l = l->next)
14080           if ((l->sec->flags & SEC_GROUP) == 0
14081               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
14082             {
14083               first->output_section = bfd_abs_section_ptr;
14084               first->kept_section = l->sec;
14085               sec->output_section = bfd_abs_section_ptr;
14086               break;
14087             }
14088     }
14089   else
14090     /* Check this linkonce section against single member groups.  */
14091     for (l = already_linked_list->entry; l != NULL; l = l->next)
14092       if (l->sec->flags & SEC_GROUP)
14093         {
14094           asection *first = elf_next_in_group (l->sec);
14095
14096           if (first != NULL
14097               && elf_next_in_group (first) == first
14098               && bfd_elf_match_symbols_in_sections (first, sec, info))
14099             {
14100               sec->output_section = bfd_abs_section_ptr;
14101               sec->kept_section = first;
14102               break;
14103             }
14104         }
14105
14106   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
14107      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
14108      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
14109      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
14110      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
14111      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
14112      `.gnu.linkonce.t.F' section from a different bfd not requiring any
14113      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
14114      The reverse order cannot happen as there is never a bfd with only the
14115      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
14116      matter as here were are looking only for cross-bfd sections.  */
14117
14118   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
14119     for (l = already_linked_list->entry; l != NULL; l = l->next)
14120       if ((l->sec->flags & SEC_GROUP) == 0
14121           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
14122         {
14123           if (abfd != l->sec->owner)
14124             sec->output_section = bfd_abs_section_ptr;
14125           break;
14126         }
14127
14128   /* This is the first section with this name.  Record it.  */
14129   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
14130     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
14131   return sec->output_section == bfd_abs_section_ptr;
14132 }
14133
14134 bfd_boolean
14135 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
14136 {
14137   return sym->st_shndx == SHN_COMMON;
14138 }
14139
14140 unsigned int
14141 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
14142 {
14143   return SHN_COMMON;
14144 }
14145
14146 asection *
14147 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
14148 {
14149   return bfd_com_section_ptr;
14150 }
14151
14152 bfd_vma
14153 _bfd_elf_default_got_elt_size (bfd *abfd,
14154                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
14155                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
14156                                bfd *ibfd ATTRIBUTE_UNUSED,
14157                                unsigned long symndx ATTRIBUTE_UNUSED)
14158 {
14159   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14160   return bed->s->arch_size / 8;
14161 }
14162
14163 /* Routines to support the creation of dynamic relocs.  */
14164
14165 /* Returns the name of the dynamic reloc section associated with SEC.  */
14166
14167 static const char *
14168 get_dynamic_reloc_section_name (bfd *       abfd,
14169                                 asection *  sec,
14170                                 bfd_boolean is_rela)
14171 {
14172   char *name;
14173   const char *old_name = bfd_get_section_name (NULL, sec);
14174   const char *prefix = is_rela ? ".rela" : ".rel";
14175
14176   if (old_name == NULL)
14177     return NULL;
14178
14179   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
14180   sprintf (name, "%s%s", prefix, old_name);
14181
14182   return name;
14183 }
14184
14185 /* Returns the dynamic reloc section associated with SEC.
14186    If necessary compute the name of the dynamic reloc section based
14187    on SEC's name (looked up in ABFD's string table) and the setting
14188    of IS_RELA.  */
14189
14190 asection *
14191 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
14192                                     asection *  sec,
14193                                     bfd_boolean is_rela)
14194 {
14195   asection * reloc_sec = elf_section_data (sec)->sreloc;
14196
14197   if (reloc_sec == NULL)
14198     {
14199       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14200
14201       if (name != NULL)
14202         {
14203           reloc_sec = bfd_get_linker_section (abfd, name);
14204
14205           if (reloc_sec != NULL)
14206             elf_section_data (sec)->sreloc = reloc_sec;
14207         }
14208     }
14209
14210   return reloc_sec;
14211 }
14212
14213 /* Returns the dynamic reloc section associated with SEC.  If the
14214    section does not exist it is created and attached to the DYNOBJ
14215    bfd and stored in the SRELOC field of SEC's elf_section_data
14216    structure.
14217
14218    ALIGNMENT is the alignment for the newly created section and
14219    IS_RELA defines whether the name should be .rela.<SEC's name>
14220    or .rel.<SEC's name>.  The section name is looked up in the
14221    string table associated with ABFD.  */
14222
14223 asection *
14224 _bfd_elf_make_dynamic_reloc_section (asection *sec,
14225                                      bfd *dynobj,
14226                                      unsigned int alignment,
14227                                      bfd *abfd,
14228                                      bfd_boolean is_rela)
14229 {
14230   asection * reloc_sec = elf_section_data (sec)->sreloc;
14231
14232   if (reloc_sec == NULL)
14233     {
14234       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14235
14236       if (name == NULL)
14237         return NULL;
14238
14239       reloc_sec = bfd_get_linker_section (dynobj, name);
14240
14241       if (reloc_sec == NULL)
14242         {
14243           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
14244                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
14245           if ((sec->flags & SEC_ALLOC) != 0)
14246             flags |= SEC_ALLOC | SEC_LOAD;
14247
14248           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
14249           if (reloc_sec != NULL)
14250             {
14251               /* _bfd_elf_get_sec_type_attr chooses a section type by
14252                  name.  Override as it may be wrong, eg. for a user
14253                  section named "auto" we'll get ".relauto" which is
14254                  seen to be a .rela section.  */
14255               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
14256               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
14257                 reloc_sec = NULL;
14258             }
14259         }
14260
14261       elf_section_data (sec)->sreloc = reloc_sec;
14262     }
14263
14264   return reloc_sec;
14265 }
14266
14267 /* Copy the ELF symbol type and other attributes for a linker script
14268    assignment from HSRC to HDEST.  Generally this should be treated as
14269    if we found a strong non-dynamic definition for HDEST (except that
14270    ld ignores multiple definition errors).  */
14271 void
14272 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
14273                                      struct bfd_link_hash_entry *hdest,
14274                                      struct bfd_link_hash_entry *hsrc)
14275 {
14276   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
14277   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
14278   Elf_Internal_Sym isym;
14279
14280   ehdest->type = ehsrc->type;
14281   ehdest->target_internal = ehsrc->target_internal;
14282
14283   isym.st_other = ehsrc->other;
14284   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
14285 }
14286
14287 /* Append a RELA relocation REL to section S in BFD.  */
14288
14289 void
14290 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14291 {
14292   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14293   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
14294   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
14295   bed->s->swap_reloca_out (abfd, rel, loc);
14296 }
14297
14298 /* Append a REL relocation REL to section S in BFD.  */
14299
14300 void
14301 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14302 {
14303   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14304   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
14305   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
14306   bed->s->swap_reloc_out (abfd, rel, loc);
14307 }
14308
14309 /* Define __start, __stop, .startof. or .sizeof. symbol.  */
14310
14311 struct bfd_link_hash_entry *
14312 bfd_elf_define_start_stop (struct bfd_link_info *info,
14313                            const char *symbol, asection *sec)
14314 {
14315   struct elf_link_hash_entry *h;
14316
14317   h = elf_link_hash_lookup (elf_hash_table (info), symbol,
14318                             FALSE, FALSE, TRUE);
14319   if (h != NULL
14320       && (h->root.type == bfd_link_hash_undefined
14321           || h->root.type == bfd_link_hash_undefweak
14322           || (h->ref_regular && !h->def_regular)))
14323     {
14324       h->root.type = bfd_link_hash_defined;
14325       h->root.u.def.section = sec;
14326       h->root.u.def.value = 0;
14327       h->def_regular = 1;
14328       h->def_dynamic = 0;
14329       h->start_stop = 1;
14330       h->u2.start_stop_section = sec;
14331       if (symbol[0] == '.')
14332         {
14333           /* .startof. and .sizeof. symbols are local.  */
14334           const struct elf_backend_data *bed;
14335           bed = get_elf_backend_data (info->output_bfd);
14336           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
14337         }
14338       else if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
14339         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_PROTECTED;
14340       return &h->root;
14341     }
14342   return NULL;
14343 }