Don't attach linker created section to --just-syms bfd
[external/binutils.git] / bfd / elflink.c
1 /* ELF linking support for BFD.
2    Copyright (C) 1995-2017 Free Software Foundation, Inc.
3
4    This file is part of BFD, the Binary File Descriptor library.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
19    MA 02110-1301, USA.  */
20
21 #include "sysdep.h"
22 #include "bfd.h"
23 #include "bfd_stdint.h"
24 #include "bfdlink.h"
25 #include "libbfd.h"
26 #define ARCH_SIZE 0
27 #include "elf-bfd.h"
28 #include "safe-ctype.h"
29 #include "libiberty.h"
30 #include "objalloc.h"
31 #if BFD_SUPPORTS_PLUGINS
32 #include "plugin-api.h"
33 #include "plugin.h"
34 #endif
35
36 /* This struct is used to pass information to routines called via
37    elf_link_hash_traverse which must return failure.  */
38
39 struct elf_info_failed
40 {
41   struct bfd_link_info *info;
42   bfd_boolean failed;
43 };
44
45 /* This structure is used to pass information to
46    _bfd_elf_link_find_version_dependencies.  */
47
48 struct elf_find_verdep_info
49 {
50   /* General link information.  */
51   struct bfd_link_info *info;
52   /* The number of dependencies.  */
53   unsigned int vers;
54   /* Whether we had a failure.  */
55   bfd_boolean failed;
56 };
57
58 static bfd_boolean _bfd_elf_fix_symbol_flags
59   (struct elf_link_hash_entry *, struct elf_info_failed *);
60
61 asection *
62 _bfd_elf_section_for_symbol (struct elf_reloc_cookie *cookie,
63                              unsigned long r_symndx,
64                              bfd_boolean discard)
65 {
66   if (r_symndx >= cookie->locsymcount
67       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
68     {
69       struct elf_link_hash_entry *h;
70
71       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
72
73       while (h->root.type == bfd_link_hash_indirect
74              || h->root.type == bfd_link_hash_warning)
75         h = (struct elf_link_hash_entry *) h->root.u.i.link;
76
77       if ((h->root.type == bfd_link_hash_defined
78            || h->root.type == bfd_link_hash_defweak)
79            && discarded_section (h->root.u.def.section))
80         return h->root.u.def.section;
81       else
82         return NULL;
83     }
84   else
85     {
86       /* It's not a relocation against a global symbol,
87          but it could be a relocation against a local
88          symbol for a discarded section.  */
89       asection *isec;
90       Elf_Internal_Sym *isym;
91
92       /* Need to: get the symbol; get the section.  */
93       isym = &cookie->locsyms[r_symndx];
94       isec = bfd_section_from_elf_index (cookie->abfd, isym->st_shndx);
95       if (isec != NULL
96           && discard ? discarded_section (isec) : 1)
97         return isec;
98      }
99   return NULL;
100 }
101
102 /* Define a symbol in a dynamic linkage section.  */
103
104 struct elf_link_hash_entry *
105 _bfd_elf_define_linkage_sym (bfd *abfd,
106                              struct bfd_link_info *info,
107                              asection *sec,
108                              const char *name)
109 {
110   struct elf_link_hash_entry *h;
111   struct bfd_link_hash_entry *bh;
112   const struct elf_backend_data *bed;
113
114   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, FALSE);
115   if (h != NULL)
116     {
117       /* Zap symbol defined in an as-needed lib that wasn't linked.
118          This is a symptom of a larger problem:  Absolute symbols
119          defined in shared libraries can't be overridden, because we
120          lose the link to the bfd which is via the symbol section.  */
121       h->root.type = bfd_link_hash_new;
122       bh = &h->root;
123     }
124   else
125     bh = NULL;
126
127   bed = get_elf_backend_data (abfd);
128   if (!_bfd_generic_link_add_one_symbol (info, abfd, name, BSF_GLOBAL,
129                                          sec, 0, NULL, FALSE, bed->collect,
130                                          &bh))
131     return NULL;
132   h = (struct elf_link_hash_entry *) bh;
133   BFD_ASSERT (h != NULL);
134   h->def_regular = 1;
135   h->non_elf = 0;
136   h->root.linker_def = 1;
137   h->type = STT_OBJECT;
138   if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
139     h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
140
141   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
142   return h;
143 }
144
145 bfd_boolean
146 _bfd_elf_create_got_section (bfd *abfd, struct bfd_link_info *info)
147 {
148   flagword flags;
149   asection *s;
150   struct elf_link_hash_entry *h;
151   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
152   struct elf_link_hash_table *htab = elf_hash_table (info);
153
154   /* This function may be called more than once.  */
155   if (htab->sgot != NULL)
156     return TRUE;
157
158   flags = bed->dynamic_sec_flags;
159
160   s = bfd_make_section_anyway_with_flags (abfd,
161                                           (bed->rela_plts_and_copies_p
162                                            ? ".rela.got" : ".rel.got"),
163                                           (bed->dynamic_sec_flags
164                                            | SEC_READONLY));
165   if (s == NULL
166       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
167     return FALSE;
168   htab->srelgot = s;
169
170   s = bfd_make_section_anyway_with_flags (abfd, ".got", flags);
171   if (s == NULL
172       || !bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
173     return FALSE;
174   htab->sgot = s;
175
176   if (bed->want_got_plt)
177     {
178       s = bfd_make_section_anyway_with_flags (abfd, ".got.plt", flags);
179       if (s == NULL
180           || !bfd_set_section_alignment (abfd, s,
181                                          bed->s->log_file_align))
182         return FALSE;
183       htab->sgotplt = s;
184     }
185
186   /* The first bit of the global offset table is the header.  */
187   s->size += bed->got_header_size;
188
189   if (bed->want_got_sym)
190     {
191       /* Define the symbol _GLOBAL_OFFSET_TABLE_ at the start of the .got
192          (or .got.plt) section.  We don't do this in the linker script
193          because we don't want to define the symbol if we are not creating
194          a global offset table.  */
195       h = _bfd_elf_define_linkage_sym (abfd, info, s,
196                                        "_GLOBAL_OFFSET_TABLE_");
197       elf_hash_table (info)->hgot = h;
198       if (h == NULL)
199         return FALSE;
200     }
201
202   return TRUE;
203 }
204 \f
205 /* Create a strtab to hold the dynamic symbol names.  */
206 static bfd_boolean
207 _bfd_elf_link_create_dynstrtab (bfd *abfd, struct bfd_link_info *info)
208 {
209   struct elf_link_hash_table *hash_table;
210
211   hash_table = elf_hash_table (info);
212   if (hash_table->dynobj == NULL)
213     {
214       /* We may not set dynobj, an input file holding linker created
215          dynamic sections to abfd, which may be a dynamic object with
216          its own dynamic sections.  We need to find a normal input file
217          to hold linker created sections if possible.  */
218       if ((abfd->flags & (DYNAMIC | BFD_PLUGIN)) != 0)
219         {
220           bfd *ibfd;
221           asection *s;
222           for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link.next)
223             if ((ibfd->flags
224                  & (DYNAMIC | BFD_LINKER_CREATED | BFD_PLUGIN)) == 0
225                 && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
226                 && !((s = ibfd->sections) != NULL
227                      && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS))
228               {
229                 abfd = ibfd;
230                 break;
231               }
232         }
233       hash_table->dynobj = abfd;
234     }
235
236   if (hash_table->dynstr == NULL)
237     {
238       hash_table->dynstr = _bfd_elf_strtab_init ();
239       if (hash_table->dynstr == NULL)
240         return FALSE;
241     }
242   return TRUE;
243 }
244
245 /* Create some sections which will be filled in with dynamic linking
246    information.  ABFD is an input file which requires dynamic sections
247    to be created.  The dynamic sections take up virtual memory space
248    when the final executable is run, so we need to create them before
249    addresses are assigned to the output sections.  We work out the
250    actual contents and size of these sections later.  */
251
252 bfd_boolean
253 _bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
254 {
255   flagword flags;
256   asection *s;
257   const struct elf_backend_data *bed;
258   struct elf_link_hash_entry *h;
259
260   if (! is_elf_hash_table (info->hash))
261     return FALSE;
262
263   if (elf_hash_table (info)->dynamic_sections_created)
264     return TRUE;
265
266   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
267     return FALSE;
268
269   abfd = elf_hash_table (info)->dynobj;
270   bed = get_elf_backend_data (abfd);
271
272   flags = bed->dynamic_sec_flags;
273
274   /* A dynamically linked executable has a .interp section, but a
275      shared library does not.  */
276   if (bfd_link_executable (info) && !info->nointerp)
277     {
278       s = bfd_make_section_anyway_with_flags (abfd, ".interp",
279                                               flags | SEC_READONLY);
280       if (s == NULL)
281         return FALSE;
282     }
283
284   /* Create sections to hold version informations.  These are removed
285      if they are not needed.  */
286   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_d",
287                                           flags | SEC_READONLY);
288   if (s == NULL
289       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
290     return FALSE;
291
292   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version",
293                                           flags | SEC_READONLY);
294   if (s == NULL
295       || ! bfd_set_section_alignment (abfd, s, 1))
296     return FALSE;
297
298   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_r",
299                                           flags | SEC_READONLY);
300   if (s == NULL
301       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
302     return FALSE;
303
304   s = bfd_make_section_anyway_with_flags (abfd, ".dynsym",
305                                           flags | SEC_READONLY);
306   if (s == NULL
307       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
308     return FALSE;
309   elf_hash_table (info)->dynsym = s;
310
311   s = bfd_make_section_anyway_with_flags (abfd, ".dynstr",
312                                           flags | SEC_READONLY);
313   if (s == NULL)
314     return FALSE;
315
316   s = bfd_make_section_anyway_with_flags (abfd, ".dynamic", flags);
317   if (s == NULL
318       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
319     return FALSE;
320
321   /* The special symbol _DYNAMIC is always set to the start of the
322      .dynamic section.  We could set _DYNAMIC in a linker script, but we
323      only want to define it if we are, in fact, creating a .dynamic
324      section.  We don't want to define it if there is no .dynamic
325      section, since on some ELF platforms the start up code examines it
326      to decide how to initialize the process.  */
327   h = _bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC");
328   elf_hash_table (info)->hdynamic = h;
329   if (h == NULL)
330     return FALSE;
331
332   if (info->emit_hash)
333     {
334       s = bfd_make_section_anyway_with_flags (abfd, ".hash",
335                                               flags | SEC_READONLY);
336       if (s == NULL
337           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
338         return FALSE;
339       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
340     }
341
342   if (info->emit_gnu_hash)
343     {
344       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
345                                               flags | SEC_READONLY);
346       if (s == NULL
347           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
348         return FALSE;
349       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
350          4 32-bit words followed by variable count of 64-bit words, then
351          variable count of 32-bit words.  */
352       if (bed->s->arch_size == 64)
353         elf_section_data (s)->this_hdr.sh_entsize = 0;
354       else
355         elf_section_data (s)->this_hdr.sh_entsize = 4;
356     }
357
358   /* Let the backend create the rest of the sections.  This lets the
359      backend set the right flags.  The backend will normally create
360      the .got and .plt sections.  */
361   if (bed->elf_backend_create_dynamic_sections == NULL
362       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
363     return FALSE;
364
365   elf_hash_table (info)->dynamic_sections_created = TRUE;
366
367   return TRUE;
368 }
369
370 /* Create dynamic sections when linking against a dynamic object.  */
371
372 bfd_boolean
373 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
374 {
375   flagword flags, pltflags;
376   struct elf_link_hash_entry *h;
377   asection *s;
378   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
379   struct elf_link_hash_table *htab = elf_hash_table (info);
380
381   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
382      .rel[a].bss sections.  */
383   flags = bed->dynamic_sec_flags;
384
385   pltflags = flags;
386   if (bed->plt_not_loaded)
387     /* We do not clear SEC_ALLOC here because we still want the OS to
388        allocate space for the section; it's just that there's nothing
389        to read in from the object file.  */
390     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
391   else
392     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
393   if (bed->plt_readonly)
394     pltflags |= SEC_READONLY;
395
396   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
397   if (s == NULL
398       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
399     return FALSE;
400   htab->splt = s;
401
402   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
403      .plt section.  */
404   if (bed->want_plt_sym)
405     {
406       h = _bfd_elf_define_linkage_sym (abfd, info, s,
407                                        "_PROCEDURE_LINKAGE_TABLE_");
408       elf_hash_table (info)->hplt = h;
409       if (h == NULL)
410         return FALSE;
411     }
412
413   s = bfd_make_section_anyway_with_flags (abfd,
414                                           (bed->rela_plts_and_copies_p
415                                            ? ".rela.plt" : ".rel.plt"),
416                                           flags | SEC_READONLY);
417   if (s == NULL
418       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
419     return FALSE;
420   htab->srelplt = s;
421
422   if (! _bfd_elf_create_got_section (abfd, info))
423     return FALSE;
424
425   if (bed->want_dynbss)
426     {
427       /* The .dynbss section is a place to put symbols which are defined
428          by dynamic objects, are referenced by regular objects, and are
429          not functions.  We must allocate space for them in the process
430          image and use a R_*_COPY reloc to tell the dynamic linker to
431          initialize them at run time.  The linker script puts the .dynbss
432          section into the .bss section of the final image.  */
433       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
434                                               SEC_ALLOC | SEC_LINKER_CREATED);
435       if (s == NULL)
436         return FALSE;
437       htab->sdynbss = s;
438
439       if (bed->want_dynrelro)
440         {
441           /* Similarly, but for symbols that were originally in read-only
442              sections.  This section doesn't really need to have contents,
443              but make it like other .data.rel.ro sections.  */
444           s = bfd_make_section_anyway_with_flags (abfd, ".data.rel.ro",
445                                                   flags);
446           if (s == NULL)
447             return FALSE;
448           htab->sdynrelro = s;
449         }
450
451       /* The .rel[a].bss section holds copy relocs.  This section is not
452          normally needed.  We need to create it here, though, so that the
453          linker will map it to an output section.  We can't just create it
454          only if we need it, because we will not know whether we need it
455          until we have seen all the input files, and the first time the
456          main linker code calls BFD after examining all the input files
457          (size_dynamic_sections) the input sections have already been
458          mapped to the output sections.  If the section turns out not to
459          be needed, we can discard it later.  We will never need this
460          section when generating a shared object, since they do not use
461          copy relocs.  */
462       if (bfd_link_executable (info))
463         {
464           s = bfd_make_section_anyway_with_flags (abfd,
465                                                   (bed->rela_plts_and_copies_p
466                                                    ? ".rela.bss" : ".rel.bss"),
467                                                   flags | SEC_READONLY);
468           if (s == NULL
469               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
470             return FALSE;
471           htab->srelbss = s;
472
473           if (bed->want_dynrelro)
474             {
475               s = (bfd_make_section_anyway_with_flags
476                    (abfd, (bed->rela_plts_and_copies_p
477                            ? ".rela.data.rel.ro" : ".rel.data.rel.ro"),
478                     flags | SEC_READONLY));
479               if (s == NULL
480                   || ! bfd_set_section_alignment (abfd, s,
481                                                   bed->s->log_file_align))
482                 return FALSE;
483               htab->sreldynrelro = s;
484             }
485         }
486     }
487
488   return TRUE;
489 }
490 \f
491 /* Record a new dynamic symbol.  We record the dynamic symbols as we
492    read the input files, since we need to have a list of all of them
493    before we can determine the final sizes of the output sections.
494    Note that we may actually call this function even though we are not
495    going to output any dynamic symbols; in some cases we know that a
496    symbol should be in the dynamic symbol table, but only if there is
497    one.  */
498
499 bfd_boolean
500 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
501                                     struct elf_link_hash_entry *h)
502 {
503   if (h->dynindx == -1)
504     {
505       struct elf_strtab_hash *dynstr;
506       char *p;
507       const char *name;
508       size_t indx;
509
510       /* XXX: The ABI draft says the linker must turn hidden and
511          internal symbols into STB_LOCAL symbols when producing the
512          DSO. However, if ld.so honors st_other in the dynamic table,
513          this would not be necessary.  */
514       switch (ELF_ST_VISIBILITY (h->other))
515         {
516         case STV_INTERNAL:
517         case STV_HIDDEN:
518           if (h->root.type != bfd_link_hash_undefined
519               && h->root.type != bfd_link_hash_undefweak)
520             {
521               h->forced_local = 1;
522               if (!elf_hash_table (info)->is_relocatable_executable)
523                 return TRUE;
524             }
525
526         default:
527           break;
528         }
529
530       h->dynindx = elf_hash_table (info)->dynsymcount;
531       ++elf_hash_table (info)->dynsymcount;
532
533       dynstr = elf_hash_table (info)->dynstr;
534       if (dynstr == NULL)
535         {
536           /* Create a strtab to hold the dynamic symbol names.  */
537           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
538           if (dynstr == NULL)
539             return FALSE;
540         }
541
542       /* We don't put any version information in the dynamic string
543          table.  */
544       name = h->root.root.string;
545       p = strchr (name, ELF_VER_CHR);
546       if (p != NULL)
547         /* We know that the p points into writable memory.  In fact,
548            there are only a few symbols that have read-only names, being
549            those like _GLOBAL_OFFSET_TABLE_ that are created specially
550            by the backends.  Most symbols will have names pointing into
551            an ELF string table read from a file, or to objalloc memory.  */
552         *p = 0;
553
554       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
555
556       if (p != NULL)
557         *p = ELF_VER_CHR;
558
559       if (indx == (size_t) -1)
560         return FALSE;
561       h->dynstr_index = indx;
562     }
563
564   return TRUE;
565 }
566 \f
567 /* Mark a symbol dynamic.  */
568
569 static void
570 bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
571                                   struct elf_link_hash_entry *h,
572                                   Elf_Internal_Sym *sym)
573 {
574   struct bfd_elf_dynamic_list *d = info->dynamic_list;
575
576   /* It may be called more than once on the same H.  */
577   if(h->dynamic || bfd_link_relocatable (info))
578     return;
579
580   if ((info->dynamic_data
581        && (h->type == STT_OBJECT
582            || h->type == STT_COMMON
583            || (sym != NULL
584                && (ELF_ST_TYPE (sym->st_info) == STT_OBJECT
585                    || ELF_ST_TYPE (sym->st_info) == STT_COMMON))))
586       || (d != NULL
587           && h->non_elf
588           && (*d->match) (&d->head, NULL, h->root.root.string)))
589     h->dynamic = 1;
590 }
591
592 /* Record an assignment to a symbol made by a linker script.  We need
593    this in case some dynamic object refers to this symbol.  */
594
595 bfd_boolean
596 bfd_elf_record_link_assignment (bfd *output_bfd,
597                                 struct bfd_link_info *info,
598                                 const char *name,
599                                 bfd_boolean provide,
600                                 bfd_boolean hidden)
601 {
602   struct elf_link_hash_entry *h, *hv;
603   struct elf_link_hash_table *htab;
604   const struct elf_backend_data *bed;
605
606   if (!is_elf_hash_table (info->hash))
607     return TRUE;
608
609   htab = elf_hash_table (info);
610   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
611   if (h == NULL)
612     return provide;
613
614   if (h->root.type == bfd_link_hash_warning)
615     h = (struct elf_link_hash_entry *) h->root.u.i.link;
616
617   if (h->versioned == unknown)
618     {
619       /* Set versioned if symbol version is unknown.  */
620       char *version = strrchr (name, ELF_VER_CHR);
621       if (version)
622         {
623           if (version > name && version[-1] != ELF_VER_CHR)
624             h->versioned = versioned_hidden;
625           else
626             h->versioned = versioned;
627         }
628     }
629
630   /* Symbols defined in a linker script but not referenced anywhere
631      else will have non_elf set.  */
632   if (h->non_elf)
633     {
634       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
635       h->non_elf = 0;
636     }
637
638   switch (h->root.type)
639     {
640     case bfd_link_hash_defined:
641     case bfd_link_hash_defweak:
642     case bfd_link_hash_common:
643       break;
644     case bfd_link_hash_undefweak:
645     case bfd_link_hash_undefined:
646       /* Since we're defining the symbol, don't let it seem to have not
647          been defined.  record_dynamic_symbol and size_dynamic_sections
648          may depend on this.  */
649       h->root.type = bfd_link_hash_new;
650       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
651         bfd_link_repair_undef_list (&htab->root);
652       break;
653     case bfd_link_hash_new:
654       break;
655     case bfd_link_hash_indirect:
656       /* We had a versioned symbol in a dynamic library.  We make the
657          the versioned symbol point to this one.  */
658       bed = get_elf_backend_data (output_bfd);
659       hv = h;
660       while (hv->root.type == bfd_link_hash_indirect
661              || hv->root.type == bfd_link_hash_warning)
662         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
663       /* We don't need to update h->root.u since linker will set them
664          later.  */
665       h->root.type = bfd_link_hash_undefined;
666       hv->root.type = bfd_link_hash_indirect;
667       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
668       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
669       break;
670     default:
671       BFD_FAIL ();
672       return FALSE;
673     }
674
675   /* If this symbol is being provided by the linker script, and it is
676      currently defined by a dynamic object, but not by a regular
677      object, then mark it as undefined so that the generic linker will
678      force the correct value.  */
679   if (provide
680       && h->def_dynamic
681       && !h->def_regular)
682     h->root.type = bfd_link_hash_undefined;
683
684   /* If this symbol is not being provided by the linker script, and it is
685      currently defined by a dynamic object, but not by a regular object,
686      then clear out any version information because the symbol will not be
687      associated with the dynamic object any more.  */
688   if (!provide
689       && h->def_dynamic
690       && !h->def_regular)
691     h->verinfo.verdef = NULL;
692
693   /* Make sure this symbol is not garbage collected.  */
694   h->mark = 1;
695
696   h->def_regular = 1;
697
698   if (hidden)
699     {
700       bed = get_elf_backend_data (output_bfd);
701       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
702         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
703       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
704     }
705
706   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
707      and executables.  */
708   if (!bfd_link_relocatable (info)
709       && h->dynindx != -1
710       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
711           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
712     h->forced_local = 1;
713
714   if ((h->def_dynamic
715        || h->ref_dynamic
716        || bfd_link_dll (info)
717        || elf_hash_table (info)->is_relocatable_executable)
718       && h->dynindx == -1)
719     {
720       if (! bfd_elf_link_record_dynamic_symbol (info, h))
721         return FALSE;
722
723       /* If this is a weak defined symbol, and we know a corresponding
724          real symbol from the same dynamic object, make sure the real
725          symbol is also made into a dynamic symbol.  */
726       if (h->u.weakdef != NULL
727           && h->u.weakdef->dynindx == -1)
728         {
729           if (! bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
730             return FALSE;
731         }
732     }
733
734   return TRUE;
735 }
736
737 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
738    success, and 2 on a failure caused by attempting to record a symbol
739    in a discarded section, eg. a discarded link-once section symbol.  */
740
741 int
742 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
743                                           bfd *input_bfd,
744                                           long input_indx)
745 {
746   bfd_size_type amt;
747   struct elf_link_local_dynamic_entry *entry;
748   struct elf_link_hash_table *eht;
749   struct elf_strtab_hash *dynstr;
750   size_t dynstr_index;
751   char *name;
752   Elf_External_Sym_Shndx eshndx;
753   char esym[sizeof (Elf64_External_Sym)];
754
755   if (! is_elf_hash_table (info->hash))
756     return 0;
757
758   /* See if the entry exists already.  */
759   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
760     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
761       return 1;
762
763   amt = sizeof (*entry);
764   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
765   if (entry == NULL)
766     return 0;
767
768   /* Go find the symbol, so that we can find it's name.  */
769   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
770                              1, input_indx, &entry->isym, esym, &eshndx))
771     {
772       bfd_release (input_bfd, entry);
773       return 0;
774     }
775
776   if (entry->isym.st_shndx != SHN_UNDEF
777       && entry->isym.st_shndx < SHN_LORESERVE)
778     {
779       asection *s;
780
781       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
782       if (s == NULL || bfd_is_abs_section (s->output_section))
783         {
784           /* We can still bfd_release here as nothing has done another
785              bfd_alloc.  We can't do this later in this function.  */
786           bfd_release (input_bfd, entry);
787           return 2;
788         }
789     }
790
791   name = (bfd_elf_string_from_elf_section
792           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
793            entry->isym.st_name));
794
795   dynstr = elf_hash_table (info)->dynstr;
796   if (dynstr == NULL)
797     {
798       /* Create a strtab to hold the dynamic symbol names.  */
799       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
800       if (dynstr == NULL)
801         return 0;
802     }
803
804   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
805   if (dynstr_index == (size_t) -1)
806     return 0;
807   entry->isym.st_name = dynstr_index;
808
809   eht = elf_hash_table (info);
810
811   entry->next = eht->dynlocal;
812   eht->dynlocal = entry;
813   entry->input_bfd = input_bfd;
814   entry->input_indx = input_indx;
815   eht->dynsymcount++;
816
817   /* Whatever binding the symbol had before, it's now local.  */
818   entry->isym.st_info
819     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
820
821   /* The dynindx will be set at the end of size_dynamic_sections.  */
822
823   return 1;
824 }
825
826 /* Return the dynindex of a local dynamic symbol.  */
827
828 long
829 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
830                                     bfd *input_bfd,
831                                     long input_indx)
832 {
833   struct elf_link_local_dynamic_entry *e;
834
835   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
836     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
837       return e->dynindx;
838   return -1;
839 }
840
841 /* This function is used to renumber the dynamic symbols, if some of
842    them are removed because they are marked as local.  This is called
843    via elf_link_hash_traverse.  */
844
845 static bfd_boolean
846 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
847                                       void *data)
848 {
849   size_t *count = (size_t *) data;
850
851   if (h->forced_local)
852     return TRUE;
853
854   if (h->dynindx != -1)
855     h->dynindx = ++(*count);
856
857   return TRUE;
858 }
859
860
861 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
862    STB_LOCAL binding.  */
863
864 static bfd_boolean
865 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
866                                             void *data)
867 {
868   size_t *count = (size_t *) data;
869
870   if (!h->forced_local)
871     return TRUE;
872
873   if (h->dynindx != -1)
874     h->dynindx = ++(*count);
875
876   return TRUE;
877 }
878
879 /* Return true if the dynamic symbol for a given section should be
880    omitted when creating a shared library.  */
881 bfd_boolean
882 _bfd_elf_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED,
883                                    struct bfd_link_info *info,
884                                    asection *p)
885 {
886   struct elf_link_hash_table *htab;
887   asection *ip;
888
889   switch (elf_section_data (p)->this_hdr.sh_type)
890     {
891     case SHT_PROGBITS:
892     case SHT_NOBITS:
893       /* If sh_type is yet undecided, assume it could be
894          SHT_PROGBITS/SHT_NOBITS.  */
895     case SHT_NULL:
896       htab = elf_hash_table (info);
897       if (p == htab->tls_sec)
898         return FALSE;
899
900       if (htab->text_index_section != NULL)
901         return p != htab->text_index_section && p != htab->data_index_section;
902
903       return (htab->dynobj != NULL
904               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
905               && ip->output_section == p);
906
907       /* There shouldn't be section relative relocations
908          against any other section.  */
909     default:
910       return TRUE;
911     }
912 }
913
914 /* Assign dynsym indices.  In a shared library we generate a section
915    symbol for each output section, which come first.  Next come symbols
916    which have been forced to local binding.  Then all of the back-end
917    allocated local dynamic syms, followed by the rest of the global
918    symbols.  */
919
920 static unsigned long
921 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
922                                 struct bfd_link_info *info,
923                                 unsigned long *section_sym_count)
924 {
925   unsigned long dynsymcount = 0;
926
927   if (bfd_link_pic (info)
928       || elf_hash_table (info)->is_relocatable_executable)
929     {
930       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
931       asection *p;
932       for (p = output_bfd->sections; p ; p = p->next)
933         if ((p->flags & SEC_EXCLUDE) == 0
934             && (p->flags & SEC_ALLOC) != 0
935             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
936           elf_section_data (p)->dynindx = ++dynsymcount;
937         else
938           elf_section_data (p)->dynindx = 0;
939     }
940   *section_sym_count = dynsymcount;
941
942   elf_link_hash_traverse (elf_hash_table (info),
943                           elf_link_renumber_local_hash_table_dynsyms,
944                           &dynsymcount);
945
946   if (elf_hash_table (info)->dynlocal)
947     {
948       struct elf_link_local_dynamic_entry *p;
949       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
950         p->dynindx = ++dynsymcount;
951     }
952   elf_hash_table (info)->local_dynsymcount = dynsymcount;
953
954   elf_link_hash_traverse (elf_hash_table (info),
955                           elf_link_renumber_hash_table_dynsyms,
956                           &dynsymcount);
957
958   /* There is an unused NULL entry at the head of the table which we
959      must account for in our count even if the table is empty since it
960      is intended for the mandatory DT_SYMTAB tag (.dynsym section) in
961      .dynamic section.  */
962   dynsymcount++;
963
964   elf_hash_table (info)->dynsymcount = dynsymcount;
965   return dynsymcount;
966 }
967
968 /* Merge st_other field.  */
969
970 static void
971 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
972                     const Elf_Internal_Sym *isym, asection *sec,
973                     bfd_boolean definition, bfd_boolean dynamic)
974 {
975   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
976
977   /* If st_other has a processor-specific meaning, specific
978      code might be needed here.  */
979   if (bed->elf_backend_merge_symbol_attribute)
980     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
981                                                 dynamic);
982
983   if (!dynamic)
984     {
985       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
986       unsigned hvis = ELF_ST_VISIBILITY (h->other);
987
988       /* Keep the most constraining visibility.  Leave the remainder
989          of the st_other field to elf_backend_merge_symbol_attribute.  */
990       if (symvis - 1 < hvis - 1)
991         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
992     }
993   else if (definition
994            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
995            && (sec->flags & SEC_READONLY) == 0)
996     h->protected_def = 1;
997 }
998
999 /* This function is called when we want to merge a new symbol with an
1000    existing symbol.  It handles the various cases which arise when we
1001    find a definition in a dynamic object, or when there is already a
1002    definition in a dynamic object.  The new symbol is described by
1003    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
1004    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
1005    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
1006    of an old common symbol.  We set OVERRIDE if the old symbol is
1007    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
1008    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
1009    to change.  By OK to change, we mean that we shouldn't warn if the
1010    type or size does change.  */
1011
1012 static bfd_boolean
1013 _bfd_elf_merge_symbol (bfd *abfd,
1014                        struct bfd_link_info *info,
1015                        const char *name,
1016                        Elf_Internal_Sym *sym,
1017                        asection **psec,
1018                        bfd_vma *pvalue,
1019                        struct elf_link_hash_entry **sym_hash,
1020                        bfd **poldbfd,
1021                        bfd_boolean *pold_weak,
1022                        unsigned int *pold_alignment,
1023                        bfd_boolean *skip,
1024                        bfd_boolean *override,
1025                        bfd_boolean *type_change_ok,
1026                        bfd_boolean *size_change_ok,
1027                        bfd_boolean *matched)
1028 {
1029   asection *sec, *oldsec;
1030   struct elf_link_hash_entry *h;
1031   struct elf_link_hash_entry *hi;
1032   struct elf_link_hash_entry *flip;
1033   int bind;
1034   bfd *oldbfd;
1035   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
1036   bfd_boolean newweak, oldweak, newfunc, oldfunc;
1037   const struct elf_backend_data *bed;
1038   char *new_version;
1039
1040   *skip = FALSE;
1041   *override = FALSE;
1042
1043   sec = *psec;
1044   bind = ELF_ST_BIND (sym->st_info);
1045
1046   if (! bfd_is_und_section (sec))
1047     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
1048   else
1049     h = ((struct elf_link_hash_entry *)
1050          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
1051   if (h == NULL)
1052     return FALSE;
1053   *sym_hash = h;
1054
1055   bed = get_elf_backend_data (abfd);
1056
1057   /* NEW_VERSION is the symbol version of the new symbol.  */
1058   if (h->versioned != unversioned)
1059     {
1060       /* Symbol version is unknown or versioned.  */
1061       new_version = strrchr (name, ELF_VER_CHR);
1062       if (new_version)
1063         {
1064           if (h->versioned == unknown)
1065             {
1066               if (new_version > name && new_version[-1] != ELF_VER_CHR)
1067                 h->versioned = versioned_hidden;
1068               else
1069                 h->versioned = versioned;
1070             }
1071           new_version += 1;
1072           if (new_version[0] == '\0')
1073             new_version = NULL;
1074         }
1075       else
1076         h->versioned = unversioned;
1077     }
1078   else
1079     new_version = NULL;
1080
1081   /* For merging, we only care about real symbols.  But we need to make
1082      sure that indirect symbol dynamic flags are updated.  */
1083   hi = h;
1084   while (h->root.type == bfd_link_hash_indirect
1085          || h->root.type == bfd_link_hash_warning)
1086     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1087
1088   if (!*matched)
1089     {
1090       if (hi == h || h->root.type == bfd_link_hash_new)
1091         *matched = TRUE;
1092       else
1093         {
1094           /* OLD_HIDDEN is true if the existing symbol is only visible
1095              to the symbol with the same symbol version.  NEW_HIDDEN is
1096              true if the new symbol is only visible to the symbol with
1097              the same symbol version.  */
1098           bfd_boolean old_hidden = h->versioned == versioned_hidden;
1099           bfd_boolean new_hidden = hi->versioned == versioned_hidden;
1100           if (!old_hidden && !new_hidden)
1101             /* The new symbol matches the existing symbol if both
1102                aren't hidden.  */
1103             *matched = TRUE;
1104           else
1105             {
1106               /* OLD_VERSION is the symbol version of the existing
1107                  symbol. */
1108               char *old_version;
1109
1110               if (h->versioned >= versioned)
1111                 old_version = strrchr (h->root.root.string,
1112                                        ELF_VER_CHR) + 1;
1113               else
1114                  old_version = NULL;
1115
1116               /* The new symbol matches the existing symbol if they
1117                  have the same symbol version.  */
1118               *matched = (old_version == new_version
1119                           || (old_version != NULL
1120                               && new_version != NULL
1121                               && strcmp (old_version, new_version) == 0));
1122             }
1123         }
1124     }
1125
1126   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
1127      existing symbol.  */
1128
1129   oldbfd = NULL;
1130   oldsec = NULL;
1131   switch (h->root.type)
1132     {
1133     default:
1134       break;
1135
1136     case bfd_link_hash_undefined:
1137     case bfd_link_hash_undefweak:
1138       oldbfd = h->root.u.undef.abfd;
1139       break;
1140
1141     case bfd_link_hash_defined:
1142     case bfd_link_hash_defweak:
1143       oldbfd = h->root.u.def.section->owner;
1144       oldsec = h->root.u.def.section;
1145       break;
1146
1147     case bfd_link_hash_common:
1148       oldbfd = h->root.u.c.p->section->owner;
1149       oldsec = h->root.u.c.p->section;
1150       if (pold_alignment)
1151         *pold_alignment = h->root.u.c.p->alignment_power;
1152       break;
1153     }
1154   if (poldbfd && *poldbfd == NULL)
1155     *poldbfd = oldbfd;
1156
1157   /* Differentiate strong and weak symbols.  */
1158   newweak = bind == STB_WEAK;
1159   oldweak = (h->root.type == bfd_link_hash_defweak
1160              || h->root.type == bfd_link_hash_undefweak);
1161   if (pold_weak)
1162     *pold_weak = oldweak;
1163
1164   /* This code is for coping with dynamic objects, and is only useful
1165      if we are doing an ELF link.  */
1166   if (!(*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
1167     return TRUE;
1168
1169   /* We have to check it for every instance since the first few may be
1170      references and not all compilers emit symbol type for undefined
1171      symbols.  */
1172   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
1173
1174   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1175      respectively, is from a dynamic object.  */
1176
1177   newdyn = (abfd->flags & DYNAMIC) != 0;
1178
1179   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
1180      syms and defined syms in dynamic libraries respectively.
1181      ref_dynamic on the other hand can be set for a symbol defined in
1182      a dynamic library, and def_dynamic may not be set;  When the
1183      definition in a dynamic lib is overridden by a definition in the
1184      executable use of the symbol in the dynamic lib becomes a
1185      reference to the executable symbol.  */
1186   if (newdyn)
1187     {
1188       if (bfd_is_und_section (sec))
1189         {
1190           if (bind != STB_WEAK)
1191             {
1192               h->ref_dynamic_nonweak = 1;
1193               hi->ref_dynamic_nonweak = 1;
1194             }
1195         }
1196       else
1197         {
1198           /* Update the existing symbol only if they match. */
1199           if (*matched)
1200             h->dynamic_def = 1;
1201           hi->dynamic_def = 1;
1202         }
1203     }
1204
1205   /* If we just created the symbol, mark it as being an ELF symbol.
1206      Other than that, there is nothing to do--there is no merge issue
1207      with a newly defined symbol--so we just return.  */
1208
1209   if (h->root.type == bfd_link_hash_new)
1210     {
1211       h->non_elf = 0;
1212       return TRUE;
1213     }
1214
1215   /* In cases involving weak versioned symbols, we may wind up trying
1216      to merge a symbol with itself.  Catch that here, to avoid the
1217      confusion that results if we try to override a symbol with
1218      itself.  The additional tests catch cases like
1219      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1220      dynamic object, which we do want to handle here.  */
1221   if (abfd == oldbfd
1222       && (newweak || oldweak)
1223       && ((abfd->flags & DYNAMIC) == 0
1224           || !h->def_regular))
1225     return TRUE;
1226
1227   olddyn = FALSE;
1228   if (oldbfd != NULL)
1229     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1230   else if (oldsec != NULL)
1231     {
1232       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1233          indices used by MIPS ELF.  */
1234       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1235     }
1236
1237   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1238      respectively, appear to be a definition rather than reference.  */
1239
1240   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1241
1242   olddef = (h->root.type != bfd_link_hash_undefined
1243             && h->root.type != bfd_link_hash_undefweak
1244             && h->root.type != bfd_link_hash_common);
1245
1246   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1247      respectively, appear to be a function.  */
1248
1249   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1250              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1251
1252   oldfunc = (h->type != STT_NOTYPE
1253              && bed->is_function_type (h->type));
1254
1255   if (!(newfunc && oldfunc)
1256       && ELF_ST_TYPE (sym->st_info) != h->type
1257       && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1258       && h->type != STT_NOTYPE
1259       && (newdef || bfd_is_com_section (sec))
1260       && (olddef || h->root.type == bfd_link_hash_common))
1261     {
1262       /* If creating a default indirect symbol ("foo" or "foo@") from
1263          a dynamic versioned definition ("foo@@") skip doing so if
1264          there is an existing regular definition with a different
1265          type.  We don't want, for example, a "time" variable in the
1266          executable overriding a "time" function in a shared library.  */
1267       if (newdyn
1268           && !olddyn)
1269         {
1270           *skip = TRUE;
1271           return TRUE;
1272         }
1273
1274       /* When adding a symbol from a regular object file after we have
1275          created indirect symbols, undo the indirection and any
1276          dynamic state.  */
1277       if (hi != h
1278           && !newdyn
1279           && olddyn)
1280         {
1281           h = hi;
1282           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1283           h->forced_local = 0;
1284           h->ref_dynamic = 0;
1285           h->def_dynamic = 0;
1286           h->dynamic_def = 0;
1287           if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1288             {
1289               h->root.type = bfd_link_hash_undefined;
1290               h->root.u.undef.abfd = abfd;
1291             }
1292           else
1293             {
1294               h->root.type = bfd_link_hash_new;
1295               h->root.u.undef.abfd = NULL;
1296             }
1297           return TRUE;
1298         }
1299     }
1300
1301   /* Check TLS symbols.  We don't check undefined symbols introduced
1302      by "ld -u" which have no type (and oldbfd NULL), and we don't
1303      check symbols from plugins because they also have no type.  */
1304   if (oldbfd != NULL
1305       && (oldbfd->flags & BFD_PLUGIN) == 0
1306       && (abfd->flags & BFD_PLUGIN) == 0
1307       && ELF_ST_TYPE (sym->st_info) != h->type
1308       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1309     {
1310       bfd *ntbfd, *tbfd;
1311       bfd_boolean ntdef, tdef;
1312       asection *ntsec, *tsec;
1313
1314       if (h->type == STT_TLS)
1315         {
1316           ntbfd = abfd;
1317           ntsec = sec;
1318           ntdef = newdef;
1319           tbfd = oldbfd;
1320           tsec = oldsec;
1321           tdef = olddef;
1322         }
1323       else
1324         {
1325           ntbfd = oldbfd;
1326           ntsec = oldsec;
1327           ntdef = olddef;
1328           tbfd = abfd;
1329           tsec = sec;
1330           tdef = newdef;
1331         }
1332
1333       if (tdef && ntdef)
1334         _bfd_error_handler
1335           /* xgettext:c-format */
1336           (_("%s: TLS definition in %B section %A "
1337              "mismatches non-TLS definition in %B section %A"),
1338            h->root.root.string, tbfd, tsec, ntbfd, ntsec);
1339       else if (!tdef && !ntdef)
1340         _bfd_error_handler
1341           /* xgettext:c-format */
1342           (_("%s: TLS reference in %B "
1343              "mismatches non-TLS reference in %B"),
1344            h->root.root.string, tbfd, ntbfd);
1345       else if (tdef)
1346         _bfd_error_handler
1347           /* xgettext:c-format */
1348           (_("%s: TLS definition in %B section %A "
1349              "mismatches non-TLS reference in %B"),
1350            h->root.root.string, tbfd, tsec, ntbfd);
1351       else
1352         _bfd_error_handler
1353           /* xgettext:c-format */
1354           (_("%s: TLS reference in %B "
1355              "mismatches non-TLS definition in %B section %A"),
1356            h->root.root.string, tbfd, ntbfd, ntsec);
1357
1358       bfd_set_error (bfd_error_bad_value);
1359       return FALSE;
1360     }
1361
1362   /* If the old symbol has non-default visibility, we ignore the new
1363      definition from a dynamic object.  */
1364   if (newdyn
1365       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1366       && !bfd_is_und_section (sec))
1367     {
1368       *skip = TRUE;
1369       /* Make sure this symbol is dynamic.  */
1370       h->ref_dynamic = 1;
1371       hi->ref_dynamic = 1;
1372       /* A protected symbol has external availability. Make sure it is
1373          recorded as dynamic.
1374
1375          FIXME: Should we check type and size for protected symbol?  */
1376       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1377         return bfd_elf_link_record_dynamic_symbol (info, h);
1378       else
1379         return TRUE;
1380     }
1381   else if (!newdyn
1382            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1383            && h->def_dynamic)
1384     {
1385       /* If the new symbol with non-default visibility comes from a
1386          relocatable file and the old definition comes from a dynamic
1387          object, we remove the old definition.  */
1388       if (hi->root.type == bfd_link_hash_indirect)
1389         {
1390           /* Handle the case where the old dynamic definition is
1391              default versioned.  We need to copy the symbol info from
1392              the symbol with default version to the normal one if it
1393              was referenced before.  */
1394           if (h->ref_regular)
1395             {
1396               hi->root.type = h->root.type;
1397               h->root.type = bfd_link_hash_indirect;
1398               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1399
1400               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1401               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1402                 {
1403                   /* If the new symbol is hidden or internal, completely undo
1404                      any dynamic link state.  */
1405                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1406                   h->forced_local = 0;
1407                   h->ref_dynamic = 0;
1408                 }
1409               else
1410                 h->ref_dynamic = 1;
1411
1412               h->def_dynamic = 0;
1413               /* FIXME: Should we check type and size for protected symbol?  */
1414               h->size = 0;
1415               h->type = 0;
1416
1417               h = hi;
1418             }
1419           else
1420             h = hi;
1421         }
1422
1423       /* If the old symbol was undefined before, then it will still be
1424          on the undefs list.  If the new symbol is undefined or
1425          common, we can't make it bfd_link_hash_new here, because new
1426          undefined or common symbols will be added to the undefs list
1427          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1428          added twice to the undefs list.  Also, if the new symbol is
1429          undefweak then we don't want to lose the strong undef.  */
1430       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1431         {
1432           h->root.type = bfd_link_hash_undefined;
1433           h->root.u.undef.abfd = abfd;
1434         }
1435       else
1436         {
1437           h->root.type = bfd_link_hash_new;
1438           h->root.u.undef.abfd = NULL;
1439         }
1440
1441       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1442         {
1443           /* If the new symbol is hidden or internal, completely undo
1444              any dynamic link state.  */
1445           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1446           h->forced_local = 0;
1447           h->ref_dynamic = 0;
1448         }
1449       else
1450         h->ref_dynamic = 1;
1451       h->def_dynamic = 0;
1452       /* FIXME: Should we check type and size for protected symbol?  */
1453       h->size = 0;
1454       h->type = 0;
1455       return TRUE;
1456     }
1457
1458   /* If a new weak symbol definition comes from a regular file and the
1459      old symbol comes from a dynamic library, we treat the new one as
1460      strong.  Similarly, an old weak symbol definition from a regular
1461      file is treated as strong when the new symbol comes from a dynamic
1462      library.  Further, an old weak symbol from a dynamic library is
1463      treated as strong if the new symbol is from a dynamic library.
1464      This reflects the way glibc's ld.so works.
1465
1466      Do this before setting *type_change_ok or *size_change_ok so that
1467      we warn properly when dynamic library symbols are overridden.  */
1468
1469   if (newdef && !newdyn && olddyn)
1470     newweak = FALSE;
1471   if (olddef && newdyn)
1472     oldweak = FALSE;
1473
1474   /* Allow changes between different types of function symbol.  */
1475   if (newfunc && oldfunc)
1476     *type_change_ok = TRUE;
1477
1478   /* It's OK to change the type if either the existing symbol or the
1479      new symbol is weak.  A type change is also OK if the old symbol
1480      is undefined and the new symbol is defined.  */
1481
1482   if (oldweak
1483       || newweak
1484       || (newdef
1485           && h->root.type == bfd_link_hash_undefined))
1486     *type_change_ok = TRUE;
1487
1488   /* It's OK to change the size if either the existing symbol or the
1489      new symbol is weak, or if the old symbol is undefined.  */
1490
1491   if (*type_change_ok
1492       || h->root.type == bfd_link_hash_undefined)
1493     *size_change_ok = TRUE;
1494
1495   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1496      symbol, respectively, appears to be a common symbol in a dynamic
1497      object.  If a symbol appears in an uninitialized section, and is
1498      not weak, and is not a function, then it may be a common symbol
1499      which was resolved when the dynamic object was created.  We want
1500      to treat such symbols specially, because they raise special
1501      considerations when setting the symbol size: if the symbol
1502      appears as a common symbol in a regular object, and the size in
1503      the regular object is larger, we must make sure that we use the
1504      larger size.  This problematic case can always be avoided in C,
1505      but it must be handled correctly when using Fortran shared
1506      libraries.
1507
1508      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1509      likewise for OLDDYNCOMMON and OLDDEF.
1510
1511      Note that this test is just a heuristic, and that it is quite
1512      possible to have an uninitialized symbol in a shared object which
1513      is really a definition, rather than a common symbol.  This could
1514      lead to some minor confusion when the symbol really is a common
1515      symbol in some regular object.  However, I think it will be
1516      harmless.  */
1517
1518   if (newdyn
1519       && newdef
1520       && !newweak
1521       && (sec->flags & SEC_ALLOC) != 0
1522       && (sec->flags & SEC_LOAD) == 0
1523       && sym->st_size > 0
1524       && !newfunc)
1525     newdyncommon = TRUE;
1526   else
1527     newdyncommon = FALSE;
1528
1529   if (olddyn
1530       && olddef
1531       && h->root.type == bfd_link_hash_defined
1532       && h->def_dynamic
1533       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1534       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1535       && h->size > 0
1536       && !oldfunc)
1537     olddyncommon = TRUE;
1538   else
1539     olddyncommon = FALSE;
1540
1541   /* We now know everything about the old and new symbols.  We ask the
1542      backend to check if we can merge them.  */
1543   if (bed->merge_symbol != NULL)
1544     {
1545       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1546         return FALSE;
1547       sec = *psec;
1548     }
1549
1550   /* If both the old and the new symbols look like common symbols in a
1551      dynamic object, set the size of the symbol to the larger of the
1552      two.  */
1553
1554   if (olddyncommon
1555       && newdyncommon
1556       && sym->st_size != h->size)
1557     {
1558       /* Since we think we have two common symbols, issue a multiple
1559          common warning if desired.  Note that we only warn if the
1560          size is different.  If the size is the same, we simply let
1561          the old symbol override the new one as normally happens with
1562          symbols defined in dynamic objects.  */
1563
1564       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1565                                            bfd_link_hash_common, sym->st_size);
1566       if (sym->st_size > h->size)
1567         h->size = sym->st_size;
1568
1569       *size_change_ok = TRUE;
1570     }
1571
1572   /* If we are looking at a dynamic object, and we have found a
1573      definition, we need to see if the symbol was already defined by
1574      some other object.  If so, we want to use the existing
1575      definition, and we do not want to report a multiple symbol
1576      definition error; we do this by clobbering *PSEC to be
1577      bfd_und_section_ptr.
1578
1579      We treat a common symbol as a definition if the symbol in the
1580      shared library is a function, since common symbols always
1581      represent variables; this can cause confusion in principle, but
1582      any such confusion would seem to indicate an erroneous program or
1583      shared library.  We also permit a common symbol in a regular
1584      object to override a weak symbol in a shared object.  */
1585
1586   if (newdyn
1587       && newdef
1588       && (olddef
1589           || (h->root.type == bfd_link_hash_common
1590               && (newweak || newfunc))))
1591     {
1592       *override = TRUE;
1593       newdef = FALSE;
1594       newdyncommon = FALSE;
1595
1596       *psec = sec = bfd_und_section_ptr;
1597       *size_change_ok = TRUE;
1598
1599       /* If we get here when the old symbol is a common symbol, then
1600          we are explicitly letting it override a weak symbol or
1601          function in a dynamic object, and we don't want to warn about
1602          a type change.  If the old symbol is a defined symbol, a type
1603          change warning may still be appropriate.  */
1604
1605       if (h->root.type == bfd_link_hash_common)
1606         *type_change_ok = TRUE;
1607     }
1608
1609   /* Handle the special case of an old common symbol merging with a
1610      new symbol which looks like a common symbol in a shared object.
1611      We change *PSEC and *PVALUE to make the new symbol look like a
1612      common symbol, and let _bfd_generic_link_add_one_symbol do the
1613      right thing.  */
1614
1615   if (newdyncommon
1616       && h->root.type == bfd_link_hash_common)
1617     {
1618       *override = TRUE;
1619       newdef = FALSE;
1620       newdyncommon = FALSE;
1621       *pvalue = sym->st_size;
1622       *psec = sec = bed->common_section (oldsec);
1623       *size_change_ok = TRUE;
1624     }
1625
1626   /* Skip weak definitions of symbols that are already defined.  */
1627   if (newdef && olddef && newweak)
1628     {
1629       /* Don't skip new non-IR weak syms.  */
1630       if (!(oldbfd != NULL
1631             && (oldbfd->flags & BFD_PLUGIN) != 0
1632             && (abfd->flags & BFD_PLUGIN) == 0))
1633         {
1634           newdef = FALSE;
1635           *skip = TRUE;
1636         }
1637
1638       /* Merge st_other.  If the symbol already has a dynamic index,
1639          but visibility says it should not be visible, turn it into a
1640          local symbol.  */
1641       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1642       if (h->dynindx != -1)
1643         switch (ELF_ST_VISIBILITY (h->other))
1644           {
1645           case STV_INTERNAL:
1646           case STV_HIDDEN:
1647             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1648             break;
1649           }
1650     }
1651
1652   /* If the old symbol is from a dynamic object, and the new symbol is
1653      a definition which is not from a dynamic object, then the new
1654      symbol overrides the old symbol.  Symbols from regular files
1655      always take precedence over symbols from dynamic objects, even if
1656      they are defined after the dynamic object in the link.
1657
1658      As above, we again permit a common symbol in a regular object to
1659      override a definition in a shared object if the shared object
1660      symbol is a function or is weak.  */
1661
1662   flip = NULL;
1663   if (!newdyn
1664       && (newdef
1665           || (bfd_is_com_section (sec)
1666               && (oldweak || oldfunc)))
1667       && olddyn
1668       && olddef
1669       && h->def_dynamic)
1670     {
1671       /* Change the hash table entry to undefined, and let
1672          _bfd_generic_link_add_one_symbol do the right thing with the
1673          new definition.  */
1674
1675       h->root.type = bfd_link_hash_undefined;
1676       h->root.u.undef.abfd = h->root.u.def.section->owner;
1677       *size_change_ok = TRUE;
1678
1679       olddef = FALSE;
1680       olddyncommon = FALSE;
1681
1682       /* We again permit a type change when a common symbol may be
1683          overriding a function.  */
1684
1685       if (bfd_is_com_section (sec))
1686         {
1687           if (oldfunc)
1688             {
1689               /* If a common symbol overrides a function, make sure
1690                  that it isn't defined dynamically nor has type
1691                  function.  */
1692               h->def_dynamic = 0;
1693               h->type = STT_NOTYPE;
1694             }
1695           *type_change_ok = TRUE;
1696         }
1697
1698       if (hi->root.type == bfd_link_hash_indirect)
1699         flip = hi;
1700       else
1701         /* This union may have been set to be non-NULL when this symbol
1702            was seen in a dynamic object.  We must force the union to be
1703            NULL, so that it is correct for a regular symbol.  */
1704         h->verinfo.vertree = NULL;
1705     }
1706
1707   /* Handle the special case of a new common symbol merging with an
1708      old symbol that looks like it might be a common symbol defined in
1709      a shared object.  Note that we have already handled the case in
1710      which a new common symbol should simply override the definition
1711      in the shared library.  */
1712
1713   if (! newdyn
1714       && bfd_is_com_section (sec)
1715       && olddyncommon)
1716     {
1717       /* It would be best if we could set the hash table entry to a
1718          common symbol, but we don't know what to use for the section
1719          or the alignment.  */
1720       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1721                                            bfd_link_hash_common, sym->st_size);
1722
1723       /* If the presumed common symbol in the dynamic object is
1724          larger, pretend that the new symbol has its size.  */
1725
1726       if (h->size > *pvalue)
1727         *pvalue = h->size;
1728
1729       /* We need to remember the alignment required by the symbol
1730          in the dynamic object.  */
1731       BFD_ASSERT (pold_alignment);
1732       *pold_alignment = h->root.u.def.section->alignment_power;
1733
1734       olddef = FALSE;
1735       olddyncommon = FALSE;
1736
1737       h->root.type = bfd_link_hash_undefined;
1738       h->root.u.undef.abfd = h->root.u.def.section->owner;
1739
1740       *size_change_ok = TRUE;
1741       *type_change_ok = TRUE;
1742
1743       if (hi->root.type == bfd_link_hash_indirect)
1744         flip = hi;
1745       else
1746         h->verinfo.vertree = NULL;
1747     }
1748
1749   if (flip != NULL)
1750     {
1751       /* Handle the case where we had a versioned symbol in a dynamic
1752          library and now find a definition in a normal object.  In this
1753          case, we make the versioned symbol point to the normal one.  */
1754       flip->root.type = h->root.type;
1755       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1756       h->root.type = bfd_link_hash_indirect;
1757       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1758       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1759       if (h->def_dynamic)
1760         {
1761           h->def_dynamic = 0;
1762           flip->ref_dynamic = 1;
1763         }
1764     }
1765
1766   return TRUE;
1767 }
1768
1769 /* This function is called to create an indirect symbol from the
1770    default for the symbol with the default version if needed. The
1771    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1772    set DYNSYM if the new indirect symbol is dynamic.  */
1773
1774 static bfd_boolean
1775 _bfd_elf_add_default_symbol (bfd *abfd,
1776                              struct bfd_link_info *info,
1777                              struct elf_link_hash_entry *h,
1778                              const char *name,
1779                              Elf_Internal_Sym *sym,
1780                              asection *sec,
1781                              bfd_vma value,
1782                              bfd **poldbfd,
1783                              bfd_boolean *dynsym)
1784 {
1785   bfd_boolean type_change_ok;
1786   bfd_boolean size_change_ok;
1787   bfd_boolean skip;
1788   char *shortname;
1789   struct elf_link_hash_entry *hi;
1790   struct bfd_link_hash_entry *bh;
1791   const struct elf_backend_data *bed;
1792   bfd_boolean collect;
1793   bfd_boolean dynamic;
1794   bfd_boolean override;
1795   char *p;
1796   size_t len, shortlen;
1797   asection *tmp_sec;
1798   bfd_boolean matched;
1799
1800   if (h->versioned == unversioned || h->versioned == versioned_hidden)
1801     return TRUE;
1802
1803   /* If this symbol has a version, and it is the default version, we
1804      create an indirect symbol from the default name to the fully
1805      decorated name.  This will cause external references which do not
1806      specify a version to be bound to this version of the symbol.  */
1807   p = strchr (name, ELF_VER_CHR);
1808   if (h->versioned == unknown)
1809     {
1810       if (p == NULL)
1811         {
1812           h->versioned = unversioned;
1813           return TRUE;
1814         }
1815       else
1816         {
1817           if (p[1] != ELF_VER_CHR)
1818             {
1819               h->versioned = versioned_hidden;
1820               return TRUE;
1821             }
1822           else
1823             h->versioned = versioned;
1824         }
1825     }
1826   else
1827     {
1828       /* PR ld/19073: We may see an unversioned definition after the
1829          default version.  */
1830       if (p == NULL)
1831         return TRUE;
1832     }
1833
1834   bed = get_elf_backend_data (abfd);
1835   collect = bed->collect;
1836   dynamic = (abfd->flags & DYNAMIC) != 0;
1837
1838   shortlen = p - name;
1839   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1840   if (shortname == NULL)
1841     return FALSE;
1842   memcpy (shortname, name, shortlen);
1843   shortname[shortlen] = '\0';
1844
1845   /* We are going to create a new symbol.  Merge it with any existing
1846      symbol with this name.  For the purposes of the merge, act as
1847      though we were defining the symbol we just defined, although we
1848      actually going to define an indirect symbol.  */
1849   type_change_ok = FALSE;
1850   size_change_ok = FALSE;
1851   matched = TRUE;
1852   tmp_sec = sec;
1853   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1854                               &hi, poldbfd, NULL, NULL, &skip, &override,
1855                               &type_change_ok, &size_change_ok, &matched))
1856     return FALSE;
1857
1858   if (skip)
1859     goto nondefault;
1860
1861   if (hi->def_regular)
1862     {
1863       /* If the undecorated symbol will have a version added by a
1864          script different to H, then don't indirect to/from the
1865          undecorated symbol.  This isn't ideal because we may not yet
1866          have seen symbol versions, if given by a script on the
1867          command line rather than via --version-script.  */
1868       if (hi->verinfo.vertree == NULL && info->version_info != NULL)
1869         {
1870           bfd_boolean hide;
1871
1872           hi->verinfo.vertree
1873             = bfd_find_version_for_sym (info->version_info,
1874                                         hi->root.root.string, &hide);
1875           if (hi->verinfo.vertree != NULL && hide)
1876             {
1877               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
1878               goto nondefault;
1879             }
1880         }
1881       if (hi->verinfo.vertree != NULL
1882           && strcmp (p + 1 + (p[1] == '@'), hi->verinfo.vertree->name) != 0)
1883         goto nondefault;
1884     }
1885
1886   if (! override)
1887     {
1888       /* Add the default symbol if not performing a relocatable link.  */
1889       if (! bfd_link_relocatable (info))
1890         {
1891           bh = &hi->root;
1892           if (! (_bfd_generic_link_add_one_symbol
1893                  (info, abfd, shortname, BSF_INDIRECT,
1894                   bfd_ind_section_ptr,
1895                   0, name, FALSE, collect, &bh)))
1896             return FALSE;
1897           hi = (struct elf_link_hash_entry *) bh;
1898         }
1899     }
1900   else
1901     {
1902       /* In this case the symbol named SHORTNAME is overriding the
1903          indirect symbol we want to add.  We were planning on making
1904          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1905          is the name without a version.  NAME is the fully versioned
1906          name, and it is the default version.
1907
1908          Overriding means that we already saw a definition for the
1909          symbol SHORTNAME in a regular object, and it is overriding
1910          the symbol defined in the dynamic object.
1911
1912          When this happens, we actually want to change NAME, the
1913          symbol we just added, to refer to SHORTNAME.  This will cause
1914          references to NAME in the shared object to become references
1915          to SHORTNAME in the regular object.  This is what we expect
1916          when we override a function in a shared object: that the
1917          references in the shared object will be mapped to the
1918          definition in the regular object.  */
1919
1920       while (hi->root.type == bfd_link_hash_indirect
1921              || hi->root.type == bfd_link_hash_warning)
1922         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1923
1924       h->root.type = bfd_link_hash_indirect;
1925       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1926       if (h->def_dynamic)
1927         {
1928           h->def_dynamic = 0;
1929           hi->ref_dynamic = 1;
1930           if (hi->ref_regular
1931               || hi->def_regular)
1932             {
1933               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1934                 return FALSE;
1935             }
1936         }
1937
1938       /* Now set HI to H, so that the following code will set the
1939          other fields correctly.  */
1940       hi = h;
1941     }
1942
1943   /* Check if HI is a warning symbol.  */
1944   if (hi->root.type == bfd_link_hash_warning)
1945     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1946
1947   /* If there is a duplicate definition somewhere, then HI may not
1948      point to an indirect symbol.  We will have reported an error to
1949      the user in that case.  */
1950
1951   if (hi->root.type == bfd_link_hash_indirect)
1952     {
1953       struct elf_link_hash_entry *ht;
1954
1955       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1956       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
1957
1958       /* A reference to the SHORTNAME symbol from a dynamic library
1959          will be satisfied by the versioned symbol at runtime.  In
1960          effect, we have a reference to the versioned symbol.  */
1961       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1962       hi->dynamic_def |= ht->dynamic_def;
1963
1964       /* See if the new flags lead us to realize that the symbol must
1965          be dynamic.  */
1966       if (! *dynsym)
1967         {
1968           if (! dynamic)
1969             {
1970               if (! bfd_link_executable (info)
1971                   || hi->def_dynamic
1972                   || hi->ref_dynamic)
1973                 *dynsym = TRUE;
1974             }
1975           else
1976             {
1977               if (hi->ref_regular)
1978                 *dynsym = TRUE;
1979             }
1980         }
1981     }
1982
1983   /* We also need to define an indirection from the nondefault version
1984      of the symbol.  */
1985
1986 nondefault:
1987   len = strlen (name);
1988   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
1989   if (shortname == NULL)
1990     return FALSE;
1991   memcpy (shortname, name, shortlen);
1992   memcpy (shortname + shortlen, p + 1, len - shortlen);
1993
1994   /* Once again, merge with any existing symbol.  */
1995   type_change_ok = FALSE;
1996   size_change_ok = FALSE;
1997   tmp_sec = sec;
1998   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1999                               &hi, poldbfd, NULL, NULL, &skip, &override,
2000                               &type_change_ok, &size_change_ok, &matched))
2001     return FALSE;
2002
2003   if (skip)
2004     return TRUE;
2005
2006   if (override)
2007     {
2008       /* Here SHORTNAME is a versioned name, so we don't expect to see
2009          the type of override we do in the case above unless it is
2010          overridden by a versioned definition.  */
2011       if (hi->root.type != bfd_link_hash_defined
2012           && hi->root.type != bfd_link_hash_defweak)
2013         _bfd_error_handler
2014           /* xgettext:c-format */
2015           (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
2016            abfd, shortname);
2017     }
2018   else
2019     {
2020       bh = &hi->root;
2021       if (! (_bfd_generic_link_add_one_symbol
2022              (info, abfd, shortname, BSF_INDIRECT,
2023               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
2024         return FALSE;
2025       hi = (struct elf_link_hash_entry *) bh;
2026
2027       /* If there is a duplicate definition somewhere, then HI may not
2028          point to an indirect symbol.  We will have reported an error
2029          to the user in that case.  */
2030
2031       if (hi->root.type == bfd_link_hash_indirect)
2032         {
2033           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
2034           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
2035           hi->dynamic_def |= h->dynamic_def;
2036
2037           /* See if the new flags lead us to realize that the symbol
2038              must be dynamic.  */
2039           if (! *dynsym)
2040             {
2041               if (! dynamic)
2042                 {
2043                   if (! bfd_link_executable (info)
2044                       || hi->ref_dynamic)
2045                     *dynsym = TRUE;
2046                 }
2047               else
2048                 {
2049                   if (hi->ref_regular)
2050                     *dynsym = TRUE;
2051                 }
2052             }
2053         }
2054     }
2055
2056   return TRUE;
2057 }
2058 \f
2059 /* This routine is used to export all defined symbols into the dynamic
2060    symbol table.  It is called via elf_link_hash_traverse.  */
2061
2062 static bfd_boolean
2063 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
2064 {
2065   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2066
2067   /* Ignore indirect symbols.  These are added by the versioning code.  */
2068   if (h->root.type == bfd_link_hash_indirect)
2069     return TRUE;
2070
2071   /* Ignore this if we won't export it.  */
2072   if (!eif->info->export_dynamic && !h->dynamic)
2073     return TRUE;
2074
2075   if (h->dynindx == -1
2076       && (h->def_regular || h->ref_regular)
2077       && ! bfd_hide_sym_by_version (eif->info->version_info,
2078                                     h->root.root.string))
2079     {
2080       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2081         {
2082           eif->failed = TRUE;
2083           return FALSE;
2084         }
2085     }
2086
2087   return TRUE;
2088 }
2089 \f
2090 /* Look through the symbols which are defined in other shared
2091    libraries and referenced here.  Update the list of version
2092    dependencies.  This will be put into the .gnu.version_r section.
2093    This function is called via elf_link_hash_traverse.  */
2094
2095 static bfd_boolean
2096 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
2097                                          void *data)
2098 {
2099   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
2100   Elf_Internal_Verneed *t;
2101   Elf_Internal_Vernaux *a;
2102   bfd_size_type amt;
2103
2104   /* We only care about symbols defined in shared objects with version
2105      information.  */
2106   if (!h->def_dynamic
2107       || h->def_regular
2108       || h->dynindx == -1
2109       || h->verinfo.verdef == NULL
2110       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
2111           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
2112     return TRUE;
2113
2114   /* See if we already know about this version.  */
2115   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
2116        t != NULL;
2117        t = t->vn_nextref)
2118     {
2119       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
2120         continue;
2121
2122       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
2123         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
2124           return TRUE;
2125
2126       break;
2127     }
2128
2129   /* This is a new version.  Add it to tree we are building.  */
2130
2131   if (t == NULL)
2132     {
2133       amt = sizeof *t;
2134       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
2135       if (t == NULL)
2136         {
2137           rinfo->failed = TRUE;
2138           return FALSE;
2139         }
2140
2141       t->vn_bfd = h->verinfo.verdef->vd_bfd;
2142       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
2143       elf_tdata (rinfo->info->output_bfd)->verref = t;
2144     }
2145
2146   amt = sizeof *a;
2147   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
2148   if (a == NULL)
2149     {
2150       rinfo->failed = TRUE;
2151       return FALSE;
2152     }
2153
2154   /* Note that we are copying a string pointer here, and testing it
2155      above.  If bfd_elf_string_from_elf_section is ever changed to
2156      discard the string data when low in memory, this will have to be
2157      fixed.  */
2158   a->vna_nodename = h->verinfo.verdef->vd_nodename;
2159
2160   a->vna_flags = h->verinfo.verdef->vd_flags;
2161   a->vna_nextptr = t->vn_auxptr;
2162
2163   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
2164   ++rinfo->vers;
2165
2166   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
2167
2168   t->vn_auxptr = a;
2169
2170   return TRUE;
2171 }
2172
2173 /* Figure out appropriate versions for all the symbols.  We may not
2174    have the version number script until we have read all of the input
2175    files, so until that point we don't know which symbols should be
2176    local.  This function is called via elf_link_hash_traverse.  */
2177
2178 static bfd_boolean
2179 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2180 {
2181   struct elf_info_failed *sinfo;
2182   struct bfd_link_info *info;
2183   const struct elf_backend_data *bed;
2184   struct elf_info_failed eif;
2185   char *p;
2186
2187   sinfo = (struct elf_info_failed *) data;
2188   info = sinfo->info;
2189
2190   /* Fix the symbol flags.  */
2191   eif.failed = FALSE;
2192   eif.info = info;
2193   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2194     {
2195       if (eif.failed)
2196         sinfo->failed = TRUE;
2197       return FALSE;
2198     }
2199
2200   /* We only need version numbers for symbols defined in regular
2201      objects.  */
2202   if (!h->def_regular)
2203     return TRUE;
2204
2205   bed = get_elf_backend_data (info->output_bfd);
2206   p = strchr (h->root.root.string, ELF_VER_CHR);
2207   if (p != NULL && h->verinfo.vertree == NULL)
2208     {
2209       struct bfd_elf_version_tree *t;
2210
2211       ++p;
2212       if (*p == ELF_VER_CHR)
2213         ++p;
2214
2215       /* If there is no version string, we can just return out.  */
2216       if (*p == '\0')
2217         return TRUE;
2218
2219       /* Look for the version.  If we find it, it is no longer weak.  */
2220       for (t = sinfo->info->version_info; t != NULL; t = t->next)
2221         {
2222           if (strcmp (t->name, p) == 0)
2223             {
2224               size_t len;
2225               char *alc;
2226               struct bfd_elf_version_expr *d;
2227
2228               len = p - h->root.root.string;
2229               alc = (char *) bfd_malloc (len);
2230               if (alc == NULL)
2231                 {
2232                   sinfo->failed = TRUE;
2233                   return FALSE;
2234                 }
2235               memcpy (alc, h->root.root.string, len - 1);
2236               alc[len - 1] = '\0';
2237               if (alc[len - 2] == ELF_VER_CHR)
2238                 alc[len - 2] = '\0';
2239
2240               h->verinfo.vertree = t;
2241               t->used = TRUE;
2242               d = NULL;
2243
2244               if (t->globals.list != NULL)
2245                 d = (*t->match) (&t->globals, NULL, alc);
2246
2247               /* See if there is anything to force this symbol to
2248                  local scope.  */
2249               if (d == NULL && t->locals.list != NULL)
2250                 {
2251                   d = (*t->match) (&t->locals, NULL, alc);
2252                   if (d != NULL
2253                       && h->dynindx != -1
2254                       && ! info->export_dynamic)
2255                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2256                 }
2257
2258               free (alc);
2259               break;
2260             }
2261         }
2262
2263       /* If we are building an application, we need to create a
2264          version node for this version.  */
2265       if (t == NULL && bfd_link_executable (info))
2266         {
2267           struct bfd_elf_version_tree **pp;
2268           int version_index;
2269
2270           /* If we aren't going to export this symbol, we don't need
2271              to worry about it.  */
2272           if (h->dynindx == -1)
2273             return TRUE;
2274
2275           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd,
2276                                                           sizeof *t);
2277           if (t == NULL)
2278             {
2279               sinfo->failed = TRUE;
2280               return FALSE;
2281             }
2282
2283           t->name = p;
2284           t->name_indx = (unsigned int) -1;
2285           t->used = TRUE;
2286
2287           version_index = 1;
2288           /* Don't count anonymous version tag.  */
2289           if (sinfo->info->version_info != NULL
2290               && sinfo->info->version_info->vernum == 0)
2291             version_index = 0;
2292           for (pp = &sinfo->info->version_info;
2293                *pp != NULL;
2294                pp = &(*pp)->next)
2295             ++version_index;
2296           t->vernum = version_index;
2297
2298           *pp = t;
2299
2300           h->verinfo.vertree = t;
2301         }
2302       else if (t == NULL)
2303         {
2304           /* We could not find the version for a symbol when
2305              generating a shared archive.  Return an error.  */
2306           _bfd_error_handler
2307             /* xgettext:c-format */
2308             (_("%B: version node not found for symbol %s"),
2309              info->output_bfd, h->root.root.string);
2310           bfd_set_error (bfd_error_bad_value);
2311           sinfo->failed = TRUE;
2312           return FALSE;
2313         }
2314     }
2315
2316   /* If we don't have a version for this symbol, see if we can find
2317      something.  */
2318   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2319     {
2320       bfd_boolean hide;
2321
2322       h->verinfo.vertree
2323         = bfd_find_version_for_sym (sinfo->info->version_info,
2324                                     h->root.root.string, &hide);
2325       if (h->verinfo.vertree != NULL && hide)
2326         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2327     }
2328
2329   return TRUE;
2330 }
2331 \f
2332 /* Read and swap the relocs from the section indicated by SHDR.  This
2333    may be either a REL or a RELA section.  The relocations are
2334    translated into RELA relocations and stored in INTERNAL_RELOCS,
2335    which should have already been allocated to contain enough space.
2336    The EXTERNAL_RELOCS are a buffer where the external form of the
2337    relocations should be stored.
2338
2339    Returns FALSE if something goes wrong.  */
2340
2341 static bfd_boolean
2342 elf_link_read_relocs_from_section (bfd *abfd,
2343                                    asection *sec,
2344                                    Elf_Internal_Shdr *shdr,
2345                                    void *external_relocs,
2346                                    Elf_Internal_Rela *internal_relocs)
2347 {
2348   const struct elf_backend_data *bed;
2349   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2350   const bfd_byte *erela;
2351   const bfd_byte *erelaend;
2352   Elf_Internal_Rela *irela;
2353   Elf_Internal_Shdr *symtab_hdr;
2354   size_t nsyms;
2355
2356   /* Position ourselves at the start of the section.  */
2357   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2358     return FALSE;
2359
2360   /* Read the relocations.  */
2361   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2362     return FALSE;
2363
2364   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2365   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2366
2367   bed = get_elf_backend_data (abfd);
2368
2369   /* Convert the external relocations to the internal format.  */
2370   if (shdr->sh_entsize == bed->s->sizeof_rel)
2371     swap_in = bed->s->swap_reloc_in;
2372   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2373     swap_in = bed->s->swap_reloca_in;
2374   else
2375     {
2376       bfd_set_error (bfd_error_wrong_format);
2377       return FALSE;
2378     }
2379
2380   erela = (const bfd_byte *) external_relocs;
2381   erelaend = erela + shdr->sh_size;
2382   irela = internal_relocs;
2383   while (erela < erelaend)
2384     {
2385       bfd_vma r_symndx;
2386
2387       (*swap_in) (abfd, erela, irela);
2388       r_symndx = ELF32_R_SYM (irela->r_info);
2389       if (bed->s->arch_size == 64)
2390         r_symndx >>= 24;
2391       if (nsyms > 0)
2392         {
2393           if ((size_t) r_symndx >= nsyms)
2394             {
2395               _bfd_error_handler
2396                 /* xgettext:c-format */
2397                 (_("%B: bad reloc symbol index (0x%lx >= 0x%lx)"
2398                    " for offset 0x%lx in section `%A'"),
2399                  abfd, (unsigned long) r_symndx, (unsigned long) nsyms,
2400                  irela->r_offset, sec);
2401               bfd_set_error (bfd_error_bad_value);
2402               return FALSE;
2403             }
2404         }
2405       else if (r_symndx != STN_UNDEF)
2406         {
2407           _bfd_error_handler
2408             /* xgettext:c-format */
2409             (_("%B: non-zero symbol index (0x%lx)"
2410                " for offset 0x%lx in section `%A'"
2411                " when the object file has no symbol table"),
2412              abfd, (unsigned long) r_symndx, (unsigned long) nsyms,
2413              irela->r_offset, sec);
2414           bfd_set_error (bfd_error_bad_value);
2415           return FALSE;
2416         }
2417       irela += bed->s->int_rels_per_ext_rel;
2418       erela += shdr->sh_entsize;
2419     }
2420
2421   return TRUE;
2422 }
2423
2424 /* Read and swap the relocs for a section O.  They may have been
2425    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2426    not NULL, they are used as buffers to read into.  They are known to
2427    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2428    the return value is allocated using either malloc or bfd_alloc,
2429    according to the KEEP_MEMORY argument.  If O has two relocation
2430    sections (both REL and RELA relocations), then the REL_HDR
2431    relocations will appear first in INTERNAL_RELOCS, followed by the
2432    RELA_HDR relocations.  */
2433
2434 Elf_Internal_Rela *
2435 _bfd_elf_link_read_relocs (bfd *abfd,
2436                            asection *o,
2437                            void *external_relocs,
2438                            Elf_Internal_Rela *internal_relocs,
2439                            bfd_boolean keep_memory)
2440 {
2441   void *alloc1 = NULL;
2442   Elf_Internal_Rela *alloc2 = NULL;
2443   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2444   struct bfd_elf_section_data *esdo = elf_section_data (o);
2445   Elf_Internal_Rela *internal_rela_relocs;
2446
2447   if (esdo->relocs != NULL)
2448     return esdo->relocs;
2449
2450   if (o->reloc_count == 0)
2451     return NULL;
2452
2453   if (internal_relocs == NULL)
2454     {
2455       bfd_size_type size;
2456
2457       size = (bfd_size_type) o->reloc_count * sizeof (Elf_Internal_Rela);
2458       if (keep_memory)
2459         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2460       else
2461         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2462       if (internal_relocs == NULL)
2463         goto error_return;
2464     }
2465
2466   if (external_relocs == NULL)
2467     {
2468       bfd_size_type size = 0;
2469
2470       if (esdo->rel.hdr)
2471         size += esdo->rel.hdr->sh_size;
2472       if (esdo->rela.hdr)
2473         size += esdo->rela.hdr->sh_size;
2474
2475       alloc1 = bfd_malloc (size);
2476       if (alloc1 == NULL)
2477         goto error_return;
2478       external_relocs = alloc1;
2479     }
2480
2481   internal_rela_relocs = internal_relocs;
2482   if (esdo->rel.hdr)
2483     {
2484       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2485                                               external_relocs,
2486                                               internal_relocs))
2487         goto error_return;
2488       external_relocs = (((bfd_byte *) external_relocs)
2489                          + esdo->rel.hdr->sh_size);
2490       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2491                                * bed->s->int_rels_per_ext_rel);
2492     }
2493
2494   if (esdo->rela.hdr
2495       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2496                                               external_relocs,
2497                                               internal_rela_relocs)))
2498     goto error_return;
2499
2500   /* Cache the results for next time, if we can.  */
2501   if (keep_memory)
2502     esdo->relocs = internal_relocs;
2503
2504   if (alloc1 != NULL)
2505     free (alloc1);
2506
2507   /* Don't free alloc2, since if it was allocated we are passing it
2508      back (under the name of internal_relocs).  */
2509
2510   return internal_relocs;
2511
2512  error_return:
2513   if (alloc1 != NULL)
2514     free (alloc1);
2515   if (alloc2 != NULL)
2516     {
2517       if (keep_memory)
2518         bfd_release (abfd, alloc2);
2519       else
2520         free (alloc2);
2521     }
2522   return NULL;
2523 }
2524
2525 /* Compute the size of, and allocate space for, REL_HDR which is the
2526    section header for a section containing relocations for O.  */
2527
2528 static bfd_boolean
2529 _bfd_elf_link_size_reloc_section (bfd *abfd,
2530                                   struct bfd_elf_section_reloc_data *reldata)
2531 {
2532   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2533
2534   /* That allows us to calculate the size of the section.  */
2535   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2536
2537   /* The contents field must last into write_object_contents, so we
2538      allocate it with bfd_alloc rather than malloc.  Also since we
2539      cannot be sure that the contents will actually be filled in,
2540      we zero the allocated space.  */
2541   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2542   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2543     return FALSE;
2544
2545   if (reldata->hashes == NULL && reldata->count)
2546     {
2547       struct elf_link_hash_entry **p;
2548
2549       p = ((struct elf_link_hash_entry **)
2550            bfd_zmalloc (reldata->count * sizeof (*p)));
2551       if (p == NULL)
2552         return FALSE;
2553
2554       reldata->hashes = p;
2555     }
2556
2557   return TRUE;
2558 }
2559
2560 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2561    originated from the section given by INPUT_REL_HDR) to the
2562    OUTPUT_BFD.  */
2563
2564 bfd_boolean
2565 _bfd_elf_link_output_relocs (bfd *output_bfd,
2566                              asection *input_section,
2567                              Elf_Internal_Shdr *input_rel_hdr,
2568                              Elf_Internal_Rela *internal_relocs,
2569                              struct elf_link_hash_entry **rel_hash
2570                                ATTRIBUTE_UNUSED)
2571 {
2572   Elf_Internal_Rela *irela;
2573   Elf_Internal_Rela *irelaend;
2574   bfd_byte *erel;
2575   struct bfd_elf_section_reloc_data *output_reldata;
2576   asection *output_section;
2577   const struct elf_backend_data *bed;
2578   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2579   struct bfd_elf_section_data *esdo;
2580
2581   output_section = input_section->output_section;
2582
2583   bed = get_elf_backend_data (output_bfd);
2584   esdo = elf_section_data (output_section);
2585   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2586     {
2587       output_reldata = &esdo->rel;
2588       swap_out = bed->s->swap_reloc_out;
2589     }
2590   else if (esdo->rela.hdr
2591            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2592     {
2593       output_reldata = &esdo->rela;
2594       swap_out = bed->s->swap_reloca_out;
2595     }
2596   else
2597     {
2598       _bfd_error_handler
2599         /* xgettext:c-format */
2600         (_("%B: relocation size mismatch in %B section %A"),
2601          output_bfd, input_section->owner, input_section);
2602       bfd_set_error (bfd_error_wrong_format);
2603       return FALSE;
2604     }
2605
2606   erel = output_reldata->hdr->contents;
2607   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2608   irela = internal_relocs;
2609   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2610                       * bed->s->int_rels_per_ext_rel);
2611   while (irela < irelaend)
2612     {
2613       (*swap_out) (output_bfd, irela, erel);
2614       irela += bed->s->int_rels_per_ext_rel;
2615       erel += input_rel_hdr->sh_entsize;
2616     }
2617
2618   /* Bump the counter, so that we know where to add the next set of
2619      relocations.  */
2620   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2621
2622   return TRUE;
2623 }
2624 \f
2625 /* Make weak undefined symbols in PIE dynamic.  */
2626
2627 bfd_boolean
2628 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2629                                  struct elf_link_hash_entry *h)
2630 {
2631   if (bfd_link_pie (info)
2632       && h->dynindx == -1
2633       && h->root.type == bfd_link_hash_undefweak)
2634     return bfd_elf_link_record_dynamic_symbol (info, h);
2635
2636   return TRUE;
2637 }
2638
2639 /* Fix up the flags for a symbol.  This handles various cases which
2640    can only be fixed after all the input files are seen.  This is
2641    currently called by both adjust_dynamic_symbol and
2642    assign_sym_version, which is unnecessary but perhaps more robust in
2643    the face of future changes.  */
2644
2645 static bfd_boolean
2646 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2647                            struct elf_info_failed *eif)
2648 {
2649   const struct elf_backend_data *bed;
2650
2651   /* If this symbol was mentioned in a non-ELF file, try to set
2652      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2653      permit a non-ELF file to correctly refer to a symbol defined in
2654      an ELF dynamic object.  */
2655   if (h->non_elf)
2656     {
2657       while (h->root.type == bfd_link_hash_indirect)
2658         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2659
2660       if (h->root.type != bfd_link_hash_defined
2661           && h->root.type != bfd_link_hash_defweak)
2662         {
2663           h->ref_regular = 1;
2664           h->ref_regular_nonweak = 1;
2665         }
2666       else
2667         {
2668           if (h->root.u.def.section->owner != NULL
2669               && (bfd_get_flavour (h->root.u.def.section->owner)
2670                   == bfd_target_elf_flavour))
2671             {
2672               h->ref_regular = 1;
2673               h->ref_regular_nonweak = 1;
2674             }
2675           else
2676             h->def_regular = 1;
2677         }
2678
2679       if (h->dynindx == -1
2680           && (h->def_dynamic
2681               || h->ref_dynamic))
2682         {
2683           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2684             {
2685               eif->failed = TRUE;
2686               return FALSE;
2687             }
2688         }
2689     }
2690   else
2691     {
2692       /* Unfortunately, NON_ELF is only correct if the symbol
2693          was first seen in a non-ELF file.  Fortunately, if the symbol
2694          was first seen in an ELF file, we're probably OK unless the
2695          symbol was defined in a non-ELF file.  Catch that case here.
2696          FIXME: We're still in trouble if the symbol was first seen in
2697          a dynamic object, and then later in a non-ELF regular object.  */
2698       if ((h->root.type == bfd_link_hash_defined
2699            || h->root.type == bfd_link_hash_defweak)
2700           && !h->def_regular
2701           && (h->root.u.def.section->owner != NULL
2702               ? (bfd_get_flavour (h->root.u.def.section->owner)
2703                  != bfd_target_elf_flavour)
2704               : (bfd_is_abs_section (h->root.u.def.section)
2705                  && !h->def_dynamic)))
2706         h->def_regular = 1;
2707     }
2708
2709   /* Backend specific symbol fixup.  */
2710   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2711   if (bed->elf_backend_fixup_symbol
2712       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2713     return FALSE;
2714
2715   /* If this is a final link, and the symbol was defined as a common
2716      symbol in a regular object file, and there was no definition in
2717      any dynamic object, then the linker will have allocated space for
2718      the symbol in a common section but the DEF_REGULAR
2719      flag will not have been set.  */
2720   if (h->root.type == bfd_link_hash_defined
2721       && !h->def_regular
2722       && h->ref_regular
2723       && !h->def_dynamic
2724       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2725     h->def_regular = 1;
2726
2727   /* If a weak undefined symbol has non-default visibility, we also
2728      hide it from the dynamic linker.  */
2729   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2730       && h->root.type == bfd_link_hash_undefweak)
2731     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2732
2733   /* A hidden versioned symbol in executable should be forced local if
2734      it is is locally defined, not referenced by shared library and not
2735      exported.  */
2736   else if (bfd_link_executable (eif->info)
2737            && h->versioned == versioned_hidden
2738            && !eif->info->export_dynamic
2739            && !h->dynamic
2740            && !h->ref_dynamic
2741            && h->def_regular)
2742     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2743
2744   /* If -Bsymbolic was used (which means to bind references to global
2745      symbols to the definition within the shared object), and this
2746      symbol was defined in a regular object, then it actually doesn't
2747      need a PLT entry.  Likewise, if the symbol has non-default
2748      visibility.  If the symbol has hidden or internal visibility, we
2749      will force it local.  */
2750   else if (h->needs_plt
2751            && bfd_link_pic (eif->info)
2752            && is_elf_hash_table (eif->info->hash)
2753            && (SYMBOLIC_BIND (eif->info, h)
2754                || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2755            && h->def_regular)
2756     {
2757       bfd_boolean force_local;
2758
2759       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2760                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2761       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2762     }
2763
2764   /* If this is a weak defined symbol in a dynamic object, and we know
2765      the real definition in the dynamic object, copy interesting flags
2766      over to the real definition.  */
2767   if (h->u.weakdef != NULL)
2768     {
2769       /* If the real definition is defined by a regular object file,
2770          don't do anything special.  See the longer description in
2771          _bfd_elf_adjust_dynamic_symbol, below.  */
2772       if (h->u.weakdef->def_regular)
2773         h->u.weakdef = NULL;
2774       else
2775         {
2776           struct elf_link_hash_entry *weakdef = h->u.weakdef;
2777
2778           while (h->root.type == bfd_link_hash_indirect)
2779             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2780
2781           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2782                       || h->root.type == bfd_link_hash_defweak);
2783           BFD_ASSERT (weakdef->def_dynamic);
2784           BFD_ASSERT (weakdef->root.type == bfd_link_hash_defined
2785                       || weakdef->root.type == bfd_link_hash_defweak);
2786           (*bed->elf_backend_copy_indirect_symbol) (eif->info, weakdef, h);
2787         }
2788     }
2789
2790   return TRUE;
2791 }
2792
2793 /* Make the backend pick a good value for a dynamic symbol.  This is
2794    called via elf_link_hash_traverse, and also calls itself
2795    recursively.  */
2796
2797 static bfd_boolean
2798 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2799 {
2800   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2801   bfd *dynobj;
2802   const struct elf_backend_data *bed;
2803
2804   if (! is_elf_hash_table (eif->info->hash))
2805     return FALSE;
2806
2807   /* Ignore indirect symbols.  These are added by the versioning code.  */
2808   if (h->root.type == bfd_link_hash_indirect)
2809     return TRUE;
2810
2811   /* Fix the symbol flags.  */
2812   if (! _bfd_elf_fix_symbol_flags (h, eif))
2813     return FALSE;
2814
2815   if (h->root.type == bfd_link_hash_undefweak)
2816     {
2817       if (eif->info->dynamic_undefined_weak == 0)
2818         _bfd_elf_link_hash_hide_symbol (eif->info, h, TRUE);
2819       else if (eif->info->dynamic_undefined_weak > 0
2820                && h->ref_regular
2821                && ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
2822                && !bfd_hide_sym_by_version (eif->info->version_info,
2823                                             h->root.root.string))
2824         {
2825           if (!bfd_elf_link_record_dynamic_symbol (eif->info, h))
2826             {
2827               eif->failed = TRUE;
2828               return FALSE;
2829             }
2830         }
2831     }
2832
2833   /* If this symbol does not require a PLT entry, and it is not
2834      defined by a dynamic object, or is not referenced by a regular
2835      object, ignore it.  We do have to handle a weak defined symbol,
2836      even if no regular object refers to it, if we decided to add it
2837      to the dynamic symbol table.  FIXME: Do we normally need to worry
2838      about symbols which are defined by one dynamic object and
2839      referenced by another one?  */
2840   if (!h->needs_plt
2841       && h->type != STT_GNU_IFUNC
2842       && (h->def_regular
2843           || !h->def_dynamic
2844           || (!h->ref_regular
2845               && (h->u.weakdef == NULL || h->u.weakdef->dynindx == -1))))
2846     {
2847       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2848       return TRUE;
2849     }
2850
2851   /* If we've already adjusted this symbol, don't do it again.  This
2852      can happen via a recursive call.  */
2853   if (h->dynamic_adjusted)
2854     return TRUE;
2855
2856   /* Don't look at this symbol again.  Note that we must set this
2857      after checking the above conditions, because we may look at a
2858      symbol once, decide not to do anything, and then get called
2859      recursively later after REF_REGULAR is set below.  */
2860   h->dynamic_adjusted = 1;
2861
2862   /* If this is a weak definition, and we know a real definition, and
2863      the real symbol is not itself defined by a regular object file,
2864      then get a good value for the real definition.  We handle the
2865      real symbol first, for the convenience of the backend routine.
2866
2867      Note that there is a confusing case here.  If the real definition
2868      is defined by a regular object file, we don't get the real symbol
2869      from the dynamic object, but we do get the weak symbol.  If the
2870      processor backend uses a COPY reloc, then if some routine in the
2871      dynamic object changes the real symbol, we will not see that
2872      change in the corresponding weak symbol.  This is the way other
2873      ELF linkers work as well, and seems to be a result of the shared
2874      library model.
2875
2876      I will clarify this issue.  Most SVR4 shared libraries define the
2877      variable _timezone and define timezone as a weak synonym.  The
2878      tzset call changes _timezone.  If you write
2879        extern int timezone;
2880        int _timezone = 5;
2881        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2882      you might expect that, since timezone is a synonym for _timezone,
2883      the same number will print both times.  However, if the processor
2884      backend uses a COPY reloc, then actually timezone will be copied
2885      into your process image, and, since you define _timezone
2886      yourself, _timezone will not.  Thus timezone and _timezone will
2887      wind up at different memory locations.  The tzset call will set
2888      _timezone, leaving timezone unchanged.  */
2889
2890   if (h->u.weakdef != NULL)
2891     {
2892       /* If we get to this point, there is an implicit reference to
2893          H->U.WEAKDEF by a regular object file via the weak symbol H.  */
2894       h->u.weakdef->ref_regular = 1;
2895
2896       /* Ensure that the backend adjust_dynamic_symbol function sees
2897          H->U.WEAKDEF before H by recursively calling ourselves.  */
2898       if (! _bfd_elf_adjust_dynamic_symbol (h->u.weakdef, eif))
2899         return FALSE;
2900     }
2901
2902   /* If a symbol has no type and no size and does not require a PLT
2903      entry, then we are probably about to do the wrong thing here: we
2904      are probably going to create a COPY reloc for an empty object.
2905      This case can arise when a shared object is built with assembly
2906      code, and the assembly code fails to set the symbol type.  */
2907   if (h->size == 0
2908       && h->type == STT_NOTYPE
2909       && !h->needs_plt)
2910     _bfd_error_handler
2911       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2912        h->root.root.string);
2913
2914   dynobj = elf_hash_table (eif->info)->dynobj;
2915   bed = get_elf_backend_data (dynobj);
2916
2917   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2918     {
2919       eif->failed = TRUE;
2920       return FALSE;
2921     }
2922
2923   return TRUE;
2924 }
2925
2926 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2927    DYNBSS.  */
2928
2929 bfd_boolean
2930 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
2931                               struct elf_link_hash_entry *h,
2932                               asection *dynbss)
2933 {
2934   unsigned int power_of_two;
2935   bfd_vma mask;
2936   asection *sec = h->root.u.def.section;
2937
2938   /* The section aligment of definition is the maximum alignment
2939      requirement of symbols defined in the section.  Since we don't
2940      know the symbol alignment requirement, we start with the
2941      maximum alignment and check low bits of the symbol address
2942      for the minimum alignment.  */
2943   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2944   mask = ((bfd_vma) 1 << power_of_two) - 1;
2945   while ((h->root.u.def.value & mask) != 0)
2946     {
2947        mask >>= 1;
2948        --power_of_two;
2949     }
2950
2951   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
2952                                                 dynbss))
2953     {
2954       /* Adjust the section alignment if needed.  */
2955       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
2956                                        power_of_two))
2957         return FALSE;
2958     }
2959
2960   /* We make sure that the symbol will be aligned properly.  */
2961   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
2962
2963   /* Define the symbol as being at this point in DYNBSS.  */
2964   h->root.u.def.section = dynbss;
2965   h->root.u.def.value = dynbss->size;
2966
2967   /* Increment the size of DYNBSS to make room for the symbol.  */
2968   dynbss->size += h->size;
2969
2970   /* No error if extern_protected_data is true.  */
2971   if (h->protected_def
2972       && (!info->extern_protected_data
2973           || (info->extern_protected_data < 0
2974               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
2975     info->callbacks->einfo
2976       (_("%P: copy reloc against protected `%T' is dangerous\n"),
2977        h->root.root.string);
2978
2979   return TRUE;
2980 }
2981
2982 /* Adjust all external symbols pointing into SEC_MERGE sections
2983    to reflect the object merging within the sections.  */
2984
2985 static bfd_boolean
2986 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
2987 {
2988   asection *sec;
2989
2990   if ((h->root.type == bfd_link_hash_defined
2991        || h->root.type == bfd_link_hash_defweak)
2992       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
2993       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
2994     {
2995       bfd *output_bfd = (bfd *) data;
2996
2997       h->root.u.def.value =
2998         _bfd_merged_section_offset (output_bfd,
2999                                     &h->root.u.def.section,
3000                                     elf_section_data (sec)->sec_info,
3001                                     h->root.u.def.value);
3002     }
3003
3004   return TRUE;
3005 }
3006
3007 /* Returns false if the symbol referred to by H should be considered
3008    to resolve local to the current module, and true if it should be
3009    considered to bind dynamically.  */
3010
3011 bfd_boolean
3012 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
3013                            struct bfd_link_info *info,
3014                            bfd_boolean not_local_protected)
3015 {
3016   bfd_boolean binding_stays_local_p;
3017   const struct elf_backend_data *bed;
3018   struct elf_link_hash_table *hash_table;
3019
3020   if (h == NULL)
3021     return FALSE;
3022
3023   while (h->root.type == bfd_link_hash_indirect
3024          || h->root.type == bfd_link_hash_warning)
3025     h = (struct elf_link_hash_entry *) h->root.u.i.link;
3026
3027   /* If it was forced local, then clearly it's not dynamic.  */
3028   if (h->dynindx == -1)
3029     return FALSE;
3030   if (h->forced_local)
3031     return FALSE;
3032
3033   /* Identify the cases where name binding rules say that a
3034      visible symbol resolves locally.  */
3035   binding_stays_local_p = (bfd_link_executable (info)
3036                            || SYMBOLIC_BIND (info, h));
3037
3038   switch (ELF_ST_VISIBILITY (h->other))
3039     {
3040     case STV_INTERNAL:
3041     case STV_HIDDEN:
3042       return FALSE;
3043
3044     case STV_PROTECTED:
3045       hash_table = elf_hash_table (info);
3046       if (!is_elf_hash_table (hash_table))
3047         return FALSE;
3048
3049       bed = get_elf_backend_data (hash_table->dynobj);
3050
3051       /* Proper resolution for function pointer equality may require
3052          that these symbols perhaps be resolved dynamically, even though
3053          we should be resolving them to the current module.  */
3054       if (!not_local_protected || !bed->is_function_type (h->type))
3055         binding_stays_local_p = TRUE;
3056       break;
3057
3058     default:
3059       break;
3060     }
3061
3062   /* If it isn't defined locally, then clearly it's dynamic.  */
3063   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
3064     return TRUE;
3065
3066   /* Otherwise, the symbol is dynamic if binding rules don't tell
3067      us that it remains local.  */
3068   return !binding_stays_local_p;
3069 }
3070
3071 /* Return true if the symbol referred to by H should be considered
3072    to resolve local to the current module, and false otherwise.  Differs
3073    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
3074    undefined symbols.  The two functions are virtually identical except
3075    for the place where dynindx == -1 is tested.  If that test is true,
3076    _bfd_elf_dynamic_symbol_p will say the symbol is local, while
3077    _bfd_elf_symbol_refs_local_p will say the symbol is local only for
3078    defined symbols.
3079    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
3080    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
3081    treatment of undefined weak symbols.  For those that do not make
3082    undefined weak symbols dynamic, both functions may return false.  */
3083
3084 bfd_boolean
3085 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
3086                               struct bfd_link_info *info,
3087                               bfd_boolean local_protected)
3088 {
3089   const struct elf_backend_data *bed;
3090   struct elf_link_hash_table *hash_table;
3091
3092   /* If it's a local sym, of course we resolve locally.  */
3093   if (h == NULL)
3094     return TRUE;
3095
3096   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
3097   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
3098       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
3099     return TRUE;
3100
3101   /* Forced local symbols resolve locally.  */
3102   if (h->forced_local)
3103     return TRUE;
3104
3105   /* Common symbols that become definitions don't get the DEF_REGULAR
3106      flag set, so test it first, and don't bail out.  */
3107   if (ELF_COMMON_DEF_P (h))
3108     /* Do nothing.  */;
3109   /* If we don't have a definition in a regular file, then we can't
3110      resolve locally.  The sym is either undefined or dynamic.  */
3111   else if (!h->def_regular)
3112     return FALSE;
3113
3114   /* Non-dynamic symbols resolve locally.  */
3115   if (h->dynindx == -1)
3116     return TRUE;
3117
3118   /* At this point, we know the symbol is defined and dynamic.  In an
3119      executable it must resolve locally, likewise when building symbolic
3120      shared libraries.  */
3121   if (bfd_link_executable (info) || SYMBOLIC_BIND (info, h))
3122     return TRUE;
3123
3124   /* Now deal with defined dynamic symbols in shared libraries.  Ones
3125      with default visibility might not resolve locally.  */
3126   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
3127     return FALSE;
3128
3129   hash_table = elf_hash_table (info);
3130   if (!is_elf_hash_table (hash_table))
3131     return TRUE;
3132
3133   bed = get_elf_backend_data (hash_table->dynobj);
3134
3135   /* If extern_protected_data is false, STV_PROTECTED non-function
3136      symbols are local.  */
3137   if ((!info->extern_protected_data
3138        || (info->extern_protected_data < 0
3139            && !bed->extern_protected_data))
3140       && !bed->is_function_type (h->type))
3141     return TRUE;
3142
3143   /* Function pointer equality tests may require that STV_PROTECTED
3144      symbols be treated as dynamic symbols.  If the address of a
3145      function not defined in an executable is set to that function's
3146      plt entry in the executable, then the address of the function in
3147      a shared library must also be the plt entry in the executable.  */
3148   return local_protected;
3149 }
3150
3151 /* Caches some TLS segment info, and ensures that the TLS segment vma is
3152    aligned.  Returns the first TLS output section.  */
3153
3154 struct bfd_section *
3155 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
3156 {
3157   struct bfd_section *sec, *tls;
3158   unsigned int align = 0;
3159
3160   for (sec = obfd->sections; sec != NULL; sec = sec->next)
3161     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
3162       break;
3163   tls = sec;
3164
3165   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
3166     if (sec->alignment_power > align)
3167       align = sec->alignment_power;
3168
3169   elf_hash_table (info)->tls_sec = tls;
3170
3171   /* Ensure the alignment of the first section is the largest alignment,
3172      so that the tls segment starts aligned.  */
3173   if (tls != NULL)
3174     tls->alignment_power = align;
3175
3176   return tls;
3177 }
3178
3179 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
3180 static bfd_boolean
3181 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
3182                                   Elf_Internal_Sym *sym)
3183 {
3184   const struct elf_backend_data *bed;
3185
3186   /* Local symbols do not count, but target specific ones might.  */
3187   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
3188       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
3189     return FALSE;
3190
3191   bed = get_elf_backend_data (abfd);
3192   /* Function symbols do not count.  */
3193   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
3194     return FALSE;
3195
3196   /* If the section is undefined, then so is the symbol.  */
3197   if (sym->st_shndx == SHN_UNDEF)
3198     return FALSE;
3199
3200   /* If the symbol is defined in the common section, then
3201      it is a common definition and so does not count.  */
3202   if (bed->common_definition (sym))
3203     return FALSE;
3204
3205   /* If the symbol is in a target specific section then we
3206      must rely upon the backend to tell us what it is.  */
3207   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3208     /* FIXME - this function is not coded yet:
3209
3210        return _bfd_is_global_symbol_definition (abfd, sym);
3211
3212        Instead for now assume that the definition is not global,
3213        Even if this is wrong, at least the linker will behave
3214        in the same way that it used to do.  */
3215     return FALSE;
3216
3217   return TRUE;
3218 }
3219
3220 /* Search the symbol table of the archive element of the archive ABFD
3221    whose archive map contains a mention of SYMDEF, and determine if
3222    the symbol is defined in this element.  */
3223 static bfd_boolean
3224 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3225 {
3226   Elf_Internal_Shdr * hdr;
3227   size_t symcount;
3228   size_t extsymcount;
3229   size_t extsymoff;
3230   Elf_Internal_Sym *isymbuf;
3231   Elf_Internal_Sym *isym;
3232   Elf_Internal_Sym *isymend;
3233   bfd_boolean result;
3234
3235   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3236   if (abfd == NULL)
3237     return FALSE;
3238
3239   if (! bfd_check_format (abfd, bfd_object))
3240     return FALSE;
3241
3242   /* Select the appropriate symbol table.  If we don't know if the
3243      object file is an IR object, give linker LTO plugin a chance to
3244      get the correct symbol table.  */
3245   if (abfd->plugin_format == bfd_plugin_yes
3246 #if BFD_SUPPORTS_PLUGINS
3247       || (abfd->plugin_format == bfd_plugin_unknown
3248           && bfd_link_plugin_object_p (abfd))
3249 #endif
3250       )
3251     {
3252       /* Use the IR symbol table if the object has been claimed by
3253          plugin.  */
3254       abfd = abfd->plugin_dummy_bfd;
3255       hdr = &elf_tdata (abfd)->symtab_hdr;
3256     }
3257   else if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3258     hdr = &elf_tdata (abfd)->symtab_hdr;
3259   else
3260     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3261
3262   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3263
3264   /* The sh_info field of the symtab header tells us where the
3265      external symbols start.  We don't care about the local symbols.  */
3266   if (elf_bad_symtab (abfd))
3267     {
3268       extsymcount = symcount;
3269       extsymoff = 0;
3270     }
3271   else
3272     {
3273       extsymcount = symcount - hdr->sh_info;
3274       extsymoff = hdr->sh_info;
3275     }
3276
3277   if (extsymcount == 0)
3278     return FALSE;
3279
3280   /* Read in the symbol table.  */
3281   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3282                                   NULL, NULL, NULL);
3283   if (isymbuf == NULL)
3284     return FALSE;
3285
3286   /* Scan the symbol table looking for SYMDEF.  */
3287   result = FALSE;
3288   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3289     {
3290       const char *name;
3291
3292       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3293                                               isym->st_name);
3294       if (name == NULL)
3295         break;
3296
3297       if (strcmp (name, symdef->name) == 0)
3298         {
3299           result = is_global_data_symbol_definition (abfd, isym);
3300           break;
3301         }
3302     }
3303
3304   free (isymbuf);
3305
3306   return result;
3307 }
3308 \f
3309 /* Add an entry to the .dynamic table.  */
3310
3311 bfd_boolean
3312 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3313                             bfd_vma tag,
3314                             bfd_vma val)
3315 {
3316   struct elf_link_hash_table *hash_table;
3317   const struct elf_backend_data *bed;
3318   asection *s;
3319   bfd_size_type newsize;
3320   bfd_byte *newcontents;
3321   Elf_Internal_Dyn dyn;
3322
3323   hash_table = elf_hash_table (info);
3324   if (! is_elf_hash_table (hash_table))
3325     return FALSE;
3326
3327   bed = get_elf_backend_data (hash_table->dynobj);
3328   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3329   BFD_ASSERT (s != NULL);
3330
3331   newsize = s->size + bed->s->sizeof_dyn;
3332   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3333   if (newcontents == NULL)
3334     return FALSE;
3335
3336   dyn.d_tag = tag;
3337   dyn.d_un.d_val = val;
3338   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3339
3340   s->size = newsize;
3341   s->contents = newcontents;
3342
3343   return TRUE;
3344 }
3345
3346 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3347    otherwise just check whether one already exists.  Returns -1 on error,
3348    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3349
3350 static int
3351 elf_add_dt_needed_tag (bfd *abfd,
3352                        struct bfd_link_info *info,
3353                        const char *soname,
3354                        bfd_boolean do_it)
3355 {
3356   struct elf_link_hash_table *hash_table;
3357   size_t strindex;
3358
3359   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3360     return -1;
3361
3362   hash_table = elf_hash_table (info);
3363   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3364   if (strindex == (size_t) -1)
3365     return -1;
3366
3367   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3368     {
3369       asection *sdyn;
3370       const struct elf_backend_data *bed;
3371       bfd_byte *extdyn;
3372
3373       bed = get_elf_backend_data (hash_table->dynobj);
3374       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3375       if (sdyn != NULL)
3376         for (extdyn = sdyn->contents;
3377              extdyn < sdyn->contents + sdyn->size;
3378              extdyn += bed->s->sizeof_dyn)
3379           {
3380             Elf_Internal_Dyn dyn;
3381
3382             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3383             if (dyn.d_tag == DT_NEEDED
3384                 && dyn.d_un.d_val == strindex)
3385               {
3386                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3387                 return 1;
3388               }
3389           }
3390     }
3391
3392   if (do_it)
3393     {
3394       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3395         return -1;
3396
3397       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3398         return -1;
3399     }
3400   else
3401     /* We were just checking for existence of the tag.  */
3402     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3403
3404   return 0;
3405 }
3406
3407 /* Return true if SONAME is on the needed list between NEEDED and STOP
3408    (or the end of list if STOP is NULL), and needed by a library that
3409    will be loaded.  */
3410
3411 static bfd_boolean
3412 on_needed_list (const char *soname,
3413                 struct bfd_link_needed_list *needed,
3414                 struct bfd_link_needed_list *stop)
3415 {
3416   struct bfd_link_needed_list *look;
3417   for (look = needed; look != stop; look = look->next)
3418     if (strcmp (soname, look->name) == 0
3419         && ((elf_dyn_lib_class (look->by) & DYN_AS_NEEDED) == 0
3420             /* If needed by a library that itself is not directly
3421                needed, recursively check whether that library is
3422                indirectly needed.  Since we add DT_NEEDED entries to
3423                the end of the list, library dependencies appear after
3424                the library.  Therefore search prior to the current
3425                LOOK, preventing possible infinite recursion.  */
3426             || on_needed_list (elf_dt_name (look->by), needed, look)))
3427       return TRUE;
3428
3429   return FALSE;
3430 }
3431
3432 /* Sort symbol by value, section, and size.  */
3433 static int
3434 elf_sort_symbol (const void *arg1, const void *arg2)
3435 {
3436   const struct elf_link_hash_entry *h1;
3437   const struct elf_link_hash_entry *h2;
3438   bfd_signed_vma vdiff;
3439
3440   h1 = *(const struct elf_link_hash_entry **) arg1;
3441   h2 = *(const struct elf_link_hash_entry **) arg2;
3442   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3443   if (vdiff != 0)
3444     return vdiff > 0 ? 1 : -1;
3445   else
3446     {
3447       int sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3448       if (sdiff != 0)
3449         return sdiff > 0 ? 1 : -1;
3450     }
3451   vdiff = h1->size - h2->size;
3452   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3453 }
3454
3455 /* This function is used to adjust offsets into .dynstr for
3456    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3457
3458 static bfd_boolean
3459 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3460 {
3461   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3462
3463   if (h->dynindx != -1)
3464     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3465   return TRUE;
3466 }
3467
3468 /* Assign string offsets in .dynstr, update all structures referencing
3469    them.  */
3470
3471 static bfd_boolean
3472 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3473 {
3474   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3475   struct elf_link_local_dynamic_entry *entry;
3476   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3477   bfd *dynobj = hash_table->dynobj;
3478   asection *sdyn;
3479   bfd_size_type size;
3480   const struct elf_backend_data *bed;
3481   bfd_byte *extdyn;
3482
3483   _bfd_elf_strtab_finalize (dynstr);
3484   size = _bfd_elf_strtab_size (dynstr);
3485
3486   bed = get_elf_backend_data (dynobj);
3487   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3488   BFD_ASSERT (sdyn != NULL);
3489
3490   /* Update all .dynamic entries referencing .dynstr strings.  */
3491   for (extdyn = sdyn->contents;
3492        extdyn < sdyn->contents + sdyn->size;
3493        extdyn += bed->s->sizeof_dyn)
3494     {
3495       Elf_Internal_Dyn dyn;
3496
3497       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3498       switch (dyn.d_tag)
3499         {
3500         case DT_STRSZ:
3501           dyn.d_un.d_val = size;
3502           break;
3503         case DT_NEEDED:
3504         case DT_SONAME:
3505         case DT_RPATH:
3506         case DT_RUNPATH:
3507         case DT_FILTER:
3508         case DT_AUXILIARY:
3509         case DT_AUDIT:
3510         case DT_DEPAUDIT:
3511           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3512           break;
3513         default:
3514           continue;
3515         }
3516       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3517     }
3518
3519   /* Now update local dynamic symbols.  */
3520   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3521     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3522                                                   entry->isym.st_name);
3523
3524   /* And the rest of dynamic symbols.  */
3525   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3526
3527   /* Adjust version definitions.  */
3528   if (elf_tdata (output_bfd)->cverdefs)
3529     {
3530       asection *s;
3531       bfd_byte *p;
3532       size_t i;
3533       Elf_Internal_Verdef def;
3534       Elf_Internal_Verdaux defaux;
3535
3536       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3537       p = s->contents;
3538       do
3539         {
3540           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3541                                    &def);
3542           p += sizeof (Elf_External_Verdef);
3543           if (def.vd_aux != sizeof (Elf_External_Verdef))
3544             continue;
3545           for (i = 0; i < def.vd_cnt; ++i)
3546             {
3547               _bfd_elf_swap_verdaux_in (output_bfd,
3548                                         (Elf_External_Verdaux *) p, &defaux);
3549               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3550                                                         defaux.vda_name);
3551               _bfd_elf_swap_verdaux_out (output_bfd,
3552                                          &defaux, (Elf_External_Verdaux *) p);
3553               p += sizeof (Elf_External_Verdaux);
3554             }
3555         }
3556       while (def.vd_next);
3557     }
3558
3559   /* Adjust version references.  */
3560   if (elf_tdata (output_bfd)->verref)
3561     {
3562       asection *s;
3563       bfd_byte *p;
3564       size_t i;
3565       Elf_Internal_Verneed need;
3566       Elf_Internal_Vernaux needaux;
3567
3568       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3569       p = s->contents;
3570       do
3571         {
3572           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3573                                     &need);
3574           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3575           _bfd_elf_swap_verneed_out (output_bfd, &need,
3576                                      (Elf_External_Verneed *) p);
3577           p += sizeof (Elf_External_Verneed);
3578           for (i = 0; i < need.vn_cnt; ++i)
3579             {
3580               _bfd_elf_swap_vernaux_in (output_bfd,
3581                                         (Elf_External_Vernaux *) p, &needaux);
3582               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3583                                                          needaux.vna_name);
3584               _bfd_elf_swap_vernaux_out (output_bfd,
3585                                          &needaux,
3586                                          (Elf_External_Vernaux *) p);
3587               p += sizeof (Elf_External_Vernaux);
3588             }
3589         }
3590       while (need.vn_next);
3591     }
3592
3593   return TRUE;
3594 }
3595 \f
3596 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3597    The default is to only match when the INPUT and OUTPUT are exactly
3598    the same target.  */
3599
3600 bfd_boolean
3601 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3602                                     const bfd_target *output)
3603 {
3604   return input == output;
3605 }
3606
3607 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3608    This version is used when different targets for the same architecture
3609    are virtually identical.  */
3610
3611 bfd_boolean
3612 _bfd_elf_relocs_compatible (const bfd_target *input,
3613                             const bfd_target *output)
3614 {
3615   const struct elf_backend_data *obed, *ibed;
3616
3617   if (input == output)
3618     return TRUE;
3619
3620   ibed = xvec_get_elf_backend_data (input);
3621   obed = xvec_get_elf_backend_data (output);
3622
3623   if (ibed->arch != obed->arch)
3624     return FALSE;
3625
3626   /* If both backends are using this function, deem them compatible.  */
3627   return ibed->relocs_compatible == obed->relocs_compatible;
3628 }
3629
3630 /* Make a special call to the linker "notice" function to tell it that
3631    we are about to handle an as-needed lib, or have finished
3632    processing the lib.  */
3633
3634 bfd_boolean
3635 _bfd_elf_notice_as_needed (bfd *ibfd,
3636                            struct bfd_link_info *info,
3637                            enum notice_asneeded_action act)
3638 {
3639   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3640 }
3641
3642 /* Check relocations an ELF object file.  */
3643
3644 bfd_boolean
3645 _bfd_elf_link_check_relocs (bfd *abfd, struct bfd_link_info *info)
3646 {
3647   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3648   struct elf_link_hash_table *htab = elf_hash_table (info);
3649
3650   /* If this object is the same format as the output object, and it is
3651      not a shared library, then let the backend look through the
3652      relocs.
3653
3654      This is required to build global offset table entries and to
3655      arrange for dynamic relocs.  It is not required for the
3656      particular common case of linking non PIC code, even when linking
3657      against shared libraries, but unfortunately there is no way of
3658      knowing whether an object file has been compiled PIC or not.
3659      Looking through the relocs is not particularly time consuming.
3660      The problem is that we must either (1) keep the relocs in memory,
3661      which causes the linker to require additional runtime memory or
3662      (2) read the relocs twice from the input file, which wastes time.
3663      This would be a good case for using mmap.
3664
3665      I have no idea how to handle linking PIC code into a file of a
3666      different format.  It probably can't be done.  */
3667   if ((abfd->flags & DYNAMIC) == 0
3668       && is_elf_hash_table (htab)
3669       && bed->check_relocs != NULL
3670       && elf_object_id (abfd) == elf_hash_table_id (htab)
3671       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
3672     {
3673       asection *o;
3674
3675       for (o = abfd->sections; o != NULL; o = o->next)
3676         {
3677           Elf_Internal_Rela *internal_relocs;
3678           bfd_boolean ok;
3679
3680           /* Don't check relocations in excluded sections.  */
3681           if ((o->flags & SEC_RELOC) == 0
3682               || (o->flags & SEC_EXCLUDE) != 0
3683               || o->reloc_count == 0
3684               || ((info->strip == strip_all || info->strip == strip_debugger)
3685                   && (o->flags & SEC_DEBUGGING) != 0)
3686               || bfd_is_abs_section (o->output_section))
3687             continue;
3688
3689           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
3690                                                        info->keep_memory);
3691           if (internal_relocs == NULL)
3692             return FALSE;
3693
3694           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
3695
3696           if (elf_section_data (o)->relocs != internal_relocs)
3697             free (internal_relocs);
3698
3699           if (! ok)
3700             return FALSE;
3701         }
3702     }
3703
3704   return TRUE;
3705 }
3706
3707 /* Add symbols from an ELF object file to the linker hash table.  */
3708
3709 static bfd_boolean
3710 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3711 {
3712   Elf_Internal_Ehdr *ehdr;
3713   Elf_Internal_Shdr *hdr;
3714   size_t symcount;
3715   size_t extsymcount;
3716   size_t extsymoff;
3717   struct elf_link_hash_entry **sym_hash;
3718   bfd_boolean dynamic;
3719   Elf_External_Versym *extversym = NULL;
3720   Elf_External_Versym *ever;
3721   struct elf_link_hash_entry *weaks;
3722   struct elf_link_hash_entry **nondeflt_vers = NULL;
3723   size_t nondeflt_vers_cnt = 0;
3724   Elf_Internal_Sym *isymbuf = NULL;
3725   Elf_Internal_Sym *isym;
3726   Elf_Internal_Sym *isymend;
3727   const struct elf_backend_data *bed;
3728   bfd_boolean add_needed;
3729   struct elf_link_hash_table *htab;
3730   bfd_size_type amt;
3731   void *alloc_mark = NULL;
3732   struct bfd_hash_entry **old_table = NULL;
3733   unsigned int old_size = 0;
3734   unsigned int old_count = 0;
3735   void *old_tab = NULL;
3736   void *old_ent;
3737   struct bfd_link_hash_entry *old_undefs = NULL;
3738   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3739   void *old_strtab = NULL;
3740   size_t tabsize = 0;
3741   asection *s;
3742   bfd_boolean just_syms;
3743
3744   htab = elf_hash_table (info);
3745   bed = get_elf_backend_data (abfd);
3746
3747   if ((abfd->flags & DYNAMIC) == 0)
3748     dynamic = FALSE;
3749   else
3750     {
3751       dynamic = TRUE;
3752
3753       /* You can't use -r against a dynamic object.  Also, there's no
3754          hope of using a dynamic object which does not exactly match
3755          the format of the output file.  */
3756       if (bfd_link_relocatable (info)
3757           || !is_elf_hash_table (htab)
3758           || info->output_bfd->xvec != abfd->xvec)
3759         {
3760           if (bfd_link_relocatable (info))
3761             bfd_set_error (bfd_error_invalid_operation);
3762           else
3763             bfd_set_error (bfd_error_wrong_format);
3764           goto error_return;
3765         }
3766     }
3767
3768   ehdr = elf_elfheader (abfd);
3769   if (info->warn_alternate_em
3770       && bed->elf_machine_code != ehdr->e_machine
3771       && ((bed->elf_machine_alt1 != 0
3772            && ehdr->e_machine == bed->elf_machine_alt1)
3773           || (bed->elf_machine_alt2 != 0
3774               && ehdr->e_machine == bed->elf_machine_alt2)))
3775     info->callbacks->einfo
3776       /* xgettext:c-format */
3777       (_("%P: alternate ELF machine code found (%d) in %B, expecting %d\n"),
3778        ehdr->e_machine, abfd, bed->elf_machine_code);
3779
3780   /* As a GNU extension, any input sections which are named
3781      .gnu.warning.SYMBOL are treated as warning symbols for the given
3782      symbol.  This differs from .gnu.warning sections, which generate
3783      warnings when they are included in an output file.  */
3784   /* PR 12761: Also generate this warning when building shared libraries.  */
3785   for (s = abfd->sections; s != NULL; s = s->next)
3786     {
3787       const char *name;
3788
3789       name = bfd_get_section_name (abfd, s);
3790       if (CONST_STRNEQ (name, ".gnu.warning."))
3791         {
3792           char *msg;
3793           bfd_size_type sz;
3794
3795           name += sizeof ".gnu.warning." - 1;
3796
3797           /* If this is a shared object, then look up the symbol
3798              in the hash table.  If it is there, and it is already
3799              been defined, then we will not be using the entry
3800              from this shared object, so we don't need to warn.
3801              FIXME: If we see the definition in a regular object
3802              later on, we will warn, but we shouldn't.  The only
3803              fix is to keep track of what warnings we are supposed
3804              to emit, and then handle them all at the end of the
3805              link.  */
3806           if (dynamic)
3807             {
3808               struct elf_link_hash_entry *h;
3809
3810               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3811
3812               /* FIXME: What about bfd_link_hash_common?  */
3813               if (h != NULL
3814                   && (h->root.type == bfd_link_hash_defined
3815                       || h->root.type == bfd_link_hash_defweak))
3816                 continue;
3817             }
3818
3819           sz = s->size;
3820           msg = (char *) bfd_alloc (abfd, sz + 1);
3821           if (msg == NULL)
3822             goto error_return;
3823
3824           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3825             goto error_return;
3826
3827           msg[sz] = '\0';
3828
3829           if (! (_bfd_generic_link_add_one_symbol
3830                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3831                   FALSE, bed->collect, NULL)))
3832             goto error_return;
3833
3834           if (bfd_link_executable (info))
3835             {
3836               /* Clobber the section size so that the warning does
3837                  not get copied into the output file.  */
3838               s->size = 0;
3839
3840               /* Also set SEC_EXCLUDE, so that symbols defined in
3841                  the warning section don't get copied to the output.  */
3842               s->flags |= SEC_EXCLUDE;
3843             }
3844         }
3845     }
3846
3847   just_syms = ((s = abfd->sections) != NULL
3848                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3849
3850   add_needed = TRUE;
3851   if (! dynamic)
3852     {
3853       /* If we are creating a shared library, create all the dynamic
3854          sections immediately.  We need to attach them to something,
3855          so we attach them to this BFD, provided it is the right
3856          format and is not from ld --just-symbols.  Always create the
3857          dynamic sections for -E/--dynamic-list.  FIXME: If there
3858          are no input BFD's of the same format as the output, we can't
3859          make a shared library.  */
3860       if (!just_syms
3861           && (bfd_link_pic (info)
3862               || (!bfd_link_relocatable (info)
3863                   && info->nointerp
3864                   && (info->export_dynamic || info->dynamic)))
3865           && is_elf_hash_table (htab)
3866           && info->output_bfd->xvec == abfd->xvec
3867           && !htab->dynamic_sections_created)
3868         {
3869           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3870             goto error_return;
3871         }
3872     }
3873   else if (!is_elf_hash_table (htab))
3874     goto error_return;
3875   else
3876     {
3877       const char *soname = NULL;
3878       char *audit = NULL;
3879       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3880       const Elf_Internal_Phdr *phdr;
3881       int ret;
3882
3883       /* ld --just-symbols and dynamic objects don't mix very well.
3884          ld shouldn't allow it.  */
3885       if (just_syms)
3886         abort ();
3887
3888       /* If this dynamic lib was specified on the command line with
3889          --as-needed in effect, then we don't want to add a DT_NEEDED
3890          tag unless the lib is actually used.  Similary for libs brought
3891          in by another lib's DT_NEEDED.  When --no-add-needed is used
3892          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3893          any dynamic library in DT_NEEDED tags in the dynamic lib at
3894          all.  */
3895       add_needed = (elf_dyn_lib_class (abfd)
3896                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3897                        | DYN_NO_NEEDED)) == 0;
3898
3899       s = bfd_get_section_by_name (abfd, ".dynamic");
3900       if (s != NULL)
3901         {
3902           bfd_byte *dynbuf;
3903           bfd_byte *extdyn;
3904           unsigned int elfsec;
3905           unsigned long shlink;
3906
3907           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3908             {
3909 error_free_dyn:
3910               free (dynbuf);
3911               goto error_return;
3912             }
3913
3914           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3915           if (elfsec == SHN_BAD)
3916             goto error_free_dyn;
3917           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3918
3919           for (extdyn = dynbuf;
3920                extdyn < dynbuf + s->size;
3921                extdyn += bed->s->sizeof_dyn)
3922             {
3923               Elf_Internal_Dyn dyn;
3924
3925               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3926               if (dyn.d_tag == DT_SONAME)
3927                 {
3928                   unsigned int tagv = dyn.d_un.d_val;
3929                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3930                   if (soname == NULL)
3931                     goto error_free_dyn;
3932                 }
3933               if (dyn.d_tag == DT_NEEDED)
3934                 {
3935                   struct bfd_link_needed_list *n, **pn;
3936                   char *fnm, *anm;
3937                   unsigned int tagv = dyn.d_un.d_val;
3938
3939                   amt = sizeof (struct bfd_link_needed_list);
3940                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3941                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3942                   if (n == NULL || fnm == NULL)
3943                     goto error_free_dyn;
3944                   amt = strlen (fnm) + 1;
3945                   anm = (char *) bfd_alloc (abfd, amt);
3946                   if (anm == NULL)
3947                     goto error_free_dyn;
3948                   memcpy (anm, fnm, amt);
3949                   n->name = anm;
3950                   n->by = abfd;
3951                   n->next = NULL;
3952                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
3953                     ;
3954                   *pn = n;
3955                 }
3956               if (dyn.d_tag == DT_RUNPATH)
3957                 {
3958                   struct bfd_link_needed_list *n, **pn;
3959                   char *fnm, *anm;
3960                   unsigned int tagv = dyn.d_un.d_val;
3961
3962                   amt = sizeof (struct bfd_link_needed_list);
3963                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3964                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3965                   if (n == NULL || fnm == NULL)
3966                     goto error_free_dyn;
3967                   amt = strlen (fnm) + 1;
3968                   anm = (char *) bfd_alloc (abfd, amt);
3969                   if (anm == NULL)
3970                     goto error_free_dyn;
3971                   memcpy (anm, fnm, amt);
3972                   n->name = anm;
3973                   n->by = abfd;
3974                   n->next = NULL;
3975                   for (pn = & runpath;
3976                        *pn != NULL;
3977                        pn = &(*pn)->next)
3978                     ;
3979                   *pn = n;
3980                 }
3981               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
3982               if (!runpath && dyn.d_tag == DT_RPATH)
3983                 {
3984                   struct bfd_link_needed_list *n, **pn;
3985                   char *fnm, *anm;
3986                   unsigned int tagv = dyn.d_un.d_val;
3987
3988                   amt = sizeof (struct bfd_link_needed_list);
3989                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3990                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3991                   if (n == NULL || fnm == NULL)
3992                     goto error_free_dyn;
3993                   amt = strlen (fnm) + 1;
3994                   anm = (char *) bfd_alloc (abfd, amt);
3995                   if (anm == NULL)
3996                     goto error_free_dyn;
3997                   memcpy (anm, fnm, amt);
3998                   n->name = anm;
3999                   n->by = abfd;
4000                   n->next = NULL;
4001                   for (pn = & rpath;
4002                        *pn != NULL;
4003                        pn = &(*pn)->next)
4004                     ;
4005                   *pn = n;
4006                 }
4007               if (dyn.d_tag == DT_AUDIT)
4008                 {
4009                   unsigned int tagv = dyn.d_un.d_val;
4010                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
4011                 }
4012             }
4013
4014           free (dynbuf);
4015         }
4016
4017       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
4018          frees all more recently bfd_alloc'd blocks as well.  */
4019       if (runpath)
4020         rpath = runpath;
4021
4022       if (rpath)
4023         {
4024           struct bfd_link_needed_list **pn;
4025           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
4026             ;
4027           *pn = rpath;
4028         }
4029
4030       /* If we have a PT_GNU_RELRO program header, mark as read-only
4031          all sections contained fully therein.  This makes relro
4032          shared library sections appear as they will at run-time.  */
4033       phdr = elf_tdata (abfd)->phdr + elf_elfheader (abfd)->e_phnum;
4034       while (--phdr >= elf_tdata (abfd)->phdr)
4035         if (phdr->p_type == PT_GNU_RELRO)
4036           {
4037             for (s = abfd->sections; s != NULL; s = s->next)
4038               if ((s->flags & SEC_ALLOC) != 0
4039                   && s->vma >= phdr->p_vaddr
4040                   && s->vma + s->size <= phdr->p_vaddr + phdr->p_memsz)
4041                 s->flags |= SEC_READONLY;
4042             break;
4043           }
4044
4045       /* We do not want to include any of the sections in a dynamic
4046          object in the output file.  We hack by simply clobbering the
4047          list of sections in the BFD.  This could be handled more
4048          cleanly by, say, a new section flag; the existing
4049          SEC_NEVER_LOAD flag is not the one we want, because that one
4050          still implies that the section takes up space in the output
4051          file.  */
4052       bfd_section_list_clear (abfd);
4053
4054       /* Find the name to use in a DT_NEEDED entry that refers to this
4055          object.  If the object has a DT_SONAME entry, we use it.
4056          Otherwise, if the generic linker stuck something in
4057          elf_dt_name, we use that.  Otherwise, we just use the file
4058          name.  */
4059       if (soname == NULL || *soname == '\0')
4060         {
4061           soname = elf_dt_name (abfd);
4062           if (soname == NULL || *soname == '\0')
4063             soname = bfd_get_filename (abfd);
4064         }
4065
4066       /* Save the SONAME because sometimes the linker emulation code
4067          will need to know it.  */
4068       elf_dt_name (abfd) = soname;
4069
4070       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4071       if (ret < 0)
4072         goto error_return;
4073
4074       /* If we have already included this dynamic object in the
4075          link, just ignore it.  There is no reason to include a
4076          particular dynamic object more than once.  */
4077       if (ret > 0)
4078         return TRUE;
4079
4080       /* Save the DT_AUDIT entry for the linker emulation code. */
4081       elf_dt_audit (abfd) = audit;
4082     }
4083
4084   /* If this is a dynamic object, we always link against the .dynsym
4085      symbol table, not the .symtab symbol table.  The dynamic linker
4086      will only see the .dynsym symbol table, so there is no reason to
4087      look at .symtab for a dynamic object.  */
4088
4089   if (! dynamic || elf_dynsymtab (abfd) == 0)
4090     hdr = &elf_tdata (abfd)->symtab_hdr;
4091   else
4092     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
4093
4094   symcount = hdr->sh_size / bed->s->sizeof_sym;
4095
4096   /* The sh_info field of the symtab header tells us where the
4097      external symbols start.  We don't care about the local symbols at
4098      this point.  */
4099   if (elf_bad_symtab (abfd))
4100     {
4101       extsymcount = symcount;
4102       extsymoff = 0;
4103     }
4104   else
4105     {
4106       extsymcount = symcount - hdr->sh_info;
4107       extsymoff = hdr->sh_info;
4108     }
4109
4110   sym_hash = elf_sym_hashes (abfd);
4111   if (extsymcount != 0)
4112     {
4113       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
4114                                       NULL, NULL, NULL);
4115       if (isymbuf == NULL)
4116         goto error_return;
4117
4118       if (sym_hash == NULL)
4119         {
4120           /* We store a pointer to the hash table entry for each
4121              external symbol.  */
4122           amt = extsymcount;
4123           amt *= sizeof (struct elf_link_hash_entry *);
4124           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
4125           if (sym_hash == NULL)
4126             goto error_free_sym;
4127           elf_sym_hashes (abfd) = sym_hash;
4128         }
4129     }
4130
4131   if (dynamic)
4132     {
4133       /* Read in any version definitions.  */
4134       if (!_bfd_elf_slurp_version_tables (abfd,
4135                                           info->default_imported_symver))
4136         goto error_free_sym;
4137
4138       /* Read in the symbol versions, but don't bother to convert them
4139          to internal format.  */
4140       if (elf_dynversym (abfd) != 0)
4141         {
4142           Elf_Internal_Shdr *versymhdr;
4143
4144           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
4145           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
4146           if (extversym == NULL)
4147             goto error_free_sym;
4148           amt = versymhdr->sh_size;
4149           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
4150               || bfd_bread (extversym, amt, abfd) != amt)
4151             goto error_free_vers;
4152         }
4153     }
4154
4155   /* If we are loading an as-needed shared lib, save the symbol table
4156      state before we start adding symbols.  If the lib turns out
4157      to be unneeded, restore the state.  */
4158   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4159     {
4160       unsigned int i;
4161       size_t entsize;
4162
4163       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
4164         {
4165           struct bfd_hash_entry *p;
4166           struct elf_link_hash_entry *h;
4167
4168           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4169             {
4170               h = (struct elf_link_hash_entry *) p;
4171               entsize += htab->root.table.entsize;
4172               if (h->root.type == bfd_link_hash_warning)
4173                 entsize += htab->root.table.entsize;
4174             }
4175         }
4176
4177       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
4178       old_tab = bfd_malloc (tabsize + entsize);
4179       if (old_tab == NULL)
4180         goto error_free_vers;
4181
4182       /* Remember the current objalloc pointer, so that all mem for
4183          symbols added can later be reclaimed.  */
4184       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
4185       if (alloc_mark == NULL)
4186         goto error_free_vers;
4187
4188       /* Make a special call to the linker "notice" function to
4189          tell it that we are about to handle an as-needed lib.  */
4190       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
4191         goto error_free_vers;
4192
4193       /* Clone the symbol table.  Remember some pointers into the
4194          symbol table, and dynamic symbol count.  */
4195       old_ent = (char *) old_tab + tabsize;
4196       memcpy (old_tab, htab->root.table.table, tabsize);
4197       old_undefs = htab->root.undefs;
4198       old_undefs_tail = htab->root.undefs_tail;
4199       old_table = htab->root.table.table;
4200       old_size = htab->root.table.size;
4201       old_count = htab->root.table.count;
4202       old_strtab = _bfd_elf_strtab_save (htab->dynstr);
4203       if (old_strtab == NULL)
4204         goto error_free_vers;
4205
4206       for (i = 0; i < htab->root.table.size; i++)
4207         {
4208           struct bfd_hash_entry *p;
4209           struct elf_link_hash_entry *h;
4210
4211           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4212             {
4213               memcpy (old_ent, p, htab->root.table.entsize);
4214               old_ent = (char *) old_ent + htab->root.table.entsize;
4215               h = (struct elf_link_hash_entry *) p;
4216               if (h->root.type == bfd_link_hash_warning)
4217                 {
4218                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
4219                   old_ent = (char *) old_ent + htab->root.table.entsize;
4220                 }
4221             }
4222         }
4223     }
4224
4225   weaks = NULL;
4226   ever = extversym != NULL ? extversym + extsymoff : NULL;
4227   for (isym = isymbuf, isymend = isymbuf + extsymcount;
4228        isym < isymend;
4229        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
4230     {
4231       int bind;
4232       bfd_vma value;
4233       asection *sec, *new_sec;
4234       flagword flags;
4235       const char *name;
4236       struct elf_link_hash_entry *h;
4237       struct elf_link_hash_entry *hi;
4238       bfd_boolean definition;
4239       bfd_boolean size_change_ok;
4240       bfd_boolean type_change_ok;
4241       bfd_boolean new_weakdef;
4242       bfd_boolean new_weak;
4243       bfd_boolean old_weak;
4244       bfd_boolean override;
4245       bfd_boolean common;
4246       bfd_boolean discarded;
4247       unsigned int old_alignment;
4248       bfd *old_bfd;
4249       bfd_boolean matched;
4250
4251       override = FALSE;
4252
4253       flags = BSF_NO_FLAGS;
4254       sec = NULL;
4255       value = isym->st_value;
4256       common = bed->common_definition (isym);
4257       discarded = FALSE;
4258
4259       bind = ELF_ST_BIND (isym->st_info);
4260       switch (bind)
4261         {
4262         case STB_LOCAL:
4263           /* This should be impossible, since ELF requires that all
4264              global symbols follow all local symbols, and that sh_info
4265              point to the first global symbol.  Unfortunately, Irix 5
4266              screws this up.  */
4267           continue;
4268
4269         case STB_GLOBAL:
4270           if (isym->st_shndx != SHN_UNDEF && !common)
4271             flags = BSF_GLOBAL;
4272           break;
4273
4274         case STB_WEAK:
4275           flags = BSF_WEAK;
4276           break;
4277
4278         case STB_GNU_UNIQUE:
4279           flags = BSF_GNU_UNIQUE;
4280           break;
4281
4282         default:
4283           /* Leave it up to the processor backend.  */
4284           break;
4285         }
4286
4287       if (isym->st_shndx == SHN_UNDEF)
4288         sec = bfd_und_section_ptr;
4289       else if (isym->st_shndx == SHN_ABS)
4290         sec = bfd_abs_section_ptr;
4291       else if (isym->st_shndx == SHN_COMMON)
4292         {
4293           sec = bfd_com_section_ptr;
4294           /* What ELF calls the size we call the value.  What ELF
4295              calls the value we call the alignment.  */
4296           value = isym->st_size;
4297         }
4298       else
4299         {
4300           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
4301           if (sec == NULL)
4302             sec = bfd_abs_section_ptr;
4303           else if (discarded_section (sec))
4304             {
4305               /* Symbols from discarded section are undefined.  We keep
4306                  its visibility.  */
4307               sec = bfd_und_section_ptr;
4308               discarded = TRUE;
4309               isym->st_shndx = SHN_UNDEF;
4310             }
4311           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
4312             value -= sec->vma;
4313         }
4314
4315       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4316                                               isym->st_name);
4317       if (name == NULL)
4318         goto error_free_vers;
4319
4320       if (isym->st_shndx == SHN_COMMON
4321           && (abfd->flags & BFD_PLUGIN) != 0)
4322         {
4323           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4324
4325           if (xc == NULL)
4326             {
4327               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4328                                  | SEC_EXCLUDE);
4329               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4330               if (xc == NULL)
4331                 goto error_free_vers;
4332             }
4333           sec = xc;
4334         }
4335       else if (isym->st_shndx == SHN_COMMON
4336                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4337                && !bfd_link_relocatable (info))
4338         {
4339           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4340
4341           if (tcomm == NULL)
4342             {
4343               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4344                                  | SEC_LINKER_CREATED);
4345               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4346               if (tcomm == NULL)
4347                 goto error_free_vers;
4348             }
4349           sec = tcomm;
4350         }
4351       else if (bed->elf_add_symbol_hook)
4352         {
4353           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4354                                              &sec, &value))
4355             goto error_free_vers;
4356
4357           /* The hook function sets the name to NULL if this symbol
4358              should be skipped for some reason.  */
4359           if (name == NULL)
4360             continue;
4361         }
4362
4363       /* Sanity check that all possibilities were handled.  */
4364       if (sec == NULL)
4365         {
4366           bfd_set_error (bfd_error_bad_value);
4367           goto error_free_vers;
4368         }
4369
4370       /* Silently discard TLS symbols from --just-syms.  There's
4371          no way to combine a static TLS block with a new TLS block
4372          for this executable.  */
4373       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4374           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4375         continue;
4376
4377       if (bfd_is_und_section (sec)
4378           || bfd_is_com_section (sec))
4379         definition = FALSE;
4380       else
4381         definition = TRUE;
4382
4383       size_change_ok = FALSE;
4384       type_change_ok = bed->type_change_ok;
4385       old_weak = FALSE;
4386       matched = FALSE;
4387       old_alignment = 0;
4388       old_bfd = NULL;
4389       new_sec = sec;
4390
4391       if (is_elf_hash_table (htab))
4392         {
4393           Elf_Internal_Versym iver;
4394           unsigned int vernum = 0;
4395           bfd_boolean skip;
4396
4397           if (ever == NULL)
4398             {
4399               if (info->default_imported_symver)
4400                 /* Use the default symbol version created earlier.  */
4401                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4402               else
4403                 iver.vs_vers = 0;
4404             }
4405           else
4406             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4407
4408           vernum = iver.vs_vers & VERSYM_VERSION;
4409
4410           /* If this is a hidden symbol, or if it is not version
4411              1, we append the version name to the symbol name.
4412              However, we do not modify a non-hidden absolute symbol
4413              if it is not a function, because it might be the version
4414              symbol itself.  FIXME: What if it isn't?  */
4415           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4416               || (vernum > 1
4417                   && (!bfd_is_abs_section (sec)
4418                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4419             {
4420               const char *verstr;
4421               size_t namelen, verlen, newlen;
4422               char *newname, *p;
4423
4424               if (isym->st_shndx != SHN_UNDEF)
4425                 {
4426                   if (vernum > elf_tdata (abfd)->cverdefs)
4427                     verstr = NULL;
4428                   else if (vernum > 1)
4429                     verstr =
4430                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4431                   else
4432                     verstr = "";
4433
4434                   if (verstr == NULL)
4435                     {
4436                       _bfd_error_handler
4437                         /* xgettext:c-format */
4438                         (_("%B: %s: invalid version %u (max %d)"),
4439                          abfd, name, vernum,
4440                          elf_tdata (abfd)->cverdefs);
4441                       bfd_set_error (bfd_error_bad_value);
4442                       goto error_free_vers;
4443                     }
4444                 }
4445               else
4446                 {
4447                   /* We cannot simply test for the number of
4448                      entries in the VERNEED section since the
4449                      numbers for the needed versions do not start
4450                      at 0.  */
4451                   Elf_Internal_Verneed *t;
4452
4453                   verstr = NULL;
4454                   for (t = elf_tdata (abfd)->verref;
4455                        t != NULL;
4456                        t = t->vn_nextref)
4457                     {
4458                       Elf_Internal_Vernaux *a;
4459
4460                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4461                         {
4462                           if (a->vna_other == vernum)
4463                             {
4464                               verstr = a->vna_nodename;
4465                               break;
4466                             }
4467                         }
4468                       if (a != NULL)
4469                         break;
4470                     }
4471                   if (verstr == NULL)
4472                     {
4473                       _bfd_error_handler
4474                         /* xgettext:c-format */
4475                         (_("%B: %s: invalid needed version %d"),
4476                          abfd, name, vernum);
4477                       bfd_set_error (bfd_error_bad_value);
4478                       goto error_free_vers;
4479                     }
4480                 }
4481
4482               namelen = strlen (name);
4483               verlen = strlen (verstr);
4484               newlen = namelen + verlen + 2;
4485               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4486                   && isym->st_shndx != SHN_UNDEF)
4487                 ++newlen;
4488
4489               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4490               if (newname == NULL)
4491                 goto error_free_vers;
4492               memcpy (newname, name, namelen);
4493               p = newname + namelen;
4494               *p++ = ELF_VER_CHR;
4495               /* If this is a defined non-hidden version symbol,
4496                  we add another @ to the name.  This indicates the
4497                  default version of the symbol.  */
4498               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4499                   && isym->st_shndx != SHN_UNDEF)
4500                 *p++ = ELF_VER_CHR;
4501               memcpy (p, verstr, verlen + 1);
4502
4503               name = newname;
4504             }
4505
4506           /* If this symbol has default visibility and the user has
4507              requested we not re-export it, then mark it as hidden.  */
4508           if (!bfd_is_und_section (sec)
4509               && !dynamic
4510               && abfd->no_export
4511               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4512             isym->st_other = (STV_HIDDEN
4513                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4514
4515           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4516                                       sym_hash, &old_bfd, &old_weak,
4517                                       &old_alignment, &skip, &override,
4518                                       &type_change_ok, &size_change_ok,
4519                                       &matched))
4520             goto error_free_vers;
4521
4522           if (skip)
4523             continue;
4524
4525           /* Override a definition only if the new symbol matches the
4526              existing one.  */
4527           if (override && matched)
4528             definition = FALSE;
4529
4530           h = *sym_hash;
4531           while (h->root.type == bfd_link_hash_indirect
4532                  || h->root.type == bfd_link_hash_warning)
4533             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4534
4535           if (elf_tdata (abfd)->verdef != NULL
4536               && vernum > 1
4537               && definition)
4538             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4539         }
4540
4541       if (! (_bfd_generic_link_add_one_symbol
4542              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4543               (struct bfd_link_hash_entry **) sym_hash)))
4544         goto error_free_vers;
4545
4546       if ((flags & BSF_GNU_UNIQUE)
4547           && (abfd->flags & DYNAMIC) == 0
4548           && bfd_get_flavour (info->output_bfd) == bfd_target_elf_flavour)
4549         elf_tdata (info->output_bfd)->has_gnu_symbols |= elf_gnu_symbol_unique;
4550
4551       h = *sym_hash;
4552       /* We need to make sure that indirect symbol dynamic flags are
4553          updated.  */
4554       hi = h;
4555       while (h->root.type == bfd_link_hash_indirect
4556              || h->root.type == bfd_link_hash_warning)
4557         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4558
4559       /* Setting the index to -3 tells elf_link_output_extsym that
4560          this symbol is defined in a discarded section.  */
4561       if (discarded)
4562         h->indx = -3;
4563
4564       *sym_hash = h;
4565
4566       new_weak = (flags & BSF_WEAK) != 0;
4567       new_weakdef = FALSE;
4568       if (dynamic
4569           && definition
4570           && new_weak
4571           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4572           && is_elf_hash_table (htab)
4573           && h->u.weakdef == NULL)
4574         {
4575           /* Keep a list of all weak defined non function symbols from
4576              a dynamic object, using the weakdef field.  Later in this
4577              function we will set the weakdef field to the correct
4578              value.  We only put non-function symbols from dynamic
4579              objects on this list, because that happens to be the only
4580              time we need to know the normal symbol corresponding to a
4581              weak symbol, and the information is time consuming to
4582              figure out.  If the weakdef field is not already NULL,
4583              then this symbol was already defined by some previous
4584              dynamic object, and we will be using that previous
4585              definition anyhow.  */
4586
4587           h->u.weakdef = weaks;
4588           weaks = h;
4589           new_weakdef = TRUE;
4590         }
4591
4592       /* Set the alignment of a common symbol.  */
4593       if ((common || bfd_is_com_section (sec))
4594           && h->root.type == bfd_link_hash_common)
4595         {
4596           unsigned int align;
4597
4598           if (common)
4599             align = bfd_log2 (isym->st_value);
4600           else
4601             {
4602               /* The new symbol is a common symbol in a shared object.
4603                  We need to get the alignment from the section.  */
4604               align = new_sec->alignment_power;
4605             }
4606           if (align > old_alignment)
4607             h->root.u.c.p->alignment_power = align;
4608           else
4609             h->root.u.c.p->alignment_power = old_alignment;
4610         }
4611
4612       if (is_elf_hash_table (htab))
4613         {
4614           /* Set a flag in the hash table entry indicating the type of
4615              reference or definition we just found.  A dynamic symbol
4616              is one which is referenced or defined by both a regular
4617              object and a shared object.  */
4618           bfd_boolean dynsym = FALSE;
4619
4620           /* Plugin symbols aren't normal.  Don't set def_regular or
4621              ref_regular for them, or make them dynamic.  */
4622           if ((abfd->flags & BFD_PLUGIN) != 0)
4623             ;
4624           else if (! dynamic)
4625             {
4626               if (! definition)
4627                 {
4628                   h->ref_regular = 1;
4629                   if (bind != STB_WEAK)
4630                     h->ref_regular_nonweak = 1;
4631                 }
4632               else
4633                 {
4634                   h->def_regular = 1;
4635                   if (h->def_dynamic)
4636                     {
4637                       h->def_dynamic = 0;
4638                       h->ref_dynamic = 1;
4639                     }
4640                 }
4641
4642               /* If the indirect symbol has been forced local, don't
4643                  make the real symbol dynamic.  */
4644               if ((h == hi || !hi->forced_local)
4645                   && (bfd_link_dll (info)
4646                       || h->def_dynamic
4647                       || h->ref_dynamic))
4648                 dynsym = TRUE;
4649             }
4650           else
4651             {
4652               if (! definition)
4653                 {
4654                   h->ref_dynamic = 1;
4655                   hi->ref_dynamic = 1;
4656                 }
4657               else
4658                 {
4659                   h->def_dynamic = 1;
4660                   hi->def_dynamic = 1;
4661                 }
4662
4663               /* If the indirect symbol has been forced local, don't
4664                  make the real symbol dynamic.  */
4665               if ((h == hi || !hi->forced_local)
4666                   && (h->def_regular
4667                       || h->ref_regular
4668                       || (h->u.weakdef != NULL
4669                           && ! new_weakdef
4670                           && h->u.weakdef->dynindx != -1)))
4671                 dynsym = TRUE;
4672             }
4673
4674           /* Check to see if we need to add an indirect symbol for
4675              the default name.  */
4676           if (definition
4677               || (!override && h->root.type == bfd_link_hash_common))
4678             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4679                                               sec, value, &old_bfd, &dynsym))
4680               goto error_free_vers;
4681
4682           /* Check the alignment when a common symbol is involved. This
4683              can change when a common symbol is overridden by a normal
4684              definition or a common symbol is ignored due to the old
4685              normal definition. We need to make sure the maximum
4686              alignment is maintained.  */
4687           if ((old_alignment || common)
4688               && h->root.type != bfd_link_hash_common)
4689             {
4690               unsigned int common_align;
4691               unsigned int normal_align;
4692               unsigned int symbol_align;
4693               bfd *normal_bfd;
4694               bfd *common_bfd;
4695
4696               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4697                           || h->root.type == bfd_link_hash_defweak);
4698
4699               symbol_align = ffs (h->root.u.def.value) - 1;
4700               if (h->root.u.def.section->owner != NULL
4701                   && (h->root.u.def.section->owner->flags
4702                        & (DYNAMIC | BFD_PLUGIN)) == 0)
4703                 {
4704                   normal_align = h->root.u.def.section->alignment_power;
4705                   if (normal_align > symbol_align)
4706                     normal_align = symbol_align;
4707                 }
4708               else
4709                 normal_align = symbol_align;
4710
4711               if (old_alignment)
4712                 {
4713                   common_align = old_alignment;
4714                   common_bfd = old_bfd;
4715                   normal_bfd = abfd;
4716                 }
4717               else
4718                 {
4719                   common_align = bfd_log2 (isym->st_value);
4720                   common_bfd = abfd;
4721                   normal_bfd = old_bfd;
4722                 }
4723
4724               if (normal_align < common_align)
4725                 {
4726                   /* PR binutils/2735 */
4727                   if (normal_bfd == NULL)
4728                     _bfd_error_handler
4729                       /* xgettext:c-format */
4730                       (_("Warning: alignment %u of common symbol `%s' in %B is"
4731                          " greater than the alignment (%u) of its section %A"),
4732                        1 << common_align, name, common_bfd,
4733                        1 << normal_align, h->root.u.def.section);
4734                   else
4735                     _bfd_error_handler
4736                       /* xgettext:c-format */
4737                       (_("Warning: alignment %u of symbol `%s' in %B"
4738                          " is smaller than %u in %B"),
4739                        1 << normal_align, name, normal_bfd,
4740                        1 << common_align, common_bfd);
4741                 }
4742             }
4743
4744           /* Remember the symbol size if it isn't undefined.  */
4745           if (isym->st_size != 0
4746               && isym->st_shndx != SHN_UNDEF
4747               && (definition || h->size == 0))
4748             {
4749               if (h->size != 0
4750                   && h->size != isym->st_size
4751                   && ! size_change_ok)
4752                 _bfd_error_handler
4753                   /* xgettext:c-format */
4754                   (_("Warning: size of symbol `%s' changed"
4755                      " from %lu in %B to %lu in %B"),
4756                    name, (unsigned long) h->size, old_bfd,
4757                    (unsigned long) isym->st_size, abfd);
4758
4759               h->size = isym->st_size;
4760             }
4761
4762           /* If this is a common symbol, then we always want H->SIZE
4763              to be the size of the common symbol.  The code just above
4764              won't fix the size if a common symbol becomes larger.  We
4765              don't warn about a size change here, because that is
4766              covered by --warn-common.  Allow changes between different
4767              function types.  */
4768           if (h->root.type == bfd_link_hash_common)
4769             h->size = h->root.u.c.size;
4770
4771           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4772               && ((definition && !new_weak)
4773                   || (old_weak && h->root.type == bfd_link_hash_common)
4774                   || h->type == STT_NOTYPE))
4775             {
4776               unsigned int type = ELF_ST_TYPE (isym->st_info);
4777
4778               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4779                  symbol.  */
4780               if (type == STT_GNU_IFUNC
4781                   && (abfd->flags & DYNAMIC) != 0)
4782                 type = STT_FUNC;
4783
4784               if (h->type != type)
4785                 {
4786                   if (h->type != STT_NOTYPE && ! type_change_ok)
4787                     /* xgettext:c-format */
4788                     _bfd_error_handler
4789                       (_("Warning: type of symbol `%s' changed"
4790                          " from %d to %d in %B"),
4791                        name, h->type, type, abfd);
4792
4793                   h->type = type;
4794                 }
4795             }
4796
4797           /* Merge st_other field.  */
4798           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4799
4800           /* We don't want to make debug symbol dynamic.  */
4801           if (definition
4802               && (sec->flags & SEC_DEBUGGING)
4803               && !bfd_link_relocatable (info))
4804             dynsym = FALSE;
4805
4806           /* Nor should we make plugin symbols dynamic.  */
4807           if ((abfd->flags & BFD_PLUGIN) != 0)
4808             dynsym = FALSE;
4809
4810           if (definition)
4811             {
4812               h->target_internal = isym->st_target_internal;
4813               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4814             }
4815
4816           if (definition && !dynamic)
4817             {
4818               char *p = strchr (name, ELF_VER_CHR);
4819               if (p != NULL && p[1] != ELF_VER_CHR)
4820                 {
4821                   /* Queue non-default versions so that .symver x, x@FOO
4822                      aliases can be checked.  */
4823                   if (!nondeflt_vers)
4824                     {
4825                       amt = ((isymend - isym + 1)
4826                              * sizeof (struct elf_link_hash_entry *));
4827                       nondeflt_vers
4828                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
4829                       if (!nondeflt_vers)
4830                         goto error_free_vers;
4831                     }
4832                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4833                 }
4834             }
4835
4836           if (dynsym && h->dynindx == -1)
4837             {
4838               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4839                 goto error_free_vers;
4840               if (h->u.weakdef != NULL
4841                   && ! new_weakdef
4842                   && h->u.weakdef->dynindx == -1)
4843                 {
4844                   if (!bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
4845                     goto error_free_vers;
4846                 }
4847             }
4848           else if (h->dynindx != -1)
4849             /* If the symbol already has a dynamic index, but
4850                visibility says it should not be visible, turn it into
4851                a local symbol.  */
4852             switch (ELF_ST_VISIBILITY (h->other))
4853               {
4854               case STV_INTERNAL:
4855               case STV_HIDDEN:
4856                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4857                 dynsym = FALSE;
4858                 break;
4859               }
4860
4861           /* Don't add DT_NEEDED for references from the dummy bfd nor
4862              for unmatched symbol.  */
4863           if (!add_needed
4864               && matched
4865               && definition
4866               && ((dynsym
4867                    && h->ref_regular_nonweak
4868                    && (old_bfd == NULL
4869                        || (old_bfd->flags & BFD_PLUGIN) == 0))
4870                   || (h->ref_dynamic_nonweak
4871                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4872                       && !on_needed_list (elf_dt_name (abfd),
4873                                           htab->needed, NULL))))
4874             {
4875               int ret;
4876               const char *soname = elf_dt_name (abfd);
4877
4878               info->callbacks->minfo ("%!", soname, old_bfd,
4879                                       h->root.root.string);
4880
4881               /* A symbol from a library loaded via DT_NEEDED of some
4882                  other library is referenced by a regular object.
4883                  Add a DT_NEEDED entry for it.  Issue an error if
4884                  --no-add-needed is used and the reference was not
4885                  a weak one.  */
4886               if (old_bfd != NULL
4887                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4888                 {
4889                   _bfd_error_handler
4890                     /* xgettext:c-format */
4891                     (_("%B: undefined reference to symbol '%s'"),
4892                      old_bfd, name);
4893                   bfd_set_error (bfd_error_missing_dso);
4894                   goto error_free_vers;
4895                 }
4896
4897               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4898                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4899
4900               add_needed = TRUE;
4901               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4902               if (ret < 0)
4903                 goto error_free_vers;
4904
4905               BFD_ASSERT (ret == 0);
4906             }
4907         }
4908     }
4909
4910   if (extversym != NULL)
4911     {
4912       free (extversym);
4913       extversym = NULL;
4914     }
4915
4916   if (isymbuf != NULL)
4917     {
4918       free (isymbuf);
4919       isymbuf = NULL;
4920     }
4921
4922   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4923     {
4924       unsigned int i;
4925
4926       /* Restore the symbol table.  */
4927       old_ent = (char *) old_tab + tabsize;
4928       memset (elf_sym_hashes (abfd), 0,
4929               extsymcount * sizeof (struct elf_link_hash_entry *));
4930       htab->root.table.table = old_table;
4931       htab->root.table.size = old_size;
4932       htab->root.table.count = old_count;
4933       memcpy (htab->root.table.table, old_tab, tabsize);
4934       htab->root.undefs = old_undefs;
4935       htab->root.undefs_tail = old_undefs_tail;
4936       _bfd_elf_strtab_restore (htab->dynstr, old_strtab);
4937       free (old_strtab);
4938       old_strtab = NULL;
4939       for (i = 0; i < htab->root.table.size; i++)
4940         {
4941           struct bfd_hash_entry *p;
4942           struct elf_link_hash_entry *h;
4943           bfd_size_type size;
4944           unsigned int alignment_power;
4945           unsigned int non_ir_ref_dynamic;
4946
4947           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4948             {
4949               h = (struct elf_link_hash_entry *) p;
4950               if (h->root.type == bfd_link_hash_warning)
4951                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
4952
4953               /* Preserve the maximum alignment and size for common
4954                  symbols even if this dynamic lib isn't on DT_NEEDED
4955                  since it can still be loaded at run time by another
4956                  dynamic lib.  */
4957               if (h->root.type == bfd_link_hash_common)
4958                 {
4959                   size = h->root.u.c.size;
4960                   alignment_power = h->root.u.c.p->alignment_power;
4961                 }
4962               else
4963                 {
4964                   size = 0;
4965                   alignment_power = 0;
4966                 }
4967               /* Preserve non_ir_ref_dynamic so that this symbol
4968                  will be exported when the dynamic lib becomes needed
4969                  in the second pass.  */
4970               non_ir_ref_dynamic = h->root.non_ir_ref_dynamic;
4971               memcpy (p, old_ent, htab->root.table.entsize);
4972               old_ent = (char *) old_ent + htab->root.table.entsize;
4973               h = (struct elf_link_hash_entry *) p;
4974               if (h->root.type == bfd_link_hash_warning)
4975                 {
4976                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
4977                   old_ent = (char *) old_ent + htab->root.table.entsize;
4978                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
4979                 }
4980               if (h->root.type == bfd_link_hash_common)
4981                 {
4982                   if (size > h->root.u.c.size)
4983                     h->root.u.c.size = size;
4984                   if (alignment_power > h->root.u.c.p->alignment_power)
4985                     h->root.u.c.p->alignment_power = alignment_power;
4986                 }
4987               h->root.non_ir_ref_dynamic = non_ir_ref_dynamic;
4988             }
4989         }
4990
4991       /* Make a special call to the linker "notice" function to
4992          tell it that symbols added for crefs may need to be removed.  */
4993       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
4994         goto error_free_vers;
4995
4996       free (old_tab);
4997       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
4998                            alloc_mark);
4999       if (nondeflt_vers != NULL)
5000         free (nondeflt_vers);
5001       return TRUE;
5002     }
5003
5004   if (old_tab != NULL)
5005     {
5006       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
5007         goto error_free_vers;
5008       free (old_tab);
5009       old_tab = NULL;
5010     }
5011
5012   /* Now that all the symbols from this input file are created, if
5013      not performing a relocatable link, handle .symver foo, foo@BAR
5014      such that any relocs against foo become foo@BAR.  */
5015   if (!bfd_link_relocatable (info) && nondeflt_vers != NULL)
5016     {
5017       size_t cnt, symidx;
5018
5019       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
5020         {
5021           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
5022           char *shortname, *p;
5023
5024           p = strchr (h->root.root.string, ELF_VER_CHR);
5025           if (p == NULL
5026               || (h->root.type != bfd_link_hash_defined
5027                   && h->root.type != bfd_link_hash_defweak))
5028             continue;
5029
5030           amt = p - h->root.root.string;
5031           shortname = (char *) bfd_malloc (amt + 1);
5032           if (!shortname)
5033             goto error_free_vers;
5034           memcpy (shortname, h->root.root.string, amt);
5035           shortname[amt] = '\0';
5036
5037           hi = (struct elf_link_hash_entry *)
5038                bfd_link_hash_lookup (&htab->root, shortname,
5039                                      FALSE, FALSE, FALSE);
5040           if (hi != NULL
5041               && hi->root.type == h->root.type
5042               && hi->root.u.def.value == h->root.u.def.value
5043               && hi->root.u.def.section == h->root.u.def.section)
5044             {
5045               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
5046               hi->root.type = bfd_link_hash_indirect;
5047               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
5048               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
5049               sym_hash = elf_sym_hashes (abfd);
5050               if (sym_hash)
5051                 for (symidx = 0; symidx < extsymcount; ++symidx)
5052                   if (sym_hash[symidx] == hi)
5053                     {
5054                       sym_hash[symidx] = h;
5055                       break;
5056                     }
5057             }
5058           free (shortname);
5059         }
5060       free (nondeflt_vers);
5061       nondeflt_vers = NULL;
5062     }
5063
5064   /* Now set the weakdefs field correctly for all the weak defined
5065      symbols we found.  The only way to do this is to search all the
5066      symbols.  Since we only need the information for non functions in
5067      dynamic objects, that's the only time we actually put anything on
5068      the list WEAKS.  We need this information so that if a regular
5069      object refers to a symbol defined weakly in a dynamic object, the
5070      real symbol in the dynamic object is also put in the dynamic
5071      symbols; we also must arrange for both symbols to point to the
5072      same memory location.  We could handle the general case of symbol
5073      aliasing, but a general symbol alias can only be generated in
5074      assembler code, handling it correctly would be very time
5075      consuming, and other ELF linkers don't handle general aliasing
5076      either.  */
5077   if (weaks != NULL)
5078     {
5079       struct elf_link_hash_entry **hpp;
5080       struct elf_link_hash_entry **hppend;
5081       struct elf_link_hash_entry **sorted_sym_hash;
5082       struct elf_link_hash_entry *h;
5083       size_t sym_count;
5084
5085       /* Since we have to search the whole symbol list for each weak
5086          defined symbol, search time for N weak defined symbols will be
5087          O(N^2). Binary search will cut it down to O(NlogN).  */
5088       amt = extsymcount;
5089       amt *= sizeof (struct elf_link_hash_entry *);
5090       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
5091       if (sorted_sym_hash == NULL)
5092         goto error_return;
5093       sym_hash = sorted_sym_hash;
5094       hpp = elf_sym_hashes (abfd);
5095       hppend = hpp + extsymcount;
5096       sym_count = 0;
5097       for (; hpp < hppend; hpp++)
5098         {
5099           h = *hpp;
5100           if (h != NULL
5101               && h->root.type == bfd_link_hash_defined
5102               && !bed->is_function_type (h->type))
5103             {
5104               *sym_hash = h;
5105               sym_hash++;
5106               sym_count++;
5107             }
5108         }
5109
5110       qsort (sorted_sym_hash, sym_count,
5111              sizeof (struct elf_link_hash_entry *),
5112              elf_sort_symbol);
5113
5114       while (weaks != NULL)
5115         {
5116           struct elf_link_hash_entry *hlook;
5117           asection *slook;
5118           bfd_vma vlook;
5119           size_t i, j, idx = 0;
5120
5121           hlook = weaks;
5122           weaks = hlook->u.weakdef;
5123           hlook->u.weakdef = NULL;
5124
5125           BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
5126                       || hlook->root.type == bfd_link_hash_defweak
5127                       || hlook->root.type == bfd_link_hash_common
5128                       || hlook->root.type == bfd_link_hash_indirect);
5129           slook = hlook->root.u.def.section;
5130           vlook = hlook->root.u.def.value;
5131
5132           i = 0;
5133           j = sym_count;
5134           while (i != j)
5135             {
5136               bfd_signed_vma vdiff;
5137               idx = (i + j) / 2;
5138               h = sorted_sym_hash[idx];
5139               vdiff = vlook - h->root.u.def.value;
5140               if (vdiff < 0)
5141                 j = idx;
5142               else if (vdiff > 0)
5143                 i = idx + 1;
5144               else
5145                 {
5146                   int sdiff = slook->id - h->root.u.def.section->id;
5147                   if (sdiff < 0)
5148                     j = idx;
5149                   else if (sdiff > 0)
5150                     i = idx + 1;
5151                   else
5152                     break;
5153                 }
5154             }
5155
5156           /* We didn't find a value/section match.  */
5157           if (i == j)
5158             continue;
5159
5160           /* With multiple aliases, or when the weak symbol is already
5161              strongly defined, we have multiple matching symbols and
5162              the binary search above may land on any of them.  Step
5163              one past the matching symbol(s).  */
5164           while (++idx != j)
5165             {
5166               h = sorted_sym_hash[idx];
5167               if (h->root.u.def.section != slook
5168                   || h->root.u.def.value != vlook)
5169                 break;
5170             }
5171
5172           /* Now look back over the aliases.  Since we sorted by size
5173              as well as value and section, we'll choose the one with
5174              the largest size.  */
5175           while (idx-- != i)
5176             {
5177               h = sorted_sym_hash[idx];
5178
5179               /* Stop if value or section doesn't match.  */
5180               if (h->root.u.def.section != slook
5181                   || h->root.u.def.value != vlook)
5182                 break;
5183               else if (h != hlook)
5184                 {
5185                   hlook->u.weakdef = h;
5186
5187                   /* If the weak definition is in the list of dynamic
5188                      symbols, make sure the real definition is put
5189                      there as well.  */
5190                   if (hlook->dynindx != -1 && h->dynindx == -1)
5191                     {
5192                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
5193                         {
5194                         err_free_sym_hash:
5195                           free (sorted_sym_hash);
5196                           goto error_return;
5197                         }
5198                     }
5199
5200                   /* If the real definition is in the list of dynamic
5201                      symbols, make sure the weak definition is put
5202                      there as well.  If we don't do this, then the
5203                      dynamic loader might not merge the entries for the
5204                      real definition and the weak definition.  */
5205                   if (h->dynindx != -1 && hlook->dynindx == -1)
5206                     {
5207                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
5208                         goto err_free_sym_hash;
5209                     }
5210                   break;
5211                 }
5212             }
5213         }
5214
5215       free (sorted_sym_hash);
5216     }
5217
5218   if (bed->check_directives
5219       && !(*bed->check_directives) (abfd, info))
5220     return FALSE;
5221
5222   if (!info->check_relocs_after_open_input
5223       && !_bfd_elf_link_check_relocs (abfd, info))
5224     return FALSE;
5225
5226   /* If this is a non-traditional link, try to optimize the handling
5227      of the .stab/.stabstr sections.  */
5228   if (! dynamic
5229       && ! info->traditional_format
5230       && is_elf_hash_table (htab)
5231       && (info->strip != strip_all && info->strip != strip_debugger))
5232     {
5233       asection *stabstr;
5234
5235       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
5236       if (stabstr != NULL)
5237         {
5238           bfd_size_type string_offset = 0;
5239           asection *stab;
5240
5241           for (stab = abfd->sections; stab; stab = stab->next)
5242             if (CONST_STRNEQ (stab->name, ".stab")
5243                 && (!stab->name[5] ||
5244                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
5245                 && (stab->flags & SEC_MERGE) == 0
5246                 && !bfd_is_abs_section (stab->output_section))
5247               {
5248                 struct bfd_elf_section_data *secdata;
5249
5250                 secdata = elf_section_data (stab);
5251                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
5252                                                stabstr, &secdata->sec_info,
5253                                                &string_offset))
5254                   goto error_return;
5255                 if (secdata->sec_info)
5256                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
5257             }
5258         }
5259     }
5260
5261   if (is_elf_hash_table (htab) && add_needed)
5262     {
5263       /* Add this bfd to the loaded list.  */
5264       struct elf_link_loaded_list *n;
5265
5266       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
5267       if (n == NULL)
5268         goto error_return;
5269       n->abfd = abfd;
5270       n->next = htab->loaded;
5271       htab->loaded = n;
5272     }
5273
5274   return TRUE;
5275
5276  error_free_vers:
5277   if (old_tab != NULL)
5278     free (old_tab);
5279   if (old_strtab != NULL)
5280     free (old_strtab);
5281   if (nondeflt_vers != NULL)
5282     free (nondeflt_vers);
5283   if (extversym != NULL)
5284     free (extversym);
5285  error_free_sym:
5286   if (isymbuf != NULL)
5287     free (isymbuf);
5288  error_return:
5289   return FALSE;
5290 }
5291
5292 /* Return the linker hash table entry of a symbol that might be
5293    satisfied by an archive symbol.  Return -1 on error.  */
5294
5295 struct elf_link_hash_entry *
5296 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5297                                 struct bfd_link_info *info,
5298                                 const char *name)
5299 {
5300   struct elf_link_hash_entry *h;
5301   char *p, *copy;
5302   size_t len, first;
5303
5304   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5305   if (h != NULL)
5306     return h;
5307
5308   /* If this is a default version (the name contains @@), look up the
5309      symbol again with only one `@' as well as without the version.
5310      The effect is that references to the symbol with and without the
5311      version will be matched by the default symbol in the archive.  */
5312
5313   p = strchr (name, ELF_VER_CHR);
5314   if (p == NULL || p[1] != ELF_VER_CHR)
5315     return h;
5316
5317   /* First check with only one `@'.  */
5318   len = strlen (name);
5319   copy = (char *) bfd_alloc (abfd, len);
5320   if (copy == NULL)
5321     return (struct elf_link_hash_entry *) 0 - 1;
5322
5323   first = p - name + 1;
5324   memcpy (copy, name, first);
5325   memcpy (copy + first, name + first + 1, len - first);
5326
5327   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5328   if (h == NULL)
5329     {
5330       /* We also need to check references to the symbol without the
5331          version.  */
5332       copy[first - 1] = '\0';
5333       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5334                                 FALSE, FALSE, TRUE);
5335     }
5336
5337   bfd_release (abfd, copy);
5338   return h;
5339 }
5340
5341 /* Add symbols from an ELF archive file to the linker hash table.  We
5342    don't use _bfd_generic_link_add_archive_symbols because we need to
5343    handle versioned symbols.
5344
5345    Fortunately, ELF archive handling is simpler than that done by
5346    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5347    oddities.  In ELF, if we find a symbol in the archive map, and the
5348    symbol is currently undefined, we know that we must pull in that
5349    object file.
5350
5351    Unfortunately, we do have to make multiple passes over the symbol
5352    table until nothing further is resolved.  */
5353
5354 static bfd_boolean
5355 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5356 {
5357   symindex c;
5358   unsigned char *included = NULL;
5359   carsym *symdefs;
5360   bfd_boolean loop;
5361   bfd_size_type amt;
5362   const struct elf_backend_data *bed;
5363   struct elf_link_hash_entry * (*archive_symbol_lookup)
5364     (bfd *, struct bfd_link_info *, const char *);
5365
5366   if (! bfd_has_map (abfd))
5367     {
5368       /* An empty archive is a special case.  */
5369       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5370         return TRUE;
5371       bfd_set_error (bfd_error_no_armap);
5372       return FALSE;
5373     }
5374
5375   /* Keep track of all symbols we know to be already defined, and all
5376      files we know to be already included.  This is to speed up the
5377      second and subsequent passes.  */
5378   c = bfd_ardata (abfd)->symdef_count;
5379   if (c == 0)
5380     return TRUE;
5381   amt = c;
5382   amt *= sizeof (*included);
5383   included = (unsigned char *) bfd_zmalloc (amt);
5384   if (included == NULL)
5385     return FALSE;
5386
5387   symdefs = bfd_ardata (abfd)->symdefs;
5388   bed = get_elf_backend_data (abfd);
5389   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5390
5391   do
5392     {
5393       file_ptr last;
5394       symindex i;
5395       carsym *symdef;
5396       carsym *symdefend;
5397
5398       loop = FALSE;
5399       last = -1;
5400
5401       symdef = symdefs;
5402       symdefend = symdef + c;
5403       for (i = 0; symdef < symdefend; symdef++, i++)
5404         {
5405           struct elf_link_hash_entry *h;
5406           bfd *element;
5407           struct bfd_link_hash_entry *undefs_tail;
5408           symindex mark;
5409
5410           if (included[i])
5411             continue;
5412           if (symdef->file_offset == last)
5413             {
5414               included[i] = TRUE;
5415               continue;
5416             }
5417
5418           h = archive_symbol_lookup (abfd, info, symdef->name);
5419           if (h == (struct elf_link_hash_entry *) 0 - 1)
5420             goto error_return;
5421
5422           if (h == NULL)
5423             continue;
5424
5425           if (h->root.type == bfd_link_hash_common)
5426             {
5427               /* We currently have a common symbol.  The archive map contains
5428                  a reference to this symbol, so we may want to include it.  We
5429                  only want to include it however, if this archive element
5430                  contains a definition of the symbol, not just another common
5431                  declaration of it.
5432
5433                  Unfortunately some archivers (including GNU ar) will put
5434                  declarations of common symbols into their archive maps, as
5435                  well as real definitions, so we cannot just go by the archive
5436                  map alone.  Instead we must read in the element's symbol
5437                  table and check that to see what kind of symbol definition
5438                  this is.  */
5439               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5440                 continue;
5441             }
5442           else if (h->root.type != bfd_link_hash_undefined)
5443             {
5444               if (h->root.type != bfd_link_hash_undefweak)
5445                 /* Symbol must be defined.  Don't check it again.  */
5446                 included[i] = TRUE;
5447               continue;
5448             }
5449
5450           /* We need to include this archive member.  */
5451           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5452           if (element == NULL)
5453             goto error_return;
5454
5455           if (! bfd_check_format (element, bfd_object))
5456             goto error_return;
5457
5458           undefs_tail = info->hash->undefs_tail;
5459
5460           if (!(*info->callbacks
5461                 ->add_archive_element) (info, element, symdef->name, &element))
5462             continue;
5463           if (!bfd_link_add_symbols (element, info))
5464             goto error_return;
5465
5466           /* If there are any new undefined symbols, we need to make
5467              another pass through the archive in order to see whether
5468              they can be defined.  FIXME: This isn't perfect, because
5469              common symbols wind up on undefs_tail and because an
5470              undefined symbol which is defined later on in this pass
5471              does not require another pass.  This isn't a bug, but it
5472              does make the code less efficient than it could be.  */
5473           if (undefs_tail != info->hash->undefs_tail)
5474             loop = TRUE;
5475
5476           /* Look backward to mark all symbols from this object file
5477              which we have already seen in this pass.  */
5478           mark = i;
5479           do
5480             {
5481               included[mark] = TRUE;
5482               if (mark == 0)
5483                 break;
5484               --mark;
5485             }
5486           while (symdefs[mark].file_offset == symdef->file_offset);
5487
5488           /* We mark subsequent symbols from this object file as we go
5489              on through the loop.  */
5490           last = symdef->file_offset;
5491         }
5492     }
5493   while (loop);
5494
5495   free (included);
5496
5497   return TRUE;
5498
5499  error_return:
5500   if (included != NULL)
5501     free (included);
5502   return FALSE;
5503 }
5504
5505 /* Given an ELF BFD, add symbols to the global hash table as
5506    appropriate.  */
5507
5508 bfd_boolean
5509 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5510 {
5511   switch (bfd_get_format (abfd))
5512     {
5513     case bfd_object:
5514       return elf_link_add_object_symbols (abfd, info);
5515     case bfd_archive:
5516       return elf_link_add_archive_symbols (abfd, info);
5517     default:
5518       bfd_set_error (bfd_error_wrong_format);
5519       return FALSE;
5520     }
5521 }
5522 \f
5523 struct hash_codes_info
5524 {
5525   unsigned long *hashcodes;
5526   bfd_boolean error;
5527 };
5528
5529 /* This function will be called though elf_link_hash_traverse to store
5530    all hash value of the exported symbols in an array.  */
5531
5532 static bfd_boolean
5533 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5534 {
5535   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5536   const char *name;
5537   unsigned long ha;
5538   char *alc = NULL;
5539
5540   /* Ignore indirect symbols.  These are added by the versioning code.  */
5541   if (h->dynindx == -1)
5542     return TRUE;
5543
5544   name = h->root.root.string;
5545   if (h->versioned >= versioned)
5546     {
5547       char *p = strchr (name, ELF_VER_CHR);
5548       if (p != NULL)
5549         {
5550           alc = (char *) bfd_malloc (p - name + 1);
5551           if (alc == NULL)
5552             {
5553               inf->error = TRUE;
5554               return FALSE;
5555             }
5556           memcpy (alc, name, p - name);
5557           alc[p - name] = '\0';
5558           name = alc;
5559         }
5560     }
5561
5562   /* Compute the hash value.  */
5563   ha = bfd_elf_hash (name);
5564
5565   /* Store the found hash value in the array given as the argument.  */
5566   *(inf->hashcodes)++ = ha;
5567
5568   /* And store it in the struct so that we can put it in the hash table
5569      later.  */
5570   h->u.elf_hash_value = ha;
5571
5572   if (alc != NULL)
5573     free (alc);
5574
5575   return TRUE;
5576 }
5577
5578 struct collect_gnu_hash_codes
5579 {
5580   bfd *output_bfd;
5581   const struct elf_backend_data *bed;
5582   unsigned long int nsyms;
5583   unsigned long int maskbits;
5584   unsigned long int *hashcodes;
5585   unsigned long int *hashval;
5586   unsigned long int *indx;
5587   unsigned long int *counts;
5588   bfd_vma *bitmask;
5589   bfd_byte *contents;
5590   long int min_dynindx;
5591   unsigned long int bucketcount;
5592   unsigned long int symindx;
5593   long int local_indx;
5594   long int shift1, shift2;
5595   unsigned long int mask;
5596   bfd_boolean error;
5597 };
5598
5599 /* This function will be called though elf_link_hash_traverse to store
5600    all hash value of the exported symbols in an array.  */
5601
5602 static bfd_boolean
5603 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5604 {
5605   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5606   const char *name;
5607   unsigned long ha;
5608   char *alc = NULL;
5609
5610   /* Ignore indirect symbols.  These are added by the versioning code.  */
5611   if (h->dynindx == -1)
5612     return TRUE;
5613
5614   /* Ignore also local symbols and undefined symbols.  */
5615   if (! (*s->bed->elf_hash_symbol) (h))
5616     return TRUE;
5617
5618   name = h->root.root.string;
5619   if (h->versioned >= versioned)
5620     {
5621       char *p = strchr (name, ELF_VER_CHR);
5622       if (p != NULL)
5623         {
5624           alc = (char *) bfd_malloc (p - name + 1);
5625           if (alc == NULL)
5626             {
5627               s->error = TRUE;
5628               return FALSE;
5629             }
5630           memcpy (alc, name, p - name);
5631           alc[p - name] = '\0';
5632           name = alc;
5633         }
5634     }
5635
5636   /* Compute the hash value.  */
5637   ha = bfd_elf_gnu_hash (name);
5638
5639   /* Store the found hash value in the array for compute_bucket_count,
5640      and also for .dynsym reordering purposes.  */
5641   s->hashcodes[s->nsyms] = ha;
5642   s->hashval[h->dynindx] = ha;
5643   ++s->nsyms;
5644   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5645     s->min_dynindx = h->dynindx;
5646
5647   if (alc != NULL)
5648     free (alc);
5649
5650   return TRUE;
5651 }
5652
5653 /* This function will be called though elf_link_hash_traverse to do
5654    final dynaminc symbol renumbering.  */
5655
5656 static bfd_boolean
5657 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5658 {
5659   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5660   unsigned long int bucket;
5661   unsigned long int val;
5662
5663   /* Ignore indirect symbols.  */
5664   if (h->dynindx == -1)
5665     return TRUE;
5666
5667   /* Ignore also local symbols and undefined symbols.  */
5668   if (! (*s->bed->elf_hash_symbol) (h))
5669     {
5670       if (h->dynindx >= s->min_dynindx)
5671         h->dynindx = s->local_indx++;
5672       return TRUE;
5673     }
5674
5675   bucket = s->hashval[h->dynindx] % s->bucketcount;
5676   val = (s->hashval[h->dynindx] >> s->shift1)
5677         & ((s->maskbits >> s->shift1) - 1);
5678   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5679   s->bitmask[val]
5680     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5681   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5682   if (s->counts[bucket] == 1)
5683     /* Last element terminates the chain.  */
5684     val |= 1;
5685   bfd_put_32 (s->output_bfd, val,
5686               s->contents + (s->indx[bucket] - s->symindx) * 4);
5687   --s->counts[bucket];
5688   h->dynindx = s->indx[bucket]++;
5689   return TRUE;
5690 }
5691
5692 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5693
5694 bfd_boolean
5695 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5696 {
5697   return !(h->forced_local
5698            || h->root.type == bfd_link_hash_undefined
5699            || h->root.type == bfd_link_hash_undefweak
5700            || ((h->root.type == bfd_link_hash_defined
5701                 || h->root.type == bfd_link_hash_defweak)
5702                && h->root.u.def.section->output_section == NULL));
5703 }
5704
5705 /* Array used to determine the number of hash table buckets to use
5706    based on the number of symbols there are.  If there are fewer than
5707    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5708    fewer than 37 we use 17 buckets, and so forth.  We never use more
5709    than 32771 buckets.  */
5710
5711 static const size_t elf_buckets[] =
5712 {
5713   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5714   16411, 32771, 0
5715 };
5716
5717 /* Compute bucket count for hashing table.  We do not use a static set
5718    of possible tables sizes anymore.  Instead we determine for all
5719    possible reasonable sizes of the table the outcome (i.e., the
5720    number of collisions etc) and choose the best solution.  The
5721    weighting functions are not too simple to allow the table to grow
5722    without bounds.  Instead one of the weighting factors is the size.
5723    Therefore the result is always a good payoff between few collisions
5724    (= short chain lengths) and table size.  */
5725 static size_t
5726 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5727                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5728                       unsigned long int nsyms,
5729                       int gnu_hash)
5730 {
5731   size_t best_size = 0;
5732   unsigned long int i;
5733
5734   /* We have a problem here.  The following code to optimize the table
5735      size requires an integer type with more the 32 bits.  If
5736      BFD_HOST_U_64_BIT is set we know about such a type.  */
5737 #ifdef BFD_HOST_U_64_BIT
5738   if (info->optimize)
5739     {
5740       size_t minsize;
5741       size_t maxsize;
5742       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5743       bfd *dynobj = elf_hash_table (info)->dynobj;
5744       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5745       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5746       unsigned long int *counts;
5747       bfd_size_type amt;
5748       unsigned int no_improvement_count = 0;
5749
5750       /* Possible optimization parameters: if we have NSYMS symbols we say
5751          that the hashing table must at least have NSYMS/4 and at most
5752          2*NSYMS buckets.  */
5753       minsize = nsyms / 4;
5754       if (minsize == 0)
5755         minsize = 1;
5756       best_size = maxsize = nsyms * 2;
5757       if (gnu_hash)
5758         {
5759           if (minsize < 2)
5760             minsize = 2;
5761           if ((best_size & 31) == 0)
5762             ++best_size;
5763         }
5764
5765       /* Create array where we count the collisions in.  We must use bfd_malloc
5766          since the size could be large.  */
5767       amt = maxsize;
5768       amt *= sizeof (unsigned long int);
5769       counts = (unsigned long int *) bfd_malloc (amt);
5770       if (counts == NULL)
5771         return 0;
5772
5773       /* Compute the "optimal" size for the hash table.  The criteria is a
5774          minimal chain length.  The minor criteria is (of course) the size
5775          of the table.  */
5776       for (i = minsize; i < maxsize; ++i)
5777         {
5778           /* Walk through the array of hashcodes and count the collisions.  */
5779           BFD_HOST_U_64_BIT max;
5780           unsigned long int j;
5781           unsigned long int fact;
5782
5783           if (gnu_hash && (i & 31) == 0)
5784             continue;
5785
5786           memset (counts, '\0', i * sizeof (unsigned long int));
5787
5788           /* Determine how often each hash bucket is used.  */
5789           for (j = 0; j < nsyms; ++j)
5790             ++counts[hashcodes[j] % i];
5791
5792           /* For the weight function we need some information about the
5793              pagesize on the target.  This is information need not be 100%
5794              accurate.  Since this information is not available (so far) we
5795              define it here to a reasonable default value.  If it is crucial
5796              to have a better value some day simply define this value.  */
5797 # ifndef BFD_TARGET_PAGESIZE
5798 #  define BFD_TARGET_PAGESIZE   (4096)
5799 # endif
5800
5801           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5802              and the chains.  */
5803           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5804
5805 # if 1
5806           /* Variant 1: optimize for short chains.  We add the squares
5807              of all the chain lengths (which favors many small chain
5808              over a few long chains).  */
5809           for (j = 0; j < i; ++j)
5810             max += counts[j] * counts[j];
5811
5812           /* This adds penalties for the overall size of the table.  */
5813           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5814           max *= fact * fact;
5815 # else
5816           /* Variant 2: Optimize a lot more for small table.  Here we
5817              also add squares of the size but we also add penalties for
5818              empty slots (the +1 term).  */
5819           for (j = 0; j < i; ++j)
5820             max += (1 + counts[j]) * (1 + counts[j]);
5821
5822           /* The overall size of the table is considered, but not as
5823              strong as in variant 1, where it is squared.  */
5824           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5825           max *= fact;
5826 # endif
5827
5828           /* Compare with current best results.  */
5829           if (max < best_chlen)
5830             {
5831               best_chlen = max;
5832               best_size = i;
5833               no_improvement_count = 0;
5834             }
5835           /* PR 11843: Avoid futile long searches for the best bucket size
5836              when there are a large number of symbols.  */
5837           else if (++no_improvement_count == 100)
5838             break;
5839         }
5840
5841       free (counts);
5842     }
5843   else
5844 #endif /* defined (BFD_HOST_U_64_BIT) */
5845     {
5846       /* This is the fallback solution if no 64bit type is available or if we
5847          are not supposed to spend much time on optimizations.  We select the
5848          bucket count using a fixed set of numbers.  */
5849       for (i = 0; elf_buckets[i] != 0; i++)
5850         {
5851           best_size = elf_buckets[i];
5852           if (nsyms < elf_buckets[i + 1])
5853             break;
5854         }
5855       if (gnu_hash && best_size < 2)
5856         best_size = 2;
5857     }
5858
5859   return best_size;
5860 }
5861
5862 /* Size any SHT_GROUP section for ld -r.  */
5863
5864 bfd_boolean
5865 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5866 {
5867   bfd *ibfd;
5868   asection *s;
5869
5870   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5871     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5872         && (s = ibfd->sections) != NULL
5873         && s->sec_info_type != SEC_INFO_TYPE_JUST_SYMS
5874         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5875       return FALSE;
5876   return TRUE;
5877 }
5878
5879 /* Set a default stack segment size.  The value in INFO wins.  If it
5880    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
5881    undefined it is initialized.  */
5882
5883 bfd_boolean
5884 bfd_elf_stack_segment_size (bfd *output_bfd,
5885                             struct bfd_link_info *info,
5886                             const char *legacy_symbol,
5887                             bfd_vma default_size)
5888 {
5889   struct elf_link_hash_entry *h = NULL;
5890
5891   /* Look for legacy symbol.  */
5892   if (legacy_symbol)
5893     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
5894                               FALSE, FALSE, FALSE);
5895   if (h && (h->root.type == bfd_link_hash_defined
5896             || h->root.type == bfd_link_hash_defweak)
5897       && h->def_regular
5898       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
5899     {
5900       /* The symbol has no type if specified on the command line.  */
5901       h->type = STT_OBJECT;
5902       if (info->stacksize)
5903         /* xgettext:c-format */
5904         _bfd_error_handler (_("%B: stack size specified and %s set"),
5905                             output_bfd, legacy_symbol);
5906       else if (h->root.u.def.section != bfd_abs_section_ptr)
5907         /* xgettext:c-format */
5908         _bfd_error_handler (_("%B: %s not absolute"),
5909                             output_bfd, legacy_symbol);
5910       else
5911         info->stacksize = h->root.u.def.value;
5912     }
5913
5914   if (!info->stacksize)
5915     /* If the user didn't set a size, or explicitly inhibit the
5916        size, set it now.  */
5917     info->stacksize = default_size;
5918
5919   /* Provide the legacy symbol, if it is referenced.  */
5920   if (h && (h->root.type == bfd_link_hash_undefined
5921             || h->root.type == bfd_link_hash_undefweak))
5922     {
5923       struct bfd_link_hash_entry *bh = NULL;
5924
5925       if (!(_bfd_generic_link_add_one_symbol
5926             (info, output_bfd, legacy_symbol,
5927              BSF_GLOBAL, bfd_abs_section_ptr,
5928              info->stacksize >= 0 ? info->stacksize : 0,
5929              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
5930         return FALSE;
5931
5932       h = (struct elf_link_hash_entry *) bh;
5933       h->def_regular = 1;
5934       h->type = STT_OBJECT;
5935     }
5936
5937   return TRUE;
5938 }
5939
5940 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
5941
5942 struct elf_gc_sweep_symbol_info
5943 {
5944   struct bfd_link_info *info;
5945   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
5946                        bfd_boolean);
5947 };
5948
5949 static bfd_boolean
5950 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
5951 {
5952   if (!h->mark
5953       && (((h->root.type == bfd_link_hash_defined
5954             || h->root.type == bfd_link_hash_defweak)
5955            && !((h->def_regular || ELF_COMMON_DEF_P (h))
5956                 && h->root.u.def.section->gc_mark))
5957           || h->root.type == bfd_link_hash_undefined
5958           || h->root.type == bfd_link_hash_undefweak))
5959     {
5960       struct elf_gc_sweep_symbol_info *inf;
5961
5962       inf = (struct elf_gc_sweep_symbol_info *) data;
5963       (*inf->hide_symbol) (inf->info, h, TRUE);
5964       h->def_regular = 0;
5965       h->ref_regular = 0;
5966       h->ref_regular_nonweak = 0;
5967     }
5968
5969   return TRUE;
5970 }
5971
5972 /* Set up the sizes and contents of the ELF dynamic sections.  This is
5973    called by the ELF linker emulation before_allocation routine.  We
5974    must set the sizes of the sections before the linker sets the
5975    addresses of the various sections.  */
5976
5977 bfd_boolean
5978 bfd_elf_size_dynamic_sections (bfd *output_bfd,
5979                                const char *soname,
5980                                const char *rpath,
5981                                const char *filter_shlib,
5982                                const char *audit,
5983                                const char *depaudit,
5984                                const char * const *auxiliary_filters,
5985                                struct bfd_link_info *info,
5986                                asection **sinterpptr)
5987 {
5988   bfd *dynobj;
5989   const struct elf_backend_data *bed;
5990
5991   *sinterpptr = NULL;
5992
5993   if (!is_elf_hash_table (info->hash))
5994     return TRUE;
5995
5996   dynobj = elf_hash_table (info)->dynobj;
5997
5998   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
5999     {
6000       struct bfd_elf_version_tree *verdefs;
6001       struct elf_info_failed asvinfo;
6002       struct bfd_elf_version_tree *t;
6003       struct bfd_elf_version_expr *d;
6004       struct elf_info_failed eif;
6005       bfd_boolean all_defined;
6006       asection *s;
6007       size_t soname_indx;
6008
6009       eif.info = info;
6010       eif.failed = FALSE;
6011
6012       /* If we are supposed to export all symbols into the dynamic symbol
6013          table (this is not the normal case), then do so.  */
6014       if (info->export_dynamic
6015           || (bfd_link_executable (info) && info->dynamic))
6016         {
6017           elf_link_hash_traverse (elf_hash_table (info),
6018                                   _bfd_elf_export_symbol,
6019                                   &eif);
6020           if (eif.failed)
6021             return FALSE;
6022         }
6023
6024       if (soname != NULL)
6025         {
6026           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6027                                              soname, TRUE);
6028           if (soname_indx == (size_t) -1
6029               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
6030             return FALSE;
6031         }
6032       else
6033         soname_indx = (size_t) -1;
6034
6035       /* Make all global versions with definition.  */
6036       for (t = info->version_info; t != NULL; t = t->next)
6037         for (d = t->globals.list; d != NULL; d = d->next)
6038           if (!d->symver && d->literal)
6039             {
6040               const char *verstr, *name;
6041               size_t namelen, verlen, newlen;
6042               char *newname, *p, leading_char;
6043               struct elf_link_hash_entry *newh;
6044
6045               leading_char = bfd_get_symbol_leading_char (output_bfd);
6046               name = d->pattern;
6047               namelen = strlen (name) + (leading_char != '\0');
6048               verstr = t->name;
6049               verlen = strlen (verstr);
6050               newlen = namelen + verlen + 3;
6051
6052               newname = (char *) bfd_malloc (newlen);
6053               if (newname == NULL)
6054                 return FALSE;
6055               newname[0] = leading_char;
6056               memcpy (newname + (leading_char != '\0'), name, namelen);
6057
6058               /* Check the hidden versioned definition.  */
6059               p = newname + namelen;
6060               *p++ = ELF_VER_CHR;
6061               memcpy (p, verstr, verlen + 1);
6062               newh = elf_link_hash_lookup (elf_hash_table (info),
6063                                            newname, FALSE, FALSE,
6064                                            FALSE);
6065               if (newh == NULL
6066                   || (newh->root.type != bfd_link_hash_defined
6067                       && newh->root.type != bfd_link_hash_defweak))
6068                 {
6069                   /* Check the default versioned definition.  */
6070                   *p++ = ELF_VER_CHR;
6071                   memcpy (p, verstr, verlen + 1);
6072                   newh = elf_link_hash_lookup (elf_hash_table (info),
6073                                                newname, FALSE, FALSE,
6074                                                FALSE);
6075                 }
6076               free (newname);
6077
6078               /* Mark this version if there is a definition and it is
6079                  not defined in a shared object.  */
6080               if (newh != NULL
6081                   && !newh->def_dynamic
6082                   && (newh->root.type == bfd_link_hash_defined
6083                       || newh->root.type == bfd_link_hash_defweak))
6084                 d->symver = 1;
6085             }
6086
6087       /* Attach all the symbols to their version information.  */
6088       asvinfo.info = info;
6089       asvinfo.failed = FALSE;
6090
6091       elf_link_hash_traverse (elf_hash_table (info),
6092                               _bfd_elf_link_assign_sym_version,
6093                               &asvinfo);
6094       if (asvinfo.failed)
6095         return FALSE;
6096
6097       if (!info->allow_undefined_version)
6098         {
6099           /* Check if all global versions have a definition.  */
6100           all_defined = TRUE;
6101           for (t = info->version_info; t != NULL; t = t->next)
6102             for (d = t->globals.list; d != NULL; d = d->next)
6103               if (d->literal && !d->symver && !d->script)
6104                 {
6105                   _bfd_error_handler
6106                     (_("%s: undefined version: %s"),
6107                      d->pattern, t->name);
6108                   all_defined = FALSE;
6109                 }
6110
6111           if (!all_defined)
6112             {
6113               bfd_set_error (bfd_error_bad_value);
6114               return FALSE;
6115             }
6116         }
6117
6118       /* Set up the version definition section.  */
6119       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6120       BFD_ASSERT (s != NULL);
6121
6122       /* We may have created additional version definitions if we are
6123          just linking a regular application.  */
6124       verdefs = info->version_info;
6125
6126       /* Skip anonymous version tag.  */
6127       if (verdefs != NULL && verdefs->vernum == 0)
6128         verdefs = verdefs->next;
6129
6130       if (verdefs == NULL && !info->create_default_symver)
6131         s->flags |= SEC_EXCLUDE;
6132       else
6133         {
6134           unsigned int cdefs;
6135           bfd_size_type size;
6136           bfd_byte *p;
6137           Elf_Internal_Verdef def;
6138           Elf_Internal_Verdaux defaux;
6139           struct bfd_link_hash_entry *bh;
6140           struct elf_link_hash_entry *h;
6141           const char *name;
6142
6143           cdefs = 0;
6144           size = 0;
6145
6146           /* Make space for the base version.  */
6147           size += sizeof (Elf_External_Verdef);
6148           size += sizeof (Elf_External_Verdaux);
6149           ++cdefs;
6150
6151           /* Make space for the default version.  */
6152           if (info->create_default_symver)
6153             {
6154               size += sizeof (Elf_External_Verdef);
6155               ++cdefs;
6156             }
6157
6158           for (t = verdefs; t != NULL; t = t->next)
6159             {
6160               struct bfd_elf_version_deps *n;
6161
6162               /* Don't emit base version twice.  */
6163               if (t->vernum == 0)
6164                 continue;
6165
6166               size += sizeof (Elf_External_Verdef);
6167               size += sizeof (Elf_External_Verdaux);
6168               ++cdefs;
6169
6170               for (n = t->deps; n != NULL; n = n->next)
6171                 size += sizeof (Elf_External_Verdaux);
6172             }
6173
6174           s->size = size;
6175           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6176           if (s->contents == NULL && s->size != 0)
6177             return FALSE;
6178
6179           /* Fill in the version definition section.  */
6180
6181           p = s->contents;
6182
6183           def.vd_version = VER_DEF_CURRENT;
6184           def.vd_flags = VER_FLG_BASE;
6185           def.vd_ndx = 1;
6186           def.vd_cnt = 1;
6187           if (info->create_default_symver)
6188             {
6189               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6190               def.vd_next = sizeof (Elf_External_Verdef);
6191             }
6192           else
6193             {
6194               def.vd_aux = sizeof (Elf_External_Verdef);
6195               def.vd_next = (sizeof (Elf_External_Verdef)
6196                              + sizeof (Elf_External_Verdaux));
6197             }
6198
6199           if (soname_indx != (size_t) -1)
6200             {
6201               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6202                                       soname_indx);
6203               def.vd_hash = bfd_elf_hash (soname);
6204               defaux.vda_name = soname_indx;
6205               name = soname;
6206             }
6207           else
6208             {
6209               size_t indx;
6210
6211               name = lbasename (output_bfd->filename);
6212               def.vd_hash = bfd_elf_hash (name);
6213               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6214                                           name, FALSE);
6215               if (indx == (size_t) -1)
6216                 return FALSE;
6217               defaux.vda_name = indx;
6218             }
6219           defaux.vda_next = 0;
6220
6221           _bfd_elf_swap_verdef_out (output_bfd, &def,
6222                                     (Elf_External_Verdef *) p);
6223           p += sizeof (Elf_External_Verdef);
6224           if (info->create_default_symver)
6225             {
6226               /* Add a symbol representing this version.  */
6227               bh = NULL;
6228               if (! (_bfd_generic_link_add_one_symbol
6229                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6230                       0, NULL, FALSE,
6231                       get_elf_backend_data (dynobj)->collect, &bh)))
6232                 return FALSE;
6233               h = (struct elf_link_hash_entry *) bh;
6234               h->non_elf = 0;
6235               h->def_regular = 1;
6236               h->type = STT_OBJECT;
6237               h->verinfo.vertree = NULL;
6238
6239               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6240                 return FALSE;
6241
6242               /* Create a duplicate of the base version with the same
6243                  aux block, but different flags.  */
6244               def.vd_flags = 0;
6245               def.vd_ndx = 2;
6246               def.vd_aux = sizeof (Elf_External_Verdef);
6247               if (verdefs)
6248                 def.vd_next = (sizeof (Elf_External_Verdef)
6249                                + sizeof (Elf_External_Verdaux));
6250               else
6251                 def.vd_next = 0;
6252               _bfd_elf_swap_verdef_out (output_bfd, &def,
6253                                         (Elf_External_Verdef *) p);
6254               p += sizeof (Elf_External_Verdef);
6255             }
6256           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6257                                      (Elf_External_Verdaux *) p);
6258           p += sizeof (Elf_External_Verdaux);
6259
6260           for (t = verdefs; t != NULL; t = t->next)
6261             {
6262               unsigned int cdeps;
6263               struct bfd_elf_version_deps *n;
6264
6265               /* Don't emit the base version twice.  */
6266               if (t->vernum == 0)
6267                 continue;
6268
6269               cdeps = 0;
6270               for (n = t->deps; n != NULL; n = n->next)
6271                 ++cdeps;
6272
6273               /* Add a symbol representing this version.  */
6274               bh = NULL;
6275               if (! (_bfd_generic_link_add_one_symbol
6276                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6277                       0, NULL, FALSE,
6278                       get_elf_backend_data (dynobj)->collect, &bh)))
6279                 return FALSE;
6280               h = (struct elf_link_hash_entry *) bh;
6281               h->non_elf = 0;
6282               h->def_regular = 1;
6283               h->type = STT_OBJECT;
6284               h->verinfo.vertree = t;
6285
6286               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6287                 return FALSE;
6288
6289               def.vd_version = VER_DEF_CURRENT;
6290               def.vd_flags = 0;
6291               if (t->globals.list == NULL
6292                   && t->locals.list == NULL
6293                   && ! t->used)
6294                 def.vd_flags |= VER_FLG_WEAK;
6295               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6296               def.vd_cnt = cdeps + 1;
6297               def.vd_hash = bfd_elf_hash (t->name);
6298               def.vd_aux = sizeof (Elf_External_Verdef);
6299               def.vd_next = 0;
6300
6301               /* If a basever node is next, it *must* be the last node in
6302                  the chain, otherwise Verdef construction breaks.  */
6303               if (t->next != NULL && t->next->vernum == 0)
6304                 BFD_ASSERT (t->next->next == NULL);
6305
6306               if (t->next != NULL && t->next->vernum != 0)
6307                 def.vd_next = (sizeof (Elf_External_Verdef)
6308                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6309
6310               _bfd_elf_swap_verdef_out (output_bfd, &def,
6311                                         (Elf_External_Verdef *) p);
6312               p += sizeof (Elf_External_Verdef);
6313
6314               defaux.vda_name = h->dynstr_index;
6315               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6316                                       h->dynstr_index);
6317               defaux.vda_next = 0;
6318               if (t->deps != NULL)
6319                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6320               t->name_indx = defaux.vda_name;
6321
6322               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6323                                          (Elf_External_Verdaux *) p);
6324               p += sizeof (Elf_External_Verdaux);
6325
6326               for (n = t->deps; n != NULL; n = n->next)
6327                 {
6328                   if (n->version_needed == NULL)
6329                     {
6330                       /* This can happen if there was an error in the
6331                          version script.  */
6332                       defaux.vda_name = 0;
6333                     }
6334                   else
6335                     {
6336                       defaux.vda_name = n->version_needed->name_indx;
6337                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6338                                               defaux.vda_name);
6339                     }
6340                   if (n->next == NULL)
6341                     defaux.vda_next = 0;
6342                   else
6343                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6344
6345                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6346                                              (Elf_External_Verdaux *) p);
6347                   p += sizeof (Elf_External_Verdaux);
6348                 }
6349             }
6350
6351           elf_tdata (output_bfd)->cverdefs = cdefs;
6352         }
6353
6354       /* Work out the size of the version reference section.  */
6355
6356       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6357       BFD_ASSERT (s != NULL);
6358       {
6359         struct elf_find_verdep_info sinfo;
6360
6361         sinfo.info = info;
6362         sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6363         if (sinfo.vers == 0)
6364           sinfo.vers = 1;
6365         sinfo.failed = FALSE;
6366
6367         elf_link_hash_traverse (elf_hash_table (info),
6368                                 _bfd_elf_link_find_version_dependencies,
6369                                 &sinfo);
6370         if (sinfo.failed)
6371           return FALSE;
6372
6373         if (elf_tdata (output_bfd)->verref == NULL)
6374           s->flags |= SEC_EXCLUDE;
6375         else
6376           {
6377             Elf_Internal_Verneed *vn;
6378             unsigned int size;
6379             unsigned int crefs;
6380             bfd_byte *p;
6381
6382             /* Build the version dependency section.  */
6383             size = 0;
6384             crefs = 0;
6385             for (vn = elf_tdata (output_bfd)->verref;
6386                  vn != NULL;
6387                  vn = vn->vn_nextref)
6388               {
6389                 Elf_Internal_Vernaux *a;
6390
6391                 size += sizeof (Elf_External_Verneed);
6392                 ++crefs;
6393                 for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6394                   size += sizeof (Elf_External_Vernaux);
6395               }
6396
6397             s->size = size;
6398             s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6399             if (s->contents == NULL)
6400               return FALSE;
6401
6402             p = s->contents;
6403             for (vn = elf_tdata (output_bfd)->verref;
6404                  vn != NULL;
6405                  vn = vn->vn_nextref)
6406               {
6407                 unsigned int caux;
6408                 Elf_Internal_Vernaux *a;
6409                 size_t indx;
6410
6411                 caux = 0;
6412                 for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6413                   ++caux;
6414
6415                 vn->vn_version = VER_NEED_CURRENT;
6416                 vn->vn_cnt = caux;
6417                 indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6418                                             elf_dt_name (vn->vn_bfd) != NULL
6419                                             ? elf_dt_name (vn->vn_bfd)
6420                                             : lbasename (vn->vn_bfd->filename),
6421                                             FALSE);
6422                 if (indx == (size_t) -1)
6423                   return FALSE;
6424                 vn->vn_file = indx;
6425                 vn->vn_aux = sizeof (Elf_External_Verneed);
6426                 if (vn->vn_nextref == NULL)
6427                   vn->vn_next = 0;
6428                 else
6429                   vn->vn_next = (sizeof (Elf_External_Verneed)
6430                                 + caux * sizeof (Elf_External_Vernaux));
6431
6432                 _bfd_elf_swap_verneed_out (output_bfd, vn,
6433                                            (Elf_External_Verneed *) p);
6434                 p += sizeof (Elf_External_Verneed);
6435
6436                 for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6437                   {
6438                     a->vna_hash = bfd_elf_hash (a->vna_nodename);
6439                     indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6440                                                 a->vna_nodename, FALSE);
6441                     if (indx == (size_t) -1)
6442                       return FALSE;
6443                     a->vna_name = indx;
6444                     if (a->vna_nextptr == NULL)
6445                       a->vna_next = 0;
6446                     else
6447                       a->vna_next = sizeof (Elf_External_Vernaux);
6448
6449                     _bfd_elf_swap_vernaux_out (output_bfd, a,
6450                                                (Elf_External_Vernaux *) p);
6451                     p += sizeof (Elf_External_Vernaux);
6452                   }
6453               }
6454
6455             elf_tdata (output_bfd)->cverrefs = crefs;
6456           }
6457       }
6458     }
6459
6460   bed = get_elf_backend_data (output_bfd);
6461
6462   if (info->gc_sections && bed->can_gc_sections)
6463     {
6464       struct elf_gc_sweep_symbol_info sweep_info;
6465       unsigned long section_sym_count;
6466
6467       /* Remove the symbols that were in the swept sections from the
6468          dynamic symbol table.  GCFIXME: Anyone know how to get them
6469          out of the static symbol table as well?  */
6470       sweep_info.info = info;
6471       sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
6472       elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
6473                               &sweep_info);
6474
6475       /* We need to reassign dynsym indices now that symbols may have
6476          been removed.  See the call in `bfd_elf_size_dynsym_hash_dynstr'
6477          for the details of the conditions used here.  */
6478       if (elf_hash_table (info)->dynamic_sections_created
6479           || bed->always_renumber_dynsyms)
6480         _bfd_elf_link_renumber_dynsyms (output_bfd, info, &section_sym_count);
6481     }
6482
6483   /* Any syms created from now on start with -1 in
6484      got.refcount/offset and plt.refcount/offset.  */
6485   elf_hash_table (info)->init_got_refcount
6486     = elf_hash_table (info)->init_got_offset;
6487   elf_hash_table (info)->init_plt_refcount
6488     = elf_hash_table (info)->init_plt_offset;
6489
6490   if (bfd_link_relocatable (info)
6491       && !_bfd_elf_size_group_sections (info))
6492     return FALSE;
6493
6494   /* The backend may have to create some sections regardless of whether
6495      we're dynamic or not.  */
6496   if (bed->elf_backend_always_size_sections
6497       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
6498     return FALSE;
6499
6500   /* Determine any GNU_STACK segment requirements, after the backend
6501      has had a chance to set a default segment size.  */
6502   if (info->execstack)
6503     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
6504   else if (info->noexecstack)
6505     elf_stack_flags (output_bfd) = PF_R | PF_W;
6506   else
6507     {
6508       bfd *inputobj;
6509       asection *notesec = NULL;
6510       int exec = 0;
6511
6512       for (inputobj = info->input_bfds;
6513            inputobj;
6514            inputobj = inputobj->link.next)
6515         {
6516           asection *s;
6517
6518           if (inputobj->flags
6519               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
6520             continue;
6521           s = inputobj->sections;
6522           if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
6523             continue;
6524
6525           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
6526           if (s)
6527             {
6528               if (s->flags & SEC_CODE)
6529                 exec = PF_X;
6530               notesec = s;
6531             }
6532           else if (bed->default_execstack)
6533             exec = PF_X;
6534         }
6535       if (notesec || info->stacksize > 0)
6536         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
6537       if (notesec && exec && bfd_link_relocatable (info)
6538           && notesec->output_section != bfd_abs_section_ptr)
6539         notesec->output_section->flags |= SEC_CODE;
6540     }
6541
6542   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6543     {
6544       struct elf_info_failed eif;
6545       struct elf_link_hash_entry *h;
6546       asection *dynstr;
6547       asection *s;
6548
6549       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
6550       BFD_ASSERT (*sinterpptr != NULL || !bfd_link_executable (info) || info->nointerp);
6551
6552       if (info->symbolic)
6553         {
6554           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
6555             return FALSE;
6556           info->flags |= DF_SYMBOLIC;
6557         }
6558
6559       if (rpath != NULL)
6560         {
6561           size_t indx;
6562           bfd_vma tag;
6563
6564           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
6565                                       TRUE);
6566           if (indx == (size_t) -1)
6567             return FALSE;
6568
6569           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
6570           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
6571             return FALSE;
6572         }
6573
6574       if (filter_shlib != NULL)
6575         {
6576           size_t indx;
6577
6578           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6579                                       filter_shlib, TRUE);
6580           if (indx == (size_t) -1
6581               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
6582             return FALSE;
6583         }
6584
6585       if (auxiliary_filters != NULL)
6586         {
6587           const char * const *p;
6588
6589           for (p = auxiliary_filters; *p != NULL; p++)
6590             {
6591               size_t indx;
6592
6593               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6594                                           *p, TRUE);
6595               if (indx == (size_t) -1
6596                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
6597                 return FALSE;
6598             }
6599         }
6600
6601       if (audit != NULL)
6602         {
6603           size_t indx;
6604
6605           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
6606                                       TRUE);
6607           if (indx == (size_t) -1
6608               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
6609             return FALSE;
6610         }
6611
6612       if (depaudit != NULL)
6613         {
6614           size_t indx;
6615
6616           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
6617                                       TRUE);
6618           if (indx == (size_t) -1
6619               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
6620             return FALSE;
6621         }
6622
6623       eif.info = info;
6624       eif.failed = FALSE;
6625
6626       /* Find all symbols which were defined in a dynamic object and make
6627          the backend pick a reasonable value for them.  */
6628       elf_link_hash_traverse (elf_hash_table (info),
6629                               _bfd_elf_adjust_dynamic_symbol,
6630                               &eif);
6631       if (eif.failed)
6632         return FALSE;
6633
6634       /* Add some entries to the .dynamic section.  We fill in some of the
6635          values later, in bfd_elf_final_link, but we must add the entries
6636          now so that we know the final size of the .dynamic section.  */
6637
6638       /* If there are initialization and/or finalization functions to
6639          call then add the corresponding DT_INIT/DT_FINI entries.  */
6640       h = (info->init_function
6641            ? elf_link_hash_lookup (elf_hash_table (info),
6642                                    info->init_function, FALSE,
6643                                    FALSE, FALSE)
6644            : NULL);
6645       if (h != NULL
6646           && (h->ref_regular
6647               || h->def_regular))
6648         {
6649           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
6650             return FALSE;
6651         }
6652       h = (info->fini_function
6653            ? elf_link_hash_lookup (elf_hash_table (info),
6654                                    info->fini_function, FALSE,
6655                                    FALSE, FALSE)
6656            : NULL);
6657       if (h != NULL
6658           && (h->ref_regular
6659               || h->def_regular))
6660         {
6661           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
6662             return FALSE;
6663         }
6664
6665       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
6666       if (s != NULL && s->linker_has_input)
6667         {
6668           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
6669           if (! bfd_link_executable (info))
6670             {
6671               bfd *sub;
6672               asection *o;
6673
6674               for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
6675                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour
6676                     && (o = sub->sections) != NULL
6677                     && o->sec_info_type != SEC_INFO_TYPE_JUST_SYMS)
6678                   for (o = sub->sections; o != NULL; o = o->next)
6679                     if (elf_section_data (o)->this_hdr.sh_type
6680                         == SHT_PREINIT_ARRAY)
6681                       {
6682                         _bfd_error_handler
6683                           (_("%B: .preinit_array section is not allowed in DSO"),
6684                            sub);
6685                         break;
6686                       }
6687
6688               bfd_set_error (bfd_error_nonrepresentable_section);
6689               return FALSE;
6690             }
6691
6692           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6693               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6694             return FALSE;
6695         }
6696       s = bfd_get_section_by_name (output_bfd, ".init_array");
6697       if (s != NULL && s->linker_has_input)
6698         {
6699           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6700               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6701             return FALSE;
6702         }
6703       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6704       if (s != NULL && s->linker_has_input)
6705         {
6706           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6707               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6708             return FALSE;
6709         }
6710
6711       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6712       /* If .dynstr is excluded from the link, we don't want any of
6713          these tags.  Strictly, we should be checking each section
6714          individually;  This quick check covers for the case where
6715          someone does a /DISCARD/ : { *(*) }.  */
6716       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6717         {
6718           bfd_size_type strsize;
6719
6720           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6721           if ((info->emit_hash
6722                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6723               || (info->emit_gnu_hash
6724                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6725               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6726               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6727               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6728               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6729                                               bed->s->sizeof_sym))
6730             return FALSE;
6731         }
6732     }
6733
6734   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6735     return FALSE;
6736
6737   /* The backend must work out the sizes of all the other dynamic
6738      sections.  */
6739   if (dynobj != NULL
6740       && bed->elf_backend_size_dynamic_sections != NULL
6741       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6742     return FALSE;
6743
6744   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6745     {
6746       unsigned long section_sym_count;
6747
6748       if (elf_tdata (output_bfd)->cverdefs)
6749         {
6750           unsigned int crefs = elf_tdata (output_bfd)->cverdefs;
6751
6752           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6753               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, crefs))
6754             return FALSE;
6755         }
6756
6757       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6758         {
6759           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6760             return FALSE;
6761         }
6762       else if (info->flags & DF_BIND_NOW)
6763         {
6764           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6765             return FALSE;
6766         }
6767
6768       if (info->flags_1)
6769         {
6770           if (bfd_link_executable (info))
6771             info->flags_1 &= ~ (DF_1_INITFIRST
6772                                 | DF_1_NODELETE
6773                                 | DF_1_NOOPEN);
6774           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6775             return FALSE;
6776         }
6777
6778       if (elf_tdata (output_bfd)->cverrefs)
6779         {
6780           unsigned int crefs = elf_tdata (output_bfd)->cverrefs;
6781
6782           if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6783               || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6784             return FALSE;
6785         }
6786
6787       if ((elf_tdata (output_bfd)->cverrefs == 0
6788            && elf_tdata (output_bfd)->cverdefs == 0)
6789           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6790                                              &section_sym_count) == 0)
6791         {
6792           asection *s;
6793
6794           s = bfd_get_linker_section (dynobj, ".gnu.version");
6795           s->flags |= SEC_EXCLUDE;
6796         }
6797     }
6798   return TRUE;
6799 }
6800
6801 /* Find the first non-excluded output section.  We'll use its
6802    section symbol for some emitted relocs.  */
6803 void
6804 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6805 {
6806   asection *s;
6807
6808   for (s = output_bfd->sections; s != NULL; s = s->next)
6809     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6810         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6811       {
6812         elf_hash_table (info)->text_index_section = s;
6813         break;
6814       }
6815 }
6816
6817 /* Find two non-excluded output sections, one for code, one for data.
6818    We'll use their section symbols for some emitted relocs.  */
6819 void
6820 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6821 {
6822   asection *s;
6823
6824   /* Data first, since setting text_index_section changes
6825      _bfd_elf_link_omit_section_dynsym.  */
6826   for (s = output_bfd->sections; s != NULL; s = s->next)
6827     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6828         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6829       {
6830         elf_hash_table (info)->data_index_section = s;
6831         break;
6832       }
6833
6834   for (s = output_bfd->sections; s != NULL; s = s->next)
6835     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6836          == (SEC_ALLOC | SEC_READONLY))
6837         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6838       {
6839         elf_hash_table (info)->text_index_section = s;
6840         break;
6841       }
6842
6843   if (elf_hash_table (info)->text_index_section == NULL)
6844     elf_hash_table (info)->text_index_section
6845       = elf_hash_table (info)->data_index_section;
6846 }
6847
6848 bfd_boolean
6849 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6850 {
6851   const struct elf_backend_data *bed;
6852   unsigned long section_sym_count;
6853   bfd_size_type dynsymcount;
6854
6855   if (!is_elf_hash_table (info->hash))
6856     return TRUE;
6857
6858   bed = get_elf_backend_data (output_bfd);
6859   (*bed->elf_backend_init_index_section) (output_bfd, info);
6860
6861   /* Assign dynsym indices.  In a shared library we generate a section
6862      symbol for each output section, which come first.  Next come all
6863      of the back-end allocated local dynamic syms, followed by the rest
6864      of the global symbols.
6865
6866      This is usually not needed for static binaries, however backends
6867      can request to always do it, e.g. the MIPS backend uses dynamic
6868      symbol counts to lay out GOT, which will be produced in the
6869      presence of GOT relocations even in static binaries (holding fixed
6870      data in that case, to satisfy those relocations).  */
6871
6872   if (elf_hash_table (info)->dynamic_sections_created
6873       || bed->always_renumber_dynsyms)
6874     dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6875                                                   &section_sym_count);
6876
6877   if (elf_hash_table (info)->dynamic_sections_created)
6878     {
6879       bfd *dynobj;
6880       asection *s;
6881       unsigned int dtagcount;
6882
6883       dynobj = elf_hash_table (info)->dynobj;
6884
6885       /* Work out the size of the symbol version section.  */
6886       s = bfd_get_linker_section (dynobj, ".gnu.version");
6887       BFD_ASSERT (s != NULL);
6888       if ((s->flags & SEC_EXCLUDE) == 0)
6889         {
6890           s->size = dynsymcount * sizeof (Elf_External_Versym);
6891           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6892           if (s->contents == NULL)
6893             return FALSE;
6894
6895           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6896             return FALSE;
6897         }
6898
6899       /* Set the size of the .dynsym and .hash sections.  We counted
6900          the number of dynamic symbols in elf_link_add_object_symbols.
6901          We will build the contents of .dynsym and .hash when we build
6902          the final symbol table, because until then we do not know the
6903          correct value to give the symbols.  We built the .dynstr
6904          section as we went along in elf_link_add_object_symbols.  */
6905       s = elf_hash_table (info)->dynsym;
6906       BFD_ASSERT (s != NULL);
6907       s->size = dynsymcount * bed->s->sizeof_sym;
6908
6909       s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6910       if (s->contents == NULL)
6911         return FALSE;
6912
6913       /* The first entry in .dynsym is a dummy symbol.  Clear all the
6914          section syms, in case we don't output them all.  */
6915       ++section_sym_count;
6916       memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6917
6918       elf_hash_table (info)->bucketcount = 0;
6919
6920       /* Compute the size of the hashing table.  As a side effect this
6921          computes the hash values for all the names we export.  */
6922       if (info->emit_hash)
6923         {
6924           unsigned long int *hashcodes;
6925           struct hash_codes_info hashinf;
6926           bfd_size_type amt;
6927           unsigned long int nsyms;
6928           size_t bucketcount;
6929           size_t hash_entry_size;
6930
6931           /* Compute the hash values for all exported symbols.  At the same
6932              time store the values in an array so that we could use them for
6933              optimizations.  */
6934           amt = dynsymcount * sizeof (unsigned long int);
6935           hashcodes = (unsigned long int *) bfd_malloc (amt);
6936           if (hashcodes == NULL)
6937             return FALSE;
6938           hashinf.hashcodes = hashcodes;
6939           hashinf.error = FALSE;
6940
6941           /* Put all hash values in HASHCODES.  */
6942           elf_link_hash_traverse (elf_hash_table (info),
6943                                   elf_collect_hash_codes, &hashinf);
6944           if (hashinf.error)
6945             {
6946               free (hashcodes);
6947               return FALSE;
6948             }
6949
6950           nsyms = hashinf.hashcodes - hashcodes;
6951           bucketcount
6952             = compute_bucket_count (info, hashcodes, nsyms, 0);
6953           free (hashcodes);
6954
6955           if (bucketcount == 0 && nsyms > 0)
6956             return FALSE;
6957
6958           elf_hash_table (info)->bucketcount = bucketcount;
6959
6960           s = bfd_get_linker_section (dynobj, ".hash");
6961           BFD_ASSERT (s != NULL);
6962           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6963           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6964           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6965           if (s->contents == NULL)
6966             return FALSE;
6967
6968           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6969           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6970                    s->contents + hash_entry_size);
6971         }
6972
6973       if (info->emit_gnu_hash)
6974         {
6975           size_t i, cnt;
6976           unsigned char *contents;
6977           struct collect_gnu_hash_codes cinfo;
6978           bfd_size_type amt;
6979           size_t bucketcount;
6980
6981           memset (&cinfo, 0, sizeof (cinfo));
6982
6983           /* Compute the hash values for all exported symbols.  At the same
6984              time store the values in an array so that we could use them for
6985              optimizations.  */
6986           amt = dynsymcount * 2 * sizeof (unsigned long int);
6987           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
6988           if (cinfo.hashcodes == NULL)
6989             return FALSE;
6990
6991           cinfo.hashval = cinfo.hashcodes + dynsymcount;
6992           cinfo.min_dynindx = -1;
6993           cinfo.output_bfd = output_bfd;
6994           cinfo.bed = bed;
6995
6996           /* Put all hash values in HASHCODES.  */
6997           elf_link_hash_traverse (elf_hash_table (info),
6998                                   elf_collect_gnu_hash_codes, &cinfo);
6999           if (cinfo.error)
7000             {
7001               free (cinfo.hashcodes);
7002               return FALSE;
7003             }
7004
7005           bucketcount
7006             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
7007
7008           if (bucketcount == 0)
7009             {
7010               free (cinfo.hashcodes);
7011               return FALSE;
7012             }
7013
7014           s = bfd_get_linker_section (dynobj, ".gnu.hash");
7015           BFD_ASSERT (s != NULL);
7016
7017           if (cinfo.nsyms == 0)
7018             {
7019               /* Empty .gnu.hash section is special.  */
7020               BFD_ASSERT (cinfo.min_dynindx == -1);
7021               free (cinfo.hashcodes);
7022               s->size = 5 * 4 + bed->s->arch_size / 8;
7023               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7024               if (contents == NULL)
7025                 return FALSE;
7026               s->contents = contents;
7027               /* 1 empty bucket.  */
7028               bfd_put_32 (output_bfd, 1, contents);
7029               /* SYMIDX above the special symbol 0.  */
7030               bfd_put_32 (output_bfd, 1, contents + 4);
7031               /* Just one word for bitmask.  */
7032               bfd_put_32 (output_bfd, 1, contents + 8);
7033               /* Only hash fn bloom filter.  */
7034               bfd_put_32 (output_bfd, 0, contents + 12);
7035               /* No hashes are valid - empty bitmask.  */
7036               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
7037               /* No hashes in the only bucket.  */
7038               bfd_put_32 (output_bfd, 0,
7039                           contents + 16 + bed->s->arch_size / 8);
7040             }
7041           else
7042             {
7043               unsigned long int maskwords, maskbitslog2, x;
7044               BFD_ASSERT (cinfo.min_dynindx != -1);
7045
7046               x = cinfo.nsyms;
7047               maskbitslog2 = 1;
7048               while ((x >>= 1) != 0)
7049                 ++maskbitslog2;
7050               if (maskbitslog2 < 3)
7051                 maskbitslog2 = 5;
7052               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
7053                 maskbitslog2 = maskbitslog2 + 3;
7054               else
7055                 maskbitslog2 = maskbitslog2 + 2;
7056               if (bed->s->arch_size == 64)
7057                 {
7058                   if (maskbitslog2 == 5)
7059                     maskbitslog2 = 6;
7060                   cinfo.shift1 = 6;
7061                 }
7062               else
7063                 cinfo.shift1 = 5;
7064               cinfo.mask = (1 << cinfo.shift1) - 1;
7065               cinfo.shift2 = maskbitslog2;
7066               cinfo.maskbits = 1 << maskbitslog2;
7067               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
7068               amt = bucketcount * sizeof (unsigned long int) * 2;
7069               amt += maskwords * sizeof (bfd_vma);
7070               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
7071               if (cinfo.bitmask == NULL)
7072                 {
7073                   free (cinfo.hashcodes);
7074                   return FALSE;
7075                 }
7076
7077               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
7078               cinfo.indx = cinfo.counts + bucketcount;
7079               cinfo.symindx = dynsymcount - cinfo.nsyms;
7080               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
7081
7082               /* Determine how often each hash bucket is used.  */
7083               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
7084               for (i = 0; i < cinfo.nsyms; ++i)
7085                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
7086
7087               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
7088                 if (cinfo.counts[i] != 0)
7089                   {
7090                     cinfo.indx[i] = cnt;
7091                     cnt += cinfo.counts[i];
7092                   }
7093               BFD_ASSERT (cnt == dynsymcount);
7094               cinfo.bucketcount = bucketcount;
7095               cinfo.local_indx = cinfo.min_dynindx;
7096
7097               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
7098               s->size += cinfo.maskbits / 8;
7099               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7100               if (contents == NULL)
7101                 {
7102                   free (cinfo.bitmask);
7103                   free (cinfo.hashcodes);
7104                   return FALSE;
7105                 }
7106
7107               s->contents = contents;
7108               bfd_put_32 (output_bfd, bucketcount, contents);
7109               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
7110               bfd_put_32 (output_bfd, maskwords, contents + 8);
7111               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
7112               contents += 16 + cinfo.maskbits / 8;
7113
7114               for (i = 0; i < bucketcount; ++i)
7115                 {
7116                   if (cinfo.counts[i] == 0)
7117                     bfd_put_32 (output_bfd, 0, contents);
7118                   else
7119                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
7120                   contents += 4;
7121                 }
7122
7123               cinfo.contents = contents;
7124
7125               /* Renumber dynamic symbols, populate .gnu.hash section.  */
7126               elf_link_hash_traverse (elf_hash_table (info),
7127                                       elf_renumber_gnu_hash_syms, &cinfo);
7128
7129               contents = s->contents + 16;
7130               for (i = 0; i < maskwords; ++i)
7131                 {
7132                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
7133                            contents);
7134                   contents += bed->s->arch_size / 8;
7135                 }
7136
7137               free (cinfo.bitmask);
7138               free (cinfo.hashcodes);
7139             }
7140         }
7141
7142       s = bfd_get_linker_section (dynobj, ".dynstr");
7143       BFD_ASSERT (s != NULL);
7144
7145       elf_finalize_dynstr (output_bfd, info);
7146
7147       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
7148
7149       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
7150         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
7151           return FALSE;
7152     }
7153
7154   return TRUE;
7155 }
7156 \f
7157 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
7158
7159 static void
7160 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
7161                             asection *sec)
7162 {
7163   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
7164   sec->sec_info_type = SEC_INFO_TYPE_NONE;
7165 }
7166
7167 /* Finish SHF_MERGE section merging.  */
7168
7169 bfd_boolean
7170 _bfd_elf_merge_sections (bfd *obfd, struct bfd_link_info *info)
7171 {
7172   bfd *ibfd;
7173   asection *sec;
7174
7175   if (!is_elf_hash_table (info->hash))
7176     return FALSE;
7177
7178   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
7179     if ((ibfd->flags & DYNAMIC) == 0
7180         && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
7181         && (elf_elfheader (ibfd)->e_ident[EI_CLASS]
7182             == get_elf_backend_data (obfd)->s->elfclass))
7183       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
7184         if ((sec->flags & SEC_MERGE) != 0
7185             && !bfd_is_abs_section (sec->output_section))
7186           {
7187             struct bfd_elf_section_data *secdata;
7188
7189             secdata = elf_section_data (sec);
7190             if (! _bfd_add_merge_section (obfd,
7191                                           &elf_hash_table (info)->merge_info,
7192                                           sec, &secdata->sec_info))
7193               return FALSE;
7194             else if (secdata->sec_info)
7195               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
7196           }
7197
7198   if (elf_hash_table (info)->merge_info != NULL)
7199     _bfd_merge_sections (obfd, info, elf_hash_table (info)->merge_info,
7200                          merge_sections_remove_hook);
7201   return TRUE;
7202 }
7203
7204 /* Create an entry in an ELF linker hash table.  */
7205
7206 struct bfd_hash_entry *
7207 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
7208                             struct bfd_hash_table *table,
7209                             const char *string)
7210 {
7211   /* Allocate the structure if it has not already been allocated by a
7212      subclass.  */
7213   if (entry == NULL)
7214     {
7215       entry = (struct bfd_hash_entry *)
7216         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
7217       if (entry == NULL)
7218         return entry;
7219     }
7220
7221   /* Call the allocation method of the superclass.  */
7222   entry = _bfd_link_hash_newfunc (entry, table, string);
7223   if (entry != NULL)
7224     {
7225       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
7226       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
7227
7228       /* Set local fields.  */
7229       ret->indx = -1;
7230       ret->dynindx = -1;
7231       ret->got = htab->init_got_refcount;
7232       ret->plt = htab->init_plt_refcount;
7233       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
7234                               - offsetof (struct elf_link_hash_entry, size)));
7235       /* Assume that we have been called by a non-ELF symbol reader.
7236          This flag is then reset by the code which reads an ELF input
7237          file.  This ensures that a symbol created by a non-ELF symbol
7238          reader will have the flag set correctly.  */
7239       ret->non_elf = 1;
7240     }
7241
7242   return entry;
7243 }
7244
7245 /* Copy data from an indirect symbol to its direct symbol, hiding the
7246    old indirect symbol.  Also used for copying flags to a weakdef.  */
7247
7248 void
7249 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
7250                                   struct elf_link_hash_entry *dir,
7251                                   struct elf_link_hash_entry *ind)
7252 {
7253   struct elf_link_hash_table *htab;
7254
7255   /* Copy down any references that we may have already seen to the
7256      symbol which just became indirect.  */
7257
7258   if (dir->versioned != versioned_hidden)
7259     dir->ref_dynamic |= ind->ref_dynamic;
7260   dir->ref_regular |= ind->ref_regular;
7261   dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
7262   dir->non_got_ref |= ind->non_got_ref;
7263   dir->needs_plt |= ind->needs_plt;
7264   dir->pointer_equality_needed |= ind->pointer_equality_needed;
7265
7266   if (ind->root.type != bfd_link_hash_indirect)
7267     return;
7268
7269   /* Copy over the global and procedure linkage table refcount entries.
7270      These may have been already set up by a check_relocs routine.  */
7271   htab = elf_hash_table (info);
7272   if (ind->got.refcount > htab->init_got_refcount.refcount)
7273     {
7274       if (dir->got.refcount < 0)
7275         dir->got.refcount = 0;
7276       dir->got.refcount += ind->got.refcount;
7277       ind->got.refcount = htab->init_got_refcount.refcount;
7278     }
7279
7280   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
7281     {
7282       if (dir->plt.refcount < 0)
7283         dir->plt.refcount = 0;
7284       dir->plt.refcount += ind->plt.refcount;
7285       ind->plt.refcount = htab->init_plt_refcount.refcount;
7286     }
7287
7288   if (ind->dynindx != -1)
7289     {
7290       if (dir->dynindx != -1)
7291         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
7292       dir->dynindx = ind->dynindx;
7293       dir->dynstr_index = ind->dynstr_index;
7294       ind->dynindx = -1;
7295       ind->dynstr_index = 0;
7296     }
7297 }
7298
7299 void
7300 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
7301                                 struct elf_link_hash_entry *h,
7302                                 bfd_boolean force_local)
7303 {
7304   /* STT_GNU_IFUNC symbol must go through PLT.  */
7305   if (h->type != STT_GNU_IFUNC)
7306     {
7307       h->plt = elf_hash_table (info)->init_plt_offset;
7308       h->needs_plt = 0;
7309     }
7310   if (force_local)
7311     {
7312       h->forced_local = 1;
7313       if (h->dynindx != -1)
7314         {
7315           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
7316                                   h->dynstr_index);
7317           h->dynindx = -1;
7318           h->dynstr_index = 0;
7319         }
7320     }
7321 }
7322
7323 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
7324    caller.  */
7325
7326 bfd_boolean
7327 _bfd_elf_link_hash_table_init
7328   (struct elf_link_hash_table *table,
7329    bfd *abfd,
7330    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
7331                                       struct bfd_hash_table *,
7332                                       const char *),
7333    unsigned int entsize,
7334    enum elf_target_id target_id)
7335 {
7336   bfd_boolean ret;
7337   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
7338
7339   table->init_got_refcount.refcount = can_refcount - 1;
7340   table->init_plt_refcount.refcount = can_refcount - 1;
7341   table->init_got_offset.offset = -(bfd_vma) 1;
7342   table->init_plt_offset.offset = -(bfd_vma) 1;
7343   /* The first dynamic symbol is a dummy.  */
7344   table->dynsymcount = 1;
7345
7346   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
7347
7348   table->root.type = bfd_link_elf_hash_table;
7349   table->hash_table_id = target_id;
7350
7351   return ret;
7352 }
7353
7354 /* Create an ELF linker hash table.  */
7355
7356 struct bfd_link_hash_table *
7357 _bfd_elf_link_hash_table_create (bfd *abfd)
7358 {
7359   struct elf_link_hash_table *ret;
7360   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7361
7362   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7363   if (ret == NULL)
7364     return NULL;
7365
7366   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7367                                        sizeof (struct elf_link_hash_entry),
7368                                        GENERIC_ELF_DATA))
7369     {
7370       free (ret);
7371       return NULL;
7372     }
7373   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7374
7375   return &ret->root;
7376 }
7377
7378 /* Destroy an ELF linker hash table.  */
7379
7380 void
7381 _bfd_elf_link_hash_table_free (bfd *obfd)
7382 {
7383   struct elf_link_hash_table *htab;
7384
7385   htab = (struct elf_link_hash_table *) obfd->link.hash;
7386   if (htab->dynstr != NULL)
7387     _bfd_elf_strtab_free (htab->dynstr);
7388   _bfd_merge_sections_free (htab->merge_info);
7389   _bfd_generic_link_hash_table_free (obfd);
7390 }
7391
7392 /* This is a hook for the ELF emulation code in the generic linker to
7393    tell the backend linker what file name to use for the DT_NEEDED
7394    entry for a dynamic object.  */
7395
7396 void
7397 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7398 {
7399   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7400       && bfd_get_format (abfd) == bfd_object)
7401     elf_dt_name (abfd) = name;
7402 }
7403
7404 int
7405 bfd_elf_get_dyn_lib_class (bfd *abfd)
7406 {
7407   int lib_class;
7408   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7409       && bfd_get_format (abfd) == bfd_object)
7410     lib_class = elf_dyn_lib_class (abfd);
7411   else
7412     lib_class = 0;
7413   return lib_class;
7414 }
7415
7416 void
7417 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7418 {
7419   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7420       && bfd_get_format (abfd) == bfd_object)
7421     elf_dyn_lib_class (abfd) = lib_class;
7422 }
7423
7424 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7425    the linker ELF emulation code.  */
7426
7427 struct bfd_link_needed_list *
7428 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7429                          struct bfd_link_info *info)
7430 {
7431   if (! is_elf_hash_table (info->hash))
7432     return NULL;
7433   return elf_hash_table (info)->needed;
7434 }
7435
7436 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7437    hook for the linker ELF emulation code.  */
7438
7439 struct bfd_link_needed_list *
7440 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7441                           struct bfd_link_info *info)
7442 {
7443   if (! is_elf_hash_table (info->hash))
7444     return NULL;
7445   return elf_hash_table (info)->runpath;
7446 }
7447
7448 /* Get the name actually used for a dynamic object for a link.  This
7449    is the SONAME entry if there is one.  Otherwise, it is the string
7450    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7451
7452 const char *
7453 bfd_elf_get_dt_soname (bfd *abfd)
7454 {
7455   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7456       && bfd_get_format (abfd) == bfd_object)
7457     return elf_dt_name (abfd);
7458   return NULL;
7459 }
7460
7461 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7462    the ELF linker emulation code.  */
7463
7464 bfd_boolean
7465 bfd_elf_get_bfd_needed_list (bfd *abfd,
7466                              struct bfd_link_needed_list **pneeded)
7467 {
7468   asection *s;
7469   bfd_byte *dynbuf = NULL;
7470   unsigned int elfsec;
7471   unsigned long shlink;
7472   bfd_byte *extdyn, *extdynend;
7473   size_t extdynsize;
7474   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7475
7476   *pneeded = NULL;
7477
7478   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7479       || bfd_get_format (abfd) != bfd_object)
7480     return TRUE;
7481
7482   s = bfd_get_section_by_name (abfd, ".dynamic");
7483   if (s == NULL || s->size == 0)
7484     return TRUE;
7485
7486   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7487     goto error_return;
7488
7489   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7490   if (elfsec == SHN_BAD)
7491     goto error_return;
7492
7493   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7494
7495   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7496   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7497
7498   extdyn = dynbuf;
7499   extdynend = extdyn + s->size;
7500   for (; extdyn < extdynend; extdyn += extdynsize)
7501     {
7502       Elf_Internal_Dyn dyn;
7503
7504       (*swap_dyn_in) (abfd, extdyn, &dyn);
7505
7506       if (dyn.d_tag == DT_NULL)
7507         break;
7508
7509       if (dyn.d_tag == DT_NEEDED)
7510         {
7511           const char *string;
7512           struct bfd_link_needed_list *l;
7513           unsigned int tagv = dyn.d_un.d_val;
7514           bfd_size_type amt;
7515
7516           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7517           if (string == NULL)
7518             goto error_return;
7519
7520           amt = sizeof *l;
7521           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7522           if (l == NULL)
7523             goto error_return;
7524
7525           l->by = abfd;
7526           l->name = string;
7527           l->next = *pneeded;
7528           *pneeded = l;
7529         }
7530     }
7531
7532   free (dynbuf);
7533
7534   return TRUE;
7535
7536  error_return:
7537   if (dynbuf != NULL)
7538     free (dynbuf);
7539   return FALSE;
7540 }
7541
7542 struct elf_symbuf_symbol
7543 {
7544   unsigned long st_name;        /* Symbol name, index in string tbl */
7545   unsigned char st_info;        /* Type and binding attributes */
7546   unsigned char st_other;       /* Visibilty, and target specific */
7547 };
7548
7549 struct elf_symbuf_head
7550 {
7551   struct elf_symbuf_symbol *ssym;
7552   size_t count;
7553   unsigned int st_shndx;
7554 };
7555
7556 struct elf_symbol
7557 {
7558   union
7559     {
7560       Elf_Internal_Sym *isym;
7561       struct elf_symbuf_symbol *ssym;
7562     } u;
7563   const char *name;
7564 };
7565
7566 /* Sort references to symbols by ascending section number.  */
7567
7568 static int
7569 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7570 {
7571   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7572   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7573
7574   return s1->st_shndx - s2->st_shndx;
7575 }
7576
7577 static int
7578 elf_sym_name_compare (const void *arg1, const void *arg2)
7579 {
7580   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7581   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7582   return strcmp (s1->name, s2->name);
7583 }
7584
7585 static struct elf_symbuf_head *
7586 elf_create_symbuf (size_t symcount, Elf_Internal_Sym *isymbuf)
7587 {
7588   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7589   struct elf_symbuf_symbol *ssym;
7590   struct elf_symbuf_head *ssymbuf, *ssymhead;
7591   size_t i, shndx_count, total_size;
7592
7593   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7594   if (indbuf == NULL)
7595     return NULL;
7596
7597   for (ind = indbuf, i = 0; i < symcount; i++)
7598     if (isymbuf[i].st_shndx != SHN_UNDEF)
7599       *ind++ = &isymbuf[i];
7600   indbufend = ind;
7601
7602   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7603          elf_sort_elf_symbol);
7604
7605   shndx_count = 0;
7606   if (indbufend > indbuf)
7607     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7608       if (ind[0]->st_shndx != ind[1]->st_shndx)
7609         shndx_count++;
7610
7611   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7612                 + (indbufend - indbuf) * sizeof (*ssym));
7613   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7614   if (ssymbuf == NULL)
7615     {
7616       free (indbuf);
7617       return NULL;
7618     }
7619
7620   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7621   ssymbuf->ssym = NULL;
7622   ssymbuf->count = shndx_count;
7623   ssymbuf->st_shndx = 0;
7624   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7625     {
7626       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7627         {
7628           ssymhead++;
7629           ssymhead->ssym = ssym;
7630           ssymhead->count = 0;
7631           ssymhead->st_shndx = (*ind)->st_shndx;
7632         }
7633       ssym->st_name = (*ind)->st_name;
7634       ssym->st_info = (*ind)->st_info;
7635       ssym->st_other = (*ind)->st_other;
7636       ssymhead->count++;
7637     }
7638   BFD_ASSERT ((size_t) (ssymhead - ssymbuf) == shndx_count
7639               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7640                   == total_size));
7641
7642   free (indbuf);
7643   return ssymbuf;
7644 }
7645
7646 /* Check if 2 sections define the same set of local and global
7647    symbols.  */
7648
7649 static bfd_boolean
7650 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7651                                    struct bfd_link_info *info)
7652 {
7653   bfd *bfd1, *bfd2;
7654   const struct elf_backend_data *bed1, *bed2;
7655   Elf_Internal_Shdr *hdr1, *hdr2;
7656   size_t symcount1, symcount2;
7657   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7658   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7659   Elf_Internal_Sym *isym, *isymend;
7660   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7661   size_t count1, count2, i;
7662   unsigned int shndx1, shndx2;
7663   bfd_boolean result;
7664
7665   bfd1 = sec1->owner;
7666   bfd2 = sec2->owner;
7667
7668   /* Both sections have to be in ELF.  */
7669   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7670       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7671     return FALSE;
7672
7673   if (elf_section_type (sec1) != elf_section_type (sec2))
7674     return FALSE;
7675
7676   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7677   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7678   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7679     return FALSE;
7680
7681   bed1 = get_elf_backend_data (bfd1);
7682   bed2 = get_elf_backend_data (bfd2);
7683   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7684   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7685   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7686   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7687
7688   if (symcount1 == 0 || symcount2 == 0)
7689     return FALSE;
7690
7691   result = FALSE;
7692   isymbuf1 = NULL;
7693   isymbuf2 = NULL;
7694   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7695   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7696
7697   if (ssymbuf1 == NULL)
7698     {
7699       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7700                                        NULL, NULL, NULL);
7701       if (isymbuf1 == NULL)
7702         goto done;
7703
7704       if (!info->reduce_memory_overheads)
7705         elf_tdata (bfd1)->symbuf = ssymbuf1
7706           = elf_create_symbuf (symcount1, isymbuf1);
7707     }
7708
7709   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7710     {
7711       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7712                                        NULL, NULL, NULL);
7713       if (isymbuf2 == NULL)
7714         goto done;
7715
7716       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7717         elf_tdata (bfd2)->symbuf = ssymbuf2
7718           = elf_create_symbuf (symcount2, isymbuf2);
7719     }
7720
7721   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7722     {
7723       /* Optimized faster version.  */
7724       size_t lo, hi, mid;
7725       struct elf_symbol *symp;
7726       struct elf_symbuf_symbol *ssym, *ssymend;
7727
7728       lo = 0;
7729       hi = ssymbuf1->count;
7730       ssymbuf1++;
7731       count1 = 0;
7732       while (lo < hi)
7733         {
7734           mid = (lo + hi) / 2;
7735           if (shndx1 < ssymbuf1[mid].st_shndx)
7736             hi = mid;
7737           else if (shndx1 > ssymbuf1[mid].st_shndx)
7738             lo = mid + 1;
7739           else
7740             {
7741               count1 = ssymbuf1[mid].count;
7742               ssymbuf1 += mid;
7743               break;
7744             }
7745         }
7746
7747       lo = 0;
7748       hi = ssymbuf2->count;
7749       ssymbuf2++;
7750       count2 = 0;
7751       while (lo < hi)
7752         {
7753           mid = (lo + hi) / 2;
7754           if (shndx2 < ssymbuf2[mid].st_shndx)
7755             hi = mid;
7756           else if (shndx2 > ssymbuf2[mid].st_shndx)
7757             lo = mid + 1;
7758           else
7759             {
7760               count2 = ssymbuf2[mid].count;
7761               ssymbuf2 += mid;
7762               break;
7763             }
7764         }
7765
7766       if (count1 == 0 || count2 == 0 || count1 != count2)
7767         goto done;
7768
7769       symtable1
7770         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
7771       symtable2
7772         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
7773       if (symtable1 == NULL || symtable2 == NULL)
7774         goto done;
7775
7776       symp = symtable1;
7777       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7778            ssym < ssymend; ssym++, symp++)
7779         {
7780           symp->u.ssym = ssym;
7781           symp->name = bfd_elf_string_from_elf_section (bfd1,
7782                                                         hdr1->sh_link,
7783                                                         ssym->st_name);
7784         }
7785
7786       symp = symtable2;
7787       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7788            ssym < ssymend; ssym++, symp++)
7789         {
7790           symp->u.ssym = ssym;
7791           symp->name = bfd_elf_string_from_elf_section (bfd2,
7792                                                         hdr2->sh_link,
7793                                                         ssym->st_name);
7794         }
7795
7796       /* Sort symbol by name.  */
7797       qsort (symtable1, count1, sizeof (struct elf_symbol),
7798              elf_sym_name_compare);
7799       qsort (symtable2, count1, sizeof (struct elf_symbol),
7800              elf_sym_name_compare);
7801
7802       for (i = 0; i < count1; i++)
7803         /* Two symbols must have the same binding, type and name.  */
7804         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7805             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7806             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7807           goto done;
7808
7809       result = TRUE;
7810       goto done;
7811     }
7812
7813   symtable1 = (struct elf_symbol *)
7814       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7815   symtable2 = (struct elf_symbol *)
7816       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7817   if (symtable1 == NULL || symtable2 == NULL)
7818     goto done;
7819
7820   /* Count definitions in the section.  */
7821   count1 = 0;
7822   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7823     if (isym->st_shndx == shndx1)
7824       symtable1[count1++].u.isym = isym;
7825
7826   count2 = 0;
7827   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7828     if (isym->st_shndx == shndx2)
7829       symtable2[count2++].u.isym = isym;
7830
7831   if (count1 == 0 || count2 == 0 || count1 != count2)
7832     goto done;
7833
7834   for (i = 0; i < count1; i++)
7835     symtable1[i].name
7836       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7837                                          symtable1[i].u.isym->st_name);
7838
7839   for (i = 0; i < count2; i++)
7840     symtable2[i].name
7841       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7842                                          symtable2[i].u.isym->st_name);
7843
7844   /* Sort symbol by name.  */
7845   qsort (symtable1, count1, sizeof (struct elf_symbol),
7846          elf_sym_name_compare);
7847   qsort (symtable2, count1, sizeof (struct elf_symbol),
7848          elf_sym_name_compare);
7849
7850   for (i = 0; i < count1; i++)
7851     /* Two symbols must have the same binding, type and name.  */
7852     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7853         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7854         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7855       goto done;
7856
7857   result = TRUE;
7858
7859 done:
7860   if (symtable1)
7861     free (symtable1);
7862   if (symtable2)
7863     free (symtable2);
7864   if (isymbuf1)
7865     free (isymbuf1);
7866   if (isymbuf2)
7867     free (isymbuf2);
7868
7869   return result;
7870 }
7871
7872 /* Return TRUE if 2 section types are compatible.  */
7873
7874 bfd_boolean
7875 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7876                                  bfd *bbfd, const asection *bsec)
7877 {
7878   if (asec == NULL
7879       || bsec == NULL
7880       || abfd->xvec->flavour != bfd_target_elf_flavour
7881       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7882     return TRUE;
7883
7884   return elf_section_type (asec) == elf_section_type (bsec);
7885 }
7886 \f
7887 /* Final phase of ELF linker.  */
7888
7889 /* A structure we use to avoid passing large numbers of arguments.  */
7890
7891 struct elf_final_link_info
7892 {
7893   /* General link information.  */
7894   struct bfd_link_info *info;
7895   /* Output BFD.  */
7896   bfd *output_bfd;
7897   /* Symbol string table.  */
7898   struct elf_strtab_hash *symstrtab;
7899   /* .hash section.  */
7900   asection *hash_sec;
7901   /* symbol version section (.gnu.version).  */
7902   asection *symver_sec;
7903   /* Buffer large enough to hold contents of any section.  */
7904   bfd_byte *contents;
7905   /* Buffer large enough to hold external relocs of any section.  */
7906   void *external_relocs;
7907   /* Buffer large enough to hold internal relocs of any section.  */
7908   Elf_Internal_Rela *internal_relocs;
7909   /* Buffer large enough to hold external local symbols of any input
7910      BFD.  */
7911   bfd_byte *external_syms;
7912   /* And a buffer for symbol section indices.  */
7913   Elf_External_Sym_Shndx *locsym_shndx;
7914   /* Buffer large enough to hold internal local symbols of any input
7915      BFD.  */
7916   Elf_Internal_Sym *internal_syms;
7917   /* Array large enough to hold a symbol index for each local symbol
7918      of any input BFD.  */
7919   long *indices;
7920   /* Array large enough to hold a section pointer for each local
7921      symbol of any input BFD.  */
7922   asection **sections;
7923   /* Buffer for SHT_SYMTAB_SHNDX section.  */
7924   Elf_External_Sym_Shndx *symshndxbuf;
7925   /* Number of STT_FILE syms seen.  */
7926   size_t filesym_count;
7927 };
7928
7929 /* This struct is used to pass information to elf_link_output_extsym.  */
7930
7931 struct elf_outext_info
7932 {
7933   bfd_boolean failed;
7934   bfd_boolean localsyms;
7935   bfd_boolean file_sym_done;
7936   struct elf_final_link_info *flinfo;
7937 };
7938
7939
7940 /* Support for evaluating a complex relocation.
7941
7942    Complex relocations are generalized, self-describing relocations.  The
7943    implementation of them consists of two parts: complex symbols, and the
7944    relocations themselves.
7945
7946    The relocations are use a reserved elf-wide relocation type code (R_RELC
7947    external / BFD_RELOC_RELC internal) and an encoding of relocation field
7948    information (start bit, end bit, word width, etc) into the addend.  This
7949    information is extracted from CGEN-generated operand tables within gas.
7950
7951    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
7952    internal) representing prefix-notation expressions, including but not
7953    limited to those sorts of expressions normally encoded as addends in the
7954    addend field.  The symbol mangling format is:
7955
7956    <node> := <literal>
7957           |  <unary-operator> ':' <node>
7958           |  <binary-operator> ':' <node> ':' <node>
7959           ;
7960
7961    <literal> := 's' <digits=N> ':' <N character symbol name>
7962              |  'S' <digits=N> ':' <N character section name>
7963              |  '#' <hexdigits>
7964              ;
7965
7966    <binary-operator> := as in C
7967    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
7968
7969 static void
7970 set_symbol_value (bfd *bfd_with_globals,
7971                   Elf_Internal_Sym *isymbuf,
7972                   size_t locsymcount,
7973                   size_t symidx,
7974                   bfd_vma val)
7975 {
7976   struct elf_link_hash_entry **sym_hashes;
7977   struct elf_link_hash_entry *h;
7978   size_t extsymoff = locsymcount;
7979
7980   if (symidx < locsymcount)
7981     {
7982       Elf_Internal_Sym *sym;
7983
7984       sym = isymbuf + symidx;
7985       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
7986         {
7987           /* It is a local symbol: move it to the
7988              "absolute" section and give it a value.  */
7989           sym->st_shndx = SHN_ABS;
7990           sym->st_value = val;
7991           return;
7992         }
7993       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
7994       extsymoff = 0;
7995     }
7996
7997   /* It is a global symbol: set its link type
7998      to "defined" and give it a value.  */
7999
8000   sym_hashes = elf_sym_hashes (bfd_with_globals);
8001   h = sym_hashes [symidx - extsymoff];
8002   while (h->root.type == bfd_link_hash_indirect
8003          || h->root.type == bfd_link_hash_warning)
8004     h = (struct elf_link_hash_entry *) h->root.u.i.link;
8005   h->root.type = bfd_link_hash_defined;
8006   h->root.u.def.value = val;
8007   h->root.u.def.section = bfd_abs_section_ptr;
8008 }
8009
8010 static bfd_boolean
8011 resolve_symbol (const char *name,
8012                 bfd *input_bfd,
8013                 struct elf_final_link_info *flinfo,
8014                 bfd_vma *result,
8015                 Elf_Internal_Sym *isymbuf,
8016                 size_t locsymcount)
8017 {
8018   Elf_Internal_Sym *sym;
8019   struct bfd_link_hash_entry *global_entry;
8020   const char *candidate = NULL;
8021   Elf_Internal_Shdr *symtab_hdr;
8022   size_t i;
8023
8024   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
8025
8026   for (i = 0; i < locsymcount; ++ i)
8027     {
8028       sym = isymbuf + i;
8029
8030       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
8031         continue;
8032
8033       candidate = bfd_elf_string_from_elf_section (input_bfd,
8034                                                    symtab_hdr->sh_link,
8035                                                    sym->st_name);
8036 #ifdef DEBUG
8037       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
8038               name, candidate, (unsigned long) sym->st_value);
8039 #endif
8040       if (candidate && strcmp (candidate, name) == 0)
8041         {
8042           asection *sec = flinfo->sections [i];
8043
8044           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
8045           *result += sec->output_offset + sec->output_section->vma;
8046 #ifdef DEBUG
8047           printf ("Found symbol with value %8.8lx\n",
8048                   (unsigned long) *result);
8049 #endif
8050           return TRUE;
8051         }
8052     }
8053
8054   /* Hmm, haven't found it yet. perhaps it is a global.  */
8055   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
8056                                        FALSE, FALSE, TRUE);
8057   if (!global_entry)
8058     return FALSE;
8059
8060   if (global_entry->type == bfd_link_hash_defined
8061       || global_entry->type == bfd_link_hash_defweak)
8062     {
8063       *result = (global_entry->u.def.value
8064                  + global_entry->u.def.section->output_section->vma
8065                  + global_entry->u.def.section->output_offset);
8066 #ifdef DEBUG
8067       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
8068               global_entry->root.string, (unsigned long) *result);
8069 #endif
8070       return TRUE;
8071     }
8072
8073   return FALSE;
8074 }
8075
8076 /* Looks up NAME in SECTIONS.  If found sets RESULT to NAME's address (in
8077    bytes) and returns TRUE, otherwise returns FALSE.  Accepts pseudo-section
8078    names like "foo.end" which is the end address of section "foo".  */
8079    
8080 static bfd_boolean
8081 resolve_section (const char *name,
8082                  asection *sections,
8083                  bfd_vma *result,
8084                  bfd * abfd)
8085 {
8086   asection *curr;
8087   unsigned int len;
8088
8089   for (curr = sections; curr; curr = curr->next)
8090     if (strcmp (curr->name, name) == 0)
8091       {
8092         *result = curr->vma;
8093         return TRUE;
8094       }
8095
8096   /* Hmm. still haven't found it. try pseudo-section names.  */
8097   /* FIXME: This could be coded more efficiently...  */
8098   for (curr = sections; curr; curr = curr->next)
8099     {
8100       len = strlen (curr->name);
8101       if (len > strlen (name))
8102         continue;
8103
8104       if (strncmp (curr->name, name, len) == 0)
8105         {
8106           if (strncmp (".end", name + len, 4) == 0)
8107             {
8108               *result = curr->vma + curr->size / bfd_octets_per_byte (abfd);
8109               return TRUE;
8110             }
8111
8112           /* Insert more pseudo-section names here, if you like.  */
8113         }
8114     }
8115
8116   return FALSE;
8117 }
8118
8119 static void
8120 undefined_reference (const char *reftype, const char *name)
8121 {
8122   /* xgettext:c-format */
8123   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
8124                       reftype, name);
8125 }
8126
8127 static bfd_boolean
8128 eval_symbol (bfd_vma *result,
8129              const char **symp,
8130              bfd *input_bfd,
8131              struct elf_final_link_info *flinfo,
8132              bfd_vma dot,
8133              Elf_Internal_Sym *isymbuf,
8134              size_t locsymcount,
8135              int signed_p)
8136 {
8137   size_t len;
8138   size_t symlen;
8139   bfd_vma a;
8140   bfd_vma b;
8141   char symbuf[4096];
8142   const char *sym = *symp;
8143   const char *symend;
8144   bfd_boolean symbol_is_section = FALSE;
8145
8146   len = strlen (sym);
8147   symend = sym + len;
8148
8149   if (len < 1 || len > sizeof (symbuf))
8150     {
8151       bfd_set_error (bfd_error_invalid_operation);
8152       return FALSE;
8153     }
8154
8155   switch (* sym)
8156     {
8157     case '.':
8158       *result = dot;
8159       *symp = sym + 1;
8160       return TRUE;
8161
8162     case '#':
8163       ++sym;
8164       *result = strtoul (sym, (char **) symp, 16);
8165       return TRUE;
8166
8167     case 'S':
8168       symbol_is_section = TRUE;
8169       /* Fall through.  */
8170     case 's':
8171       ++sym;
8172       symlen = strtol (sym, (char **) symp, 10);
8173       sym = *symp + 1; /* Skip the trailing ':'.  */
8174
8175       if (symend < sym || symlen + 1 > sizeof (symbuf))
8176         {
8177           bfd_set_error (bfd_error_invalid_operation);
8178           return FALSE;
8179         }
8180
8181       memcpy (symbuf, sym, symlen);
8182       symbuf[symlen] = '\0';
8183       *symp = sym + symlen;
8184
8185       /* Is it always possible, with complex symbols, that gas "mis-guessed"
8186          the symbol as a section, or vice-versa. so we're pretty liberal in our
8187          interpretation here; section means "try section first", not "must be a
8188          section", and likewise with symbol.  */
8189
8190       if (symbol_is_section)
8191         {
8192           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result, input_bfd)
8193               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
8194                                   isymbuf, locsymcount))
8195             {
8196               undefined_reference ("section", symbuf);
8197               return FALSE;
8198             }
8199         }
8200       else
8201         {
8202           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
8203                                isymbuf, locsymcount)
8204               && !resolve_section (symbuf, flinfo->output_bfd->sections,
8205                                    result, input_bfd))
8206             {
8207               undefined_reference ("symbol", symbuf);
8208               return FALSE;
8209             }
8210         }
8211
8212       return TRUE;
8213
8214       /* All that remains are operators.  */
8215
8216 #define UNARY_OP(op)                                            \
8217   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8218     {                                                           \
8219       sym += strlen (#op);                                      \
8220       if (*sym == ':')                                          \
8221         ++sym;                                                  \
8222       *symp = sym;                                              \
8223       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8224                         isymbuf, locsymcount, signed_p))        \
8225         return FALSE;                                           \
8226       if (signed_p)                                             \
8227         *result = op ((bfd_signed_vma) a);                      \
8228       else                                                      \
8229         *result = op a;                                         \
8230       return TRUE;                                              \
8231     }
8232
8233 #define BINARY_OP(op)                                           \
8234   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8235     {                                                           \
8236       sym += strlen (#op);                                      \
8237       if (*sym == ':')                                          \
8238         ++sym;                                                  \
8239       *symp = sym;                                              \
8240       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8241                         isymbuf, locsymcount, signed_p))        \
8242         return FALSE;                                           \
8243       ++*symp;                                                  \
8244       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
8245                         isymbuf, locsymcount, signed_p))        \
8246         return FALSE;                                           \
8247       if (signed_p)                                             \
8248         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
8249       else                                                      \
8250         *result = a op b;                                       \
8251       return TRUE;                                              \
8252     }
8253
8254     default:
8255       UNARY_OP  (0-);
8256       BINARY_OP (<<);
8257       BINARY_OP (>>);
8258       BINARY_OP (==);
8259       BINARY_OP (!=);
8260       BINARY_OP (<=);
8261       BINARY_OP (>=);
8262       BINARY_OP (&&);
8263       BINARY_OP (||);
8264       UNARY_OP  (~);
8265       UNARY_OP  (!);
8266       BINARY_OP (*);
8267       BINARY_OP (/);
8268       BINARY_OP (%);
8269       BINARY_OP (^);
8270       BINARY_OP (|);
8271       BINARY_OP (&);
8272       BINARY_OP (+);
8273       BINARY_OP (-);
8274       BINARY_OP (<);
8275       BINARY_OP (>);
8276 #undef UNARY_OP
8277 #undef BINARY_OP
8278       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
8279       bfd_set_error (bfd_error_invalid_operation);
8280       return FALSE;
8281     }
8282 }
8283
8284 static void
8285 put_value (bfd_vma size,
8286            unsigned long chunksz,
8287            bfd *input_bfd,
8288            bfd_vma x,
8289            bfd_byte *location)
8290 {
8291   location += (size - chunksz);
8292
8293   for (; size; size -= chunksz, location -= chunksz)
8294     {
8295       switch (chunksz)
8296         {
8297         case 1:
8298           bfd_put_8 (input_bfd, x, location);
8299           x >>= 8;
8300           break;
8301         case 2:
8302           bfd_put_16 (input_bfd, x, location);
8303           x >>= 16;
8304           break;
8305         case 4:
8306           bfd_put_32 (input_bfd, x, location);
8307           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
8308           x >>= 16;
8309           x >>= 16;
8310           break;
8311 #ifdef BFD64
8312         case 8:
8313           bfd_put_64 (input_bfd, x, location);
8314           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
8315           x >>= 32;
8316           x >>= 32;
8317           break;
8318 #endif
8319         default:
8320           abort ();
8321           break;
8322         }
8323     }
8324 }
8325
8326 static bfd_vma
8327 get_value (bfd_vma size,
8328            unsigned long chunksz,
8329            bfd *input_bfd,
8330            bfd_byte *location)
8331 {
8332   int shift;
8333   bfd_vma x = 0;
8334
8335   /* Sanity checks.  */
8336   BFD_ASSERT (chunksz <= sizeof (x)
8337               && size >= chunksz
8338               && chunksz != 0
8339               && (size % chunksz) == 0
8340               && input_bfd != NULL
8341               && location != NULL);
8342
8343   if (chunksz == sizeof (x))
8344     {
8345       BFD_ASSERT (size == chunksz);
8346
8347       /* Make sure that we do not perform an undefined shift operation.
8348          We know that size == chunksz so there will only be one iteration
8349          of the loop below.  */
8350       shift = 0;
8351     }
8352   else
8353     shift = 8 * chunksz;
8354
8355   for (; size; size -= chunksz, location += chunksz)
8356     {
8357       switch (chunksz)
8358         {
8359         case 1:
8360           x = (x << shift) | bfd_get_8 (input_bfd, location);
8361           break;
8362         case 2:
8363           x = (x << shift) | bfd_get_16 (input_bfd, location);
8364           break;
8365         case 4:
8366           x = (x << shift) | bfd_get_32 (input_bfd, location);
8367           break;
8368 #ifdef BFD64
8369         case 8:
8370           x = (x << shift) | bfd_get_64 (input_bfd, location);
8371           break;
8372 #endif
8373         default:
8374           abort ();
8375         }
8376     }
8377   return x;
8378 }
8379
8380 static void
8381 decode_complex_addend (unsigned long *start,   /* in bits */
8382                        unsigned long *oplen,   /* in bits */
8383                        unsigned long *len,     /* in bits */
8384                        unsigned long *wordsz,  /* in bytes */
8385                        unsigned long *chunksz, /* in bytes */
8386                        unsigned long *lsb0_p,
8387                        unsigned long *signed_p,
8388                        unsigned long *trunc_p,
8389                        unsigned long encoded)
8390 {
8391   * start     =  encoded        & 0x3F;
8392   * len       = (encoded >>  6) & 0x3F;
8393   * oplen     = (encoded >> 12) & 0x3F;
8394   * wordsz    = (encoded >> 18) & 0xF;
8395   * chunksz   = (encoded >> 22) & 0xF;
8396   * lsb0_p    = (encoded >> 27) & 1;
8397   * signed_p  = (encoded >> 28) & 1;
8398   * trunc_p   = (encoded >> 29) & 1;
8399 }
8400
8401 bfd_reloc_status_type
8402 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8403                                     asection *input_section ATTRIBUTE_UNUSED,
8404                                     bfd_byte *contents,
8405                                     Elf_Internal_Rela *rel,
8406                                     bfd_vma relocation)
8407 {
8408   bfd_vma shift, x, mask;
8409   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8410   bfd_reloc_status_type r;
8411
8412   /*  Perform this reloc, since it is complex.
8413       (this is not to say that it necessarily refers to a complex
8414       symbol; merely that it is a self-describing CGEN based reloc.
8415       i.e. the addend has the complete reloc information (bit start, end,
8416       word size, etc) encoded within it.).  */
8417
8418   decode_complex_addend (&start, &oplen, &len, &wordsz,
8419                          &chunksz, &lsb0_p, &signed_p,
8420                          &trunc_p, rel->r_addend);
8421
8422   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8423
8424   if (lsb0_p)
8425     shift = (start + 1) - len;
8426   else
8427     shift = (8 * wordsz) - (start + len);
8428
8429   x = get_value (wordsz, chunksz, input_bfd,
8430                  contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8431
8432 #ifdef DEBUG
8433   printf ("Doing complex reloc: "
8434           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8435           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8436           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8437           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8438           oplen, (unsigned long) x, (unsigned long) mask,
8439           (unsigned long) relocation);
8440 #endif
8441
8442   r = bfd_reloc_ok;
8443   if (! trunc_p)
8444     /* Now do an overflow check.  */
8445     r = bfd_check_overflow ((signed_p
8446                              ? complain_overflow_signed
8447                              : complain_overflow_unsigned),
8448                             len, 0, (8 * wordsz),
8449                             relocation);
8450
8451   /* Do the deed.  */
8452   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8453
8454 #ifdef DEBUG
8455   printf ("           relocation: %8.8lx\n"
8456           "         shifted mask: %8.8lx\n"
8457           " shifted/masked reloc: %8.8lx\n"
8458           "               result: %8.8lx\n",
8459           (unsigned long) relocation, (unsigned long) (mask << shift),
8460           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8461 #endif
8462   put_value (wordsz, chunksz, input_bfd, x,
8463              contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8464   return r;
8465 }
8466
8467 /* Functions to read r_offset from external (target order) reloc
8468    entry.  Faster than bfd_getl32 et al, because we let the compiler
8469    know the value is aligned.  */
8470
8471 static bfd_vma
8472 ext32l_r_offset (const void *p)
8473 {
8474   union aligned32
8475   {
8476     uint32_t v;
8477     unsigned char c[4];
8478   };
8479   const union aligned32 *a
8480     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8481
8482   uint32_t aval = (  (uint32_t) a->c[0]
8483                    | (uint32_t) a->c[1] << 8
8484                    | (uint32_t) a->c[2] << 16
8485                    | (uint32_t) a->c[3] << 24);
8486   return aval;
8487 }
8488
8489 static bfd_vma
8490 ext32b_r_offset (const void *p)
8491 {
8492   union aligned32
8493   {
8494     uint32_t v;
8495     unsigned char c[4];
8496   };
8497   const union aligned32 *a
8498     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8499
8500   uint32_t aval = (  (uint32_t) a->c[0] << 24
8501                    | (uint32_t) a->c[1] << 16
8502                    | (uint32_t) a->c[2] << 8
8503                    | (uint32_t) a->c[3]);
8504   return aval;
8505 }
8506
8507 #ifdef BFD_HOST_64_BIT
8508 static bfd_vma
8509 ext64l_r_offset (const void *p)
8510 {
8511   union aligned64
8512   {
8513     uint64_t v;
8514     unsigned char c[8];
8515   };
8516   const union aligned64 *a
8517     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8518
8519   uint64_t aval = (  (uint64_t) a->c[0]
8520                    | (uint64_t) a->c[1] << 8
8521                    | (uint64_t) a->c[2] << 16
8522                    | (uint64_t) a->c[3] << 24
8523                    | (uint64_t) a->c[4] << 32
8524                    | (uint64_t) a->c[5] << 40
8525                    | (uint64_t) a->c[6] << 48
8526                    | (uint64_t) a->c[7] << 56);
8527   return aval;
8528 }
8529
8530 static bfd_vma
8531 ext64b_r_offset (const void *p)
8532 {
8533   union aligned64
8534   {
8535     uint64_t v;
8536     unsigned char c[8];
8537   };
8538   const union aligned64 *a
8539     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8540
8541   uint64_t aval = (  (uint64_t) a->c[0] << 56
8542                    | (uint64_t) a->c[1] << 48
8543                    | (uint64_t) a->c[2] << 40
8544                    | (uint64_t) a->c[3] << 32
8545                    | (uint64_t) a->c[4] << 24
8546                    | (uint64_t) a->c[5] << 16
8547                    | (uint64_t) a->c[6] << 8
8548                    | (uint64_t) a->c[7]);
8549   return aval;
8550 }
8551 #endif
8552
8553 /* When performing a relocatable link, the input relocations are
8554    preserved.  But, if they reference global symbols, the indices
8555    referenced must be updated.  Update all the relocations found in
8556    RELDATA.  */
8557
8558 static bfd_boolean
8559 elf_link_adjust_relocs (bfd *abfd,
8560                         asection *sec,
8561                         struct bfd_elf_section_reloc_data *reldata,
8562                         bfd_boolean sort,
8563                         struct bfd_link_info *info)
8564 {
8565   unsigned int i;
8566   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8567   bfd_byte *erela;
8568   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8569   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8570   bfd_vma r_type_mask;
8571   int r_sym_shift;
8572   unsigned int count = reldata->count;
8573   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8574
8575   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8576     {
8577       swap_in = bed->s->swap_reloc_in;
8578       swap_out = bed->s->swap_reloc_out;
8579     }
8580   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8581     {
8582       swap_in = bed->s->swap_reloca_in;
8583       swap_out = bed->s->swap_reloca_out;
8584     }
8585   else
8586     abort ();
8587
8588   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8589     abort ();
8590
8591   if (bed->s->arch_size == 32)
8592     {
8593       r_type_mask = 0xff;
8594       r_sym_shift = 8;
8595     }
8596   else
8597     {
8598       r_type_mask = 0xffffffff;
8599       r_sym_shift = 32;
8600     }
8601
8602   erela = reldata->hdr->contents;
8603   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8604     {
8605       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8606       unsigned int j;
8607
8608       if (*rel_hash == NULL)
8609         continue;
8610
8611       if ((*rel_hash)->indx == -2
8612           && info->gc_sections
8613           && ! info->gc_keep_exported)
8614         {
8615           /* PR 21524: Let the user know if a symbol was removed by garbage collection.  */
8616           _bfd_error_handler (_("%B:%A: error: relocation references symbol %s which was removed by garbage collection."),
8617                               abfd, sec,
8618                               (*rel_hash)->root.root.string);
8619           _bfd_error_handler (_("%B:%A: error: try relinking with --gc-keep-exported enabled."),
8620                               abfd, sec,
8621                               (*rel_hash)->root.root.string);
8622           bfd_set_error (bfd_error_invalid_operation);
8623           return FALSE;
8624         }
8625       BFD_ASSERT ((*rel_hash)->indx >= 0);
8626
8627       (*swap_in) (abfd, erela, irela);
8628       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8629         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8630                            | (irela[j].r_info & r_type_mask));
8631       (*swap_out) (abfd, irela, erela);
8632     }
8633
8634   if (bed->elf_backend_update_relocs)
8635     (*bed->elf_backend_update_relocs) (sec, reldata);
8636
8637   if (sort && count != 0)
8638     {
8639       bfd_vma (*ext_r_off) (const void *);
8640       bfd_vma r_off;
8641       size_t elt_size;
8642       bfd_byte *base, *end, *p, *loc;
8643       bfd_byte *buf = NULL;
8644
8645       if (bed->s->arch_size == 32)
8646         {
8647           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8648             ext_r_off = ext32l_r_offset;
8649           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8650             ext_r_off = ext32b_r_offset;
8651           else
8652             abort ();
8653         }
8654       else
8655         {
8656 #ifdef BFD_HOST_64_BIT
8657           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8658             ext_r_off = ext64l_r_offset;
8659           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8660             ext_r_off = ext64b_r_offset;
8661           else
8662 #endif
8663             abort ();
8664         }
8665
8666       /*  Must use a stable sort here.  A modified insertion sort,
8667           since the relocs are mostly sorted already.  */
8668       elt_size = reldata->hdr->sh_entsize;
8669       base = reldata->hdr->contents;
8670       end = base + count * elt_size;
8671       if (elt_size > sizeof (Elf64_External_Rela))
8672         abort ();
8673
8674       /* Ensure the first element is lowest.  This acts as a sentinel,
8675          speeding the main loop below.  */
8676       r_off = (*ext_r_off) (base);
8677       for (p = loc = base; (p += elt_size) < end; )
8678         {
8679           bfd_vma r_off2 = (*ext_r_off) (p);
8680           if (r_off > r_off2)
8681             {
8682               r_off = r_off2;
8683               loc = p;
8684             }
8685         }
8686       if (loc != base)
8687         {
8688           /* Don't just swap *base and *loc as that changes the order
8689              of the original base[0] and base[1] if they happen to
8690              have the same r_offset.  */
8691           bfd_byte onebuf[sizeof (Elf64_External_Rela)];
8692           memcpy (onebuf, loc, elt_size);
8693           memmove (base + elt_size, base, loc - base);
8694           memcpy (base, onebuf, elt_size);
8695         }
8696
8697       for (p = base + elt_size; (p += elt_size) < end; )
8698         {
8699           /* base to p is sorted, *p is next to insert.  */
8700           r_off = (*ext_r_off) (p);
8701           /* Search the sorted region for location to insert.  */
8702           loc = p - elt_size;
8703           while (r_off < (*ext_r_off) (loc))
8704             loc -= elt_size;
8705           loc += elt_size;
8706           if (loc != p)
8707             {
8708               /* Chances are there is a run of relocs to insert here,
8709                  from one of more input files.  Files are not always
8710                  linked in order due to the way elf_link_input_bfd is
8711                  called.  See pr17666.  */
8712               size_t sortlen = p - loc;
8713               bfd_vma r_off2 = (*ext_r_off) (loc);
8714               size_t runlen = elt_size;
8715               size_t buf_size = 96 * 1024;
8716               while (p + runlen < end
8717                      && (sortlen <= buf_size
8718                          || runlen + elt_size <= buf_size)
8719                      && r_off2 > (*ext_r_off) (p + runlen))
8720                 runlen += elt_size;
8721               if (buf == NULL)
8722                 {
8723                   buf = bfd_malloc (buf_size);
8724                   if (buf == NULL)
8725                     return FALSE;
8726                 }
8727               if (runlen < sortlen)
8728                 {
8729                   memcpy (buf, p, runlen);
8730                   memmove (loc + runlen, loc, sortlen);
8731                   memcpy (loc, buf, runlen);
8732                 }
8733               else
8734                 {
8735                   memcpy (buf, loc, sortlen);
8736                   memmove (loc, p, runlen);
8737                   memcpy (loc + runlen, buf, sortlen);
8738                 }
8739               p += runlen - elt_size;
8740             }
8741         }
8742       /* Hashes are no longer valid.  */
8743       free (reldata->hashes);
8744       reldata->hashes = NULL;
8745       free (buf);
8746     }
8747   return TRUE;
8748 }
8749
8750 struct elf_link_sort_rela
8751 {
8752   union {
8753     bfd_vma offset;
8754     bfd_vma sym_mask;
8755   } u;
8756   enum elf_reloc_type_class type;
8757   /* We use this as an array of size int_rels_per_ext_rel.  */
8758   Elf_Internal_Rela rela[1];
8759 };
8760
8761 static int
8762 elf_link_sort_cmp1 (const void *A, const void *B)
8763 {
8764   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8765   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8766   int relativea, relativeb;
8767
8768   relativea = a->type == reloc_class_relative;
8769   relativeb = b->type == reloc_class_relative;
8770
8771   if (relativea < relativeb)
8772     return 1;
8773   if (relativea > relativeb)
8774     return -1;
8775   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8776     return -1;
8777   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8778     return 1;
8779   if (a->rela->r_offset < b->rela->r_offset)
8780     return -1;
8781   if (a->rela->r_offset > b->rela->r_offset)
8782     return 1;
8783   return 0;
8784 }
8785
8786 static int
8787 elf_link_sort_cmp2 (const void *A, const void *B)
8788 {
8789   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8790   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8791
8792   if (a->type < b->type)
8793     return -1;
8794   if (a->type > b->type)
8795     return 1;
8796   if (a->u.offset < b->u.offset)
8797     return -1;
8798   if (a->u.offset > b->u.offset)
8799     return 1;
8800   if (a->rela->r_offset < b->rela->r_offset)
8801     return -1;
8802   if (a->rela->r_offset > b->rela->r_offset)
8803     return 1;
8804   return 0;
8805 }
8806
8807 static size_t
8808 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8809 {
8810   asection *dynamic_relocs;
8811   asection *rela_dyn;
8812   asection *rel_dyn;
8813   bfd_size_type count, size;
8814   size_t i, ret, sort_elt, ext_size;
8815   bfd_byte *sort, *s_non_relative, *p;
8816   struct elf_link_sort_rela *sq;
8817   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8818   int i2e = bed->s->int_rels_per_ext_rel;
8819   unsigned int opb = bfd_octets_per_byte (abfd);
8820   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8821   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8822   struct bfd_link_order *lo;
8823   bfd_vma r_sym_mask;
8824   bfd_boolean use_rela;
8825
8826   /* Find a dynamic reloc section.  */
8827   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8828   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8829   if (rela_dyn != NULL && rela_dyn->size > 0
8830       && rel_dyn != NULL && rel_dyn->size > 0)
8831     {
8832       bfd_boolean use_rela_initialised = FALSE;
8833
8834       /* This is just here to stop gcc from complaining.
8835          Its initialization checking code is not perfect.  */
8836       use_rela = TRUE;
8837
8838       /* Both sections are present.  Examine the sizes
8839          of the indirect sections to help us choose.  */
8840       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8841         if (lo->type == bfd_indirect_link_order)
8842           {
8843             asection *o = lo->u.indirect.section;
8844
8845             if ((o->size % bed->s->sizeof_rela) == 0)
8846               {
8847                 if ((o->size % bed->s->sizeof_rel) == 0)
8848                   /* Section size is divisible by both rel and rela sizes.
8849                      It is of no help to us.  */
8850                   ;
8851                 else
8852                   {
8853                     /* Section size is only divisible by rela.  */
8854                     if (use_rela_initialised && !use_rela)
8855                       {
8856                         _bfd_error_handler (_("%B: Unable to sort relocs - "
8857                                               "they are in more than one size"),
8858                                             abfd);
8859                         bfd_set_error (bfd_error_invalid_operation);
8860                         return 0;
8861                       }
8862                     else
8863                       {
8864                         use_rela = TRUE;
8865                         use_rela_initialised = TRUE;
8866                       }
8867                   }
8868               }
8869             else if ((o->size % bed->s->sizeof_rel) == 0)
8870               {
8871                 /* Section size is only divisible by rel.  */
8872                 if (use_rela_initialised && use_rela)
8873                   {
8874                     _bfd_error_handler (_("%B: Unable to sort relocs - "
8875                                           "they are in more than one size"),
8876                                         abfd);
8877                     bfd_set_error (bfd_error_invalid_operation);
8878                     return 0;
8879                   }
8880                 else
8881                   {
8882                     use_rela = FALSE;
8883                     use_rela_initialised = TRUE;
8884                   }
8885               }
8886             else
8887               {
8888                 /* The section size is not divisible by either -
8889                    something is wrong.  */
8890                 _bfd_error_handler (_("%B: Unable to sort relocs - "
8891                                       "they are of an unknown size"), abfd);
8892                 bfd_set_error (bfd_error_invalid_operation);
8893                 return 0;
8894               }
8895           }
8896
8897       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8898         if (lo->type == bfd_indirect_link_order)
8899           {
8900             asection *o = lo->u.indirect.section;
8901
8902             if ((o->size % bed->s->sizeof_rela) == 0)
8903               {
8904                 if ((o->size % bed->s->sizeof_rel) == 0)
8905                   /* Section size is divisible by both rel and rela sizes.
8906                      It is of no help to us.  */
8907                   ;
8908                 else
8909                   {
8910                     /* Section size is only divisible by rela.  */
8911                     if (use_rela_initialised && !use_rela)
8912                       {
8913                         _bfd_error_handler (_("%B: Unable to sort relocs - "
8914                                               "they are in more than one size"),
8915                                             abfd);
8916                         bfd_set_error (bfd_error_invalid_operation);
8917                         return 0;
8918                       }
8919                     else
8920                       {
8921                         use_rela = TRUE;
8922                         use_rela_initialised = TRUE;
8923                       }
8924                   }
8925               }
8926             else if ((o->size % bed->s->sizeof_rel) == 0)
8927               {
8928                 /* Section size is only divisible by rel.  */
8929                 if (use_rela_initialised && use_rela)
8930                   {
8931                     _bfd_error_handler (_("%B: Unable to sort relocs - "
8932                                           "they are in more than one size"),
8933                                         abfd);
8934                     bfd_set_error (bfd_error_invalid_operation);
8935                     return 0;
8936                   }
8937                 else
8938                   {
8939                     use_rela = FALSE;
8940                     use_rela_initialised = TRUE;
8941                   }
8942               }
8943             else
8944               {
8945                 /* The section size is not divisible by either -
8946                    something is wrong.  */
8947                 _bfd_error_handler (_("%B: Unable to sort relocs - "
8948                                       "they are of an unknown size"), abfd);
8949                 bfd_set_error (bfd_error_invalid_operation);
8950                 return 0;
8951               }
8952           }
8953
8954       if (! use_rela_initialised)
8955         /* Make a guess.  */
8956         use_rela = TRUE;
8957     }
8958   else if (rela_dyn != NULL && rela_dyn->size > 0)
8959     use_rela = TRUE;
8960   else if (rel_dyn != NULL && rel_dyn->size > 0)
8961     use_rela = FALSE;
8962   else
8963     return 0;
8964
8965   if (use_rela)
8966     {
8967       dynamic_relocs = rela_dyn;
8968       ext_size = bed->s->sizeof_rela;
8969       swap_in = bed->s->swap_reloca_in;
8970       swap_out = bed->s->swap_reloca_out;
8971     }
8972   else
8973     {
8974       dynamic_relocs = rel_dyn;
8975       ext_size = bed->s->sizeof_rel;
8976       swap_in = bed->s->swap_reloc_in;
8977       swap_out = bed->s->swap_reloc_out;
8978     }
8979
8980   size = 0;
8981   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8982     if (lo->type == bfd_indirect_link_order)
8983       size += lo->u.indirect.section->size;
8984
8985   if (size != dynamic_relocs->size)
8986     return 0;
8987
8988   sort_elt = (sizeof (struct elf_link_sort_rela)
8989               + (i2e - 1) * sizeof (Elf_Internal_Rela));
8990
8991   count = dynamic_relocs->size / ext_size;
8992   if (count == 0)
8993     return 0;
8994   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
8995
8996   if (sort == NULL)
8997     {
8998       (*info->callbacks->warning)
8999         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
9000       return 0;
9001     }
9002
9003   if (bed->s->arch_size == 32)
9004     r_sym_mask = ~(bfd_vma) 0xff;
9005   else
9006     r_sym_mask = ~(bfd_vma) 0xffffffff;
9007
9008   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9009     if (lo->type == bfd_indirect_link_order)
9010       {
9011         bfd_byte *erel, *erelend;
9012         asection *o = lo->u.indirect.section;
9013
9014         if (o->contents == NULL && o->size != 0)
9015           {
9016             /* This is a reloc section that is being handled as a normal
9017                section.  See bfd_section_from_shdr.  We can't combine
9018                relocs in this case.  */
9019             free (sort);
9020             return 0;
9021           }
9022         erel = o->contents;
9023         erelend = o->contents + o->size;
9024         p = sort + o->output_offset * opb / ext_size * sort_elt;
9025
9026         while (erel < erelend)
9027           {
9028             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9029
9030             (*swap_in) (abfd, erel, s->rela);
9031             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
9032             s->u.sym_mask = r_sym_mask;
9033             p += sort_elt;
9034             erel += ext_size;
9035           }
9036       }
9037
9038   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
9039
9040   for (i = 0, p = sort; i < count; i++, p += sort_elt)
9041     {
9042       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9043       if (s->type != reloc_class_relative)
9044         break;
9045     }
9046   ret = i;
9047   s_non_relative = p;
9048
9049   sq = (struct elf_link_sort_rela *) s_non_relative;
9050   for (; i < count; i++, p += sort_elt)
9051     {
9052       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
9053       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
9054         sq = sp;
9055       sp->u.offset = sq->rela->r_offset;
9056     }
9057
9058   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
9059
9060   struct elf_link_hash_table *htab = elf_hash_table (info);
9061   if (htab->srelplt && htab->srelplt->output_section == dynamic_relocs)
9062     {
9063       /* We have plt relocs in .rela.dyn.  */
9064       sq = (struct elf_link_sort_rela *) sort;
9065       for (i = 0; i < count; i++)
9066         if (sq[count - i - 1].type != reloc_class_plt)
9067           break;
9068       if (i != 0 && htab->srelplt->size == i * ext_size)
9069         {
9070           struct bfd_link_order **plo;
9071           /* Put srelplt link_order last.  This is so the output_offset
9072              set in the next loop is correct for DT_JMPREL.  */
9073           for (plo = &dynamic_relocs->map_head.link_order; *plo != NULL; )
9074             if ((*plo)->type == bfd_indirect_link_order
9075                 && (*plo)->u.indirect.section == htab->srelplt)
9076               {
9077                 lo = *plo;
9078                 *plo = lo->next;
9079               }
9080             else
9081               plo = &(*plo)->next;
9082           *plo = lo;
9083           lo->next = NULL;
9084           dynamic_relocs->map_tail.link_order = lo;
9085         }
9086     }
9087
9088   p = sort;
9089   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
9090     if (lo->type == bfd_indirect_link_order)
9091       {
9092         bfd_byte *erel, *erelend;
9093         asection *o = lo->u.indirect.section;
9094
9095         erel = o->contents;
9096         erelend = o->contents + o->size;
9097         o->output_offset = (p - sort) / sort_elt * ext_size / opb;
9098         while (erel < erelend)
9099           {
9100             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9101             (*swap_out) (abfd, s->rela, erel);
9102             p += sort_elt;
9103             erel += ext_size;
9104           }
9105       }
9106
9107   free (sort);
9108   *psec = dynamic_relocs;
9109   return ret;
9110 }
9111
9112 /* Add a symbol to the output symbol string table.  */
9113
9114 static int
9115 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
9116                            const char *name,
9117                            Elf_Internal_Sym *elfsym,
9118                            asection *input_sec,
9119                            struct elf_link_hash_entry *h)
9120 {
9121   int (*output_symbol_hook)
9122     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
9123      struct elf_link_hash_entry *);
9124   struct elf_link_hash_table *hash_table;
9125   const struct elf_backend_data *bed;
9126   bfd_size_type strtabsize;
9127
9128   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9129
9130   bed = get_elf_backend_data (flinfo->output_bfd);
9131   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
9132   if (output_symbol_hook != NULL)
9133     {
9134       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
9135       if (ret != 1)
9136         return ret;
9137     }
9138
9139   if (name == NULL
9140       || *name == '\0'
9141       || (input_sec->flags & SEC_EXCLUDE))
9142     elfsym->st_name = (unsigned long) -1;
9143   else
9144     {
9145       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
9146          to get the final offset for st_name.  */
9147       elfsym->st_name
9148         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
9149                                                name, FALSE);
9150       if (elfsym->st_name == (unsigned long) -1)
9151         return 0;
9152     }
9153
9154   hash_table = elf_hash_table (flinfo->info);
9155   strtabsize = hash_table->strtabsize;
9156   if (strtabsize <= hash_table->strtabcount)
9157     {
9158       strtabsize += strtabsize;
9159       hash_table->strtabsize = strtabsize;
9160       strtabsize *= sizeof (*hash_table->strtab);
9161       hash_table->strtab
9162         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
9163                                                  strtabsize);
9164       if (hash_table->strtab == NULL)
9165         return 0;
9166     }
9167   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
9168   hash_table->strtab[hash_table->strtabcount].dest_index
9169     = hash_table->strtabcount;
9170   hash_table->strtab[hash_table->strtabcount].destshndx_index
9171     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
9172
9173   bfd_get_symcount (flinfo->output_bfd) += 1;
9174   hash_table->strtabcount += 1;
9175
9176   return 1;
9177 }
9178
9179 /* Swap symbols out to the symbol table and flush the output symbols to
9180    the file.  */
9181
9182 static bfd_boolean
9183 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
9184 {
9185   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
9186   bfd_size_type amt;
9187   size_t i;
9188   const struct elf_backend_data *bed;
9189   bfd_byte *symbuf;
9190   Elf_Internal_Shdr *hdr;
9191   file_ptr pos;
9192   bfd_boolean ret;
9193
9194   if (!hash_table->strtabcount)
9195     return TRUE;
9196
9197   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9198
9199   bed = get_elf_backend_data (flinfo->output_bfd);
9200
9201   amt = bed->s->sizeof_sym * hash_table->strtabcount;
9202   symbuf = (bfd_byte *) bfd_malloc (amt);
9203   if (symbuf == NULL)
9204     return FALSE;
9205
9206   if (flinfo->symshndxbuf)
9207     {
9208       amt = sizeof (Elf_External_Sym_Shndx);
9209       amt *= bfd_get_symcount (flinfo->output_bfd);
9210       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
9211       if (flinfo->symshndxbuf == NULL)
9212         {
9213           free (symbuf);
9214           return FALSE;
9215         }
9216     }
9217
9218   for (i = 0; i < hash_table->strtabcount; i++)
9219     {
9220       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
9221       if (elfsym->sym.st_name == (unsigned long) -1)
9222         elfsym->sym.st_name = 0;
9223       else
9224         elfsym->sym.st_name
9225           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
9226                                                     elfsym->sym.st_name);
9227       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
9228                                ((bfd_byte *) symbuf
9229                                 + (elfsym->dest_index
9230                                    * bed->s->sizeof_sym)),
9231                                (flinfo->symshndxbuf
9232                                 + elfsym->destshndx_index));
9233     }
9234
9235   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
9236   pos = hdr->sh_offset + hdr->sh_size;
9237   amt = hash_table->strtabcount * bed->s->sizeof_sym;
9238   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
9239       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
9240     {
9241       hdr->sh_size += amt;
9242       ret = TRUE;
9243     }
9244   else
9245     ret = FALSE;
9246
9247   free (symbuf);
9248
9249   free (hash_table->strtab);
9250   hash_table->strtab = NULL;
9251
9252   return ret;
9253 }
9254
9255 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
9256
9257 static bfd_boolean
9258 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
9259 {
9260   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
9261       && sym->st_shndx < SHN_LORESERVE)
9262     {
9263       /* The gABI doesn't support dynamic symbols in output sections
9264          beyond 64k.  */
9265       _bfd_error_handler
9266         /* xgettext:c-format */
9267         (_("%B: Too many sections: %d (>= %d)"),
9268          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
9269       bfd_set_error (bfd_error_nonrepresentable_section);
9270       return FALSE;
9271     }
9272   return TRUE;
9273 }
9274
9275 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
9276    allowing an unsatisfied unversioned symbol in the DSO to match a
9277    versioned symbol that would normally require an explicit version.
9278    We also handle the case that a DSO references a hidden symbol
9279    which may be satisfied by a versioned symbol in another DSO.  */
9280
9281 static bfd_boolean
9282 elf_link_check_versioned_symbol (struct bfd_link_info *info,
9283                                  const struct elf_backend_data *bed,
9284                                  struct elf_link_hash_entry *h)
9285 {
9286   bfd *abfd;
9287   struct elf_link_loaded_list *loaded;
9288
9289   if (!is_elf_hash_table (info->hash))
9290     return FALSE;
9291
9292   /* Check indirect symbol.  */
9293   while (h->root.type == bfd_link_hash_indirect)
9294     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9295
9296   switch (h->root.type)
9297     {
9298     default:
9299       abfd = NULL;
9300       break;
9301
9302     case bfd_link_hash_undefined:
9303     case bfd_link_hash_undefweak:
9304       abfd = h->root.u.undef.abfd;
9305       if (abfd == NULL
9306           || (abfd->flags & DYNAMIC) == 0
9307           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
9308         return FALSE;
9309       break;
9310
9311     case bfd_link_hash_defined:
9312     case bfd_link_hash_defweak:
9313       abfd = h->root.u.def.section->owner;
9314       break;
9315
9316     case bfd_link_hash_common:
9317       abfd = h->root.u.c.p->section->owner;
9318       break;
9319     }
9320   BFD_ASSERT (abfd != NULL);
9321
9322   for (loaded = elf_hash_table (info)->loaded;
9323        loaded != NULL;
9324        loaded = loaded->next)
9325     {
9326       bfd *input;
9327       Elf_Internal_Shdr *hdr;
9328       size_t symcount;
9329       size_t extsymcount;
9330       size_t extsymoff;
9331       Elf_Internal_Shdr *versymhdr;
9332       Elf_Internal_Sym *isym;
9333       Elf_Internal_Sym *isymend;
9334       Elf_Internal_Sym *isymbuf;
9335       Elf_External_Versym *ever;
9336       Elf_External_Versym *extversym;
9337
9338       input = loaded->abfd;
9339
9340       /* We check each DSO for a possible hidden versioned definition.  */
9341       if (input == abfd
9342           || (input->flags & DYNAMIC) == 0
9343           || elf_dynversym (input) == 0)
9344         continue;
9345
9346       hdr = &elf_tdata (input)->dynsymtab_hdr;
9347
9348       symcount = hdr->sh_size / bed->s->sizeof_sym;
9349       if (elf_bad_symtab (input))
9350         {
9351           extsymcount = symcount;
9352           extsymoff = 0;
9353         }
9354       else
9355         {
9356           extsymcount = symcount - hdr->sh_info;
9357           extsymoff = hdr->sh_info;
9358         }
9359
9360       if (extsymcount == 0)
9361         continue;
9362
9363       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
9364                                       NULL, NULL, NULL);
9365       if (isymbuf == NULL)
9366         return FALSE;
9367
9368       /* Read in any version definitions.  */
9369       versymhdr = &elf_tdata (input)->dynversym_hdr;
9370       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
9371       if (extversym == NULL)
9372         goto error_ret;
9373
9374       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
9375           || (bfd_bread (extversym, versymhdr->sh_size, input)
9376               != versymhdr->sh_size))
9377         {
9378           free (extversym);
9379         error_ret:
9380           free (isymbuf);
9381           return FALSE;
9382         }
9383
9384       ever = extversym + extsymoff;
9385       isymend = isymbuf + extsymcount;
9386       for (isym = isymbuf; isym < isymend; isym++, ever++)
9387         {
9388           const char *name;
9389           Elf_Internal_Versym iver;
9390           unsigned short version_index;
9391
9392           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
9393               || isym->st_shndx == SHN_UNDEF)
9394             continue;
9395
9396           name = bfd_elf_string_from_elf_section (input,
9397                                                   hdr->sh_link,
9398                                                   isym->st_name);
9399           if (strcmp (name, h->root.root.string) != 0)
9400             continue;
9401
9402           _bfd_elf_swap_versym_in (input, ever, &iver);
9403
9404           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
9405               && !(h->def_regular
9406                    && h->forced_local))
9407             {
9408               /* If we have a non-hidden versioned sym, then it should
9409                  have provided a definition for the undefined sym unless
9410                  it is defined in a non-shared object and forced local.
9411                */
9412               abort ();
9413             }
9414
9415           version_index = iver.vs_vers & VERSYM_VERSION;
9416           if (version_index == 1 || version_index == 2)
9417             {
9418               /* This is the base or first version.  We can use it.  */
9419               free (extversym);
9420               free (isymbuf);
9421               return TRUE;
9422             }
9423         }
9424
9425       free (extversym);
9426       free (isymbuf);
9427     }
9428
9429   return FALSE;
9430 }
9431
9432 /* Convert ELF common symbol TYPE.  */
9433
9434 static int
9435 elf_link_convert_common_type (struct bfd_link_info *info, int type)
9436 {
9437   /* Commom symbol can only appear in relocatable link.  */
9438   if (!bfd_link_relocatable (info))
9439     abort ();
9440   switch (info->elf_stt_common)
9441     {
9442     case unchanged:
9443       break;
9444     case elf_stt_common:
9445       type = STT_COMMON;
9446       break;
9447     case no_elf_stt_common:
9448       type = STT_OBJECT;
9449       break;
9450     }
9451   return type;
9452 }
9453
9454 /* Add an external symbol to the symbol table.  This is called from
9455    the hash table traversal routine.  When generating a shared object,
9456    we go through the symbol table twice.  The first time we output
9457    anything that might have been forced to local scope in a version
9458    script.  The second time we output the symbols that are still
9459    global symbols.  */
9460
9461 static bfd_boolean
9462 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
9463 {
9464   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
9465   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
9466   struct elf_final_link_info *flinfo = eoinfo->flinfo;
9467   bfd_boolean strip;
9468   Elf_Internal_Sym sym;
9469   asection *input_sec;
9470   const struct elf_backend_data *bed;
9471   long indx;
9472   int ret;
9473   unsigned int type;
9474
9475   if (h->root.type == bfd_link_hash_warning)
9476     {
9477       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9478       if (h->root.type == bfd_link_hash_new)
9479         return TRUE;
9480     }
9481
9482   /* Decide whether to output this symbol in this pass.  */
9483   if (eoinfo->localsyms)
9484     {
9485       if (!h->forced_local)
9486         return TRUE;
9487     }
9488   else
9489     {
9490       if (h->forced_local)
9491         return TRUE;
9492     }
9493
9494   bed = get_elf_backend_data (flinfo->output_bfd);
9495
9496   if (h->root.type == bfd_link_hash_undefined)
9497     {
9498       /* If we have an undefined symbol reference here then it must have
9499          come from a shared library that is being linked in.  (Undefined
9500          references in regular files have already been handled unless
9501          they are in unreferenced sections which are removed by garbage
9502          collection).  */
9503       bfd_boolean ignore_undef = FALSE;
9504
9505       /* Some symbols may be special in that the fact that they're
9506          undefined can be safely ignored - let backend determine that.  */
9507       if (bed->elf_backend_ignore_undef_symbol)
9508         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9509
9510       /* If we are reporting errors for this situation then do so now.  */
9511       if (!ignore_undef
9512           && h->ref_dynamic
9513           && (!h->ref_regular || flinfo->info->gc_sections)
9514           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9515           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9516         (*flinfo->info->callbacks->undefined_symbol)
9517           (flinfo->info, h->root.root.string,
9518            h->ref_regular ? NULL : h->root.u.undef.abfd,
9519            NULL, 0,
9520            flinfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR);
9521
9522       /* Strip a global symbol defined in a discarded section.  */
9523       if (h->indx == -3)
9524         return TRUE;
9525     }
9526
9527   /* We should also warn if a forced local symbol is referenced from
9528      shared libraries.  */
9529   if (bfd_link_executable (flinfo->info)
9530       && h->forced_local
9531       && h->ref_dynamic
9532       && h->def_regular
9533       && !h->dynamic_def
9534       && h->ref_dynamic_nonweak
9535       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9536     {
9537       bfd *def_bfd;
9538       const char *msg;
9539       struct elf_link_hash_entry *hi = h;
9540
9541       /* Check indirect symbol.  */
9542       while (hi->root.type == bfd_link_hash_indirect)
9543         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9544
9545       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9546         /* xgettext:c-format */
9547         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
9548       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9549         /* xgettext:c-format */
9550         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
9551       else
9552         /* xgettext:c-format */
9553         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
9554       def_bfd = flinfo->output_bfd;
9555       if (hi->root.u.def.section != bfd_abs_section_ptr)
9556         def_bfd = hi->root.u.def.section->owner;
9557       _bfd_error_handler (msg, flinfo->output_bfd,
9558                           h->root.root.string, def_bfd);
9559       bfd_set_error (bfd_error_bad_value);
9560       eoinfo->failed = TRUE;
9561       return FALSE;
9562     }
9563
9564   /* We don't want to output symbols that have never been mentioned by
9565      a regular file, or that we have been told to strip.  However, if
9566      h->indx is set to -2, the symbol is used by a reloc and we must
9567      output it.  */
9568   strip = FALSE;
9569   if (h->indx == -2)
9570     ;
9571   else if ((h->def_dynamic
9572             || h->ref_dynamic
9573             || h->root.type == bfd_link_hash_new)
9574            && !h->def_regular
9575            && !h->ref_regular)
9576     strip = TRUE;
9577   else if (flinfo->info->strip == strip_all)
9578     strip = TRUE;
9579   else if (flinfo->info->strip == strip_some
9580            && bfd_hash_lookup (flinfo->info->keep_hash,
9581                                h->root.root.string, FALSE, FALSE) == NULL)
9582     strip = TRUE;
9583   else if ((h->root.type == bfd_link_hash_defined
9584             || h->root.type == bfd_link_hash_defweak)
9585            && ((flinfo->info->strip_discarded
9586                 && discarded_section (h->root.u.def.section))
9587                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9588                    && h->root.u.def.section->owner != NULL
9589                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9590     strip = TRUE;
9591   else if ((h->root.type == bfd_link_hash_undefined
9592             || h->root.type == bfd_link_hash_undefweak)
9593            && h->root.u.undef.abfd != NULL
9594            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9595     strip = TRUE;
9596
9597   type = h->type;
9598
9599   /* If we're stripping it, and it's not a dynamic symbol, there's
9600      nothing else to do.   However, if it is a forced local symbol or
9601      an ifunc symbol we need to give the backend finish_dynamic_symbol
9602      function a chance to make it dynamic.  */
9603   if (strip
9604       && h->dynindx == -1
9605       && type != STT_GNU_IFUNC
9606       && !h->forced_local)
9607     return TRUE;
9608
9609   sym.st_value = 0;
9610   sym.st_size = h->size;
9611   sym.st_other = h->other;
9612   switch (h->root.type)
9613     {
9614     default:
9615     case bfd_link_hash_new:
9616     case bfd_link_hash_warning:
9617       abort ();
9618       return FALSE;
9619
9620     case bfd_link_hash_undefined:
9621     case bfd_link_hash_undefweak:
9622       input_sec = bfd_und_section_ptr;
9623       sym.st_shndx = SHN_UNDEF;
9624       break;
9625
9626     case bfd_link_hash_defined:
9627     case bfd_link_hash_defweak:
9628       {
9629         input_sec = h->root.u.def.section;
9630         if (input_sec->output_section != NULL)
9631           {
9632             sym.st_shndx =
9633               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9634                                                  input_sec->output_section);
9635             if (sym.st_shndx == SHN_BAD)
9636               {
9637                 _bfd_error_handler
9638                   /* xgettext:c-format */
9639                   (_("%B: could not find output section %A for input section %A"),
9640                    flinfo->output_bfd, input_sec->output_section, input_sec);
9641                 bfd_set_error (bfd_error_nonrepresentable_section);
9642                 eoinfo->failed = TRUE;
9643                 return FALSE;
9644               }
9645
9646             /* ELF symbols in relocatable files are section relative,
9647                but in nonrelocatable files they are virtual
9648                addresses.  */
9649             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9650             if (!bfd_link_relocatable (flinfo->info))
9651               {
9652                 sym.st_value += input_sec->output_section->vma;
9653                 if (h->type == STT_TLS)
9654                   {
9655                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9656                     if (tls_sec != NULL)
9657                       sym.st_value -= tls_sec->vma;
9658                   }
9659               }
9660           }
9661         else
9662           {
9663             BFD_ASSERT (input_sec->owner == NULL
9664                         || (input_sec->owner->flags & DYNAMIC) != 0);
9665             sym.st_shndx = SHN_UNDEF;
9666             input_sec = bfd_und_section_ptr;
9667           }
9668       }
9669       break;
9670
9671     case bfd_link_hash_common:
9672       input_sec = h->root.u.c.p->section;
9673       sym.st_shndx = bed->common_section_index (input_sec);
9674       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9675       break;
9676
9677     case bfd_link_hash_indirect:
9678       /* These symbols are created by symbol versioning.  They point
9679          to the decorated version of the name.  For example, if the
9680          symbol foo@@GNU_1.2 is the default, which should be used when
9681          foo is used with no version, then we add an indirect symbol
9682          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9683          since the indirected symbol is already in the hash table.  */
9684       return TRUE;
9685     }
9686
9687   if (type == STT_COMMON || type == STT_OBJECT)
9688     switch (h->root.type)
9689       {
9690       case bfd_link_hash_common:
9691         type = elf_link_convert_common_type (flinfo->info, type);
9692         break;
9693       case bfd_link_hash_defined:
9694       case bfd_link_hash_defweak:
9695         if (bed->common_definition (&sym))
9696           type = elf_link_convert_common_type (flinfo->info, type);
9697         else
9698           type = STT_OBJECT;
9699         break;
9700       case bfd_link_hash_undefined:
9701       case bfd_link_hash_undefweak:
9702         break;
9703       default:
9704         abort ();
9705       }
9706
9707   if (h->forced_local)
9708     {
9709       sym.st_info = ELF_ST_INFO (STB_LOCAL, type);
9710       /* Turn off visibility on local symbol.  */
9711       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9712     }
9713   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9714   else if (h->unique_global && h->def_regular)
9715     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, type);
9716   else if (h->root.type == bfd_link_hash_undefweak
9717            || h->root.type == bfd_link_hash_defweak)
9718     sym.st_info = ELF_ST_INFO (STB_WEAK, type);
9719   else
9720     sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9721   sym.st_target_internal = h->target_internal;
9722
9723   /* Give the processor backend a chance to tweak the symbol value,
9724      and also to finish up anything that needs to be done for this
9725      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9726      forced local syms when non-shared is due to a historical quirk.
9727      STT_GNU_IFUNC symbol must go through PLT.  */
9728   if ((h->type == STT_GNU_IFUNC
9729        && h->def_regular
9730        && !bfd_link_relocatable (flinfo->info))
9731       || ((h->dynindx != -1
9732            || h->forced_local)
9733           && ((bfd_link_pic (flinfo->info)
9734                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9735                    || h->root.type != bfd_link_hash_undefweak))
9736               || !h->forced_local)
9737           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9738     {
9739       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9740              (flinfo->output_bfd, flinfo->info, h, &sym)))
9741         {
9742           eoinfo->failed = TRUE;
9743           return FALSE;
9744         }
9745     }
9746
9747   /* If we are marking the symbol as undefined, and there are no
9748      non-weak references to this symbol from a regular object, then
9749      mark the symbol as weak undefined; if there are non-weak
9750      references, mark the symbol as strong.  We can't do this earlier,
9751      because it might not be marked as undefined until the
9752      finish_dynamic_symbol routine gets through with it.  */
9753   if (sym.st_shndx == SHN_UNDEF
9754       && h->ref_regular
9755       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9756           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9757     {
9758       int bindtype;
9759       type = ELF_ST_TYPE (sym.st_info);
9760
9761       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9762       if (type == STT_GNU_IFUNC)
9763         type = STT_FUNC;
9764
9765       if (h->ref_regular_nonweak)
9766         bindtype = STB_GLOBAL;
9767       else
9768         bindtype = STB_WEAK;
9769       sym.st_info = ELF_ST_INFO (bindtype, type);
9770     }
9771
9772   /* If this is a symbol defined in a dynamic library, don't use the
9773      symbol size from the dynamic library.  Relinking an executable
9774      against a new library may introduce gratuitous changes in the
9775      executable's symbols if we keep the size.  */
9776   if (sym.st_shndx == SHN_UNDEF
9777       && !h->def_regular
9778       && h->def_dynamic)
9779     sym.st_size = 0;
9780
9781   /* If a non-weak symbol with non-default visibility is not defined
9782      locally, it is a fatal error.  */
9783   if (!bfd_link_relocatable (flinfo->info)
9784       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9785       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9786       && h->root.type == bfd_link_hash_undefined
9787       && !h->def_regular)
9788     {
9789       const char *msg;
9790
9791       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9792         /* xgettext:c-format */
9793         msg = _("%B: protected symbol `%s' isn't defined");
9794       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9795         /* xgettext:c-format */
9796         msg = _("%B: internal symbol `%s' isn't defined");
9797       else
9798         /* xgettext:c-format */
9799         msg = _("%B: hidden symbol `%s' isn't defined");
9800       _bfd_error_handler (msg, flinfo->output_bfd, h->root.root.string);
9801       bfd_set_error (bfd_error_bad_value);
9802       eoinfo->failed = TRUE;
9803       return FALSE;
9804     }
9805
9806   /* If this symbol should be put in the .dynsym section, then put it
9807      there now.  We already know the symbol index.  We also fill in
9808      the entry in the .hash section.  */
9809   if (elf_hash_table (flinfo->info)->dynsym != NULL
9810       && h->dynindx != -1
9811       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9812     {
9813       bfd_byte *esym;
9814
9815       /* Since there is no version information in the dynamic string,
9816          if there is no version info in symbol version section, we will
9817          have a run-time problem if not linking executable, referenced
9818          by shared library, or not bound locally.  */
9819       if (h->verinfo.verdef == NULL
9820           && (!bfd_link_executable (flinfo->info)
9821               || h->ref_dynamic
9822               || !h->def_regular))
9823         {
9824           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9825
9826           if (p && p [1] != '\0')
9827             {
9828               _bfd_error_handler
9829                 /* xgettext:c-format */
9830                 (_("%B: No symbol version section for versioned symbol `%s'"),
9831                  flinfo->output_bfd, h->root.root.string);
9832               eoinfo->failed = TRUE;
9833               return FALSE;
9834             }
9835         }
9836
9837       sym.st_name = h->dynstr_index;
9838       esym = (elf_hash_table (flinfo->info)->dynsym->contents
9839               + h->dynindx * bed->s->sizeof_sym);
9840       if (!check_dynsym (flinfo->output_bfd, &sym))
9841         {
9842           eoinfo->failed = TRUE;
9843           return FALSE;
9844         }
9845       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9846
9847       if (flinfo->hash_sec != NULL)
9848         {
9849           size_t hash_entry_size;
9850           bfd_byte *bucketpos;
9851           bfd_vma chain;
9852           size_t bucketcount;
9853           size_t bucket;
9854
9855           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9856           bucket = h->u.elf_hash_value % bucketcount;
9857
9858           hash_entry_size
9859             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9860           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9861                        + (bucket + 2) * hash_entry_size);
9862           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9863           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9864                    bucketpos);
9865           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9866                    ((bfd_byte *) flinfo->hash_sec->contents
9867                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9868         }
9869
9870       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9871         {
9872           Elf_Internal_Versym iversym;
9873           Elf_External_Versym *eversym;
9874
9875           if (!h->def_regular)
9876             {
9877               if (h->verinfo.verdef == NULL
9878                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9879                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9880                 iversym.vs_vers = 0;
9881               else
9882                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9883             }
9884           else
9885             {
9886               if (h->verinfo.vertree == NULL)
9887                 iversym.vs_vers = 1;
9888               else
9889                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9890               if (flinfo->info->create_default_symver)
9891                 iversym.vs_vers++;
9892             }
9893
9894           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
9895              defined locally.  */
9896           if (h->versioned == versioned_hidden && h->def_regular)
9897             iversym.vs_vers |= VERSYM_HIDDEN;
9898
9899           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
9900           eversym += h->dynindx;
9901           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
9902         }
9903     }
9904
9905   /* If the symbol is undefined, and we didn't output it to .dynsym,
9906      strip it from .symtab too.  Obviously we can't do this for
9907      relocatable output or when needed for --emit-relocs.  */
9908   else if (input_sec == bfd_und_section_ptr
9909            && h->indx != -2
9910            && !bfd_link_relocatable (flinfo->info))
9911     return TRUE;
9912   /* Also strip others that we couldn't earlier due to dynamic symbol
9913      processing.  */
9914   if (strip)
9915     return TRUE;
9916   if ((input_sec->flags & SEC_EXCLUDE) != 0)
9917     return TRUE;
9918
9919   /* Output a FILE symbol so that following locals are not associated
9920      with the wrong input file.  We need one for forced local symbols
9921      if we've seen more than one FILE symbol or when we have exactly
9922      one FILE symbol but global symbols are present in a file other
9923      than the one with the FILE symbol.  We also need one if linker
9924      defined symbols are present.  In practice these conditions are
9925      always met, so just emit the FILE symbol unconditionally.  */
9926   if (eoinfo->localsyms
9927       && !eoinfo->file_sym_done
9928       && eoinfo->flinfo->filesym_count != 0)
9929     {
9930       Elf_Internal_Sym fsym;
9931
9932       memset (&fsym, 0, sizeof (fsym));
9933       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9934       fsym.st_shndx = SHN_ABS;
9935       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
9936                                       bfd_und_section_ptr, NULL))
9937         return FALSE;
9938
9939       eoinfo->file_sym_done = TRUE;
9940     }
9941
9942   indx = bfd_get_symcount (flinfo->output_bfd);
9943   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
9944                                    input_sec, h);
9945   if (ret == 0)
9946     {
9947       eoinfo->failed = TRUE;
9948       return FALSE;
9949     }
9950   else if (ret == 1)
9951     h->indx = indx;
9952   else if (h->indx == -2)
9953     abort();
9954
9955   return TRUE;
9956 }
9957
9958 /* Return TRUE if special handling is done for relocs in SEC against
9959    symbols defined in discarded sections.  */
9960
9961 static bfd_boolean
9962 elf_section_ignore_discarded_relocs (asection *sec)
9963 {
9964   const struct elf_backend_data *bed;
9965
9966   switch (sec->sec_info_type)
9967     {
9968     case SEC_INFO_TYPE_STABS:
9969     case SEC_INFO_TYPE_EH_FRAME:
9970     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
9971       return TRUE;
9972     default:
9973       break;
9974     }
9975
9976   bed = get_elf_backend_data (sec->owner);
9977   if (bed->elf_backend_ignore_discarded_relocs != NULL
9978       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
9979     return TRUE;
9980
9981   return FALSE;
9982 }
9983
9984 /* Return a mask saying how ld should treat relocations in SEC against
9985    symbols defined in discarded sections.  If this function returns
9986    COMPLAIN set, ld will issue a warning message.  If this function
9987    returns PRETEND set, and the discarded section was link-once and the
9988    same size as the kept link-once section, ld will pretend that the
9989    symbol was actually defined in the kept section.  Otherwise ld will
9990    zero the reloc (at least that is the intent, but some cooperation by
9991    the target dependent code is needed, particularly for REL targets).  */
9992
9993 unsigned int
9994 _bfd_elf_default_action_discarded (asection *sec)
9995 {
9996   if (sec->flags & SEC_DEBUGGING)
9997     return PRETEND;
9998
9999   if (strcmp (".eh_frame", sec->name) == 0)
10000     return 0;
10001
10002   if (strcmp (".gcc_except_table", sec->name) == 0)
10003     return 0;
10004
10005   return COMPLAIN | PRETEND;
10006 }
10007
10008 /* Find a match between a section and a member of a section group.  */
10009
10010 static asection *
10011 match_group_member (asection *sec, asection *group,
10012                     struct bfd_link_info *info)
10013 {
10014   asection *first = elf_next_in_group (group);
10015   asection *s = first;
10016
10017   while (s != NULL)
10018     {
10019       if (bfd_elf_match_symbols_in_sections (s, sec, info))
10020         return s;
10021
10022       s = elf_next_in_group (s);
10023       if (s == first)
10024         break;
10025     }
10026
10027   return NULL;
10028 }
10029
10030 /* Check if the kept section of a discarded section SEC can be used
10031    to replace it.  Return the replacement if it is OK.  Otherwise return
10032    NULL.  */
10033
10034 asection *
10035 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
10036 {
10037   asection *kept;
10038
10039   kept = sec->kept_section;
10040   if (kept != NULL)
10041     {
10042       if ((kept->flags & SEC_GROUP) != 0)
10043         kept = match_group_member (sec, kept, info);
10044       if (kept != NULL
10045           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
10046               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
10047         kept = NULL;
10048       sec->kept_section = kept;
10049     }
10050   return kept;
10051 }
10052
10053 /* Link an input file into the linker output file.  This function
10054    handles all the sections and relocations of the input file at once.
10055    This is so that we only have to read the local symbols once, and
10056    don't have to keep them in memory.  */
10057
10058 static bfd_boolean
10059 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
10060 {
10061   int (*relocate_section)
10062     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
10063      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
10064   bfd *output_bfd;
10065   Elf_Internal_Shdr *symtab_hdr;
10066   size_t locsymcount;
10067   size_t extsymoff;
10068   Elf_Internal_Sym *isymbuf;
10069   Elf_Internal_Sym *isym;
10070   Elf_Internal_Sym *isymend;
10071   long *pindex;
10072   asection **ppsection;
10073   asection *o;
10074   const struct elf_backend_data *bed;
10075   struct elf_link_hash_entry **sym_hashes;
10076   bfd_size_type address_size;
10077   bfd_vma r_type_mask;
10078   int r_sym_shift;
10079   bfd_boolean have_file_sym = FALSE;
10080
10081   output_bfd = flinfo->output_bfd;
10082   bed = get_elf_backend_data (output_bfd);
10083   relocate_section = bed->elf_backend_relocate_section;
10084
10085   /* If this is a dynamic object, we don't want to do anything here:
10086      we don't want the local symbols, and we don't want the section
10087      contents.  */
10088   if ((input_bfd->flags & DYNAMIC) != 0)
10089     return TRUE;
10090
10091   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
10092   if (elf_bad_symtab (input_bfd))
10093     {
10094       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
10095       extsymoff = 0;
10096     }
10097   else
10098     {
10099       locsymcount = symtab_hdr->sh_info;
10100       extsymoff = symtab_hdr->sh_info;
10101     }
10102
10103   /* Read the local symbols.  */
10104   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
10105   if (isymbuf == NULL && locsymcount != 0)
10106     {
10107       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
10108                                       flinfo->internal_syms,
10109                                       flinfo->external_syms,
10110                                       flinfo->locsym_shndx);
10111       if (isymbuf == NULL)
10112         return FALSE;
10113     }
10114
10115   /* Find local symbol sections and adjust values of symbols in
10116      SEC_MERGE sections.  Write out those local symbols we know are
10117      going into the output file.  */
10118   isymend = isymbuf + locsymcount;
10119   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
10120        isym < isymend;
10121        isym++, pindex++, ppsection++)
10122     {
10123       asection *isec;
10124       const char *name;
10125       Elf_Internal_Sym osym;
10126       long indx;
10127       int ret;
10128
10129       *pindex = -1;
10130
10131       if (elf_bad_symtab (input_bfd))
10132         {
10133           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
10134             {
10135               *ppsection = NULL;
10136               continue;
10137             }
10138         }
10139
10140       if (isym->st_shndx == SHN_UNDEF)
10141         isec = bfd_und_section_ptr;
10142       else if (isym->st_shndx == SHN_ABS)
10143         isec = bfd_abs_section_ptr;
10144       else if (isym->st_shndx == SHN_COMMON)
10145         isec = bfd_com_section_ptr;
10146       else
10147         {
10148           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
10149           if (isec == NULL)
10150             {
10151               /* Don't attempt to output symbols with st_shnx in the
10152                  reserved range other than SHN_ABS and SHN_COMMON.  */
10153               *ppsection = NULL;
10154               continue;
10155             }
10156           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
10157                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
10158             isym->st_value =
10159               _bfd_merged_section_offset (output_bfd, &isec,
10160                                           elf_section_data (isec)->sec_info,
10161                                           isym->st_value);
10162         }
10163
10164       *ppsection = isec;
10165
10166       /* Don't output the first, undefined, symbol.  In fact, don't
10167          output any undefined local symbol.  */
10168       if (isec == bfd_und_section_ptr)
10169         continue;
10170
10171       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
10172         {
10173           /* We never output section symbols.  Instead, we use the
10174              section symbol of the corresponding section in the output
10175              file.  */
10176           continue;
10177         }
10178
10179       /* If we are stripping all symbols, we don't want to output this
10180          one.  */
10181       if (flinfo->info->strip == strip_all)
10182         continue;
10183
10184       /* If we are discarding all local symbols, we don't want to
10185          output this one.  If we are generating a relocatable output
10186          file, then some of the local symbols may be required by
10187          relocs; we output them below as we discover that they are
10188          needed.  */
10189       if (flinfo->info->discard == discard_all)
10190         continue;
10191
10192       /* If this symbol is defined in a section which we are
10193          discarding, we don't need to keep it.  */
10194       if (isym->st_shndx != SHN_UNDEF
10195           && isym->st_shndx < SHN_LORESERVE
10196           && bfd_section_removed_from_list (output_bfd,
10197                                             isec->output_section))
10198         continue;
10199
10200       /* Get the name of the symbol.  */
10201       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
10202                                               isym->st_name);
10203       if (name == NULL)
10204         return FALSE;
10205
10206       /* See if we are discarding symbols with this name.  */
10207       if ((flinfo->info->strip == strip_some
10208            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
10209                == NULL))
10210           || (((flinfo->info->discard == discard_sec_merge
10211                 && (isec->flags & SEC_MERGE)
10212                 && !bfd_link_relocatable (flinfo->info))
10213                || flinfo->info->discard == discard_l)
10214               && bfd_is_local_label_name (input_bfd, name)))
10215         continue;
10216
10217       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
10218         {
10219           if (input_bfd->lto_output)
10220             /* -flto puts a temp file name here.  This means builds
10221                are not reproducible.  Discard the symbol.  */
10222             continue;
10223           have_file_sym = TRUE;
10224           flinfo->filesym_count += 1;
10225         }
10226       if (!have_file_sym)
10227         {
10228           /* In the absence of debug info, bfd_find_nearest_line uses
10229              FILE symbols to determine the source file for local
10230              function symbols.  Provide a FILE symbol here if input
10231              files lack such, so that their symbols won't be
10232              associated with a previous input file.  It's not the
10233              source file, but the best we can do.  */
10234           have_file_sym = TRUE;
10235           flinfo->filesym_count += 1;
10236           memset (&osym, 0, sizeof (osym));
10237           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10238           osym.st_shndx = SHN_ABS;
10239           if (!elf_link_output_symstrtab (flinfo,
10240                                           (input_bfd->lto_output ? NULL
10241                                            : input_bfd->filename),
10242                                           &osym, bfd_abs_section_ptr,
10243                                           NULL))
10244             return FALSE;
10245         }
10246
10247       osym = *isym;
10248
10249       /* Adjust the section index for the output file.  */
10250       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10251                                                          isec->output_section);
10252       if (osym.st_shndx == SHN_BAD)
10253         return FALSE;
10254
10255       /* ELF symbols in relocatable files are section relative, but
10256          in executable files they are virtual addresses.  Note that
10257          this code assumes that all ELF sections have an associated
10258          BFD section with a reasonable value for output_offset; below
10259          we assume that they also have a reasonable value for
10260          output_section.  Any special sections must be set up to meet
10261          these requirements.  */
10262       osym.st_value += isec->output_offset;
10263       if (!bfd_link_relocatable (flinfo->info))
10264         {
10265           osym.st_value += isec->output_section->vma;
10266           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
10267             {
10268               /* STT_TLS symbols are relative to PT_TLS segment base.  */
10269               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
10270               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
10271             }
10272         }
10273
10274       indx = bfd_get_symcount (output_bfd);
10275       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
10276       if (ret == 0)
10277         return FALSE;
10278       else if (ret == 1)
10279         *pindex = indx;
10280     }
10281
10282   if (bed->s->arch_size == 32)
10283     {
10284       r_type_mask = 0xff;
10285       r_sym_shift = 8;
10286       address_size = 4;
10287     }
10288   else
10289     {
10290       r_type_mask = 0xffffffff;
10291       r_sym_shift = 32;
10292       address_size = 8;
10293     }
10294
10295   /* Relocate the contents of each section.  */
10296   sym_hashes = elf_sym_hashes (input_bfd);
10297   for (o = input_bfd->sections; o != NULL; o = o->next)
10298     {
10299       bfd_byte *contents;
10300
10301       if (! o->linker_mark)
10302         {
10303           /* This section was omitted from the link.  */
10304           continue;
10305         }
10306
10307       if (!flinfo->info->resolve_section_groups
10308           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
10309         {
10310           /* Deal with the group signature symbol.  */
10311           struct bfd_elf_section_data *sec_data = elf_section_data (o);
10312           unsigned long symndx = sec_data->this_hdr.sh_info;
10313           asection *osec = o->output_section;
10314
10315           BFD_ASSERT (bfd_link_relocatable (flinfo->info));
10316           if (symndx >= locsymcount
10317               || (elf_bad_symtab (input_bfd)
10318                   && flinfo->sections[symndx] == NULL))
10319             {
10320               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
10321               while (h->root.type == bfd_link_hash_indirect
10322                      || h->root.type == bfd_link_hash_warning)
10323                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
10324               /* Arrange for symbol to be output.  */
10325               h->indx = -2;
10326               elf_section_data (osec)->this_hdr.sh_info = -2;
10327             }
10328           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
10329             {
10330               /* We'll use the output section target_index.  */
10331               asection *sec = flinfo->sections[symndx]->output_section;
10332               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
10333             }
10334           else
10335             {
10336               if (flinfo->indices[symndx] == -1)
10337                 {
10338                   /* Otherwise output the local symbol now.  */
10339                   Elf_Internal_Sym sym = isymbuf[symndx];
10340                   asection *sec = flinfo->sections[symndx]->output_section;
10341                   const char *name;
10342                   long indx;
10343                   int ret;
10344
10345                   name = bfd_elf_string_from_elf_section (input_bfd,
10346                                                           symtab_hdr->sh_link,
10347                                                           sym.st_name);
10348                   if (name == NULL)
10349                     return FALSE;
10350
10351                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10352                                                                     sec);
10353                   if (sym.st_shndx == SHN_BAD)
10354                     return FALSE;
10355
10356                   sym.st_value += o->output_offset;
10357
10358                   indx = bfd_get_symcount (output_bfd);
10359                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
10360                                                    NULL);
10361                   if (ret == 0)
10362                     return FALSE;
10363                   else if (ret == 1)
10364                     flinfo->indices[symndx] = indx;
10365                   else
10366                     abort ();
10367                 }
10368               elf_section_data (osec)->this_hdr.sh_info
10369                 = flinfo->indices[symndx];
10370             }
10371         }
10372
10373       if ((o->flags & SEC_HAS_CONTENTS) == 0
10374           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
10375         continue;
10376
10377       if ((o->flags & SEC_LINKER_CREATED) != 0)
10378         {
10379           /* Section was created by _bfd_elf_link_create_dynamic_sections
10380              or somesuch.  */
10381           continue;
10382         }
10383
10384       /* Get the contents of the section.  They have been cached by a
10385          relaxation routine.  Note that o is a section in an input
10386          file, so the contents field will not have been set by any of
10387          the routines which work on output files.  */
10388       if (elf_section_data (o)->this_hdr.contents != NULL)
10389         {
10390           contents = elf_section_data (o)->this_hdr.contents;
10391           if (bed->caches_rawsize
10392               && o->rawsize != 0
10393               && o->rawsize < o->size)
10394             {
10395               memcpy (flinfo->contents, contents, o->rawsize);
10396               contents = flinfo->contents;
10397             }
10398         }
10399       else
10400         {
10401           contents = flinfo->contents;
10402           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
10403             return FALSE;
10404         }
10405
10406       if ((o->flags & SEC_RELOC) != 0)
10407         {
10408           Elf_Internal_Rela *internal_relocs;
10409           Elf_Internal_Rela *rel, *relend;
10410           int action_discarded;
10411           int ret;
10412
10413           /* Get the swapped relocs.  */
10414           internal_relocs
10415             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
10416                                          flinfo->internal_relocs, FALSE);
10417           if (internal_relocs == NULL
10418               && o->reloc_count > 0)
10419             return FALSE;
10420
10421           /* We need to reverse-copy input .ctors/.dtors sections if
10422              they are placed in .init_array/.finit_array for output.  */
10423           if (o->size > address_size
10424               && ((strncmp (o->name, ".ctors", 6) == 0
10425                    && strcmp (o->output_section->name,
10426                               ".init_array") == 0)
10427                   || (strncmp (o->name, ".dtors", 6) == 0
10428                       && strcmp (o->output_section->name,
10429                                  ".fini_array") == 0))
10430               && (o->name[6] == 0 || o->name[6] == '.'))
10431             {
10432               if (o->size * bed->s->int_rels_per_ext_rel
10433                   != o->reloc_count * address_size)
10434                 {
10435                   _bfd_error_handler
10436                     /* xgettext:c-format */
10437                     (_("error: %B: size of section %A is not "
10438                        "multiple of address size"),
10439                      input_bfd, o);
10440                   bfd_set_error (bfd_error_on_input);
10441                   return FALSE;
10442                 }
10443               o->flags |= SEC_ELF_REVERSE_COPY;
10444             }
10445
10446           action_discarded = -1;
10447           if (!elf_section_ignore_discarded_relocs (o))
10448             action_discarded = (*bed->action_discarded) (o);
10449
10450           /* Run through the relocs evaluating complex reloc symbols and
10451              looking for relocs against symbols from discarded sections
10452              or section symbols from removed link-once sections.
10453              Complain about relocs against discarded sections.  Zero
10454              relocs against removed link-once sections.  */
10455
10456           rel = internal_relocs;
10457           relend = rel + o->reloc_count;
10458           for ( ; rel < relend; rel++)
10459             {
10460               unsigned long r_symndx = rel->r_info >> r_sym_shift;
10461               unsigned int s_type;
10462               asection **ps, *sec;
10463               struct elf_link_hash_entry *h = NULL;
10464               const char *sym_name;
10465
10466               if (r_symndx == STN_UNDEF)
10467                 continue;
10468
10469               if (r_symndx >= locsymcount
10470                   || (elf_bad_symtab (input_bfd)
10471                       && flinfo->sections[r_symndx] == NULL))
10472                 {
10473                   h = sym_hashes[r_symndx - extsymoff];
10474
10475                   /* Badly formatted input files can contain relocs that
10476                      reference non-existant symbols.  Check here so that
10477                      we do not seg fault.  */
10478                   if (h == NULL)
10479                     {
10480                       char buffer [32];
10481
10482                       sprintf_vma (buffer, rel->r_info);
10483                       _bfd_error_handler
10484                         /* xgettext:c-format */
10485                         (_("error: %B contains a reloc (0x%s) for section %A "
10486                            "that references a non-existent global symbol"),
10487                          input_bfd, buffer, o);
10488                       bfd_set_error (bfd_error_bad_value);
10489                       return FALSE;
10490                     }
10491
10492                   while (h->root.type == bfd_link_hash_indirect
10493                          || h->root.type == bfd_link_hash_warning)
10494                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10495
10496                   s_type = h->type;
10497
10498                   /* If a plugin symbol is referenced from a non-IR file,
10499                      mark the symbol as undefined.  Note that the
10500                      linker may attach linker created dynamic sections
10501                      to the plugin bfd.  Symbols defined in linker
10502                      created sections are not plugin symbols.  */
10503                   if ((h->root.non_ir_ref_regular
10504                        || h->root.non_ir_ref_dynamic)
10505                       && (h->root.type == bfd_link_hash_defined
10506                           || h->root.type == bfd_link_hash_defweak)
10507                       && (h->root.u.def.section->flags
10508                           & SEC_LINKER_CREATED) == 0
10509                       && h->root.u.def.section->owner != NULL
10510                       && (h->root.u.def.section->owner->flags
10511                           & BFD_PLUGIN) != 0)
10512                     {
10513                       h->root.type = bfd_link_hash_undefined;
10514                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10515                     }
10516
10517                   ps = NULL;
10518                   if (h->root.type == bfd_link_hash_defined
10519                       || h->root.type == bfd_link_hash_defweak)
10520                     ps = &h->root.u.def.section;
10521
10522                   sym_name = h->root.root.string;
10523                 }
10524               else
10525                 {
10526                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10527
10528                   s_type = ELF_ST_TYPE (sym->st_info);
10529                   ps = &flinfo->sections[r_symndx];
10530                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10531                                                sym, *ps);
10532                 }
10533
10534               if ((s_type == STT_RELC || s_type == STT_SRELC)
10535                   && !bfd_link_relocatable (flinfo->info))
10536                 {
10537                   bfd_vma val;
10538                   bfd_vma dot = (rel->r_offset
10539                                  + o->output_offset + o->output_section->vma);
10540 #ifdef DEBUG
10541                   printf ("Encountered a complex symbol!");
10542                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10543                           input_bfd->filename, o->name,
10544                           (long) (rel - internal_relocs));
10545                   printf (" symbol: idx  %8.8lx, name %s\n",
10546                           r_symndx, sym_name);
10547                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10548                           (unsigned long) rel->r_info,
10549                           (unsigned long) rel->r_offset);
10550 #endif
10551                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10552                                     isymbuf, locsymcount, s_type == STT_SRELC))
10553                     return FALSE;
10554
10555                   /* Symbol evaluated OK.  Update to absolute value.  */
10556                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10557                                     r_symndx, val);
10558                   continue;
10559                 }
10560
10561               if (action_discarded != -1 && ps != NULL)
10562                 {
10563                   /* Complain if the definition comes from a
10564                      discarded section.  */
10565                   if ((sec = *ps) != NULL && discarded_section (sec))
10566                     {
10567                       BFD_ASSERT (r_symndx != STN_UNDEF);
10568                       if (action_discarded & COMPLAIN)
10569                         (*flinfo->info->callbacks->einfo)
10570                           /* xgettext:c-format */
10571                           (_("%X`%s' referenced in section `%A' of %B: "
10572                              "defined in discarded section `%A' of %B\n"),
10573                            sym_name, o, input_bfd, sec, sec->owner);
10574
10575                       /* Try to do the best we can to support buggy old
10576                          versions of gcc.  Pretend that the symbol is
10577                          really defined in the kept linkonce section.
10578                          FIXME: This is quite broken.  Modifying the
10579                          symbol here means we will be changing all later
10580                          uses of the symbol, not just in this section.  */
10581                       if (action_discarded & PRETEND)
10582                         {
10583                           asection *kept;
10584
10585                           kept = _bfd_elf_check_kept_section (sec,
10586                                                               flinfo->info);
10587                           if (kept != NULL)
10588                             {
10589                               *ps = kept;
10590                               continue;
10591                             }
10592                         }
10593                     }
10594                 }
10595             }
10596
10597           /* Relocate the section by invoking a back end routine.
10598
10599              The back end routine is responsible for adjusting the
10600              section contents as necessary, and (if using Rela relocs
10601              and generating a relocatable output file) adjusting the
10602              reloc addend as necessary.
10603
10604              The back end routine does not have to worry about setting
10605              the reloc address or the reloc symbol index.
10606
10607              The back end routine is given a pointer to the swapped in
10608              internal symbols, and can access the hash table entries
10609              for the external symbols via elf_sym_hashes (input_bfd).
10610
10611              When generating relocatable output, the back end routine
10612              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10613              output symbol is going to be a section symbol
10614              corresponding to the output section, which will require
10615              the addend to be adjusted.  */
10616
10617           ret = (*relocate_section) (output_bfd, flinfo->info,
10618                                      input_bfd, o, contents,
10619                                      internal_relocs,
10620                                      isymbuf,
10621                                      flinfo->sections);
10622           if (!ret)
10623             return FALSE;
10624
10625           if (ret == 2
10626               || bfd_link_relocatable (flinfo->info)
10627               || flinfo->info->emitrelocations)
10628             {
10629               Elf_Internal_Rela *irela;
10630               Elf_Internal_Rela *irelaend, *irelamid;
10631               bfd_vma last_offset;
10632               struct elf_link_hash_entry **rel_hash;
10633               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10634               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10635               unsigned int next_erel;
10636               bfd_boolean rela_normal;
10637               struct bfd_elf_section_data *esdi, *esdo;
10638
10639               esdi = elf_section_data (o);
10640               esdo = elf_section_data (o->output_section);
10641               rela_normal = FALSE;
10642
10643               /* Adjust the reloc addresses and symbol indices.  */
10644
10645               irela = internal_relocs;
10646               irelaend = irela + o->reloc_count;
10647               rel_hash = esdo->rel.hashes + esdo->rel.count;
10648               /* We start processing the REL relocs, if any.  When we reach
10649                  IRELAMID in the loop, we switch to the RELA relocs.  */
10650               irelamid = irela;
10651               if (esdi->rel.hdr != NULL)
10652                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10653                              * bed->s->int_rels_per_ext_rel);
10654               rel_hash_list = rel_hash;
10655               rela_hash_list = NULL;
10656               last_offset = o->output_offset;
10657               if (!bfd_link_relocatable (flinfo->info))
10658                 last_offset += o->output_section->vma;
10659               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10660                 {
10661                   unsigned long r_symndx;
10662                   asection *sec;
10663                   Elf_Internal_Sym sym;
10664
10665                   if (next_erel == bed->s->int_rels_per_ext_rel)
10666                     {
10667                       rel_hash++;
10668                       next_erel = 0;
10669                     }
10670
10671                   if (irela == irelamid)
10672                     {
10673                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10674                       rela_hash_list = rel_hash;
10675                       rela_normal = bed->rela_normal;
10676                     }
10677
10678                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10679                                                              flinfo->info, o,
10680                                                              irela->r_offset);
10681                   if (irela->r_offset >= (bfd_vma) -2)
10682                     {
10683                       /* This is a reloc for a deleted entry or somesuch.
10684                          Turn it into an R_*_NONE reloc, at the same
10685                          offset as the last reloc.  elf_eh_frame.c and
10686                          bfd_elf_discard_info rely on reloc offsets
10687                          being ordered.  */
10688                       irela->r_offset = last_offset;
10689                       irela->r_info = 0;
10690                       irela->r_addend = 0;
10691                       continue;
10692                     }
10693
10694                   irela->r_offset += o->output_offset;
10695
10696                   /* Relocs in an executable have to be virtual addresses.  */
10697                   if (!bfd_link_relocatable (flinfo->info))
10698                     irela->r_offset += o->output_section->vma;
10699
10700                   last_offset = irela->r_offset;
10701
10702                   r_symndx = irela->r_info >> r_sym_shift;
10703                   if (r_symndx == STN_UNDEF)
10704                     continue;
10705
10706                   if (r_symndx >= locsymcount
10707                       || (elf_bad_symtab (input_bfd)
10708                           && flinfo->sections[r_symndx] == NULL))
10709                     {
10710                       struct elf_link_hash_entry *rh;
10711                       unsigned long indx;
10712
10713                       /* This is a reloc against a global symbol.  We
10714                          have not yet output all the local symbols, so
10715                          we do not know the symbol index of any global
10716                          symbol.  We set the rel_hash entry for this
10717                          reloc to point to the global hash table entry
10718                          for this symbol.  The symbol index is then
10719                          set at the end of bfd_elf_final_link.  */
10720                       indx = r_symndx - extsymoff;
10721                       rh = elf_sym_hashes (input_bfd)[indx];
10722                       while (rh->root.type == bfd_link_hash_indirect
10723                              || rh->root.type == bfd_link_hash_warning)
10724                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10725
10726                       /* Setting the index to -2 tells
10727                          elf_link_output_extsym that this symbol is
10728                          used by a reloc.  */
10729                       BFD_ASSERT (rh->indx < 0);
10730                       rh->indx = -2;
10731                       *rel_hash = rh;
10732
10733                       continue;
10734                     }
10735
10736                   /* This is a reloc against a local symbol.  */
10737
10738                   *rel_hash = NULL;
10739                   sym = isymbuf[r_symndx];
10740                   sec = flinfo->sections[r_symndx];
10741                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10742                     {
10743                       /* I suppose the backend ought to fill in the
10744                          section of any STT_SECTION symbol against a
10745                          processor specific section.  */
10746                       r_symndx = STN_UNDEF;
10747                       if (bfd_is_abs_section (sec))
10748                         ;
10749                       else if (sec == NULL || sec->owner == NULL)
10750                         {
10751                           bfd_set_error (bfd_error_bad_value);
10752                           return FALSE;
10753                         }
10754                       else
10755                         {
10756                           asection *osec = sec->output_section;
10757
10758                           /* If we have discarded a section, the output
10759                              section will be the absolute section.  In
10760                              case of discarded SEC_MERGE sections, use
10761                              the kept section.  relocate_section should
10762                              have already handled discarded linkonce
10763                              sections.  */
10764                           if (bfd_is_abs_section (osec)
10765                               && sec->kept_section != NULL
10766                               && sec->kept_section->output_section != NULL)
10767                             {
10768                               osec = sec->kept_section->output_section;
10769                               irela->r_addend -= osec->vma;
10770                             }
10771
10772                           if (!bfd_is_abs_section (osec))
10773                             {
10774                               r_symndx = osec->target_index;
10775                               if (r_symndx == STN_UNDEF)
10776                                 {
10777                                   irela->r_addend += osec->vma;
10778                                   osec = _bfd_nearby_section (output_bfd, osec,
10779                                                               osec->vma);
10780                                   irela->r_addend -= osec->vma;
10781                                   r_symndx = osec->target_index;
10782                                 }
10783                             }
10784                         }
10785
10786                       /* Adjust the addend according to where the
10787                          section winds up in the output section.  */
10788                       if (rela_normal)
10789                         irela->r_addend += sec->output_offset;
10790                     }
10791                   else
10792                     {
10793                       if (flinfo->indices[r_symndx] == -1)
10794                         {
10795                           unsigned long shlink;
10796                           const char *name;
10797                           asection *osec;
10798                           long indx;
10799
10800                           if (flinfo->info->strip == strip_all)
10801                             {
10802                               /* You can't do ld -r -s.  */
10803                               bfd_set_error (bfd_error_invalid_operation);
10804                               return FALSE;
10805                             }
10806
10807                           /* This symbol was skipped earlier, but
10808                              since it is needed by a reloc, we
10809                              must output it now.  */
10810                           shlink = symtab_hdr->sh_link;
10811                           name = (bfd_elf_string_from_elf_section
10812                                   (input_bfd, shlink, sym.st_name));
10813                           if (name == NULL)
10814                             return FALSE;
10815
10816                           osec = sec->output_section;
10817                           sym.st_shndx =
10818                             _bfd_elf_section_from_bfd_section (output_bfd,
10819                                                                osec);
10820                           if (sym.st_shndx == SHN_BAD)
10821                             return FALSE;
10822
10823                           sym.st_value += sec->output_offset;
10824                           if (!bfd_link_relocatable (flinfo->info))
10825                             {
10826                               sym.st_value += osec->vma;
10827                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10828                                 {
10829                                   /* STT_TLS symbols are relative to PT_TLS
10830                                      segment base.  */
10831                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10832                                               ->tls_sec != NULL);
10833                                   sym.st_value -= (elf_hash_table (flinfo->info)
10834                                                    ->tls_sec->vma);
10835                                 }
10836                             }
10837
10838                           indx = bfd_get_symcount (output_bfd);
10839                           ret = elf_link_output_symstrtab (flinfo, name,
10840                                                            &sym, sec,
10841                                                            NULL);
10842                           if (ret == 0)
10843                             return FALSE;
10844                           else if (ret == 1)
10845                             flinfo->indices[r_symndx] = indx;
10846                           else
10847                             abort ();
10848                         }
10849
10850                       r_symndx = flinfo->indices[r_symndx];
10851                     }
10852
10853                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10854                                    | (irela->r_info & r_type_mask));
10855                 }
10856
10857               /* Swap out the relocs.  */
10858               input_rel_hdr = esdi->rel.hdr;
10859               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10860                 {
10861                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10862                                                      input_rel_hdr,
10863                                                      internal_relocs,
10864                                                      rel_hash_list))
10865                     return FALSE;
10866                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10867                                       * bed->s->int_rels_per_ext_rel);
10868                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10869                 }
10870
10871               input_rela_hdr = esdi->rela.hdr;
10872               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10873                 {
10874                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10875                                                      input_rela_hdr,
10876                                                      internal_relocs,
10877                                                      rela_hash_list))
10878                     return FALSE;
10879                 }
10880             }
10881         }
10882
10883       /* Write out the modified section contents.  */
10884       if (bed->elf_backend_write_section
10885           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10886                                                 contents))
10887         {
10888           /* Section written out.  */
10889         }
10890       else switch (o->sec_info_type)
10891         {
10892         case SEC_INFO_TYPE_STABS:
10893           if (! (_bfd_write_section_stabs
10894                  (output_bfd,
10895                   &elf_hash_table (flinfo->info)->stab_info,
10896                   o, &elf_section_data (o)->sec_info, contents)))
10897             return FALSE;
10898           break;
10899         case SEC_INFO_TYPE_MERGE:
10900           if (! _bfd_write_merged_section (output_bfd, o,
10901                                            elf_section_data (o)->sec_info))
10902             return FALSE;
10903           break;
10904         case SEC_INFO_TYPE_EH_FRAME:
10905           {
10906             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
10907                                                    o, contents))
10908               return FALSE;
10909           }
10910           break;
10911         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10912           {
10913             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
10914                                                          flinfo->info,
10915                                                          o, contents))
10916               return FALSE;
10917           }
10918           break;
10919         default:
10920           {
10921             if (! (o->flags & SEC_EXCLUDE))
10922               {
10923                 file_ptr offset = (file_ptr) o->output_offset;
10924                 bfd_size_type todo = o->size;
10925
10926                 offset *= bfd_octets_per_byte (output_bfd);
10927
10928                 if ((o->flags & SEC_ELF_REVERSE_COPY))
10929                   {
10930                     /* Reverse-copy input section to output.  */
10931                     do
10932                       {
10933                         todo -= address_size;
10934                         if (! bfd_set_section_contents (output_bfd,
10935                                                         o->output_section,
10936                                                         contents + todo,
10937                                                         offset,
10938                                                         address_size))
10939                           return FALSE;
10940                         if (todo == 0)
10941                           break;
10942                         offset += address_size;
10943                       }
10944                     while (1);
10945                   }
10946                 else if (! bfd_set_section_contents (output_bfd,
10947                                                      o->output_section,
10948                                                      contents,
10949                                                      offset, todo))
10950                   return FALSE;
10951               }
10952           }
10953           break;
10954         }
10955     }
10956
10957   return TRUE;
10958 }
10959
10960 /* Generate a reloc when linking an ELF file.  This is a reloc
10961    requested by the linker, and does not come from any input file.  This
10962    is used to build constructor and destructor tables when linking
10963    with -Ur.  */
10964
10965 static bfd_boolean
10966 elf_reloc_link_order (bfd *output_bfd,
10967                       struct bfd_link_info *info,
10968                       asection *output_section,
10969                       struct bfd_link_order *link_order)
10970 {
10971   reloc_howto_type *howto;
10972   long indx;
10973   bfd_vma offset;
10974   bfd_vma addend;
10975   struct bfd_elf_section_reloc_data *reldata;
10976   struct elf_link_hash_entry **rel_hash_ptr;
10977   Elf_Internal_Shdr *rel_hdr;
10978   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
10979   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
10980   bfd_byte *erel;
10981   unsigned int i;
10982   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
10983
10984   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
10985   if (howto == NULL)
10986     {
10987       bfd_set_error (bfd_error_bad_value);
10988       return FALSE;
10989     }
10990
10991   addend = link_order->u.reloc.p->addend;
10992
10993   if (esdo->rel.hdr)
10994     reldata = &esdo->rel;
10995   else if (esdo->rela.hdr)
10996     reldata = &esdo->rela;
10997   else
10998     {
10999       reldata = NULL;
11000       BFD_ASSERT (0);
11001     }
11002
11003   /* Figure out the symbol index.  */
11004   rel_hash_ptr = reldata->hashes + reldata->count;
11005   if (link_order->type == bfd_section_reloc_link_order)
11006     {
11007       indx = link_order->u.reloc.p->u.section->target_index;
11008       BFD_ASSERT (indx != 0);
11009       *rel_hash_ptr = NULL;
11010     }
11011   else
11012     {
11013       struct elf_link_hash_entry *h;
11014
11015       /* Treat a reloc against a defined symbol as though it were
11016          actually against the section.  */
11017       h = ((struct elf_link_hash_entry *)
11018            bfd_wrapped_link_hash_lookup (output_bfd, info,
11019                                          link_order->u.reloc.p->u.name,
11020                                          FALSE, FALSE, TRUE));
11021       if (h != NULL
11022           && (h->root.type == bfd_link_hash_defined
11023               || h->root.type == bfd_link_hash_defweak))
11024         {
11025           asection *section;
11026
11027           section = h->root.u.def.section;
11028           indx = section->output_section->target_index;
11029           *rel_hash_ptr = NULL;
11030           /* It seems that we ought to add the symbol value to the
11031              addend here, but in practice it has already been added
11032              because it was passed to constructor_callback.  */
11033           addend += section->output_section->vma + section->output_offset;
11034         }
11035       else if (h != NULL)
11036         {
11037           /* Setting the index to -2 tells elf_link_output_extsym that
11038              this symbol is used by a reloc.  */
11039           h->indx = -2;
11040           *rel_hash_ptr = h;
11041           indx = 0;
11042         }
11043       else
11044         {
11045           (*info->callbacks->unattached_reloc)
11046             (info, link_order->u.reloc.p->u.name, NULL, NULL, 0);
11047           indx = 0;
11048         }
11049     }
11050
11051   /* If this is an inplace reloc, we must write the addend into the
11052      object file.  */
11053   if (howto->partial_inplace && addend != 0)
11054     {
11055       bfd_size_type size;
11056       bfd_reloc_status_type rstat;
11057       bfd_byte *buf;
11058       bfd_boolean ok;
11059       const char *sym_name;
11060
11061       size = (bfd_size_type) bfd_get_reloc_size (howto);
11062       buf = (bfd_byte *) bfd_zmalloc (size);
11063       if (buf == NULL && size != 0)
11064         return FALSE;
11065       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
11066       switch (rstat)
11067         {
11068         case bfd_reloc_ok:
11069           break;
11070
11071         default:
11072         case bfd_reloc_outofrange:
11073           abort ();
11074
11075         case bfd_reloc_overflow:
11076           if (link_order->type == bfd_section_reloc_link_order)
11077             sym_name = bfd_section_name (output_bfd,
11078                                          link_order->u.reloc.p->u.section);
11079           else
11080             sym_name = link_order->u.reloc.p->u.name;
11081           (*info->callbacks->reloc_overflow) (info, NULL, sym_name,
11082                                               howto->name, addend, NULL, NULL,
11083                                               (bfd_vma) 0);
11084           break;
11085         }
11086
11087       ok = bfd_set_section_contents (output_bfd, output_section, buf,
11088                                      link_order->offset
11089                                      * bfd_octets_per_byte (output_bfd),
11090                                      size);
11091       free (buf);
11092       if (! ok)
11093         return FALSE;
11094     }
11095
11096   /* The address of a reloc is relative to the section in a
11097      relocatable file, and is a virtual address in an executable
11098      file.  */
11099   offset = link_order->offset;
11100   if (! bfd_link_relocatable (info))
11101     offset += output_section->vma;
11102
11103   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
11104     {
11105       irel[i].r_offset = offset;
11106       irel[i].r_info = 0;
11107       irel[i].r_addend = 0;
11108     }
11109   if (bed->s->arch_size == 32)
11110     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
11111   else
11112     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
11113
11114   rel_hdr = reldata->hdr;
11115   erel = rel_hdr->contents;
11116   if (rel_hdr->sh_type == SHT_REL)
11117     {
11118       erel += reldata->count * bed->s->sizeof_rel;
11119       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
11120     }
11121   else
11122     {
11123       irel[0].r_addend = addend;
11124       erel += reldata->count * bed->s->sizeof_rela;
11125       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
11126     }
11127
11128   ++reldata->count;
11129
11130   return TRUE;
11131 }
11132
11133
11134 /* Get the output vma of the section pointed to by the sh_link field.  */
11135
11136 static bfd_vma
11137 elf_get_linked_section_vma (struct bfd_link_order *p)
11138 {
11139   Elf_Internal_Shdr **elf_shdrp;
11140   asection *s;
11141   int elfsec;
11142
11143   s = p->u.indirect.section;
11144   elf_shdrp = elf_elfsections (s->owner);
11145   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
11146   elfsec = elf_shdrp[elfsec]->sh_link;
11147   /* PR 290:
11148      The Intel C compiler generates SHT_IA_64_UNWIND with
11149      SHF_LINK_ORDER.  But it doesn't set the sh_link or
11150      sh_info fields.  Hence we could get the situation
11151      where elfsec is 0.  */
11152   if (elfsec == 0)
11153     {
11154       const struct elf_backend_data *bed
11155         = get_elf_backend_data (s->owner);
11156       if (bed->link_order_error_handler)
11157         bed->link_order_error_handler
11158           /* xgettext:c-format */
11159           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
11160       return 0;
11161     }
11162   else
11163     {
11164       s = elf_shdrp[elfsec]->bfd_section;
11165       return s->output_section->vma + s->output_offset;
11166     }
11167 }
11168
11169
11170 /* Compare two sections based on the locations of the sections they are
11171    linked to.  Used by elf_fixup_link_order.  */
11172
11173 static int
11174 compare_link_order (const void * a, const void * b)
11175 {
11176   bfd_vma apos;
11177   bfd_vma bpos;
11178
11179   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
11180   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
11181   if (apos < bpos)
11182     return -1;
11183   return apos > bpos;
11184 }
11185
11186
11187 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
11188    order as their linked sections.  Returns false if this could not be done
11189    because an output section includes both ordered and unordered
11190    sections.  Ideally we'd do this in the linker proper.  */
11191
11192 static bfd_boolean
11193 elf_fixup_link_order (bfd *abfd, asection *o)
11194 {
11195   int seen_linkorder;
11196   int seen_other;
11197   int n;
11198   struct bfd_link_order *p;
11199   bfd *sub;
11200   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11201   unsigned elfsec;
11202   struct bfd_link_order **sections;
11203   asection *s, *other_sec, *linkorder_sec;
11204   bfd_vma offset;
11205
11206   other_sec = NULL;
11207   linkorder_sec = NULL;
11208   seen_other = 0;
11209   seen_linkorder = 0;
11210   for (p = o->map_head.link_order; p != NULL; p = p->next)
11211     {
11212       if (p->type == bfd_indirect_link_order)
11213         {
11214           s = p->u.indirect.section;
11215           sub = s->owner;
11216           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11217               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
11218               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
11219               && elfsec < elf_numsections (sub)
11220               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
11221               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
11222             {
11223               seen_linkorder++;
11224               linkorder_sec = s;
11225             }
11226           else
11227             {
11228               seen_other++;
11229               other_sec = s;
11230             }
11231         }
11232       else
11233         seen_other++;
11234
11235       if (seen_other && seen_linkorder)
11236         {
11237           if (other_sec && linkorder_sec)
11238             _bfd_error_handler
11239               /* xgettext:c-format */
11240               (_("%A has both ordered [`%A' in %B] "
11241                  "and unordered [`%A' in %B] sections"),
11242                o, linkorder_sec, linkorder_sec->owner,
11243                other_sec, other_sec->owner);
11244           else
11245             _bfd_error_handler
11246               (_("%A has both ordered and unordered sections"), o);
11247           bfd_set_error (bfd_error_bad_value);
11248           return FALSE;
11249         }
11250     }
11251
11252   if (!seen_linkorder)
11253     return TRUE;
11254
11255   sections = (struct bfd_link_order **)
11256     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
11257   if (sections == NULL)
11258     return FALSE;
11259   seen_linkorder = 0;
11260
11261   for (p = o->map_head.link_order; p != NULL; p = p->next)
11262     {
11263       sections[seen_linkorder++] = p;
11264     }
11265   /* Sort the input sections in the order of their linked section.  */
11266   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
11267          compare_link_order);
11268
11269   /* Change the offsets of the sections.  */
11270   offset = 0;
11271   for (n = 0; n < seen_linkorder; n++)
11272     {
11273       s = sections[n]->u.indirect.section;
11274       offset &= ~(bfd_vma) 0 << s->alignment_power;
11275       s->output_offset = offset / bfd_octets_per_byte (abfd);
11276       sections[n]->offset = offset;
11277       offset += sections[n]->size;
11278     }
11279
11280   free (sections);
11281   return TRUE;
11282 }
11283
11284 /* Generate an import library in INFO->implib_bfd from symbols in ABFD.
11285    Returns TRUE upon success, FALSE otherwise.  */
11286
11287 static bfd_boolean
11288 elf_output_implib (bfd *abfd, struct bfd_link_info *info)
11289 {
11290   bfd_boolean ret = FALSE;
11291   bfd *implib_bfd;
11292   const struct elf_backend_data *bed;
11293   flagword flags;
11294   enum bfd_architecture arch;
11295   unsigned int mach;
11296   asymbol **sympp = NULL;
11297   long symsize;
11298   long symcount;
11299   long src_count;
11300   elf_symbol_type *osymbuf;
11301
11302   implib_bfd = info->out_implib_bfd;
11303   bed = get_elf_backend_data (abfd);
11304
11305   if (!bfd_set_format (implib_bfd, bfd_object))
11306     return FALSE;
11307
11308   /* Use flag from executable but make it a relocatable object.  */
11309   flags = bfd_get_file_flags (abfd);
11310   flags &= ~HAS_RELOC;
11311   if (!bfd_set_start_address (implib_bfd, 0)
11312       || !bfd_set_file_flags (implib_bfd, flags & ~EXEC_P))
11313     return FALSE;
11314
11315   /* Copy architecture of output file to import library file.  */
11316   arch = bfd_get_arch (abfd);
11317   mach = bfd_get_mach (abfd);
11318   if (!bfd_set_arch_mach (implib_bfd, arch, mach)
11319       && (abfd->target_defaulted
11320           || bfd_get_arch (abfd) != bfd_get_arch (implib_bfd)))
11321     return FALSE;
11322
11323   /* Get symbol table size.  */
11324   symsize = bfd_get_symtab_upper_bound (abfd);
11325   if (symsize < 0)
11326     return FALSE;
11327
11328   /* Read in the symbol table.  */
11329   sympp = (asymbol **) xmalloc (symsize);
11330   symcount = bfd_canonicalize_symtab (abfd, sympp);
11331   if (symcount < 0)
11332     goto free_sym_buf;
11333
11334   /* Allow the BFD backend to copy any private header data it
11335      understands from the output BFD to the import library BFD.  */
11336   if (! bfd_copy_private_header_data (abfd, implib_bfd))
11337     goto free_sym_buf;
11338
11339   /* Filter symbols to appear in the import library.  */
11340   if (bed->elf_backend_filter_implib_symbols)
11341     symcount = bed->elf_backend_filter_implib_symbols (abfd, info, sympp,
11342                                                        symcount);
11343   else
11344     symcount = _bfd_elf_filter_global_symbols (abfd, info, sympp, symcount);
11345   if (symcount == 0)
11346     {
11347       bfd_set_error (bfd_error_no_symbols);
11348       _bfd_error_handler (_("%B: no symbol found for import library"),
11349                           implib_bfd);
11350       goto free_sym_buf;
11351     }
11352
11353
11354   /* Make symbols absolute.  */
11355   osymbuf = (elf_symbol_type *) bfd_alloc2 (implib_bfd, symcount,
11356                                             sizeof (*osymbuf));
11357   for (src_count = 0; src_count < symcount; src_count++)
11358     {
11359       memcpy (&osymbuf[src_count], (elf_symbol_type *) sympp[src_count],
11360               sizeof (*osymbuf));
11361       osymbuf[src_count].symbol.section = bfd_abs_section_ptr;
11362       osymbuf[src_count].internal_elf_sym.st_shndx = SHN_ABS;
11363       osymbuf[src_count].symbol.value += sympp[src_count]->section->vma;
11364       osymbuf[src_count].internal_elf_sym.st_value =
11365         osymbuf[src_count].symbol.value;
11366       sympp[src_count] = &osymbuf[src_count].symbol;
11367     }
11368
11369   bfd_set_symtab (implib_bfd, sympp, symcount);
11370
11371   /* Allow the BFD backend to copy any private data it understands
11372      from the output BFD to the import library BFD.  This is done last
11373      to permit the routine to look at the filtered symbol table.  */
11374   if (! bfd_copy_private_bfd_data (abfd, implib_bfd))
11375     goto free_sym_buf;
11376
11377   if (!bfd_close (implib_bfd))
11378     goto free_sym_buf;
11379
11380   ret = TRUE;
11381
11382 free_sym_buf:
11383   free (sympp);
11384   return ret;
11385 }
11386
11387 static void
11388 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
11389 {
11390   asection *o;
11391
11392   if (flinfo->symstrtab != NULL)
11393     _bfd_elf_strtab_free (flinfo->symstrtab);
11394   if (flinfo->contents != NULL)
11395     free (flinfo->contents);
11396   if (flinfo->external_relocs != NULL)
11397     free (flinfo->external_relocs);
11398   if (flinfo->internal_relocs != NULL)
11399     free (flinfo->internal_relocs);
11400   if (flinfo->external_syms != NULL)
11401     free (flinfo->external_syms);
11402   if (flinfo->locsym_shndx != NULL)
11403     free (flinfo->locsym_shndx);
11404   if (flinfo->internal_syms != NULL)
11405     free (flinfo->internal_syms);
11406   if (flinfo->indices != NULL)
11407     free (flinfo->indices);
11408   if (flinfo->sections != NULL)
11409     free (flinfo->sections);
11410   if (flinfo->symshndxbuf != NULL)
11411     free (flinfo->symshndxbuf);
11412   for (o = obfd->sections; o != NULL; o = o->next)
11413     {
11414       struct bfd_elf_section_data *esdo = elf_section_data (o);
11415       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11416         free (esdo->rel.hashes);
11417       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11418         free (esdo->rela.hashes);
11419     }
11420 }
11421
11422 /* Do the final step of an ELF link.  */
11423
11424 bfd_boolean
11425 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
11426 {
11427   bfd_boolean dynamic;
11428   bfd_boolean emit_relocs;
11429   bfd *dynobj;
11430   struct elf_final_link_info flinfo;
11431   asection *o;
11432   struct bfd_link_order *p;
11433   bfd *sub;
11434   bfd_size_type max_contents_size;
11435   bfd_size_type max_external_reloc_size;
11436   bfd_size_type max_internal_reloc_count;
11437   bfd_size_type max_sym_count;
11438   bfd_size_type max_sym_shndx_count;
11439   Elf_Internal_Sym elfsym;
11440   unsigned int i;
11441   Elf_Internal_Shdr *symtab_hdr;
11442   Elf_Internal_Shdr *symtab_shndx_hdr;
11443   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11444   struct elf_outext_info eoinfo;
11445   bfd_boolean merged;
11446   size_t relativecount = 0;
11447   asection *reldyn = 0;
11448   bfd_size_type amt;
11449   asection *attr_section = NULL;
11450   bfd_vma attr_size = 0;
11451   const char *std_attrs_section;
11452   struct elf_link_hash_table *htab = elf_hash_table (info);
11453
11454   if (!is_elf_hash_table (htab))
11455     return FALSE;
11456
11457   if (bfd_link_pic (info))
11458     abfd->flags |= DYNAMIC;
11459
11460   dynamic = htab->dynamic_sections_created;
11461   dynobj = htab->dynobj;
11462
11463   emit_relocs = (bfd_link_relocatable (info)
11464                  || info->emitrelocations);
11465
11466   flinfo.info = info;
11467   flinfo.output_bfd = abfd;
11468   flinfo.symstrtab = _bfd_elf_strtab_init ();
11469   if (flinfo.symstrtab == NULL)
11470     return FALSE;
11471
11472   if (! dynamic)
11473     {
11474       flinfo.hash_sec = NULL;
11475       flinfo.symver_sec = NULL;
11476     }
11477   else
11478     {
11479       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
11480       /* Note that dynsym_sec can be NULL (on VMS).  */
11481       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
11482       /* Note that it is OK if symver_sec is NULL.  */
11483     }
11484
11485   flinfo.contents = NULL;
11486   flinfo.external_relocs = NULL;
11487   flinfo.internal_relocs = NULL;
11488   flinfo.external_syms = NULL;
11489   flinfo.locsym_shndx = NULL;
11490   flinfo.internal_syms = NULL;
11491   flinfo.indices = NULL;
11492   flinfo.sections = NULL;
11493   flinfo.symshndxbuf = NULL;
11494   flinfo.filesym_count = 0;
11495
11496   /* The object attributes have been merged.  Remove the input
11497      sections from the link, and set the contents of the output
11498      secton.  */
11499   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
11500   for (o = abfd->sections; o != NULL; o = o->next)
11501     {
11502       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
11503           || strcmp (o->name, ".gnu.attributes") == 0)
11504         {
11505           for (p = o->map_head.link_order; p != NULL; p = p->next)
11506             {
11507               asection *input_section;
11508
11509               if (p->type != bfd_indirect_link_order)
11510                 continue;
11511               input_section = p->u.indirect.section;
11512               /* Hack: reset the SEC_HAS_CONTENTS flag so that
11513                  elf_link_input_bfd ignores this section.  */
11514               input_section->flags &= ~SEC_HAS_CONTENTS;
11515             }
11516
11517           attr_size = bfd_elf_obj_attr_size (abfd);
11518           if (attr_size)
11519             {
11520               bfd_set_section_size (abfd, o, attr_size);
11521               attr_section = o;
11522               /* Skip this section later on.  */
11523               o->map_head.link_order = NULL;
11524             }
11525           else
11526             o->flags |= SEC_EXCLUDE;
11527         }
11528     }
11529
11530   /* Count up the number of relocations we will output for each output
11531      section, so that we know the sizes of the reloc sections.  We
11532      also figure out some maximum sizes.  */
11533   max_contents_size = 0;
11534   max_external_reloc_size = 0;
11535   max_internal_reloc_count = 0;
11536   max_sym_count = 0;
11537   max_sym_shndx_count = 0;
11538   merged = FALSE;
11539   for (o = abfd->sections; o != NULL; o = o->next)
11540     {
11541       struct bfd_elf_section_data *esdo = elf_section_data (o);
11542       o->reloc_count = 0;
11543
11544       for (p = o->map_head.link_order; p != NULL; p = p->next)
11545         {
11546           unsigned int reloc_count = 0;
11547           unsigned int additional_reloc_count = 0;
11548           struct bfd_elf_section_data *esdi = NULL;
11549
11550           if (p->type == bfd_section_reloc_link_order
11551               || p->type == bfd_symbol_reloc_link_order)
11552             reloc_count = 1;
11553           else if (p->type == bfd_indirect_link_order)
11554             {
11555               asection *sec;
11556
11557               sec = p->u.indirect.section;
11558
11559               /* Mark all sections which are to be included in the
11560                  link.  This will normally be every section.  We need
11561                  to do this so that we can identify any sections which
11562                  the linker has decided to not include.  */
11563               sec->linker_mark = TRUE;
11564
11565               if (sec->flags & SEC_MERGE)
11566                 merged = TRUE;
11567
11568               if (sec->rawsize > max_contents_size)
11569                 max_contents_size = sec->rawsize;
11570               if (sec->size > max_contents_size)
11571                 max_contents_size = sec->size;
11572
11573               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
11574                   && (sec->owner->flags & DYNAMIC) == 0)
11575                 {
11576                   size_t sym_count;
11577
11578                   /* We are interested in just local symbols, not all
11579                      symbols.  */
11580                   if (elf_bad_symtab (sec->owner))
11581                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
11582                                  / bed->s->sizeof_sym);
11583                   else
11584                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
11585
11586                   if (sym_count > max_sym_count)
11587                     max_sym_count = sym_count;
11588
11589                   if (sym_count > max_sym_shndx_count
11590                       && elf_symtab_shndx_list (sec->owner) != NULL)
11591                     max_sym_shndx_count = sym_count;
11592
11593                   if (esdo->this_hdr.sh_type == SHT_REL
11594                       || esdo->this_hdr.sh_type == SHT_RELA)
11595                     /* Some backends use reloc_count in relocation sections
11596                        to count particular types of relocs.  Of course,
11597                        reloc sections themselves can't have relocations.  */
11598                     ;
11599                   else if (emit_relocs)
11600                     {
11601                       reloc_count = sec->reloc_count;
11602                       if (bed->elf_backend_count_additional_relocs)
11603                         {
11604                           int c;
11605                           c = (*bed->elf_backend_count_additional_relocs) (sec);
11606                           additional_reloc_count += c;
11607                         }
11608                     }
11609                   else if (bed->elf_backend_count_relocs)
11610                     reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
11611
11612                   esdi = elf_section_data (sec);
11613
11614                   if ((sec->flags & SEC_RELOC) != 0)
11615                     {
11616                       size_t ext_size = 0;
11617
11618                       if (esdi->rel.hdr != NULL)
11619                         ext_size = esdi->rel.hdr->sh_size;
11620                       if (esdi->rela.hdr != NULL)
11621                         ext_size += esdi->rela.hdr->sh_size;
11622
11623                       if (ext_size > max_external_reloc_size)
11624                         max_external_reloc_size = ext_size;
11625                       if (sec->reloc_count > max_internal_reloc_count)
11626                         max_internal_reloc_count = sec->reloc_count;
11627                     }
11628                 }
11629             }
11630
11631           if (reloc_count == 0)
11632             continue;
11633
11634           reloc_count += additional_reloc_count;
11635           o->reloc_count += reloc_count;
11636
11637           if (p->type == bfd_indirect_link_order && emit_relocs)
11638             {
11639               if (esdi->rel.hdr)
11640                 {
11641                   esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11642                   esdo->rel.count += additional_reloc_count;
11643                 }
11644               if (esdi->rela.hdr)
11645                 {
11646                   esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11647                   esdo->rela.count += additional_reloc_count;
11648                 }
11649             }
11650           else
11651             {
11652               if (o->use_rela_p)
11653                 esdo->rela.count += reloc_count;
11654               else
11655                 esdo->rel.count += reloc_count;
11656             }
11657         }
11658
11659       if (o->reloc_count > 0)
11660         o->flags |= SEC_RELOC;
11661       else
11662         {
11663           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11664              set it (this is probably a bug) and if it is set
11665              assign_section_numbers will create a reloc section.  */
11666           o->flags &=~ SEC_RELOC;
11667         }
11668
11669       /* If the SEC_ALLOC flag is not set, force the section VMA to
11670          zero.  This is done in elf_fake_sections as well, but forcing
11671          the VMA to 0 here will ensure that relocs against these
11672          sections are handled correctly.  */
11673       if ((o->flags & SEC_ALLOC) == 0
11674           && ! o->user_set_vma)
11675         o->vma = 0;
11676     }
11677
11678   if (! bfd_link_relocatable (info) && merged)
11679     elf_link_hash_traverse (htab, _bfd_elf_link_sec_merge_syms, abfd);
11680
11681   /* Figure out the file positions for everything but the symbol table
11682      and the relocs.  We set symcount to force assign_section_numbers
11683      to create a symbol table.  */
11684   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11685   BFD_ASSERT (! abfd->output_has_begun);
11686   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11687     goto error_return;
11688
11689   /* Set sizes, and assign file positions for reloc sections.  */
11690   for (o = abfd->sections; o != NULL; o = o->next)
11691     {
11692       struct bfd_elf_section_data *esdo = elf_section_data (o);
11693       if ((o->flags & SEC_RELOC) != 0)
11694         {
11695           if (esdo->rel.hdr
11696               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11697             goto error_return;
11698
11699           if (esdo->rela.hdr
11700               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11701             goto error_return;
11702         }
11703
11704       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
11705          to count upwards while actually outputting the relocations.  */
11706       esdo->rel.count = 0;
11707       esdo->rela.count = 0;
11708
11709       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
11710         {
11711           /* Cache the section contents so that they can be compressed
11712              later.  Use bfd_malloc since it will be freed by
11713              bfd_compress_section_contents.  */
11714           unsigned char *contents = esdo->this_hdr.contents;
11715           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
11716             abort ();
11717           contents
11718             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
11719           if (contents == NULL)
11720             goto error_return;
11721           esdo->this_hdr.contents = contents;
11722         }
11723     }
11724
11725   /* We have now assigned file positions for all the sections except
11726      .symtab, .strtab, and non-loaded reloc sections.  We start the
11727      .symtab section at the current file position, and write directly
11728      to it.  We build the .strtab section in memory.  */
11729   bfd_get_symcount (abfd) = 0;
11730   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11731   /* sh_name is set in prep_headers.  */
11732   symtab_hdr->sh_type = SHT_SYMTAB;
11733   /* sh_flags, sh_addr and sh_size all start off zero.  */
11734   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
11735   /* sh_link is set in assign_section_numbers.  */
11736   /* sh_info is set below.  */
11737   /* sh_offset is set just below.  */
11738   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
11739
11740   if (max_sym_count < 20)
11741     max_sym_count = 20;
11742   htab->strtabsize = max_sym_count;
11743   amt = max_sym_count * sizeof (struct elf_sym_strtab);
11744   htab->strtab = (struct elf_sym_strtab *) bfd_malloc (amt);
11745   if (htab->strtab == NULL)
11746     goto error_return;
11747   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
11748   flinfo.symshndxbuf
11749     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
11750        ? (Elf_External_Sym_Shndx *) -1 : NULL);
11751
11752   if (info->strip != strip_all || emit_relocs)
11753     {
11754       file_ptr off = elf_next_file_pos (abfd);
11755
11756       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
11757
11758       /* Note that at this point elf_next_file_pos (abfd) is
11759          incorrect.  We do not yet know the size of the .symtab section.
11760          We correct next_file_pos below, after we do know the size.  */
11761
11762       /* Start writing out the symbol table.  The first symbol is always a
11763          dummy symbol.  */
11764       elfsym.st_value = 0;
11765       elfsym.st_size = 0;
11766       elfsym.st_info = 0;
11767       elfsym.st_other = 0;
11768       elfsym.st_shndx = SHN_UNDEF;
11769       elfsym.st_target_internal = 0;
11770       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
11771                                      bfd_und_section_ptr, NULL) != 1)
11772         goto error_return;
11773
11774       /* Output a symbol for each section.  We output these even if we are
11775          discarding local symbols, since they are used for relocs.  These
11776          symbols have no names.  We store the index of each one in the
11777          index field of the section, so that we can find it again when
11778          outputting relocs.  */
11779
11780       elfsym.st_size = 0;
11781       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11782       elfsym.st_other = 0;
11783       elfsym.st_value = 0;
11784       elfsym.st_target_internal = 0;
11785       for (i = 1; i < elf_numsections (abfd); i++)
11786         {
11787           o = bfd_section_from_elf_index (abfd, i);
11788           if (o != NULL)
11789             {
11790               o->target_index = bfd_get_symcount (abfd);
11791               elfsym.st_shndx = i;
11792               if (!bfd_link_relocatable (info))
11793                 elfsym.st_value = o->vma;
11794               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
11795                                              NULL) != 1)
11796                 goto error_return;
11797             }
11798         }
11799     }
11800
11801   /* Allocate some memory to hold information read in from the input
11802      files.  */
11803   if (max_contents_size != 0)
11804     {
11805       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
11806       if (flinfo.contents == NULL)
11807         goto error_return;
11808     }
11809
11810   if (max_external_reloc_size != 0)
11811     {
11812       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
11813       if (flinfo.external_relocs == NULL)
11814         goto error_return;
11815     }
11816
11817   if (max_internal_reloc_count != 0)
11818     {
11819       amt = max_internal_reloc_count * sizeof (Elf_Internal_Rela);
11820       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
11821       if (flinfo.internal_relocs == NULL)
11822         goto error_return;
11823     }
11824
11825   if (max_sym_count != 0)
11826     {
11827       amt = max_sym_count * bed->s->sizeof_sym;
11828       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
11829       if (flinfo.external_syms == NULL)
11830         goto error_return;
11831
11832       amt = max_sym_count * sizeof (Elf_Internal_Sym);
11833       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
11834       if (flinfo.internal_syms == NULL)
11835         goto error_return;
11836
11837       amt = max_sym_count * sizeof (long);
11838       flinfo.indices = (long int *) bfd_malloc (amt);
11839       if (flinfo.indices == NULL)
11840         goto error_return;
11841
11842       amt = max_sym_count * sizeof (asection *);
11843       flinfo.sections = (asection **) bfd_malloc (amt);
11844       if (flinfo.sections == NULL)
11845         goto error_return;
11846     }
11847
11848   if (max_sym_shndx_count != 0)
11849     {
11850       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
11851       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
11852       if (flinfo.locsym_shndx == NULL)
11853         goto error_return;
11854     }
11855
11856   if (htab->tls_sec)
11857     {
11858       bfd_vma base, end = 0;
11859       asection *sec;
11860
11861       for (sec = htab->tls_sec;
11862            sec && (sec->flags & SEC_THREAD_LOCAL);
11863            sec = sec->next)
11864         {
11865           bfd_size_type size = sec->size;
11866
11867           if (size == 0
11868               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11869             {
11870               struct bfd_link_order *ord = sec->map_tail.link_order;
11871
11872               if (ord != NULL)
11873                 size = ord->offset + ord->size;
11874             }
11875           end = sec->vma + size;
11876         }
11877       base = htab->tls_sec->vma;
11878       /* Only align end of TLS section if static TLS doesn't have special
11879          alignment requirements.  */
11880       if (bed->static_tls_alignment == 1)
11881         end = align_power (end, htab->tls_sec->alignment_power);
11882       htab->tls_size = end - base;
11883     }
11884
11885   /* Reorder SHF_LINK_ORDER sections.  */
11886   for (o = abfd->sections; o != NULL; o = o->next)
11887     {
11888       if (!elf_fixup_link_order (abfd, o))
11889         return FALSE;
11890     }
11891
11892   if (!_bfd_elf_fixup_eh_frame_hdr (info))
11893     return FALSE;
11894
11895   /* Since ELF permits relocations to be against local symbols, we
11896      must have the local symbols available when we do the relocations.
11897      Since we would rather only read the local symbols once, and we
11898      would rather not keep them in memory, we handle all the
11899      relocations for a single input file at the same time.
11900
11901      Unfortunately, there is no way to know the total number of local
11902      symbols until we have seen all of them, and the local symbol
11903      indices precede the global symbol indices.  This means that when
11904      we are generating relocatable output, and we see a reloc against
11905      a global symbol, we can not know the symbol index until we have
11906      finished examining all the local symbols to see which ones we are
11907      going to output.  To deal with this, we keep the relocations in
11908      memory, and don't output them until the end of the link.  This is
11909      an unfortunate waste of memory, but I don't see a good way around
11910      it.  Fortunately, it only happens when performing a relocatable
11911      link, which is not the common case.  FIXME: If keep_memory is set
11912      we could write the relocs out and then read them again; I don't
11913      know how bad the memory loss will be.  */
11914
11915   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11916     sub->output_has_begun = FALSE;
11917   for (o = abfd->sections; o != NULL; o = o->next)
11918     {
11919       for (p = o->map_head.link_order; p != NULL; p = p->next)
11920         {
11921           if (p->type == bfd_indirect_link_order
11922               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
11923                   == bfd_target_elf_flavour)
11924               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
11925             {
11926               if (! sub->output_has_begun)
11927                 {
11928                   if (! elf_link_input_bfd (&flinfo, sub))
11929                     goto error_return;
11930                   sub->output_has_begun = TRUE;
11931                 }
11932             }
11933           else if (p->type == bfd_section_reloc_link_order
11934                    || p->type == bfd_symbol_reloc_link_order)
11935             {
11936               if (! elf_reloc_link_order (abfd, info, o, p))
11937                 goto error_return;
11938             }
11939           else
11940             {
11941               if (! _bfd_default_link_order (abfd, info, o, p))
11942                 {
11943                   if (p->type == bfd_indirect_link_order
11944                       && (bfd_get_flavour (sub)
11945                           == bfd_target_elf_flavour)
11946                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
11947                           != bed->s->elfclass))
11948                     {
11949                       const char *iclass, *oclass;
11950
11951                       switch (bed->s->elfclass)
11952                         {
11953                         case ELFCLASS64: oclass = "ELFCLASS64"; break;
11954                         case ELFCLASS32: oclass = "ELFCLASS32"; break;
11955                         case ELFCLASSNONE: oclass = "ELFCLASSNONE"; break;
11956                         default: abort ();
11957                         }
11958
11959                       switch (elf_elfheader (sub)->e_ident[EI_CLASS])
11960                         {
11961                         case ELFCLASS64: iclass = "ELFCLASS64"; break;
11962                         case ELFCLASS32: iclass = "ELFCLASS32"; break;
11963                         case ELFCLASSNONE: iclass = "ELFCLASSNONE"; break;
11964                         default: abort ();
11965                         }
11966
11967                       bfd_set_error (bfd_error_wrong_format);
11968                       _bfd_error_handler
11969                         /* xgettext:c-format */
11970                         (_("%B: file class %s incompatible with %s"),
11971                          sub, iclass, oclass);
11972                     }
11973
11974                   goto error_return;
11975                 }
11976             }
11977         }
11978     }
11979
11980   /* Free symbol buffer if needed.  */
11981   if (!info->reduce_memory_overheads)
11982     {
11983       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11984         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11985             && elf_tdata (sub)->symbuf)
11986           {
11987             free (elf_tdata (sub)->symbuf);
11988             elf_tdata (sub)->symbuf = NULL;
11989           }
11990     }
11991
11992   /* Output any global symbols that got converted to local in a
11993      version script or due to symbol visibility.  We do this in a
11994      separate step since ELF requires all local symbols to appear
11995      prior to any global symbols.  FIXME: We should only do this if
11996      some global symbols were, in fact, converted to become local.
11997      FIXME: Will this work correctly with the Irix 5 linker?  */
11998   eoinfo.failed = FALSE;
11999   eoinfo.flinfo = &flinfo;
12000   eoinfo.localsyms = TRUE;
12001   eoinfo.file_sym_done = FALSE;
12002   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12003   if (eoinfo.failed)
12004     return FALSE;
12005
12006   /* If backend needs to output some local symbols not present in the hash
12007      table, do it now.  */
12008   if (bed->elf_backend_output_arch_local_syms
12009       && (info->strip != strip_all || emit_relocs))
12010     {
12011       typedef int (*out_sym_func)
12012         (void *, const char *, Elf_Internal_Sym *, asection *,
12013          struct elf_link_hash_entry *);
12014
12015       if (! ((*bed->elf_backend_output_arch_local_syms)
12016              (abfd, info, &flinfo,
12017               (out_sym_func) elf_link_output_symstrtab)))
12018         return FALSE;
12019     }
12020
12021   /* That wrote out all the local symbols.  Finish up the symbol table
12022      with the global symbols. Even if we want to strip everything we
12023      can, we still need to deal with those global symbols that got
12024      converted to local in a version script.  */
12025
12026   /* The sh_info field records the index of the first non local symbol.  */
12027   symtab_hdr->sh_info = bfd_get_symcount (abfd);
12028
12029   if (dynamic
12030       && htab->dynsym != NULL
12031       && htab->dynsym->output_section != bfd_abs_section_ptr)
12032     {
12033       Elf_Internal_Sym sym;
12034       bfd_byte *dynsym = htab->dynsym->contents;
12035
12036       o = htab->dynsym->output_section;
12037       elf_section_data (o)->this_hdr.sh_info = htab->local_dynsymcount + 1;
12038
12039       /* Write out the section symbols for the output sections.  */
12040       if (bfd_link_pic (info)
12041           || htab->is_relocatable_executable)
12042         {
12043           asection *s;
12044
12045           sym.st_size = 0;
12046           sym.st_name = 0;
12047           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
12048           sym.st_other = 0;
12049           sym.st_target_internal = 0;
12050
12051           for (s = abfd->sections; s != NULL; s = s->next)
12052             {
12053               int indx;
12054               bfd_byte *dest;
12055               long dynindx;
12056
12057               dynindx = elf_section_data (s)->dynindx;
12058               if (dynindx <= 0)
12059                 continue;
12060               indx = elf_section_data (s)->this_idx;
12061               BFD_ASSERT (indx > 0);
12062               sym.st_shndx = indx;
12063               if (! check_dynsym (abfd, &sym))
12064                 return FALSE;
12065               sym.st_value = s->vma;
12066               dest = dynsym + dynindx * bed->s->sizeof_sym;
12067               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12068             }
12069         }
12070
12071       /* Write out the local dynsyms.  */
12072       if (htab->dynlocal)
12073         {
12074           struct elf_link_local_dynamic_entry *e;
12075           for (e = htab->dynlocal; e ; e = e->next)
12076             {
12077               asection *s;
12078               bfd_byte *dest;
12079
12080               /* Copy the internal symbol and turn off visibility.
12081                  Note that we saved a word of storage and overwrote
12082                  the original st_name with the dynstr_index.  */
12083               sym = e->isym;
12084               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
12085
12086               s = bfd_section_from_elf_index (e->input_bfd,
12087                                               e->isym.st_shndx);
12088               if (s != NULL)
12089                 {
12090                   sym.st_shndx =
12091                     elf_section_data (s->output_section)->this_idx;
12092                   if (! check_dynsym (abfd, &sym))
12093                     return FALSE;
12094                   sym.st_value = (s->output_section->vma
12095                                   + s->output_offset
12096                                   + e->isym.st_value);
12097                 }
12098
12099               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
12100               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12101             }
12102         }
12103     }
12104
12105   /* We get the global symbols from the hash table.  */
12106   eoinfo.failed = FALSE;
12107   eoinfo.localsyms = FALSE;
12108   eoinfo.flinfo = &flinfo;
12109   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12110   if (eoinfo.failed)
12111     return FALSE;
12112
12113   /* If backend needs to output some symbols not present in the hash
12114      table, do it now.  */
12115   if (bed->elf_backend_output_arch_syms
12116       && (info->strip != strip_all || emit_relocs))
12117     {
12118       typedef int (*out_sym_func)
12119         (void *, const char *, Elf_Internal_Sym *, asection *,
12120          struct elf_link_hash_entry *);
12121
12122       if (! ((*bed->elf_backend_output_arch_syms)
12123              (abfd, info, &flinfo,
12124               (out_sym_func) elf_link_output_symstrtab)))
12125         return FALSE;
12126     }
12127
12128   /* Finalize the .strtab section.  */
12129   _bfd_elf_strtab_finalize (flinfo.symstrtab);
12130
12131   /* Swap out the .strtab section. */
12132   if (!elf_link_swap_symbols_out (&flinfo))
12133     return FALSE;
12134
12135   /* Now we know the size of the symtab section.  */
12136   if (bfd_get_symcount (abfd) > 0)
12137     {
12138       /* Finish up and write out the symbol string table (.strtab)
12139          section.  */
12140       Elf_Internal_Shdr *symstrtab_hdr = NULL;
12141       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
12142
12143       if (elf_symtab_shndx_list (abfd))
12144         {
12145           symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
12146
12147           if (symtab_shndx_hdr != NULL && symtab_shndx_hdr->sh_name != 0)
12148             {
12149               symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
12150               symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
12151               symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
12152               amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
12153               symtab_shndx_hdr->sh_size = amt;
12154
12155               off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
12156                                                                off, TRUE);
12157
12158               if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
12159                   || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
12160                 return FALSE;
12161             }
12162         }
12163
12164       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
12165       /* sh_name was set in prep_headers.  */
12166       symstrtab_hdr->sh_type = SHT_STRTAB;
12167       symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
12168       symstrtab_hdr->sh_addr = 0;
12169       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
12170       symstrtab_hdr->sh_entsize = 0;
12171       symstrtab_hdr->sh_link = 0;
12172       symstrtab_hdr->sh_info = 0;
12173       /* sh_offset is set just below.  */
12174       symstrtab_hdr->sh_addralign = 1;
12175
12176       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
12177                                                        off, TRUE);
12178       elf_next_file_pos (abfd) = off;
12179
12180       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
12181           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
12182         return FALSE;
12183     }
12184
12185   if (info->out_implib_bfd && !elf_output_implib (abfd, info))
12186     {
12187       _bfd_error_handler (_("%B: failed to generate import library"),
12188                           info->out_implib_bfd);
12189       return FALSE;
12190     }
12191
12192   /* Adjust the relocs to have the correct symbol indices.  */
12193   for (o = abfd->sections; o != NULL; o = o->next)
12194     {
12195       struct bfd_elf_section_data *esdo = elf_section_data (o);
12196       bfd_boolean sort;
12197
12198       if ((o->flags & SEC_RELOC) == 0)
12199         continue;
12200
12201       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
12202       if (esdo->rel.hdr != NULL
12203           && !elf_link_adjust_relocs (abfd, o, &esdo->rel, sort, info))
12204         return FALSE;
12205       if (esdo->rela.hdr != NULL
12206           && !elf_link_adjust_relocs (abfd, o, &esdo->rela, sort, info))
12207         return FALSE;
12208
12209       /* Set the reloc_count field to 0 to prevent write_relocs from
12210          trying to swap the relocs out itself.  */
12211       o->reloc_count = 0;
12212     }
12213
12214   if (dynamic && info->combreloc && dynobj != NULL)
12215     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
12216
12217   /* If we are linking against a dynamic object, or generating a
12218      shared library, finish up the dynamic linking information.  */
12219   if (dynamic)
12220     {
12221       bfd_byte *dyncon, *dynconend;
12222
12223       /* Fix up .dynamic entries.  */
12224       o = bfd_get_linker_section (dynobj, ".dynamic");
12225       BFD_ASSERT (o != NULL);
12226
12227       dyncon = o->contents;
12228       dynconend = o->contents + o->size;
12229       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12230         {
12231           Elf_Internal_Dyn dyn;
12232           const char *name;
12233           unsigned int type;
12234           bfd_size_type sh_size;
12235           bfd_vma sh_addr;
12236
12237           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12238
12239           switch (dyn.d_tag)
12240             {
12241             default:
12242               continue;
12243             case DT_NULL:
12244               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
12245                 {
12246                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
12247                     {
12248                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
12249                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
12250                     default: continue;
12251                     }
12252                   dyn.d_un.d_val = relativecount;
12253                   relativecount = 0;
12254                   break;
12255                 }
12256               continue;
12257
12258             case DT_INIT:
12259               name = info->init_function;
12260               goto get_sym;
12261             case DT_FINI:
12262               name = info->fini_function;
12263             get_sym:
12264               {
12265                 struct elf_link_hash_entry *h;
12266
12267                 h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
12268                 if (h != NULL
12269                     && (h->root.type == bfd_link_hash_defined
12270                         || h->root.type == bfd_link_hash_defweak))
12271                   {
12272                     dyn.d_un.d_ptr = h->root.u.def.value;
12273                     o = h->root.u.def.section;
12274                     if (o->output_section != NULL)
12275                       dyn.d_un.d_ptr += (o->output_section->vma
12276                                          + o->output_offset);
12277                     else
12278                       {
12279                         /* The symbol is imported from another shared
12280                            library and does not apply to this one.  */
12281                         dyn.d_un.d_ptr = 0;
12282                       }
12283                     break;
12284                   }
12285               }
12286               continue;
12287
12288             case DT_PREINIT_ARRAYSZ:
12289               name = ".preinit_array";
12290               goto get_out_size;
12291             case DT_INIT_ARRAYSZ:
12292               name = ".init_array";
12293               goto get_out_size;
12294             case DT_FINI_ARRAYSZ:
12295               name = ".fini_array";
12296             get_out_size:
12297               o = bfd_get_section_by_name (abfd, name);
12298               if (o == NULL)
12299                 {
12300                   _bfd_error_handler
12301                     (_("could not find section %s"), name);
12302                   goto error_return;
12303                 }
12304               if (o->size == 0)
12305                 _bfd_error_handler
12306                   (_("warning: %s section has zero size"), name);
12307               dyn.d_un.d_val = o->size;
12308               break;
12309
12310             case DT_PREINIT_ARRAY:
12311               name = ".preinit_array";
12312               goto get_out_vma;
12313             case DT_INIT_ARRAY:
12314               name = ".init_array";
12315               goto get_out_vma;
12316             case DT_FINI_ARRAY:
12317               name = ".fini_array";
12318             get_out_vma:
12319               o = bfd_get_section_by_name (abfd, name);
12320               goto do_vma;
12321
12322             case DT_HASH:
12323               name = ".hash";
12324               goto get_vma;
12325             case DT_GNU_HASH:
12326               name = ".gnu.hash";
12327               goto get_vma;
12328             case DT_STRTAB:
12329               name = ".dynstr";
12330               goto get_vma;
12331             case DT_SYMTAB:
12332               name = ".dynsym";
12333               goto get_vma;
12334             case DT_VERDEF:
12335               name = ".gnu.version_d";
12336               goto get_vma;
12337             case DT_VERNEED:
12338               name = ".gnu.version_r";
12339               goto get_vma;
12340             case DT_VERSYM:
12341               name = ".gnu.version";
12342             get_vma:
12343               o = bfd_get_linker_section (dynobj, name);
12344             do_vma:
12345               if (o == NULL)
12346                 {
12347                   _bfd_error_handler
12348                     (_("could not find section %s"), name);
12349                   goto error_return;
12350                 }
12351               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
12352                 {
12353                   _bfd_error_handler
12354                     (_("warning: section '%s' is being made into a note"), name);
12355                   bfd_set_error (bfd_error_nonrepresentable_section);
12356                   goto error_return;
12357                 }
12358               dyn.d_un.d_ptr = o->output_section->vma + o->output_offset;
12359               break;
12360
12361             case DT_REL:
12362             case DT_RELA:
12363             case DT_RELSZ:
12364             case DT_RELASZ:
12365               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
12366                 type = SHT_REL;
12367               else
12368                 type = SHT_RELA;
12369               sh_size = 0;
12370               sh_addr = 0;
12371               for (i = 1; i < elf_numsections (abfd); i++)
12372                 {
12373                   Elf_Internal_Shdr *hdr;
12374
12375                   hdr = elf_elfsections (abfd)[i];
12376                   if (hdr->sh_type == type
12377                       && (hdr->sh_flags & SHF_ALLOC) != 0)
12378                     {
12379                       sh_size += hdr->sh_size;
12380                       if (sh_addr == 0
12381                           || sh_addr > hdr->sh_addr)
12382                         sh_addr = hdr->sh_addr;
12383                     }
12384                 }
12385
12386               if (bed->dtrel_excludes_plt && htab->srelplt != NULL)
12387                 {
12388                   /* Don't count procedure linkage table relocs in the
12389                      overall reloc count.  */
12390                   sh_size -= htab->srelplt->size;
12391                   if (sh_size == 0)
12392                     /* If the size is zero, make the address zero too.
12393                        This is to avoid a glibc bug.  If the backend
12394                        emits DT_RELA/DT_RELASZ even when DT_RELASZ is
12395                        zero, then we'll put DT_RELA at the end of
12396                        DT_JMPREL.  glibc will interpret the end of
12397                        DT_RELA matching the end of DT_JMPREL as the
12398                        case where DT_RELA includes DT_JMPREL, and for
12399                        LD_BIND_NOW will decide that processing DT_RELA
12400                        will process the PLT relocs too.  Net result:
12401                        No PLT relocs applied.  */
12402                     sh_addr = 0;
12403
12404                   /* If .rela.plt is the first .rela section, exclude
12405                      it from DT_RELA.  */
12406                   else if (sh_addr == (htab->srelplt->output_section->vma
12407                                        + htab->srelplt->output_offset))
12408                     sh_addr += htab->srelplt->size;
12409                 }
12410
12411               if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
12412                 dyn.d_un.d_val = sh_size;
12413               else
12414                 dyn.d_un.d_ptr = sh_addr;
12415               break;
12416             }
12417           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
12418         }
12419     }
12420
12421   /* If we have created any dynamic sections, then output them.  */
12422   if (dynobj != NULL)
12423     {
12424       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
12425         goto error_return;
12426
12427       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
12428       if (((info->warn_shared_textrel && bfd_link_pic (info))
12429            || info->error_textrel)
12430           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
12431         {
12432           bfd_byte *dyncon, *dynconend;
12433
12434           dyncon = o->contents;
12435           dynconend = o->contents + o->size;
12436           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12437             {
12438               Elf_Internal_Dyn dyn;
12439
12440               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12441
12442               if (dyn.d_tag == DT_TEXTREL)
12443                 {
12444                   if (info->error_textrel)
12445                     info->callbacks->einfo
12446                       (_("%P%X: read-only segment has dynamic relocations.\n"));
12447                   else
12448                     info->callbacks->einfo
12449                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
12450                   break;
12451                 }
12452             }
12453         }
12454
12455       for (o = dynobj->sections; o != NULL; o = o->next)
12456         {
12457           if ((o->flags & SEC_HAS_CONTENTS) == 0
12458               || o->size == 0
12459               || o->output_section == bfd_abs_section_ptr)
12460             continue;
12461           if ((o->flags & SEC_LINKER_CREATED) == 0)
12462             {
12463               /* At this point, we are only interested in sections
12464                  created by _bfd_elf_link_create_dynamic_sections.  */
12465               continue;
12466             }
12467           if (htab->stab_info.stabstr == o)
12468             continue;
12469           if (htab->eh_info.hdr_sec == o)
12470             continue;
12471           if (strcmp (o->name, ".dynstr") != 0)
12472             {
12473               if (! bfd_set_section_contents (abfd, o->output_section,
12474                                               o->contents,
12475                                               (file_ptr) o->output_offset
12476                                               * bfd_octets_per_byte (abfd),
12477                                               o->size))
12478                 goto error_return;
12479             }
12480           else
12481             {
12482               /* The contents of the .dynstr section are actually in a
12483                  stringtab.  */
12484               file_ptr off;
12485
12486               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
12487               if (bfd_seek (abfd, off, SEEK_SET) != 0
12488                   || !_bfd_elf_strtab_emit (abfd, htab->dynstr))
12489                 goto error_return;
12490             }
12491         }
12492     }
12493
12494   if (!info->resolve_section_groups)
12495     {
12496       bfd_boolean failed = FALSE;
12497
12498       BFD_ASSERT (bfd_link_relocatable (info));
12499       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
12500       if (failed)
12501         goto error_return;
12502     }
12503
12504   /* If we have optimized stabs strings, output them.  */
12505   if (htab->stab_info.stabstr != NULL)
12506     {
12507       if (!_bfd_write_stab_strings (abfd, &htab->stab_info))
12508         goto error_return;
12509     }
12510
12511   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
12512     goto error_return;
12513
12514   elf_final_link_free (abfd, &flinfo);
12515
12516   elf_linker (abfd) = TRUE;
12517
12518   if (attr_section)
12519     {
12520       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
12521       if (contents == NULL)
12522         return FALSE;   /* Bail out and fail.  */
12523       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
12524       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
12525       free (contents);
12526     }
12527
12528   return TRUE;
12529
12530  error_return:
12531   elf_final_link_free (abfd, &flinfo);
12532   return FALSE;
12533 }
12534 \f
12535 /* Initialize COOKIE for input bfd ABFD.  */
12536
12537 static bfd_boolean
12538 init_reloc_cookie (struct elf_reloc_cookie *cookie,
12539                    struct bfd_link_info *info, bfd *abfd)
12540 {
12541   Elf_Internal_Shdr *symtab_hdr;
12542   const struct elf_backend_data *bed;
12543
12544   bed = get_elf_backend_data (abfd);
12545   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12546
12547   cookie->abfd = abfd;
12548   cookie->sym_hashes = elf_sym_hashes (abfd);
12549   cookie->bad_symtab = elf_bad_symtab (abfd);
12550   if (cookie->bad_symtab)
12551     {
12552       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12553       cookie->extsymoff = 0;
12554     }
12555   else
12556     {
12557       cookie->locsymcount = symtab_hdr->sh_info;
12558       cookie->extsymoff = symtab_hdr->sh_info;
12559     }
12560
12561   if (bed->s->arch_size == 32)
12562     cookie->r_sym_shift = 8;
12563   else
12564     cookie->r_sym_shift = 32;
12565
12566   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
12567   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
12568     {
12569       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12570                                               cookie->locsymcount, 0,
12571                                               NULL, NULL, NULL);
12572       if (cookie->locsyms == NULL)
12573         {
12574           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
12575           return FALSE;
12576         }
12577       if (info->keep_memory)
12578         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
12579     }
12580   return TRUE;
12581 }
12582
12583 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
12584
12585 static void
12586 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
12587 {
12588   Elf_Internal_Shdr *symtab_hdr;
12589
12590   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12591   if (cookie->locsyms != NULL
12592       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
12593     free (cookie->locsyms);
12594 }
12595
12596 /* Initialize the relocation information in COOKIE for input section SEC
12597    of input bfd ABFD.  */
12598
12599 static bfd_boolean
12600 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12601                         struct bfd_link_info *info, bfd *abfd,
12602                         asection *sec)
12603 {
12604   if (sec->reloc_count == 0)
12605     {
12606       cookie->rels = NULL;
12607       cookie->relend = NULL;
12608     }
12609   else
12610     {
12611       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
12612                                                 info->keep_memory);
12613       if (cookie->rels == NULL)
12614         return FALSE;
12615       cookie->rel = cookie->rels;
12616       cookie->relend = cookie->rels + sec->reloc_count;
12617     }
12618   cookie->rel = cookie->rels;
12619   return TRUE;
12620 }
12621
12622 /* Free the memory allocated by init_reloc_cookie_rels,
12623    if appropriate.  */
12624
12625 static void
12626 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12627                         asection *sec)
12628 {
12629   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
12630     free (cookie->rels);
12631 }
12632
12633 /* Initialize the whole of COOKIE for input section SEC.  */
12634
12635 static bfd_boolean
12636 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12637                                struct bfd_link_info *info,
12638                                asection *sec)
12639 {
12640   if (!init_reloc_cookie (cookie, info, sec->owner))
12641     goto error1;
12642   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
12643     goto error2;
12644   return TRUE;
12645
12646  error2:
12647   fini_reloc_cookie (cookie, sec->owner);
12648  error1:
12649   return FALSE;
12650 }
12651
12652 /* Free the memory allocated by init_reloc_cookie_for_section,
12653    if appropriate.  */
12654
12655 static void
12656 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12657                                asection *sec)
12658 {
12659   fini_reloc_cookie_rels (cookie, sec);
12660   fini_reloc_cookie (cookie, sec->owner);
12661 }
12662 \f
12663 /* Garbage collect unused sections.  */
12664
12665 /* Default gc_mark_hook.  */
12666
12667 asection *
12668 _bfd_elf_gc_mark_hook (asection *sec,
12669                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12670                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12671                        struct elf_link_hash_entry *h,
12672                        Elf_Internal_Sym *sym)
12673 {
12674   if (h != NULL)
12675     {
12676       switch (h->root.type)
12677         {
12678         case bfd_link_hash_defined:
12679         case bfd_link_hash_defweak:
12680           return h->root.u.def.section;
12681
12682         case bfd_link_hash_common:
12683           return h->root.u.c.p->section;
12684
12685         default:
12686           break;
12687         }
12688     }
12689   else
12690     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12691
12692   return NULL;
12693 }
12694
12695 /* Return the global debug definition section.  */
12696
12697 static asection *
12698 elf_gc_mark_debug_section (asection *sec ATTRIBUTE_UNUSED,
12699                            struct bfd_link_info *info ATTRIBUTE_UNUSED,
12700                            Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12701                            struct elf_link_hash_entry *h,
12702                            Elf_Internal_Sym *sym ATTRIBUTE_UNUSED)
12703 {
12704   if (h != NULL
12705       && (h->root.type == bfd_link_hash_defined
12706           || h->root.type == bfd_link_hash_defweak)
12707       && (h->root.u.def.section->flags & SEC_DEBUGGING) != 0)
12708     return h->root.u.def.section;
12709
12710   return NULL;
12711 }
12712
12713 /* COOKIE->rel describes a relocation against section SEC, which is
12714    a section we've decided to keep.  Return the section that contains
12715    the relocation symbol, or NULL if no section contains it.  */
12716
12717 asection *
12718 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
12719                        elf_gc_mark_hook_fn gc_mark_hook,
12720                        struct elf_reloc_cookie *cookie,
12721                        bfd_boolean *start_stop)
12722 {
12723   unsigned long r_symndx;
12724   struct elf_link_hash_entry *h;
12725
12726   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
12727   if (r_symndx == STN_UNDEF)
12728     return NULL;
12729
12730   if (r_symndx >= cookie->locsymcount
12731       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12732     {
12733       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
12734       if (h == NULL)
12735         {
12736           info->callbacks->einfo (_("%F%P: corrupt input: %B\n"),
12737                                   sec->owner);
12738           return NULL;
12739         }
12740       while (h->root.type == bfd_link_hash_indirect
12741              || h->root.type == bfd_link_hash_warning)
12742         h = (struct elf_link_hash_entry *) h->root.u.i.link;
12743       h->mark = 1;
12744       /* If this symbol is weak and there is a non-weak definition, we
12745          keep the non-weak definition because many backends put
12746          dynamic reloc info on the non-weak definition for code
12747          handling copy relocs.  */
12748       if (h->u.weakdef != NULL)
12749         h->u.weakdef->mark = 1;
12750
12751       if (start_stop != NULL)
12752         {
12753           /* To work around a glibc bug, mark XXX input sections
12754              when there is a reference to __start_XXX or __stop_XXX
12755              symbols.  */
12756           if (h->start_stop)
12757             {
12758               asection *s = h->u2.start_stop_section;
12759               *start_stop = !s->gc_mark;
12760               return s;
12761             }
12762         }
12763
12764       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
12765     }
12766
12767   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
12768                           &cookie->locsyms[r_symndx]);
12769 }
12770
12771 /* COOKIE->rel describes a relocation against section SEC, which is
12772    a section we've decided to keep.  Mark the section that contains
12773    the relocation symbol.  */
12774
12775 bfd_boolean
12776 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
12777                         asection *sec,
12778                         elf_gc_mark_hook_fn gc_mark_hook,
12779                         struct elf_reloc_cookie *cookie)
12780 {
12781   asection *rsec;
12782   bfd_boolean start_stop = FALSE;
12783
12784   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie, &start_stop);
12785   while (rsec != NULL)
12786     {
12787       if (!rsec->gc_mark)
12788         {
12789           if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
12790               || (rsec->owner->flags & DYNAMIC) != 0)
12791             rsec->gc_mark = 1;
12792           else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
12793             return FALSE;
12794         }
12795       if (!start_stop)
12796         break;
12797       rsec = bfd_get_next_section_by_name (rsec->owner, rsec);
12798     }
12799   return TRUE;
12800 }
12801
12802 /* The mark phase of garbage collection.  For a given section, mark
12803    it and any sections in this section's group, and all the sections
12804    which define symbols to which it refers.  */
12805
12806 bfd_boolean
12807 _bfd_elf_gc_mark (struct bfd_link_info *info,
12808                   asection *sec,
12809                   elf_gc_mark_hook_fn gc_mark_hook)
12810 {
12811   bfd_boolean ret;
12812   asection *group_sec, *eh_frame;
12813
12814   sec->gc_mark = 1;
12815
12816   /* Mark all the sections in the group.  */
12817   group_sec = elf_section_data (sec)->next_in_group;
12818   if (group_sec && !group_sec->gc_mark)
12819     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
12820       return FALSE;
12821
12822   /* Look through the section relocs.  */
12823   ret = TRUE;
12824   eh_frame = elf_eh_frame_section (sec->owner);
12825   if ((sec->flags & SEC_RELOC) != 0
12826       && sec->reloc_count > 0
12827       && sec != eh_frame)
12828     {
12829       struct elf_reloc_cookie cookie;
12830
12831       if (!init_reloc_cookie_for_section (&cookie, info, sec))
12832         ret = FALSE;
12833       else
12834         {
12835           for (; cookie.rel < cookie.relend; cookie.rel++)
12836             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
12837               {
12838                 ret = FALSE;
12839                 break;
12840               }
12841           fini_reloc_cookie_for_section (&cookie, sec);
12842         }
12843     }
12844
12845   if (ret && eh_frame && elf_fde_list (sec))
12846     {
12847       struct elf_reloc_cookie cookie;
12848
12849       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
12850         ret = FALSE;
12851       else
12852         {
12853           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
12854                                       gc_mark_hook, &cookie))
12855             ret = FALSE;
12856           fini_reloc_cookie_for_section (&cookie, eh_frame);
12857         }
12858     }
12859
12860   eh_frame = elf_section_eh_frame_entry (sec);
12861   if (ret && eh_frame && !eh_frame->gc_mark)
12862     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
12863       ret = FALSE;
12864
12865   return ret;
12866 }
12867
12868 /* Scan and mark sections in a special or debug section group.  */
12869
12870 static void
12871 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
12872 {
12873   /* Point to first section of section group.  */
12874   asection *ssec;
12875   /* Used to iterate the section group.  */
12876   asection *msec;
12877
12878   bfd_boolean is_special_grp = TRUE;
12879   bfd_boolean is_debug_grp = TRUE;
12880
12881   /* First scan to see if group contains any section other than debug
12882      and special section.  */
12883   ssec = msec = elf_next_in_group (grp);
12884   do
12885     {
12886       if ((msec->flags & SEC_DEBUGGING) == 0)
12887         is_debug_grp = FALSE;
12888
12889       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
12890         is_special_grp = FALSE;
12891
12892       msec = elf_next_in_group (msec);
12893     }
12894   while (msec != ssec);
12895
12896   /* If this is a pure debug section group or pure special section group,
12897      keep all sections in this group.  */
12898   if (is_debug_grp || is_special_grp)
12899     {
12900       do
12901         {
12902           msec->gc_mark = 1;
12903           msec = elf_next_in_group (msec);
12904         }
12905       while (msec != ssec);
12906     }
12907 }
12908
12909 /* Keep debug and special sections.  */
12910
12911 bfd_boolean
12912 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
12913                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
12914 {
12915   bfd *ibfd;
12916
12917   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
12918     {
12919       asection *isec;
12920       bfd_boolean some_kept;
12921       bfd_boolean debug_frag_seen;
12922       bfd_boolean has_kept_debug_info;
12923
12924       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
12925         continue;
12926       isec = ibfd->sections;
12927       if (isec == NULL || isec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
12928         continue;
12929
12930       /* Ensure all linker created sections are kept,
12931          see if any other section is already marked,
12932          and note if we have any fragmented debug sections.  */
12933       debug_frag_seen = some_kept = has_kept_debug_info = FALSE;
12934       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12935         {
12936           if ((isec->flags & SEC_LINKER_CREATED) != 0)
12937             isec->gc_mark = 1;
12938           else if (isec->gc_mark
12939                    && (isec->flags & SEC_ALLOC) != 0
12940                    && elf_section_type (isec) != SHT_NOTE)
12941             some_kept = TRUE;
12942
12943           if (!debug_frag_seen
12944               && (isec->flags & SEC_DEBUGGING)
12945               && CONST_STRNEQ (isec->name, ".debug_line."))
12946             debug_frag_seen = TRUE;
12947         }
12948
12949       /* If no non-note alloc section in this file will be kept, then
12950          we can toss out the debug and special sections.  */
12951       if (!some_kept)
12952         continue;
12953
12954       /* Keep debug and special sections like .comment when they are
12955          not part of a group.  Also keep section groups that contain
12956          just debug sections or special sections.  */
12957       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12958         {
12959           if ((isec->flags & SEC_GROUP) != 0)
12960             _bfd_elf_gc_mark_debug_special_section_group (isec);
12961           else if (((isec->flags & SEC_DEBUGGING) != 0
12962                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
12963                    && elf_next_in_group (isec) == NULL)
12964             isec->gc_mark = 1;
12965           if (isec->gc_mark && (isec->flags & SEC_DEBUGGING) != 0)
12966             has_kept_debug_info = TRUE;
12967         }
12968
12969       /* Look for CODE sections which are going to be discarded,
12970          and find and discard any fragmented debug sections which
12971          are associated with that code section.  */
12972       if (debug_frag_seen)
12973         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12974           if ((isec->flags & SEC_CODE) != 0
12975               && isec->gc_mark == 0)
12976             {
12977               unsigned int ilen;
12978               asection *dsec;
12979
12980               ilen = strlen (isec->name);
12981
12982               /* Association is determined by the name of the debug
12983                  section containing the name of the code section as
12984                  a suffix.  For example .debug_line.text.foo is a
12985                  debug section associated with .text.foo.  */
12986               for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
12987                 {
12988                   unsigned int dlen;
12989
12990                   if (dsec->gc_mark == 0
12991                       || (dsec->flags & SEC_DEBUGGING) == 0)
12992                     continue;
12993
12994                   dlen = strlen (dsec->name);
12995
12996                   if (dlen > ilen
12997                       && strncmp (dsec->name + (dlen - ilen),
12998                                   isec->name, ilen) == 0)
12999                     dsec->gc_mark = 0;
13000                 }
13001           }
13002
13003       /* Mark debug sections referenced by kept debug sections.  */
13004       if (has_kept_debug_info)
13005         for (isec = ibfd->sections; isec != NULL; isec = isec->next)
13006           if (isec->gc_mark
13007               && (isec->flags & SEC_DEBUGGING) != 0)
13008             if (!_bfd_elf_gc_mark (info, isec,
13009                                    elf_gc_mark_debug_section))
13010               return FALSE;
13011     }
13012   return TRUE;
13013 }
13014
13015 /* The sweep phase of garbage collection.  Remove all garbage sections.  */
13016
13017 typedef bfd_boolean (*gc_sweep_hook_fn)
13018   (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
13019
13020 static bfd_boolean
13021 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
13022 {
13023   bfd *sub;
13024   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13025   gc_sweep_hook_fn gc_sweep_hook = bed->gc_sweep_hook;
13026
13027   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13028     {
13029       asection *o;
13030
13031       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13032           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13033         continue;
13034       o = sub->sections;
13035       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13036         continue;
13037
13038       for (o = sub->sections; o != NULL; o = o->next)
13039         {
13040           /* When any section in a section group is kept, we keep all
13041              sections in the section group.  If the first member of
13042              the section group is excluded, we will also exclude the
13043              group section.  */
13044           if (o->flags & SEC_GROUP)
13045             {
13046               asection *first = elf_next_in_group (o);
13047               o->gc_mark = first->gc_mark;
13048             }
13049
13050           if (o->gc_mark)
13051             continue;
13052
13053           /* Skip sweeping sections already excluded.  */
13054           if (o->flags & SEC_EXCLUDE)
13055             continue;
13056
13057           /* Since this is early in the link process, it is simple
13058              to remove a section from the output.  */
13059           o->flags |= SEC_EXCLUDE;
13060
13061           if (info->print_gc_sections && o->size != 0)
13062             /* xgettext:c-format */
13063             _bfd_error_handler (_("Removing unused section '%A' in file '%B'"),
13064                                 o, sub);
13065
13066           /* But we also have to update some of the relocation
13067              info we collected before.  */
13068           if (gc_sweep_hook
13069               && (o->flags & SEC_RELOC) != 0
13070               && o->reloc_count != 0
13071               && !((info->strip == strip_all || info->strip == strip_debugger)
13072                    && (o->flags & SEC_DEBUGGING) != 0)
13073               && !bfd_is_abs_section (o->output_section))
13074             {
13075               Elf_Internal_Rela *internal_relocs;
13076               bfd_boolean r;
13077
13078               internal_relocs
13079                 = _bfd_elf_link_read_relocs (o->owner, o, NULL, NULL,
13080                                              info->keep_memory);
13081               if (internal_relocs == NULL)
13082                 return FALSE;
13083
13084               r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
13085
13086               if (elf_section_data (o)->relocs != internal_relocs)
13087                 free (internal_relocs);
13088
13089               if (!r)
13090                 return FALSE;
13091             }
13092         }
13093     }
13094
13095   return TRUE;
13096 }
13097
13098 /* Propagate collected vtable information.  This is called through
13099    elf_link_hash_traverse.  */
13100
13101 static bfd_boolean
13102 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
13103 {
13104   /* Those that are not vtables.  */
13105   if (h->start_stop
13106       || h->u2.vtable == NULL
13107       || h->u2.vtable->parent == NULL)
13108     return TRUE;
13109
13110   /* Those vtables that do not have parents, we cannot merge.  */
13111   if (h->u2.vtable->parent == (struct elf_link_hash_entry *) -1)
13112     return TRUE;
13113
13114   /* If we've already been done, exit.  */
13115   if (h->u2.vtable->used && h->u2.vtable->used[-1])
13116     return TRUE;
13117
13118   /* Make sure the parent's table is up to date.  */
13119   elf_gc_propagate_vtable_entries_used (h->u2.vtable->parent, okp);
13120
13121   if (h->u2.vtable->used == NULL)
13122     {
13123       /* None of this table's entries were referenced.  Re-use the
13124          parent's table.  */
13125       h->u2.vtable->used = h->u2.vtable->parent->u2.vtable->used;
13126       h->u2.vtable->size = h->u2.vtable->parent->u2.vtable->size;
13127     }
13128   else
13129     {
13130       size_t n;
13131       bfd_boolean *cu, *pu;
13132
13133       /* Or the parent's entries into ours.  */
13134       cu = h->u2.vtable->used;
13135       cu[-1] = TRUE;
13136       pu = h->u2.vtable->parent->u2.vtable->used;
13137       if (pu != NULL)
13138         {
13139           const struct elf_backend_data *bed;
13140           unsigned int log_file_align;
13141
13142           bed = get_elf_backend_data (h->root.u.def.section->owner);
13143           log_file_align = bed->s->log_file_align;
13144           n = h->u2.vtable->parent->u2.vtable->size >> log_file_align;
13145           while (n--)
13146             {
13147               if (*pu)
13148                 *cu = TRUE;
13149               pu++;
13150               cu++;
13151             }
13152         }
13153     }
13154
13155   return TRUE;
13156 }
13157
13158 static bfd_boolean
13159 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
13160 {
13161   asection *sec;
13162   bfd_vma hstart, hend;
13163   Elf_Internal_Rela *relstart, *relend, *rel;
13164   const struct elf_backend_data *bed;
13165   unsigned int log_file_align;
13166
13167   /* Take care of both those symbols that do not describe vtables as
13168      well as those that are not loaded.  */
13169   if (h->start_stop
13170       || h->u2.vtable == NULL
13171       || h->u2.vtable->parent == NULL)
13172     return TRUE;
13173
13174   BFD_ASSERT (h->root.type == bfd_link_hash_defined
13175               || h->root.type == bfd_link_hash_defweak);
13176
13177   sec = h->root.u.def.section;
13178   hstart = h->root.u.def.value;
13179   hend = hstart + h->size;
13180
13181   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
13182   if (!relstart)
13183     return *(bfd_boolean *) okp = FALSE;
13184   bed = get_elf_backend_data (sec->owner);
13185   log_file_align = bed->s->log_file_align;
13186
13187   relend = relstart + sec->reloc_count;
13188
13189   for (rel = relstart; rel < relend; ++rel)
13190     if (rel->r_offset >= hstart && rel->r_offset < hend)
13191       {
13192         /* If the entry is in use, do nothing.  */
13193         if (h->u2.vtable->used
13194             && (rel->r_offset - hstart) < h->u2.vtable->size)
13195           {
13196             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
13197             if (h->u2.vtable->used[entry])
13198               continue;
13199           }
13200         /* Otherwise, kill it.  */
13201         rel->r_offset = rel->r_info = rel->r_addend = 0;
13202       }
13203
13204   return TRUE;
13205 }
13206
13207 /* Mark sections containing dynamically referenced symbols.  When
13208    building shared libraries, we must assume that any visible symbol is
13209    referenced.  */
13210
13211 bfd_boolean
13212 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
13213 {
13214   struct bfd_link_info *info = (struct bfd_link_info *) inf;
13215   struct bfd_elf_dynamic_list *d = info->dynamic_list;
13216
13217   if ((h->root.type == bfd_link_hash_defined
13218        || h->root.type == bfd_link_hash_defweak)
13219       && (h->ref_dynamic
13220           || ((h->def_regular || ELF_COMMON_DEF_P (h))
13221               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
13222               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
13223               && (!bfd_link_executable (info)
13224                   || info->gc_keep_exported
13225                   || info->export_dynamic
13226                   || (h->dynamic
13227                       && d != NULL
13228                       && (*d->match) (&d->head, NULL, h->root.root.string)))
13229               && (h->versioned >= versioned
13230                   || !bfd_hide_sym_by_version (info->version_info,
13231                                                h->root.root.string)))))
13232     h->root.u.def.section->flags |= SEC_KEEP;
13233
13234   return TRUE;
13235 }
13236
13237 /* Keep all sections containing symbols undefined on the command-line,
13238    and the section containing the entry symbol.  */
13239
13240 void
13241 _bfd_elf_gc_keep (struct bfd_link_info *info)
13242 {
13243   struct bfd_sym_chain *sym;
13244
13245   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
13246     {
13247       struct elf_link_hash_entry *h;
13248
13249       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
13250                                 FALSE, FALSE, FALSE);
13251
13252       if (h != NULL
13253           && (h->root.type == bfd_link_hash_defined
13254               || h->root.type == bfd_link_hash_defweak)
13255           && !bfd_is_abs_section (h->root.u.def.section)
13256           && !bfd_is_und_section (h->root.u.def.section))
13257         h->root.u.def.section->flags |= SEC_KEEP;
13258     }
13259 }
13260
13261 bfd_boolean
13262 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
13263                                 struct bfd_link_info *info)
13264 {
13265   bfd *ibfd = info->input_bfds;
13266
13267   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13268     {
13269       asection *sec;
13270       struct elf_reloc_cookie cookie;
13271
13272       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13273         continue;
13274       sec = ibfd->sections;
13275       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13276         continue;
13277
13278       if (!init_reloc_cookie (&cookie, info, ibfd))
13279         return FALSE;
13280
13281       for (sec = ibfd->sections; sec; sec = sec->next)
13282         {
13283           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
13284               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
13285             {
13286               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
13287               fini_reloc_cookie_rels (&cookie, sec);
13288             }
13289         }
13290     }
13291   return TRUE;
13292 }
13293
13294 /* Do mark and sweep of unused sections.  */
13295
13296 bfd_boolean
13297 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
13298 {
13299   bfd_boolean ok = TRUE;
13300   bfd *sub;
13301   elf_gc_mark_hook_fn gc_mark_hook;
13302   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13303   struct elf_link_hash_table *htab;
13304
13305   if (!bed->can_gc_sections
13306       || !is_elf_hash_table (info->hash))
13307     {
13308       _bfd_error_handler(_("Warning: gc-sections option ignored"));
13309       return TRUE;
13310     }
13311
13312   bed->gc_keep (info);
13313   htab = elf_hash_table (info);
13314
13315   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
13316      at the .eh_frame section if we can mark the FDEs individually.  */
13317   for (sub = info->input_bfds;
13318        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
13319        sub = sub->link.next)
13320     {
13321       asection *sec;
13322       struct elf_reloc_cookie cookie;
13323
13324       sec = sub->sections;
13325       if (sec == NULL || sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13326         continue;
13327       sec = bfd_get_section_by_name (sub, ".eh_frame");
13328       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
13329         {
13330           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
13331           if (elf_section_data (sec)->sec_info
13332               && (sec->flags & SEC_LINKER_CREATED) == 0)
13333             elf_eh_frame_section (sub) = sec;
13334           fini_reloc_cookie_for_section (&cookie, sec);
13335           sec = bfd_get_next_section_by_name (NULL, sec);
13336         }
13337     }
13338
13339   /* Apply transitive closure to the vtable entry usage info.  */
13340   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
13341   if (!ok)
13342     return FALSE;
13343
13344   /* Kill the vtable relocations that were not used.  */
13345   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
13346   if (!ok)
13347     return FALSE;
13348
13349   /* Mark dynamically referenced symbols.  */
13350   if (htab->dynamic_sections_created || info->gc_keep_exported)
13351     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
13352
13353   /* Grovel through relocs to find out who stays ...  */
13354   gc_mark_hook = bed->gc_mark_hook;
13355   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13356     {
13357       asection *o;
13358
13359       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13360           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13361         continue;
13362
13363       o = sub->sections;
13364       if (o == NULL || o->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13365         continue;
13366
13367       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
13368          Also treat note sections as a root, if the section is not part
13369          of a group.  */
13370       for (o = sub->sections; o != NULL; o = o->next)
13371         if (!o->gc_mark
13372             && (o->flags & SEC_EXCLUDE) == 0
13373             && ((o->flags & SEC_KEEP) != 0
13374                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
13375                     && elf_next_in_group (o) == NULL )))
13376           {
13377             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
13378               return FALSE;
13379           }
13380     }
13381
13382   /* Allow the backend to mark additional target specific sections.  */
13383   bed->gc_mark_extra_sections (info, gc_mark_hook);
13384
13385   /* ... and mark SEC_EXCLUDE for those that go.  */
13386   return elf_gc_sweep (abfd, info);
13387 }
13388 \f
13389 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
13390
13391 bfd_boolean
13392 bfd_elf_gc_record_vtinherit (bfd *abfd,
13393                              asection *sec,
13394                              struct elf_link_hash_entry *h,
13395                              bfd_vma offset)
13396 {
13397   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
13398   struct elf_link_hash_entry **search, *child;
13399   size_t extsymcount;
13400   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13401
13402   /* The sh_info field of the symtab header tells us where the
13403      external symbols start.  We don't care about the local symbols at
13404      this point.  */
13405   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
13406   if (!elf_bad_symtab (abfd))
13407     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
13408
13409   sym_hashes = elf_sym_hashes (abfd);
13410   sym_hashes_end = sym_hashes + extsymcount;
13411
13412   /* Hunt down the child symbol, which is in this section at the same
13413      offset as the relocation.  */
13414   for (search = sym_hashes; search != sym_hashes_end; ++search)
13415     {
13416       if ((child = *search) != NULL
13417           && (child->root.type == bfd_link_hash_defined
13418               || child->root.type == bfd_link_hash_defweak)
13419           && child->root.u.def.section == sec
13420           && child->root.u.def.value == offset)
13421         goto win;
13422     }
13423
13424   /* xgettext:c-format */
13425   _bfd_error_handler (_("%B: %A+%lu: No symbol found for INHERIT"),
13426                       abfd, sec, (unsigned long) offset);
13427   bfd_set_error (bfd_error_invalid_operation);
13428   return FALSE;
13429
13430  win:
13431   if (!child->u2.vtable)
13432     {
13433       child->u2.vtable = ((struct elf_link_virtual_table_entry *)
13434                           bfd_zalloc (abfd, sizeof (*child->u2.vtable)));
13435       if (!child->u2.vtable)
13436         return FALSE;
13437     }
13438   if (!h)
13439     {
13440       /* This *should* only be the absolute section.  It could potentially
13441          be that someone has defined a non-global vtable though, which
13442          would be bad.  It isn't worth paging in the local symbols to be
13443          sure though; that case should simply be handled by the assembler.  */
13444
13445       child->u2.vtable->parent = (struct elf_link_hash_entry *) -1;
13446     }
13447   else
13448     child->u2.vtable->parent = h;
13449
13450   return TRUE;
13451 }
13452
13453 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
13454
13455 bfd_boolean
13456 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
13457                            asection *sec ATTRIBUTE_UNUSED,
13458                            struct elf_link_hash_entry *h,
13459                            bfd_vma addend)
13460 {
13461   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13462   unsigned int log_file_align = bed->s->log_file_align;
13463
13464   if (!h->u2.vtable)
13465     {
13466       h->u2.vtable = ((struct elf_link_virtual_table_entry *)
13467                       bfd_zalloc (abfd, sizeof (*h->u2.vtable)));
13468       if (!h->u2.vtable)
13469         return FALSE;
13470     }
13471
13472   if (addend >= h->u2.vtable->size)
13473     {
13474       size_t size, bytes, file_align;
13475       bfd_boolean *ptr = h->u2.vtable->used;
13476
13477       /* While the symbol is undefined, we have to be prepared to handle
13478          a zero size.  */
13479       file_align = 1 << log_file_align;
13480       if (h->root.type == bfd_link_hash_undefined)
13481         size = addend + file_align;
13482       else
13483         {
13484           size = h->size;
13485           if (addend >= size)
13486             {
13487               /* Oops!  We've got a reference past the defined end of
13488                  the table.  This is probably a bug -- shall we warn?  */
13489               size = addend + file_align;
13490             }
13491         }
13492       size = (size + file_align - 1) & -file_align;
13493
13494       /* Allocate one extra entry for use as a "done" flag for the
13495          consolidation pass.  */
13496       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
13497
13498       if (ptr)
13499         {
13500           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
13501
13502           if (ptr != NULL)
13503             {
13504               size_t oldbytes;
13505
13506               oldbytes = (((h->u2.vtable->size >> log_file_align) + 1)
13507                           * sizeof (bfd_boolean));
13508               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
13509             }
13510         }
13511       else
13512         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
13513
13514       if (ptr == NULL)
13515         return FALSE;
13516
13517       /* And arrange for that done flag to be at index -1.  */
13518       h->u2.vtable->used = ptr + 1;
13519       h->u2.vtable->size = size;
13520     }
13521
13522   h->u2.vtable->used[addend >> log_file_align] = TRUE;
13523
13524   return TRUE;
13525 }
13526
13527 /* Map an ELF section header flag to its corresponding string.  */
13528 typedef struct
13529 {
13530   char *flag_name;
13531   flagword flag_value;
13532 } elf_flags_to_name_table;
13533
13534 static elf_flags_to_name_table elf_flags_to_names [] =
13535 {
13536   { "SHF_WRITE", SHF_WRITE },
13537   { "SHF_ALLOC", SHF_ALLOC },
13538   { "SHF_EXECINSTR", SHF_EXECINSTR },
13539   { "SHF_MERGE", SHF_MERGE },
13540   { "SHF_STRINGS", SHF_STRINGS },
13541   { "SHF_INFO_LINK", SHF_INFO_LINK},
13542   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
13543   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
13544   { "SHF_GROUP", SHF_GROUP },
13545   { "SHF_TLS", SHF_TLS },
13546   { "SHF_MASKOS", SHF_MASKOS },
13547   { "SHF_EXCLUDE", SHF_EXCLUDE },
13548 };
13549
13550 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
13551 bfd_boolean
13552 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
13553                               struct flag_info *flaginfo,
13554                               asection *section)
13555 {
13556   const bfd_vma sh_flags = elf_section_flags (section);
13557
13558   if (!flaginfo->flags_initialized)
13559     {
13560       bfd *obfd = info->output_bfd;
13561       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13562       struct flag_info_list *tf = flaginfo->flag_list;
13563       int with_hex = 0;
13564       int without_hex = 0;
13565
13566       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
13567         {
13568           unsigned i;
13569           flagword (*lookup) (char *);
13570
13571           lookup = bed->elf_backend_lookup_section_flags_hook;
13572           if (lookup != NULL)
13573             {
13574               flagword hexval = (*lookup) ((char *) tf->name);
13575
13576               if (hexval != 0)
13577                 {
13578                   if (tf->with == with_flags)
13579                     with_hex |= hexval;
13580                   else if (tf->with == without_flags)
13581                     without_hex |= hexval;
13582                   tf->valid = TRUE;
13583                   continue;
13584                 }
13585             }
13586           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
13587             {
13588               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
13589                 {
13590                   if (tf->with == with_flags)
13591                     with_hex |= elf_flags_to_names[i].flag_value;
13592                   else if (tf->with == without_flags)
13593                     without_hex |= elf_flags_to_names[i].flag_value;
13594                   tf->valid = TRUE;
13595                   break;
13596                 }
13597             }
13598           if (!tf->valid)
13599             {
13600               info->callbacks->einfo
13601                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
13602               return FALSE;
13603             }
13604         }
13605       flaginfo->flags_initialized = TRUE;
13606       flaginfo->only_with_flags |= with_hex;
13607       flaginfo->not_with_flags |= without_hex;
13608     }
13609
13610   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
13611     return FALSE;
13612
13613   if ((flaginfo->not_with_flags & sh_flags) != 0)
13614     return FALSE;
13615
13616   return TRUE;
13617 }
13618
13619 struct alloc_got_off_arg {
13620   bfd_vma gotoff;
13621   struct bfd_link_info *info;
13622 };
13623
13624 /* We need a special top-level link routine to convert got reference counts
13625    to real got offsets.  */
13626
13627 static bfd_boolean
13628 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
13629 {
13630   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
13631   bfd *obfd = gofarg->info->output_bfd;
13632   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13633
13634   if (h->got.refcount > 0)
13635     {
13636       h->got.offset = gofarg->gotoff;
13637       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
13638     }
13639   else
13640     h->got.offset = (bfd_vma) -1;
13641
13642   return TRUE;
13643 }
13644
13645 /* And an accompanying bit to work out final got entry offsets once
13646    we're done.  Should be called from final_link.  */
13647
13648 bfd_boolean
13649 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
13650                                         struct bfd_link_info *info)
13651 {
13652   bfd *i;
13653   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13654   bfd_vma gotoff;
13655   struct alloc_got_off_arg gofarg;
13656
13657   BFD_ASSERT (abfd == info->output_bfd);
13658
13659   if (! is_elf_hash_table (info->hash))
13660     return FALSE;
13661
13662   /* The GOT offset is relative to the .got section, but the GOT header is
13663      put into the .got.plt section, if the backend uses it.  */
13664   if (bed->want_got_plt)
13665     gotoff = 0;
13666   else
13667     gotoff = bed->got_header_size;
13668
13669   /* Do the local .got entries first.  */
13670   for (i = info->input_bfds; i; i = i->link.next)
13671     {
13672       bfd_signed_vma *local_got;
13673       size_t j, locsymcount;
13674       Elf_Internal_Shdr *symtab_hdr;
13675
13676       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13677         continue;
13678
13679       local_got = elf_local_got_refcounts (i);
13680       if (!local_got)
13681         continue;
13682
13683       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13684       if (elf_bad_symtab (i))
13685         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13686       else
13687         locsymcount = symtab_hdr->sh_info;
13688
13689       for (j = 0; j < locsymcount; ++j)
13690         {
13691           if (local_got[j] > 0)
13692             {
13693               local_got[j] = gotoff;
13694               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13695             }
13696           else
13697             local_got[j] = (bfd_vma) -1;
13698         }
13699     }
13700
13701   /* Then the global .got entries.  .plt refcounts are handled by
13702      adjust_dynamic_symbol  */
13703   gofarg.gotoff = gotoff;
13704   gofarg.info = info;
13705   elf_link_hash_traverse (elf_hash_table (info),
13706                           elf_gc_allocate_got_offsets,
13707                           &gofarg);
13708   return TRUE;
13709 }
13710
13711 /* Many folk need no more in the way of final link than this, once
13712    got entry reference counting is enabled.  */
13713
13714 bfd_boolean
13715 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
13716 {
13717   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
13718     return FALSE;
13719
13720   /* Invoke the regular ELF backend linker to do all the work.  */
13721   return bfd_elf_final_link (abfd, info);
13722 }
13723
13724 bfd_boolean
13725 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
13726 {
13727   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
13728
13729   if (rcookie->bad_symtab)
13730     rcookie->rel = rcookie->rels;
13731
13732   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
13733     {
13734       unsigned long r_symndx;
13735
13736       if (! rcookie->bad_symtab)
13737         if (rcookie->rel->r_offset > offset)
13738           return FALSE;
13739       if (rcookie->rel->r_offset != offset)
13740         continue;
13741
13742       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
13743       if (r_symndx == STN_UNDEF)
13744         return TRUE;
13745
13746       if (r_symndx >= rcookie->locsymcount
13747           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13748         {
13749           struct elf_link_hash_entry *h;
13750
13751           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
13752
13753           while (h->root.type == bfd_link_hash_indirect
13754                  || h->root.type == bfd_link_hash_warning)
13755             h = (struct elf_link_hash_entry *) h->root.u.i.link;
13756
13757           if ((h->root.type == bfd_link_hash_defined
13758                || h->root.type == bfd_link_hash_defweak)
13759               && (h->root.u.def.section->owner != rcookie->abfd
13760                   || h->root.u.def.section->kept_section != NULL
13761                   || discarded_section (h->root.u.def.section)))
13762             return TRUE;
13763         }
13764       else
13765         {
13766           /* It's not a relocation against a global symbol,
13767              but it could be a relocation against a local
13768              symbol for a discarded section.  */
13769           asection *isec;
13770           Elf_Internal_Sym *isym;
13771
13772           /* Need to: get the symbol; get the section.  */
13773           isym = &rcookie->locsyms[r_symndx];
13774           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
13775           if (isec != NULL
13776               && (isec->kept_section != NULL
13777                   || discarded_section (isec)))
13778             return TRUE;
13779         }
13780       return FALSE;
13781     }
13782   return FALSE;
13783 }
13784
13785 /* Discard unneeded references to discarded sections.
13786    Returns -1 on error, 1 if any section's size was changed, 0 if
13787    nothing changed.  This function assumes that the relocations are in
13788    sorted order, which is true for all known assemblers.  */
13789
13790 int
13791 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
13792 {
13793   struct elf_reloc_cookie cookie;
13794   asection *o;
13795   bfd *abfd;
13796   int changed = 0;
13797
13798   if (info->traditional_format
13799       || !is_elf_hash_table (info->hash))
13800     return 0;
13801
13802   o = bfd_get_section_by_name (output_bfd, ".stab");
13803   if (o != NULL)
13804     {
13805       asection *i;
13806
13807       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13808         {
13809           if (i->size == 0
13810               || i->reloc_count == 0
13811               || i->sec_info_type != SEC_INFO_TYPE_STABS)
13812             continue;
13813
13814           abfd = i->owner;
13815           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13816             continue;
13817
13818           if (!init_reloc_cookie_for_section (&cookie, info, i))
13819             return -1;
13820
13821           if (_bfd_discard_section_stabs (abfd, i,
13822                                           elf_section_data (i)->sec_info,
13823                                           bfd_elf_reloc_symbol_deleted_p,
13824                                           &cookie))
13825             changed = 1;
13826
13827           fini_reloc_cookie_for_section (&cookie, i);
13828         }
13829     }
13830
13831   o = NULL;
13832   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
13833     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
13834   if (o != NULL)
13835     {
13836       asection *i;
13837       int eh_changed = 0;
13838
13839       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13840         {
13841           if (i->size == 0)
13842             continue;
13843
13844           abfd = i->owner;
13845           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13846             continue;
13847
13848           if (!init_reloc_cookie_for_section (&cookie, info, i))
13849             return -1;
13850
13851           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
13852           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
13853                                                  bfd_elf_reloc_symbol_deleted_p,
13854                                                  &cookie))
13855             {
13856               eh_changed = 1;
13857               if (i->size != i->rawsize)
13858                 changed = 1;
13859             }
13860
13861           fini_reloc_cookie_for_section (&cookie, i);
13862         }
13863       if (eh_changed)
13864         elf_link_hash_traverse (elf_hash_table (info),
13865                                 _bfd_elf_adjust_eh_frame_global_symbol, NULL);
13866     }
13867
13868   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
13869     {
13870       const struct elf_backend_data *bed;
13871       asection *s;
13872
13873       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13874         continue;
13875       s = abfd->sections;
13876       if (s == NULL || s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
13877         continue;
13878
13879       bed = get_elf_backend_data (abfd);
13880
13881       if (bed->elf_backend_discard_info != NULL)
13882         {
13883           if (!init_reloc_cookie (&cookie, info, abfd))
13884             return -1;
13885
13886           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
13887             changed = 1;
13888
13889           fini_reloc_cookie (&cookie, abfd);
13890         }
13891     }
13892
13893   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
13894     _bfd_elf_end_eh_frame_parsing (info);
13895
13896   if (info->eh_frame_hdr_type
13897       && !bfd_link_relocatable (info)
13898       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
13899     changed = 1;
13900
13901   return changed;
13902 }
13903
13904 bfd_boolean
13905 _bfd_elf_section_already_linked (bfd *abfd,
13906                                  asection *sec,
13907                                  struct bfd_link_info *info)
13908 {
13909   flagword flags;
13910   const char *name, *key;
13911   struct bfd_section_already_linked *l;
13912   struct bfd_section_already_linked_hash_entry *already_linked_list;
13913
13914   if (sec->output_section == bfd_abs_section_ptr)
13915     return FALSE;
13916
13917   flags = sec->flags;
13918
13919   /* Return if it isn't a linkonce section.  A comdat group section
13920      also has SEC_LINK_ONCE set.  */
13921   if ((flags & SEC_LINK_ONCE) == 0)
13922     return FALSE;
13923
13924   /* Don't put group member sections on our list of already linked
13925      sections.  They are handled as a group via their group section.  */
13926   if (elf_sec_group (sec) != NULL)
13927     return FALSE;
13928
13929   /* For a SHT_GROUP section, use the group signature as the key.  */
13930   name = sec->name;
13931   if ((flags & SEC_GROUP) != 0
13932       && elf_next_in_group (sec) != NULL
13933       && elf_group_name (elf_next_in_group (sec)) != NULL)
13934     key = elf_group_name (elf_next_in_group (sec));
13935   else
13936     {
13937       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
13938       if (CONST_STRNEQ (name, ".gnu.linkonce.")
13939           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
13940         key++;
13941       else
13942         /* Must be a user linkonce section that doesn't follow gcc's
13943            naming convention.  In this case we won't be matching
13944            single member groups.  */
13945         key = name;
13946     }
13947
13948   already_linked_list = bfd_section_already_linked_table_lookup (key);
13949
13950   for (l = already_linked_list->entry; l != NULL; l = l->next)
13951     {
13952       /* We may have 2 different types of sections on the list: group
13953          sections with a signature of <key> (<key> is some string),
13954          and linkonce sections named .gnu.linkonce.<type>.<key>.
13955          Match like sections.  LTO plugin sections are an exception.
13956          They are always named .gnu.linkonce.t.<key> and match either
13957          type of section.  */
13958       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
13959            && ((flags & SEC_GROUP) != 0
13960                || strcmp (name, l->sec->name) == 0))
13961           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
13962         {
13963           /* The section has already been linked.  See if we should
13964              issue a warning.  */
13965           if (!_bfd_handle_already_linked (sec, l, info))
13966             return FALSE;
13967
13968           if (flags & SEC_GROUP)
13969             {
13970               asection *first = elf_next_in_group (sec);
13971               asection *s = first;
13972
13973               while (s != NULL)
13974                 {
13975                   s->output_section = bfd_abs_section_ptr;
13976                   /* Record which group discards it.  */
13977                   s->kept_section = l->sec;
13978                   s = elf_next_in_group (s);
13979                   /* These lists are circular.  */
13980                   if (s == first)
13981                     break;
13982                 }
13983             }
13984
13985           return TRUE;
13986         }
13987     }
13988
13989   /* A single member comdat group section may be discarded by a
13990      linkonce section and vice versa.  */
13991   if ((flags & SEC_GROUP) != 0)
13992     {
13993       asection *first = elf_next_in_group (sec);
13994
13995       if (first != NULL && elf_next_in_group (first) == first)
13996         /* Check this single member group against linkonce sections.  */
13997         for (l = already_linked_list->entry; l != NULL; l = l->next)
13998           if ((l->sec->flags & SEC_GROUP) == 0
13999               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
14000             {
14001               first->output_section = bfd_abs_section_ptr;
14002               first->kept_section = l->sec;
14003               sec->output_section = bfd_abs_section_ptr;
14004               break;
14005             }
14006     }
14007   else
14008     /* Check this linkonce section against single member groups.  */
14009     for (l = already_linked_list->entry; l != NULL; l = l->next)
14010       if (l->sec->flags & SEC_GROUP)
14011         {
14012           asection *first = elf_next_in_group (l->sec);
14013
14014           if (first != NULL
14015               && elf_next_in_group (first) == first
14016               && bfd_elf_match_symbols_in_sections (first, sec, info))
14017             {
14018               sec->output_section = bfd_abs_section_ptr;
14019               sec->kept_section = first;
14020               break;
14021             }
14022         }
14023
14024   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
14025      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
14026      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
14027      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
14028      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
14029      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
14030      `.gnu.linkonce.t.F' section from a different bfd not requiring any
14031      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
14032      The reverse order cannot happen as there is never a bfd with only the
14033      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
14034      matter as here were are looking only for cross-bfd sections.  */
14035
14036   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
14037     for (l = already_linked_list->entry; l != NULL; l = l->next)
14038       if ((l->sec->flags & SEC_GROUP) == 0
14039           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
14040         {
14041           if (abfd != l->sec->owner)
14042             sec->output_section = bfd_abs_section_ptr;
14043           break;
14044         }
14045
14046   /* This is the first section with this name.  Record it.  */
14047   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
14048     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
14049   return sec->output_section == bfd_abs_section_ptr;
14050 }
14051
14052 bfd_boolean
14053 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
14054 {
14055   return sym->st_shndx == SHN_COMMON;
14056 }
14057
14058 unsigned int
14059 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
14060 {
14061   return SHN_COMMON;
14062 }
14063
14064 asection *
14065 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
14066 {
14067   return bfd_com_section_ptr;
14068 }
14069
14070 bfd_vma
14071 _bfd_elf_default_got_elt_size (bfd *abfd,
14072                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
14073                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
14074                                bfd *ibfd ATTRIBUTE_UNUSED,
14075                                unsigned long symndx ATTRIBUTE_UNUSED)
14076 {
14077   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14078   return bed->s->arch_size / 8;
14079 }
14080
14081 /* Routines to support the creation of dynamic relocs.  */
14082
14083 /* Returns the name of the dynamic reloc section associated with SEC.  */
14084
14085 static const char *
14086 get_dynamic_reloc_section_name (bfd *       abfd,
14087                                 asection *  sec,
14088                                 bfd_boolean is_rela)
14089 {
14090   char *name;
14091   const char *old_name = bfd_get_section_name (NULL, sec);
14092   const char *prefix = is_rela ? ".rela" : ".rel";
14093
14094   if (old_name == NULL)
14095     return NULL;
14096
14097   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
14098   sprintf (name, "%s%s", prefix, old_name);
14099
14100   return name;
14101 }
14102
14103 /* Returns the dynamic reloc section associated with SEC.
14104    If necessary compute the name of the dynamic reloc section based
14105    on SEC's name (looked up in ABFD's string table) and the setting
14106    of IS_RELA.  */
14107
14108 asection *
14109 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
14110                                     asection *  sec,
14111                                     bfd_boolean is_rela)
14112 {
14113   asection * reloc_sec = elf_section_data (sec)->sreloc;
14114
14115   if (reloc_sec == NULL)
14116     {
14117       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14118
14119       if (name != NULL)
14120         {
14121           reloc_sec = bfd_get_linker_section (abfd, name);
14122
14123           if (reloc_sec != NULL)
14124             elf_section_data (sec)->sreloc = reloc_sec;
14125         }
14126     }
14127
14128   return reloc_sec;
14129 }
14130
14131 /* Returns the dynamic reloc section associated with SEC.  If the
14132    section does not exist it is created and attached to the DYNOBJ
14133    bfd and stored in the SRELOC field of SEC's elf_section_data
14134    structure.
14135
14136    ALIGNMENT is the alignment for the newly created section and
14137    IS_RELA defines whether the name should be .rela.<SEC's name>
14138    or .rel.<SEC's name>.  The section name is looked up in the
14139    string table associated with ABFD.  */
14140
14141 asection *
14142 _bfd_elf_make_dynamic_reloc_section (asection *sec,
14143                                      bfd *dynobj,
14144                                      unsigned int alignment,
14145                                      bfd *abfd,
14146                                      bfd_boolean is_rela)
14147 {
14148   asection * reloc_sec = elf_section_data (sec)->sreloc;
14149
14150   if (reloc_sec == NULL)
14151     {
14152       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14153
14154       if (name == NULL)
14155         return NULL;
14156
14157       reloc_sec = bfd_get_linker_section (dynobj, name);
14158
14159       if (reloc_sec == NULL)
14160         {
14161           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
14162                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
14163           if ((sec->flags & SEC_ALLOC) != 0)
14164             flags |= SEC_ALLOC | SEC_LOAD;
14165
14166           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
14167           if (reloc_sec != NULL)
14168             {
14169               /* _bfd_elf_get_sec_type_attr chooses a section type by
14170                  name.  Override as it may be wrong, eg. for a user
14171                  section named "auto" we'll get ".relauto" which is
14172                  seen to be a .rela section.  */
14173               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
14174               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
14175                 reloc_sec = NULL;
14176             }
14177         }
14178
14179       elf_section_data (sec)->sreloc = reloc_sec;
14180     }
14181
14182   return reloc_sec;
14183 }
14184
14185 /* Copy the ELF symbol type and other attributes for a linker script
14186    assignment from HSRC to HDEST.  Generally this should be treated as
14187    if we found a strong non-dynamic definition for HDEST (except that
14188    ld ignores multiple definition errors).  */
14189 void
14190 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
14191                                      struct bfd_link_hash_entry *hdest,
14192                                      struct bfd_link_hash_entry *hsrc)
14193 {
14194   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
14195   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
14196   Elf_Internal_Sym isym;
14197
14198   ehdest->type = ehsrc->type;
14199   ehdest->target_internal = ehsrc->target_internal;
14200
14201   isym.st_other = ehsrc->other;
14202   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
14203 }
14204
14205 /* Append a RELA relocation REL to section S in BFD.  */
14206
14207 void
14208 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14209 {
14210   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14211   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
14212   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
14213   bed->s->swap_reloca_out (abfd, rel, loc);
14214 }
14215
14216 /* Append a REL relocation REL to section S in BFD.  */
14217
14218 void
14219 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14220 {
14221   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14222   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
14223   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
14224   bed->s->swap_reloc_out (abfd, rel, loc);
14225 }
14226
14227 /* Define __start, __stop, .startof. or .sizeof. symbol.  */
14228
14229 struct bfd_link_hash_entry *
14230 bfd_elf_define_start_stop (struct bfd_link_info *info,
14231                            const char *symbol, asection *sec)
14232 {
14233   struct bfd_link_hash_entry *h;
14234
14235   h = bfd_generic_define_start_stop (info, symbol, sec);
14236   if (h != NULL)
14237     {
14238       struct elf_link_hash_entry *eh = (struct elf_link_hash_entry *) h;
14239       eh->start_stop = 1;
14240       eh->u2.start_stop_section = sec;
14241       _bfd_elf_link_hash_hide_symbol (info, eh, TRUE);
14242       if (ELF_ST_VISIBILITY (eh->other) != STV_INTERNAL)
14243         eh->other = ((eh->other & ~ELF_ST_VISIBILITY (-1))
14244                      | STV_HIDDEN);
14245     }
14246   return h;
14247 }