Fix null pointer dereferences when using a link built with clang.
[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           for (ibfd = info->input_bfds; ibfd; ibfd = ibfd->link.next)
222             if ((ibfd->flags
223                  & (DYNAMIC | BFD_LINKER_CREATED | BFD_PLUGIN)) == 0)
224               {
225                 abfd = ibfd;
226                 break;
227               }
228         }
229       hash_table->dynobj = abfd;
230     }
231
232   if (hash_table->dynstr == NULL)
233     {
234       hash_table->dynstr = _bfd_elf_strtab_init ();
235       if (hash_table->dynstr == NULL)
236         return FALSE;
237     }
238   return TRUE;
239 }
240
241 /* Create some sections which will be filled in with dynamic linking
242    information.  ABFD is an input file which requires dynamic sections
243    to be created.  The dynamic sections take up virtual memory space
244    when the final executable is run, so we need to create them before
245    addresses are assigned to the output sections.  We work out the
246    actual contents and size of these sections later.  */
247
248 bfd_boolean
249 _bfd_elf_link_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
250 {
251   flagword flags;
252   asection *s;
253   const struct elf_backend_data *bed;
254   struct elf_link_hash_entry *h;
255
256   if (! is_elf_hash_table (info->hash))
257     return FALSE;
258
259   if (elf_hash_table (info)->dynamic_sections_created)
260     return TRUE;
261
262   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
263     return FALSE;
264
265   abfd = elf_hash_table (info)->dynobj;
266   bed = get_elf_backend_data (abfd);
267
268   flags = bed->dynamic_sec_flags;
269
270   /* A dynamically linked executable has a .interp section, but a
271      shared library does not.  */
272   if (bfd_link_executable (info) && !info->nointerp)
273     {
274       s = bfd_make_section_anyway_with_flags (abfd, ".interp",
275                                               flags | SEC_READONLY);
276       if (s == NULL)
277         return FALSE;
278     }
279
280   /* Create sections to hold version informations.  These are removed
281      if they are not needed.  */
282   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_d",
283                                           flags | SEC_READONLY);
284   if (s == NULL
285       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
286     return FALSE;
287
288   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version",
289                                           flags | SEC_READONLY);
290   if (s == NULL
291       || ! bfd_set_section_alignment (abfd, s, 1))
292     return FALSE;
293
294   s = bfd_make_section_anyway_with_flags (abfd, ".gnu.version_r",
295                                           flags | SEC_READONLY);
296   if (s == NULL
297       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
298     return FALSE;
299
300   s = bfd_make_section_anyway_with_flags (abfd, ".dynsym",
301                                           flags | SEC_READONLY);
302   if (s == NULL
303       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
304     return FALSE;
305   elf_hash_table (info)->dynsym = s;
306
307   s = bfd_make_section_anyway_with_flags (abfd, ".dynstr",
308                                           flags | SEC_READONLY);
309   if (s == NULL)
310     return FALSE;
311
312   s = bfd_make_section_anyway_with_flags (abfd, ".dynamic", flags);
313   if (s == NULL
314       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
315     return FALSE;
316
317   /* The special symbol _DYNAMIC is always set to the start of the
318      .dynamic section.  We could set _DYNAMIC in a linker script, but we
319      only want to define it if we are, in fact, creating a .dynamic
320      section.  We don't want to define it if there is no .dynamic
321      section, since on some ELF platforms the start up code examines it
322      to decide how to initialize the process.  */
323   h = _bfd_elf_define_linkage_sym (abfd, info, s, "_DYNAMIC");
324   elf_hash_table (info)->hdynamic = h;
325   if (h == NULL)
326     return FALSE;
327
328   if (info->emit_hash)
329     {
330       s = bfd_make_section_anyway_with_flags (abfd, ".hash",
331                                               flags | SEC_READONLY);
332       if (s == NULL
333           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
334         return FALSE;
335       elf_section_data (s)->this_hdr.sh_entsize = bed->s->sizeof_hash_entry;
336     }
337
338   if (info->emit_gnu_hash)
339     {
340       s = bfd_make_section_anyway_with_flags (abfd, ".gnu.hash",
341                                               flags | SEC_READONLY);
342       if (s == NULL
343           || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
344         return FALSE;
345       /* For 64-bit ELF, .gnu.hash is a non-uniform entity size section:
346          4 32-bit words followed by variable count of 64-bit words, then
347          variable count of 32-bit words.  */
348       if (bed->s->arch_size == 64)
349         elf_section_data (s)->this_hdr.sh_entsize = 0;
350       else
351         elf_section_data (s)->this_hdr.sh_entsize = 4;
352     }
353
354   /* Let the backend create the rest of the sections.  This lets the
355      backend set the right flags.  The backend will normally create
356      the .got and .plt sections.  */
357   if (bed->elf_backend_create_dynamic_sections == NULL
358       || ! (*bed->elf_backend_create_dynamic_sections) (abfd, info))
359     return FALSE;
360
361   elf_hash_table (info)->dynamic_sections_created = TRUE;
362
363   return TRUE;
364 }
365
366 /* Create dynamic sections when linking against a dynamic object.  */
367
368 bfd_boolean
369 _bfd_elf_create_dynamic_sections (bfd *abfd, struct bfd_link_info *info)
370 {
371   flagword flags, pltflags;
372   struct elf_link_hash_entry *h;
373   asection *s;
374   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
375   struct elf_link_hash_table *htab = elf_hash_table (info);
376
377   /* We need to create .plt, .rel[a].plt, .got, .got.plt, .dynbss, and
378      .rel[a].bss sections.  */
379   flags = bed->dynamic_sec_flags;
380
381   pltflags = flags;
382   if (bed->plt_not_loaded)
383     /* We do not clear SEC_ALLOC here because we still want the OS to
384        allocate space for the section; it's just that there's nothing
385        to read in from the object file.  */
386     pltflags &= ~ (SEC_CODE | SEC_LOAD | SEC_HAS_CONTENTS);
387   else
388     pltflags |= SEC_ALLOC | SEC_CODE | SEC_LOAD;
389   if (bed->plt_readonly)
390     pltflags |= SEC_READONLY;
391
392   s = bfd_make_section_anyway_with_flags (abfd, ".plt", pltflags);
393   if (s == NULL
394       || ! bfd_set_section_alignment (abfd, s, bed->plt_alignment))
395     return FALSE;
396   htab->splt = s;
397
398   /* Define the symbol _PROCEDURE_LINKAGE_TABLE_ at the start of the
399      .plt section.  */
400   if (bed->want_plt_sym)
401     {
402       h = _bfd_elf_define_linkage_sym (abfd, info, s,
403                                        "_PROCEDURE_LINKAGE_TABLE_");
404       elf_hash_table (info)->hplt = h;
405       if (h == NULL)
406         return FALSE;
407     }
408
409   s = bfd_make_section_anyway_with_flags (abfd,
410                                           (bed->rela_plts_and_copies_p
411                                            ? ".rela.plt" : ".rel.plt"),
412                                           flags | SEC_READONLY);
413   if (s == NULL
414       || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
415     return FALSE;
416   htab->srelplt = s;
417
418   if (! _bfd_elf_create_got_section (abfd, info))
419     return FALSE;
420
421   if (bed->want_dynbss)
422     {
423       /* The .dynbss section is a place to put symbols which are defined
424          by dynamic objects, are referenced by regular objects, and are
425          not functions.  We must allocate space for them in the process
426          image and use a R_*_COPY reloc to tell the dynamic linker to
427          initialize them at run time.  The linker script puts the .dynbss
428          section into the .bss section of the final image.  */
429       s = bfd_make_section_anyway_with_flags (abfd, ".dynbss",
430                                               SEC_ALLOC | SEC_LINKER_CREATED);
431       if (s == NULL)
432         return FALSE;
433       htab->sdynbss = s;
434
435       if (bed->want_dynrelro)
436         {
437           /* Similarly, but for symbols that were originally in read-only
438              sections.  This section doesn't really need to have contents,
439              but make it like other .data.rel.ro sections.  */
440           s = bfd_make_section_anyway_with_flags (abfd, ".data.rel.ro",
441                                                   flags);
442           if (s == NULL)
443             return FALSE;
444           htab->sdynrelro = s;
445         }
446
447       /* The .rel[a].bss section holds copy relocs.  This section is not
448          normally needed.  We need to create it here, though, so that the
449          linker will map it to an output section.  We can't just create it
450          only if we need it, because we will not know whether we need it
451          until we have seen all the input files, and the first time the
452          main linker code calls BFD after examining all the input files
453          (size_dynamic_sections) the input sections have already been
454          mapped to the output sections.  If the section turns out not to
455          be needed, we can discard it later.  We will never need this
456          section when generating a shared object, since they do not use
457          copy relocs.  */
458       if (bfd_link_executable (info))
459         {
460           s = bfd_make_section_anyway_with_flags (abfd,
461                                                   (bed->rela_plts_and_copies_p
462                                                    ? ".rela.bss" : ".rel.bss"),
463                                                   flags | SEC_READONLY);
464           if (s == NULL
465               || ! bfd_set_section_alignment (abfd, s, bed->s->log_file_align))
466             return FALSE;
467           htab->srelbss = s;
468
469           if (bed->want_dynrelro)
470             {
471               s = (bfd_make_section_anyway_with_flags
472                    (abfd, (bed->rela_plts_and_copies_p
473                            ? ".rela.data.rel.ro" : ".rel.data.rel.ro"),
474                     flags | SEC_READONLY));
475               if (s == NULL
476                   || ! bfd_set_section_alignment (abfd, s,
477                                                   bed->s->log_file_align))
478                 return FALSE;
479               htab->sreldynrelro = s;
480             }
481         }
482     }
483
484   return TRUE;
485 }
486 \f
487 /* Record a new dynamic symbol.  We record the dynamic symbols as we
488    read the input files, since we need to have a list of all of them
489    before we can determine the final sizes of the output sections.
490    Note that we may actually call this function even though we are not
491    going to output any dynamic symbols; in some cases we know that a
492    symbol should be in the dynamic symbol table, but only if there is
493    one.  */
494
495 bfd_boolean
496 bfd_elf_link_record_dynamic_symbol (struct bfd_link_info *info,
497                                     struct elf_link_hash_entry *h)
498 {
499   if (h->dynindx == -1)
500     {
501       struct elf_strtab_hash *dynstr;
502       char *p;
503       const char *name;
504       size_t indx;
505
506       /* XXX: The ABI draft says the linker must turn hidden and
507          internal symbols into STB_LOCAL symbols when producing the
508          DSO. However, if ld.so honors st_other in the dynamic table,
509          this would not be necessary.  */
510       switch (ELF_ST_VISIBILITY (h->other))
511         {
512         case STV_INTERNAL:
513         case STV_HIDDEN:
514           if (h->root.type != bfd_link_hash_undefined
515               && h->root.type != bfd_link_hash_undefweak)
516             {
517               h->forced_local = 1;
518               if (!elf_hash_table (info)->is_relocatable_executable)
519                 return TRUE;
520             }
521
522         default:
523           break;
524         }
525
526       h->dynindx = elf_hash_table (info)->dynsymcount;
527       ++elf_hash_table (info)->dynsymcount;
528
529       dynstr = elf_hash_table (info)->dynstr;
530       if (dynstr == NULL)
531         {
532           /* Create a strtab to hold the dynamic symbol names.  */
533           elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
534           if (dynstr == NULL)
535             return FALSE;
536         }
537
538       /* We don't put any version information in the dynamic string
539          table.  */
540       name = h->root.root.string;
541       p = strchr (name, ELF_VER_CHR);
542       if (p != NULL)
543         /* We know that the p points into writable memory.  In fact,
544            there are only a few symbols that have read-only names, being
545            those like _GLOBAL_OFFSET_TABLE_ that are created specially
546            by the backends.  Most symbols will have names pointing into
547            an ELF string table read from a file, or to objalloc memory.  */
548         *p = 0;
549
550       indx = _bfd_elf_strtab_add (dynstr, name, p != NULL);
551
552       if (p != NULL)
553         *p = ELF_VER_CHR;
554
555       if (indx == (size_t) -1)
556         return FALSE;
557       h->dynstr_index = indx;
558     }
559
560   return TRUE;
561 }
562 \f
563 /* Mark a symbol dynamic.  */
564
565 static void
566 bfd_elf_link_mark_dynamic_symbol (struct bfd_link_info *info,
567                                   struct elf_link_hash_entry *h,
568                                   Elf_Internal_Sym *sym)
569 {
570   struct bfd_elf_dynamic_list *d = info->dynamic_list;
571
572   /* It may be called more than once on the same H.  */
573   if(h->dynamic || bfd_link_relocatable (info))
574     return;
575
576   if ((info->dynamic_data
577        && (h->type == STT_OBJECT
578            || h->type == STT_COMMON
579            || (sym != NULL
580                && (ELF_ST_TYPE (sym->st_info) == STT_OBJECT
581                    || ELF_ST_TYPE (sym->st_info) == STT_COMMON))))
582       || (d != NULL
583           && h->root.type == bfd_link_hash_new
584           && (*d->match) (&d->head, NULL, h->root.root.string)))
585     h->dynamic = 1;
586 }
587
588 /* Record an assignment to a symbol made by a linker script.  We need
589    this in case some dynamic object refers to this symbol.  */
590
591 bfd_boolean
592 bfd_elf_record_link_assignment (bfd *output_bfd,
593                                 struct bfd_link_info *info,
594                                 const char *name,
595                                 bfd_boolean provide,
596                                 bfd_boolean hidden)
597 {
598   struct elf_link_hash_entry *h, *hv;
599   struct elf_link_hash_table *htab;
600   const struct elf_backend_data *bed;
601
602   if (!is_elf_hash_table (info->hash))
603     return TRUE;
604
605   htab = elf_hash_table (info);
606   h = elf_link_hash_lookup (htab, name, !provide, TRUE, FALSE);
607   if (h == NULL)
608     return provide;
609
610   if (h->root.type == bfd_link_hash_warning)
611     h = (struct elf_link_hash_entry *) h->root.u.i.link;
612
613   if (h->versioned == unknown)
614     {
615       /* Set versioned if symbol version is unknown.  */
616       char *version = strrchr (name, ELF_VER_CHR);
617       if (version)
618         {
619           if (version > name && version[-1] != ELF_VER_CHR)
620             h->versioned = versioned_hidden;
621           else
622             h->versioned = versioned;
623         }
624     }
625
626   switch (h->root.type)
627     {
628     case bfd_link_hash_defined:
629     case bfd_link_hash_defweak:
630     case bfd_link_hash_common:
631       break;
632     case bfd_link_hash_undefweak:
633     case bfd_link_hash_undefined:
634       /* Since we're defining the symbol, don't let it seem to have not
635          been defined.  record_dynamic_symbol and size_dynamic_sections
636          may depend on this.  */
637       h->root.type = bfd_link_hash_new;
638       if (h->root.u.undef.next != NULL || htab->root.undefs_tail == &h->root)
639         bfd_link_repair_undef_list (&htab->root);
640       break;
641     case bfd_link_hash_new:
642       bfd_elf_link_mark_dynamic_symbol (info, h, NULL);
643       h->non_elf = 0;
644       break;
645     case bfd_link_hash_indirect:
646       /* We had a versioned symbol in a dynamic library.  We make the
647          the versioned symbol point to this one.  */
648       bed = get_elf_backend_data (output_bfd);
649       hv = h;
650       while (hv->root.type == bfd_link_hash_indirect
651              || hv->root.type == bfd_link_hash_warning)
652         hv = (struct elf_link_hash_entry *) hv->root.u.i.link;
653       /* We don't need to update h->root.u since linker will set them
654          later.  */
655       h->root.type = bfd_link_hash_undefined;
656       hv->root.type = bfd_link_hash_indirect;
657       hv->root.u.i.link = (struct bfd_link_hash_entry *) h;
658       (*bed->elf_backend_copy_indirect_symbol) (info, h, hv);
659       break;
660     default:
661       BFD_FAIL ();
662       return FALSE;
663     }
664
665   /* If this symbol is being provided by the linker script, and it is
666      currently defined by a dynamic object, but not by a regular
667      object, then mark it as undefined so that the generic linker will
668      force the correct value.  */
669   if (provide
670       && h->def_dynamic
671       && !h->def_regular)
672     h->root.type = bfd_link_hash_undefined;
673
674   /* If this symbol is not being provided by the linker script, and it is
675      currently defined by a dynamic object, but not by a regular object,
676      then clear out any version information because the symbol will not be
677      associated with the dynamic object any more.  */
678   if (!provide
679       && h->def_dynamic
680       && !h->def_regular)
681     h->verinfo.verdef = NULL;
682
683   /* Make sure this symbol is not garbage collected.  */
684   h->mark = 1;
685
686   h->def_regular = 1;
687
688   if (hidden)
689     {
690       bed = get_elf_backend_data (output_bfd);
691       if (ELF_ST_VISIBILITY (h->other) != STV_INTERNAL)
692         h->other = (h->other & ~ELF_ST_VISIBILITY (-1)) | STV_HIDDEN;
693       (*bed->elf_backend_hide_symbol) (info, h, TRUE);
694     }
695
696   /* STV_HIDDEN and STV_INTERNAL symbols must be STB_LOCAL in shared objects
697      and executables.  */
698   if (!bfd_link_relocatable (info)
699       && h->dynindx != -1
700       && (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
701           || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL))
702     h->forced_local = 1;
703
704   if ((h->def_dynamic
705        || h->ref_dynamic
706        || bfd_link_dll (info)
707        || elf_hash_table (info)->is_relocatable_executable)
708       && h->dynindx == -1)
709     {
710       if (! bfd_elf_link_record_dynamic_symbol (info, h))
711         return FALSE;
712
713       /* If this is a weak defined symbol, and we know a corresponding
714          real symbol from the same dynamic object, make sure the real
715          symbol is also made into a dynamic symbol.  */
716       if (h->u.weakdef != NULL
717           && h->u.weakdef->dynindx == -1)
718         {
719           if (! bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
720             return FALSE;
721         }
722     }
723
724   return TRUE;
725 }
726
727 /* Record a new local dynamic symbol.  Returns 0 on failure, 1 on
728    success, and 2 on a failure caused by attempting to record a symbol
729    in a discarded section, eg. a discarded link-once section symbol.  */
730
731 int
732 bfd_elf_link_record_local_dynamic_symbol (struct bfd_link_info *info,
733                                           bfd *input_bfd,
734                                           long input_indx)
735 {
736   bfd_size_type amt;
737   struct elf_link_local_dynamic_entry *entry;
738   struct elf_link_hash_table *eht;
739   struct elf_strtab_hash *dynstr;
740   size_t dynstr_index;
741   char *name;
742   Elf_External_Sym_Shndx eshndx;
743   char esym[sizeof (Elf64_External_Sym)];
744
745   if (! is_elf_hash_table (info->hash))
746     return 0;
747
748   /* See if the entry exists already.  */
749   for (entry = elf_hash_table (info)->dynlocal; entry ; entry = entry->next)
750     if (entry->input_bfd == input_bfd && entry->input_indx == input_indx)
751       return 1;
752
753   amt = sizeof (*entry);
754   entry = (struct elf_link_local_dynamic_entry *) bfd_alloc (input_bfd, amt);
755   if (entry == NULL)
756     return 0;
757
758   /* Go find the symbol, so that we can find it's name.  */
759   if (!bfd_elf_get_elf_syms (input_bfd, &elf_tdata (input_bfd)->symtab_hdr,
760                              1, input_indx, &entry->isym, esym, &eshndx))
761     {
762       bfd_release (input_bfd, entry);
763       return 0;
764     }
765
766   if (entry->isym.st_shndx != SHN_UNDEF
767       && entry->isym.st_shndx < SHN_LORESERVE)
768     {
769       asection *s;
770
771       s = bfd_section_from_elf_index (input_bfd, entry->isym.st_shndx);
772       if (s == NULL || bfd_is_abs_section (s->output_section))
773         {
774           /* We can still bfd_release here as nothing has done another
775              bfd_alloc.  We can't do this later in this function.  */
776           bfd_release (input_bfd, entry);
777           return 2;
778         }
779     }
780
781   name = (bfd_elf_string_from_elf_section
782           (input_bfd, elf_tdata (input_bfd)->symtab_hdr.sh_link,
783            entry->isym.st_name));
784
785   dynstr = elf_hash_table (info)->dynstr;
786   if (dynstr == NULL)
787     {
788       /* Create a strtab to hold the dynamic symbol names.  */
789       elf_hash_table (info)->dynstr = dynstr = _bfd_elf_strtab_init ();
790       if (dynstr == NULL)
791         return 0;
792     }
793
794   dynstr_index = _bfd_elf_strtab_add (dynstr, name, FALSE);
795   if (dynstr_index == (size_t) -1)
796     return 0;
797   entry->isym.st_name = dynstr_index;
798
799   eht = elf_hash_table (info);
800
801   entry->next = eht->dynlocal;
802   eht->dynlocal = entry;
803   entry->input_bfd = input_bfd;
804   entry->input_indx = input_indx;
805   eht->dynsymcount++;
806
807   /* Whatever binding the symbol had before, it's now local.  */
808   entry->isym.st_info
809     = ELF_ST_INFO (STB_LOCAL, ELF_ST_TYPE (entry->isym.st_info));
810
811   /* The dynindx will be set at the end of size_dynamic_sections.  */
812
813   return 1;
814 }
815
816 /* Return the dynindex of a local dynamic symbol.  */
817
818 long
819 _bfd_elf_link_lookup_local_dynindx (struct bfd_link_info *info,
820                                     bfd *input_bfd,
821                                     long input_indx)
822 {
823   struct elf_link_local_dynamic_entry *e;
824
825   for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
826     if (e->input_bfd == input_bfd && e->input_indx == input_indx)
827       return e->dynindx;
828   return -1;
829 }
830
831 /* This function is used to renumber the dynamic symbols, if some of
832    them are removed because they are marked as local.  This is called
833    via elf_link_hash_traverse.  */
834
835 static bfd_boolean
836 elf_link_renumber_hash_table_dynsyms (struct elf_link_hash_entry *h,
837                                       void *data)
838 {
839   size_t *count = (size_t *) data;
840
841   if (h->forced_local)
842     return TRUE;
843
844   if (h->dynindx != -1)
845     h->dynindx = ++(*count);
846
847   return TRUE;
848 }
849
850
851 /* Like elf_link_renumber_hash_table_dynsyms, but just number symbols with
852    STB_LOCAL binding.  */
853
854 static bfd_boolean
855 elf_link_renumber_local_hash_table_dynsyms (struct elf_link_hash_entry *h,
856                                             void *data)
857 {
858   size_t *count = (size_t *) data;
859
860   if (!h->forced_local)
861     return TRUE;
862
863   if (h->dynindx != -1)
864     h->dynindx = ++(*count);
865
866   return TRUE;
867 }
868
869 /* Return true if the dynamic symbol for a given section should be
870    omitted when creating a shared library.  */
871 bfd_boolean
872 _bfd_elf_link_omit_section_dynsym (bfd *output_bfd ATTRIBUTE_UNUSED,
873                                    struct bfd_link_info *info,
874                                    asection *p)
875 {
876   struct elf_link_hash_table *htab;
877   asection *ip;
878
879   switch (elf_section_data (p)->this_hdr.sh_type)
880     {
881     case SHT_PROGBITS:
882     case SHT_NOBITS:
883       /* If sh_type is yet undecided, assume it could be
884          SHT_PROGBITS/SHT_NOBITS.  */
885     case SHT_NULL:
886       htab = elf_hash_table (info);
887       if (p == htab->tls_sec)
888         return FALSE;
889
890       if (htab->text_index_section != NULL)
891         return p != htab->text_index_section && p != htab->data_index_section;
892
893       return (htab->dynobj != NULL
894               && (ip = bfd_get_linker_section (htab->dynobj, p->name)) != NULL
895               && ip->output_section == p);
896
897       /* There shouldn't be section relative relocations
898          against any other section.  */
899     default:
900       return TRUE;
901     }
902 }
903
904 /* Assign dynsym indices.  In a shared library we generate a section
905    symbol for each output section, which come first.  Next come symbols
906    which have been forced to local binding.  Then all of the back-end
907    allocated local dynamic syms, followed by the rest of the global
908    symbols.  */
909
910 static unsigned long
911 _bfd_elf_link_renumber_dynsyms (bfd *output_bfd,
912                                 struct bfd_link_info *info,
913                                 unsigned long *section_sym_count)
914 {
915   unsigned long dynsymcount = 0;
916
917   if (bfd_link_pic (info)
918       || elf_hash_table (info)->is_relocatable_executable)
919     {
920       const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
921       asection *p;
922       for (p = output_bfd->sections; p ; p = p->next)
923         if ((p->flags & SEC_EXCLUDE) == 0
924             && (p->flags & SEC_ALLOC) != 0
925             && !(*bed->elf_backend_omit_section_dynsym) (output_bfd, info, p))
926           elf_section_data (p)->dynindx = ++dynsymcount;
927         else
928           elf_section_data (p)->dynindx = 0;
929     }
930   *section_sym_count = dynsymcount;
931
932   elf_link_hash_traverse (elf_hash_table (info),
933                           elf_link_renumber_local_hash_table_dynsyms,
934                           &dynsymcount);
935
936   if (elf_hash_table (info)->dynlocal)
937     {
938       struct elf_link_local_dynamic_entry *p;
939       for (p = elf_hash_table (info)->dynlocal; p ; p = p->next)
940         p->dynindx = ++dynsymcount;
941     }
942   elf_hash_table (info)->local_dynsymcount = dynsymcount;
943
944   elf_link_hash_traverse (elf_hash_table (info),
945                           elf_link_renumber_hash_table_dynsyms,
946                           &dynsymcount);
947
948   /* There is an unused NULL entry at the head of the table which we
949      must account for in our count even if the table is empty since it
950      is intended for the mandatory DT_SYMTAB tag (.dynsym section) in
951      .dynamic section.  */
952   dynsymcount++;
953
954   elf_hash_table (info)->dynsymcount = dynsymcount;
955   return dynsymcount;
956 }
957
958 /* Merge st_other field.  */
959
960 static void
961 elf_merge_st_other (bfd *abfd, struct elf_link_hash_entry *h,
962                     const Elf_Internal_Sym *isym, asection *sec,
963                     bfd_boolean definition, bfd_boolean dynamic)
964 {
965   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
966
967   /* If st_other has a processor-specific meaning, specific
968      code might be needed here.  */
969   if (bed->elf_backend_merge_symbol_attribute)
970     (*bed->elf_backend_merge_symbol_attribute) (h, isym, definition,
971                                                 dynamic);
972
973   if (!dynamic)
974     {
975       unsigned symvis = ELF_ST_VISIBILITY (isym->st_other);
976       unsigned hvis = ELF_ST_VISIBILITY (h->other);
977
978       /* Keep the most constraining visibility.  Leave the remainder
979          of the st_other field to elf_backend_merge_symbol_attribute.  */
980       if (symvis - 1 < hvis - 1)
981         h->other = symvis | (h->other & ~ELF_ST_VISIBILITY (-1));
982     }
983   else if (definition
984            && ELF_ST_VISIBILITY (isym->st_other) != STV_DEFAULT
985            && (sec->flags & SEC_READONLY) == 0)
986     h->protected_def = 1;
987 }
988
989 /* This function is called when we want to merge a new symbol with an
990    existing symbol.  It handles the various cases which arise when we
991    find a definition in a dynamic object, or when there is already a
992    definition in a dynamic object.  The new symbol is described by
993    NAME, SYM, PSEC, and PVALUE.  We set SYM_HASH to the hash table
994    entry.  We set POLDBFD to the old symbol's BFD.  We set POLD_WEAK
995    if the old symbol was weak.  We set POLD_ALIGNMENT to the alignment
996    of an old common symbol.  We set OVERRIDE if the old symbol is
997    overriding a new definition.  We set TYPE_CHANGE_OK if it is OK for
998    the type to change.  We set SIZE_CHANGE_OK if it is OK for the size
999    to change.  By OK to change, we mean that we shouldn't warn if the
1000    type or size does change.  */
1001
1002 static bfd_boolean
1003 _bfd_elf_merge_symbol (bfd *abfd,
1004                        struct bfd_link_info *info,
1005                        const char *name,
1006                        Elf_Internal_Sym *sym,
1007                        asection **psec,
1008                        bfd_vma *pvalue,
1009                        struct elf_link_hash_entry **sym_hash,
1010                        bfd **poldbfd,
1011                        bfd_boolean *pold_weak,
1012                        unsigned int *pold_alignment,
1013                        bfd_boolean *skip,
1014                        bfd_boolean *override,
1015                        bfd_boolean *type_change_ok,
1016                        bfd_boolean *size_change_ok,
1017                        bfd_boolean *matched)
1018 {
1019   asection *sec, *oldsec;
1020   struct elf_link_hash_entry *h;
1021   struct elf_link_hash_entry *hi;
1022   struct elf_link_hash_entry *flip;
1023   int bind;
1024   bfd *oldbfd;
1025   bfd_boolean newdyn, olddyn, olddef, newdef, newdyncommon, olddyncommon;
1026   bfd_boolean newweak, oldweak, newfunc, oldfunc;
1027   const struct elf_backend_data *bed;
1028   char *new_version;
1029
1030   *skip = FALSE;
1031   *override = FALSE;
1032
1033   sec = *psec;
1034   bind = ELF_ST_BIND (sym->st_info);
1035
1036   if (! bfd_is_und_section (sec))
1037     h = elf_link_hash_lookup (elf_hash_table (info), name, TRUE, FALSE, FALSE);
1038   else
1039     h = ((struct elf_link_hash_entry *)
1040          bfd_wrapped_link_hash_lookup (abfd, info, name, TRUE, FALSE, FALSE));
1041   if (h == NULL)
1042     return FALSE;
1043   *sym_hash = h;
1044
1045   bed = get_elf_backend_data (abfd);
1046
1047   /* NEW_VERSION is the symbol version of the new symbol.  */
1048   if (h->versioned != unversioned)
1049     {
1050       /* Symbol version is unknown or versioned.  */
1051       new_version = strrchr (name, ELF_VER_CHR);
1052       if (new_version)
1053         {
1054           if (h->versioned == unknown)
1055             {
1056               if (new_version > name && new_version[-1] != ELF_VER_CHR)
1057                 h->versioned = versioned_hidden;
1058               else
1059                 h->versioned = versioned;
1060             }
1061           new_version += 1;
1062           if (new_version[0] == '\0')
1063             new_version = NULL;
1064         }
1065       else
1066         h->versioned = unversioned;
1067     }
1068   else
1069     new_version = NULL;
1070
1071   /* For merging, we only care about real symbols.  But we need to make
1072      sure that indirect symbol dynamic flags are updated.  */
1073   hi = h;
1074   while (h->root.type == bfd_link_hash_indirect
1075          || h->root.type == bfd_link_hash_warning)
1076     h = (struct elf_link_hash_entry *) h->root.u.i.link;
1077
1078   if (!*matched)
1079     {
1080       if (hi == h || h->root.type == bfd_link_hash_new)
1081         *matched = TRUE;
1082       else
1083         {
1084           /* OLD_HIDDEN is true if the existing symbol is only visible
1085              to the symbol with the same symbol version.  NEW_HIDDEN is
1086              true if the new symbol is only visible to the symbol with
1087              the same symbol version.  */
1088           bfd_boolean old_hidden = h->versioned == versioned_hidden;
1089           bfd_boolean new_hidden = hi->versioned == versioned_hidden;
1090           if (!old_hidden && !new_hidden)
1091             /* The new symbol matches the existing symbol if both
1092                aren't hidden.  */
1093             *matched = TRUE;
1094           else
1095             {
1096               /* OLD_VERSION is the symbol version of the existing
1097                  symbol. */
1098               char *old_version;
1099
1100               if (h->versioned >= versioned)
1101                 old_version = strrchr (h->root.root.string,
1102                                        ELF_VER_CHR) + 1;
1103               else
1104                  old_version = NULL;
1105
1106               /* The new symbol matches the existing symbol if they
1107                  have the same symbol version.  */
1108               *matched = (old_version == new_version
1109                           || (old_version != NULL
1110                               && new_version != NULL
1111                               && strcmp (old_version, new_version) == 0));
1112             }
1113         }
1114     }
1115
1116   /* OLDBFD and OLDSEC are a BFD and an ASECTION associated with the
1117      existing symbol.  */
1118
1119   oldbfd = NULL;
1120   oldsec = NULL;
1121   switch (h->root.type)
1122     {
1123     default:
1124       break;
1125
1126     case bfd_link_hash_undefined:
1127     case bfd_link_hash_undefweak:
1128       oldbfd = h->root.u.undef.abfd;
1129       break;
1130
1131     case bfd_link_hash_defined:
1132     case bfd_link_hash_defweak:
1133       oldbfd = h->root.u.def.section->owner;
1134       oldsec = h->root.u.def.section;
1135       break;
1136
1137     case bfd_link_hash_common:
1138       oldbfd = h->root.u.c.p->section->owner;
1139       oldsec = h->root.u.c.p->section;
1140       if (pold_alignment)
1141         *pold_alignment = h->root.u.c.p->alignment_power;
1142       break;
1143     }
1144   if (poldbfd && *poldbfd == NULL)
1145     *poldbfd = oldbfd;
1146
1147   /* Differentiate strong and weak symbols.  */
1148   newweak = bind == STB_WEAK;
1149   oldweak = (h->root.type == bfd_link_hash_defweak
1150              || h->root.type == bfd_link_hash_undefweak);
1151   if (pold_weak)
1152     *pold_weak = oldweak;
1153
1154   /* This code is for coping with dynamic objects, and is only useful
1155      if we are doing an ELF link.  */
1156   if (!(*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
1157     return TRUE;
1158
1159   /* We have to check it for every instance since the first few may be
1160      references and not all compilers emit symbol type for undefined
1161      symbols.  */
1162   bfd_elf_link_mark_dynamic_symbol (info, h, sym);
1163
1164   /* NEWDYN and OLDDYN indicate whether the new or old symbol,
1165      respectively, is from a dynamic object.  */
1166
1167   newdyn = (abfd->flags & DYNAMIC) != 0;
1168
1169   /* ref_dynamic_nonweak and dynamic_def flags track actual undefined
1170      syms and defined syms in dynamic libraries respectively.
1171      ref_dynamic on the other hand can be set for a symbol defined in
1172      a dynamic library, and def_dynamic may not be set;  When the
1173      definition in a dynamic lib is overridden by a definition in the
1174      executable use of the symbol in the dynamic lib becomes a
1175      reference to the executable symbol.  */
1176   if (newdyn)
1177     {
1178       if (bfd_is_und_section (sec))
1179         {
1180           if (bind != STB_WEAK)
1181             {
1182               h->ref_dynamic_nonweak = 1;
1183               hi->ref_dynamic_nonweak = 1;
1184             }
1185         }
1186       else
1187         {
1188           /* Update the existing symbol only if they match. */
1189           if (*matched)
1190             h->dynamic_def = 1;
1191           hi->dynamic_def = 1;
1192         }
1193     }
1194
1195   /* If we just created the symbol, mark it as being an ELF symbol.
1196      Other than that, there is nothing to do--there is no merge issue
1197      with a newly defined symbol--so we just return.  */
1198
1199   if (h->root.type == bfd_link_hash_new)
1200     {
1201       h->non_elf = 0;
1202       return TRUE;
1203     }
1204
1205   /* In cases involving weak versioned symbols, we may wind up trying
1206      to merge a symbol with itself.  Catch that here, to avoid the
1207      confusion that results if we try to override a symbol with
1208      itself.  The additional tests catch cases like
1209      _GLOBAL_OFFSET_TABLE_, which are regular symbols defined in a
1210      dynamic object, which we do want to handle here.  */
1211   if (abfd == oldbfd
1212       && (newweak || oldweak)
1213       && ((abfd->flags & DYNAMIC) == 0
1214           || !h->def_regular))
1215     return TRUE;
1216
1217   olddyn = FALSE;
1218   if (oldbfd != NULL)
1219     olddyn = (oldbfd->flags & DYNAMIC) != 0;
1220   else if (oldsec != NULL)
1221     {
1222       /* This handles the special SHN_MIPS_{TEXT,DATA} section
1223          indices used by MIPS ELF.  */
1224       olddyn = (oldsec->symbol->flags & BSF_DYNAMIC) != 0;
1225     }
1226
1227   /* NEWDEF and OLDDEF indicate whether the new or old symbol,
1228      respectively, appear to be a definition rather than reference.  */
1229
1230   newdef = !bfd_is_und_section (sec) && !bfd_is_com_section (sec);
1231
1232   olddef = (h->root.type != bfd_link_hash_undefined
1233             && h->root.type != bfd_link_hash_undefweak
1234             && h->root.type != bfd_link_hash_common);
1235
1236   /* NEWFUNC and OLDFUNC indicate whether the new or old symbol,
1237      respectively, appear to be a function.  */
1238
1239   newfunc = (ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1240              && bed->is_function_type (ELF_ST_TYPE (sym->st_info)));
1241
1242   oldfunc = (h->type != STT_NOTYPE
1243              && bed->is_function_type (h->type));
1244
1245   /* If creating a default indirect symbol ("foo" or "foo@") from a
1246      dynamic versioned definition ("foo@@") skip doing so if there is
1247      an existing regular definition with a different type.  We don't
1248      want, for example, a "time" variable in the executable overriding
1249      a "time" function in a shared library.  */
1250   if (pold_alignment == NULL
1251       && newdyn
1252       && newdef
1253       && !olddyn
1254       && (olddef || h->root.type == bfd_link_hash_common)
1255       && ELF_ST_TYPE (sym->st_info) != h->type
1256       && ELF_ST_TYPE (sym->st_info) != STT_NOTYPE
1257       && h->type != STT_NOTYPE
1258       && !(newfunc && oldfunc))
1259     {
1260       *skip = TRUE;
1261       return TRUE;
1262     }
1263
1264   /* Check TLS symbols.  We don't check undefined symbols introduced
1265      by "ld -u" which have no type (and oldbfd NULL), and we don't
1266      check symbols from plugins because they also have no type.  */
1267   if (oldbfd != NULL
1268       && (oldbfd->flags & BFD_PLUGIN) == 0
1269       && (abfd->flags & BFD_PLUGIN) == 0
1270       && ELF_ST_TYPE (sym->st_info) != h->type
1271       && (ELF_ST_TYPE (sym->st_info) == STT_TLS || h->type == STT_TLS))
1272     {
1273       bfd *ntbfd, *tbfd;
1274       bfd_boolean ntdef, tdef;
1275       asection *ntsec, *tsec;
1276
1277       if (h->type == STT_TLS)
1278         {
1279           ntbfd = abfd;
1280           ntsec = sec;
1281           ntdef = newdef;
1282           tbfd = oldbfd;
1283           tsec = oldsec;
1284           tdef = olddef;
1285         }
1286       else
1287         {
1288           ntbfd = oldbfd;
1289           ntsec = oldsec;
1290           ntdef = olddef;
1291           tbfd = abfd;
1292           tsec = sec;
1293           tdef = newdef;
1294         }
1295
1296       if (tdef && ntdef)
1297         _bfd_error_handler
1298           /* xgettext:c-format */
1299           (_("%s: TLS definition in %B section %A "
1300              "mismatches non-TLS definition in %B section %A"),
1301            tbfd, tsec, ntbfd, ntsec, h->root.root.string);
1302       else if (!tdef && !ntdef)
1303         _bfd_error_handler
1304           /* xgettext:c-format */
1305           (_("%s: TLS reference in %B "
1306              "mismatches non-TLS reference in %B"),
1307            tbfd, ntbfd, h->root.root.string);
1308       else if (tdef)
1309         _bfd_error_handler
1310           /* xgettext:c-format */
1311           (_("%s: TLS definition in %B section %A "
1312              "mismatches non-TLS reference in %B"),
1313            tbfd, tsec, ntbfd, h->root.root.string);
1314       else
1315         _bfd_error_handler
1316           /* xgettext:c-format */
1317           (_("%s: TLS reference in %B "
1318              "mismatches non-TLS definition in %B section %A"),
1319            tbfd, ntbfd, ntsec, h->root.root.string);
1320
1321       bfd_set_error (bfd_error_bad_value);
1322       return FALSE;
1323     }
1324
1325   /* If the old symbol has non-default visibility, we ignore the new
1326      definition from a dynamic object.  */
1327   if (newdyn
1328       && ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
1329       && !bfd_is_und_section (sec))
1330     {
1331       *skip = TRUE;
1332       /* Make sure this symbol is dynamic.  */
1333       h->ref_dynamic = 1;
1334       hi->ref_dynamic = 1;
1335       /* A protected symbol has external availability. Make sure it is
1336          recorded as dynamic.
1337
1338          FIXME: Should we check type and size for protected symbol?  */
1339       if (ELF_ST_VISIBILITY (h->other) == STV_PROTECTED)
1340         return bfd_elf_link_record_dynamic_symbol (info, h);
1341       else
1342         return TRUE;
1343     }
1344   else if (!newdyn
1345            && ELF_ST_VISIBILITY (sym->st_other) != STV_DEFAULT
1346            && h->def_dynamic)
1347     {
1348       /* If the new symbol with non-default visibility comes from a
1349          relocatable file and the old definition comes from a dynamic
1350          object, we remove the old definition.  */
1351       if (hi->root.type == bfd_link_hash_indirect)
1352         {
1353           /* Handle the case where the old dynamic definition is
1354              default versioned.  We need to copy the symbol info from
1355              the symbol with default version to the normal one if it
1356              was referenced before.  */
1357           if (h->ref_regular)
1358             {
1359               hi->root.type = h->root.type;
1360               h->root.type = bfd_link_hash_indirect;
1361               (*bed->elf_backend_copy_indirect_symbol) (info, hi, h);
1362
1363               h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1364               if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1365                 {
1366                   /* If the new symbol is hidden or internal, completely undo
1367                      any dynamic link state.  */
1368                   (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1369                   h->forced_local = 0;
1370                   h->ref_dynamic = 0;
1371                 }
1372               else
1373                 h->ref_dynamic = 1;
1374
1375               h->def_dynamic = 0;
1376               /* FIXME: Should we check type and size for protected symbol?  */
1377               h->size = 0;
1378               h->type = 0;
1379
1380               h = hi;
1381             }
1382           else
1383             h = hi;
1384         }
1385
1386       /* If the old symbol was undefined before, then it will still be
1387          on the undefs list.  If the new symbol is undefined or
1388          common, we can't make it bfd_link_hash_new here, because new
1389          undefined or common symbols will be added to the undefs list
1390          by _bfd_generic_link_add_one_symbol.  Symbols may not be
1391          added twice to the undefs list.  Also, if the new symbol is
1392          undefweak then we don't want to lose the strong undef.  */
1393       if (h->root.u.undef.next || info->hash->undefs_tail == &h->root)
1394         {
1395           h->root.type = bfd_link_hash_undefined;
1396           h->root.u.undef.abfd = abfd;
1397         }
1398       else
1399         {
1400           h->root.type = bfd_link_hash_new;
1401           h->root.u.undef.abfd = NULL;
1402         }
1403
1404       if (ELF_ST_VISIBILITY (sym->st_other) != STV_PROTECTED)
1405         {
1406           /* If the new symbol is hidden or internal, completely undo
1407              any dynamic link state.  */
1408           (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1409           h->forced_local = 0;
1410           h->ref_dynamic = 0;
1411         }
1412       else
1413         h->ref_dynamic = 1;
1414       h->def_dynamic = 0;
1415       /* FIXME: Should we check type and size for protected symbol?  */
1416       h->size = 0;
1417       h->type = 0;
1418       return TRUE;
1419     }
1420
1421   /* If a new weak symbol definition comes from a regular file and the
1422      old symbol comes from a dynamic library, we treat the new one as
1423      strong.  Similarly, an old weak symbol definition from a regular
1424      file is treated as strong when the new symbol comes from a dynamic
1425      library.  Further, an old weak symbol from a dynamic library is
1426      treated as strong if the new symbol is from a dynamic library.
1427      This reflects the way glibc's ld.so works.
1428
1429      Do this before setting *type_change_ok or *size_change_ok so that
1430      we warn properly when dynamic library symbols are overridden.  */
1431
1432   if (newdef && !newdyn && olddyn)
1433     newweak = FALSE;
1434   if (olddef && newdyn)
1435     oldweak = FALSE;
1436
1437   /* Allow changes between different types of function symbol.  */
1438   if (newfunc && oldfunc)
1439     *type_change_ok = TRUE;
1440
1441   /* It's OK to change the type if either the existing symbol or the
1442      new symbol is weak.  A type change is also OK if the old symbol
1443      is undefined and the new symbol is defined.  */
1444
1445   if (oldweak
1446       || newweak
1447       || (newdef
1448           && h->root.type == bfd_link_hash_undefined))
1449     *type_change_ok = TRUE;
1450
1451   /* It's OK to change the size if either the existing symbol or the
1452      new symbol is weak, or if the old symbol is undefined.  */
1453
1454   if (*type_change_ok
1455       || h->root.type == bfd_link_hash_undefined)
1456     *size_change_ok = TRUE;
1457
1458   /* NEWDYNCOMMON and OLDDYNCOMMON indicate whether the new or old
1459      symbol, respectively, appears to be a common symbol in a dynamic
1460      object.  If a symbol appears in an uninitialized section, and is
1461      not weak, and is not a function, then it may be a common symbol
1462      which was resolved when the dynamic object was created.  We want
1463      to treat such symbols specially, because they raise special
1464      considerations when setting the symbol size: if the symbol
1465      appears as a common symbol in a regular object, and the size in
1466      the regular object is larger, we must make sure that we use the
1467      larger size.  This problematic case can always be avoided in C,
1468      but it must be handled correctly when using Fortran shared
1469      libraries.
1470
1471      Note that if NEWDYNCOMMON is set, NEWDEF will be set, and
1472      likewise for OLDDYNCOMMON and OLDDEF.
1473
1474      Note that this test is just a heuristic, and that it is quite
1475      possible to have an uninitialized symbol in a shared object which
1476      is really a definition, rather than a common symbol.  This could
1477      lead to some minor confusion when the symbol really is a common
1478      symbol in some regular object.  However, I think it will be
1479      harmless.  */
1480
1481   if (newdyn
1482       && newdef
1483       && !newweak
1484       && (sec->flags & SEC_ALLOC) != 0
1485       && (sec->flags & SEC_LOAD) == 0
1486       && sym->st_size > 0
1487       && !newfunc)
1488     newdyncommon = TRUE;
1489   else
1490     newdyncommon = FALSE;
1491
1492   if (olddyn
1493       && olddef
1494       && h->root.type == bfd_link_hash_defined
1495       && h->def_dynamic
1496       && (h->root.u.def.section->flags & SEC_ALLOC) != 0
1497       && (h->root.u.def.section->flags & SEC_LOAD) == 0
1498       && h->size > 0
1499       && !oldfunc)
1500     olddyncommon = TRUE;
1501   else
1502     olddyncommon = FALSE;
1503
1504   /* We now know everything about the old and new symbols.  We ask the
1505      backend to check if we can merge them.  */
1506   if (bed->merge_symbol != NULL)
1507     {
1508       if (!bed->merge_symbol (h, sym, psec, newdef, olddef, oldbfd, oldsec))
1509         return FALSE;
1510       sec = *psec;
1511     }
1512
1513   /* If both the old and the new symbols look like common symbols in a
1514      dynamic object, set the size of the symbol to the larger of the
1515      two.  */
1516
1517   if (olddyncommon
1518       && newdyncommon
1519       && sym->st_size != h->size)
1520     {
1521       /* Since we think we have two common symbols, issue a multiple
1522          common warning if desired.  Note that we only warn if the
1523          size is different.  If the size is the same, we simply let
1524          the old symbol override the new one as normally happens with
1525          symbols defined in dynamic objects.  */
1526
1527       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1528                                            bfd_link_hash_common, sym->st_size);
1529       if (sym->st_size > h->size)
1530         h->size = sym->st_size;
1531
1532       *size_change_ok = TRUE;
1533     }
1534
1535   /* If we are looking at a dynamic object, and we have found a
1536      definition, we need to see if the symbol was already defined by
1537      some other object.  If so, we want to use the existing
1538      definition, and we do not want to report a multiple symbol
1539      definition error; we do this by clobbering *PSEC to be
1540      bfd_und_section_ptr.
1541
1542      We treat a common symbol as a definition if the symbol in the
1543      shared library is a function, since common symbols always
1544      represent variables; this can cause confusion in principle, but
1545      any such confusion would seem to indicate an erroneous program or
1546      shared library.  We also permit a common symbol in a regular
1547      object to override a weak symbol in a shared object.  A common
1548      symbol in executable also overrides a symbol in a shared object.  */
1549
1550   if (newdyn
1551       && newdef
1552       && (olddef
1553           || (h->root.type == bfd_link_hash_common
1554               && (newweak
1555                   || newfunc
1556                   || (!olddyn && bfd_link_executable (info))))))
1557     {
1558       *override = TRUE;
1559       newdef = FALSE;
1560       newdyncommon = FALSE;
1561
1562       *psec = sec = bfd_und_section_ptr;
1563       *size_change_ok = TRUE;
1564
1565       /* If we get here when the old symbol is a common symbol, then
1566          we are explicitly letting it override a weak symbol or
1567          function in a dynamic object, and we don't want to warn about
1568          a type change.  If the old symbol is a defined symbol, a type
1569          change warning may still be appropriate.  */
1570
1571       if (h->root.type == bfd_link_hash_common)
1572         *type_change_ok = TRUE;
1573     }
1574
1575   /* Handle the special case of an old common symbol merging with a
1576      new symbol which looks like a common symbol in a shared object.
1577      We change *PSEC and *PVALUE to make the new symbol look like a
1578      common symbol, and let _bfd_generic_link_add_one_symbol do the
1579      right thing.  */
1580
1581   if (newdyncommon
1582       && h->root.type == bfd_link_hash_common)
1583     {
1584       *override = TRUE;
1585       newdef = FALSE;
1586       newdyncommon = FALSE;
1587       *pvalue = sym->st_size;
1588       *psec = sec = bed->common_section (oldsec);
1589       *size_change_ok = TRUE;
1590     }
1591
1592   /* Skip weak definitions of symbols that are already defined.  */
1593   if (newdef && olddef && newweak)
1594     {
1595       /* Don't skip new non-IR weak syms.  */
1596       if (!(oldbfd != NULL
1597             && (oldbfd->flags & BFD_PLUGIN) != 0
1598             && (abfd->flags & BFD_PLUGIN) == 0))
1599         {
1600           newdef = FALSE;
1601           *skip = TRUE;
1602         }
1603
1604       /* Merge st_other.  If the symbol already has a dynamic index,
1605          but visibility says it should not be visible, turn it into a
1606          local symbol.  */
1607       elf_merge_st_other (abfd, h, sym, sec, newdef, newdyn);
1608       if (h->dynindx != -1)
1609         switch (ELF_ST_VISIBILITY (h->other))
1610           {
1611           case STV_INTERNAL:
1612           case STV_HIDDEN:
1613             (*bed->elf_backend_hide_symbol) (info, h, TRUE);
1614             break;
1615           }
1616     }
1617
1618   /* If the old symbol is from a dynamic object, and the new symbol is
1619      a definition which is not from a dynamic object, then the new
1620      symbol overrides the old symbol.  Symbols from regular files
1621      always take precedence over symbols from dynamic objects, even if
1622      they are defined after the dynamic object in the link.
1623
1624      As above, we again permit a common symbol in a regular object to
1625      override a definition in a shared object if the shared object
1626      symbol is a function or is weak.  */
1627
1628   flip = NULL;
1629   if (!newdyn
1630       && (newdef
1631           || (bfd_is_com_section (sec)
1632               && (oldweak || oldfunc)))
1633       && olddyn
1634       && olddef
1635       && h->def_dynamic)
1636     {
1637       /* Change the hash table entry to undefined, and let
1638          _bfd_generic_link_add_one_symbol do the right thing with the
1639          new definition.  */
1640
1641       h->root.type = bfd_link_hash_undefined;
1642       h->root.u.undef.abfd = h->root.u.def.section->owner;
1643       *size_change_ok = TRUE;
1644
1645       olddef = FALSE;
1646       olddyncommon = FALSE;
1647
1648       /* We again permit a type change when a common symbol may be
1649          overriding a function.  */
1650
1651       if (bfd_is_com_section (sec))
1652         {
1653           if (oldfunc)
1654             {
1655               /* If a common symbol overrides a function, make sure
1656                  that it isn't defined dynamically nor has type
1657                  function.  */
1658               h->def_dynamic = 0;
1659               h->type = STT_NOTYPE;
1660             }
1661           *type_change_ok = TRUE;
1662         }
1663
1664       if (hi->root.type == bfd_link_hash_indirect)
1665         flip = hi;
1666       else
1667         /* This union may have been set to be non-NULL when this symbol
1668            was seen in a dynamic object.  We must force the union to be
1669            NULL, so that it is correct for a regular symbol.  */
1670         h->verinfo.vertree = NULL;
1671     }
1672
1673   /* Handle the special case of a new common symbol merging with an
1674      old symbol that looks like it might be a common symbol defined in
1675      a shared object.  Note that we have already handled the case in
1676      which a new common symbol should simply override the definition
1677      in the shared library.  */
1678
1679   if (! newdyn
1680       && bfd_is_com_section (sec)
1681       && olddyncommon)
1682     {
1683       /* It would be best if we could set the hash table entry to a
1684          common symbol, but we don't know what to use for the section
1685          or the alignment.  */
1686       (*info->callbacks->multiple_common) (info, &h->root, abfd,
1687                                            bfd_link_hash_common, sym->st_size);
1688
1689       /* If the presumed common symbol in the dynamic object is
1690          larger, pretend that the new symbol has its size.  */
1691
1692       if (h->size > *pvalue)
1693         *pvalue = h->size;
1694
1695       /* We need to remember the alignment required by the symbol
1696          in the dynamic object.  */
1697       BFD_ASSERT (pold_alignment);
1698       *pold_alignment = h->root.u.def.section->alignment_power;
1699
1700       olddef = FALSE;
1701       olddyncommon = FALSE;
1702
1703       h->root.type = bfd_link_hash_undefined;
1704       h->root.u.undef.abfd = h->root.u.def.section->owner;
1705
1706       *size_change_ok = TRUE;
1707       *type_change_ok = TRUE;
1708
1709       if (hi->root.type == bfd_link_hash_indirect)
1710         flip = hi;
1711       else
1712         h->verinfo.vertree = NULL;
1713     }
1714
1715   if (flip != NULL)
1716     {
1717       /* Handle the case where we had a versioned symbol in a dynamic
1718          library and now find a definition in a normal object.  In this
1719          case, we make the versioned symbol point to the normal one.  */
1720       flip->root.type = h->root.type;
1721       flip->root.u.undef.abfd = h->root.u.undef.abfd;
1722       h->root.type = bfd_link_hash_indirect;
1723       h->root.u.i.link = (struct bfd_link_hash_entry *) flip;
1724       (*bed->elf_backend_copy_indirect_symbol) (info, flip, h);
1725       if (h->def_dynamic)
1726         {
1727           h->def_dynamic = 0;
1728           flip->ref_dynamic = 1;
1729         }
1730     }
1731
1732   return TRUE;
1733 }
1734
1735 /* This function is called to create an indirect symbol from the
1736    default for the symbol with the default version if needed. The
1737    symbol is described by H, NAME, SYM, SEC, and VALUE.  We
1738    set DYNSYM if the new indirect symbol is dynamic.  */
1739
1740 static bfd_boolean
1741 _bfd_elf_add_default_symbol (bfd *abfd,
1742                              struct bfd_link_info *info,
1743                              struct elf_link_hash_entry *h,
1744                              const char *name,
1745                              Elf_Internal_Sym *sym,
1746                              asection *sec,
1747                              bfd_vma value,
1748                              bfd **poldbfd,
1749                              bfd_boolean *dynsym)
1750 {
1751   bfd_boolean type_change_ok;
1752   bfd_boolean size_change_ok;
1753   bfd_boolean skip;
1754   char *shortname;
1755   struct elf_link_hash_entry *hi;
1756   struct bfd_link_hash_entry *bh;
1757   const struct elf_backend_data *bed;
1758   bfd_boolean collect;
1759   bfd_boolean dynamic;
1760   bfd_boolean override;
1761   char *p;
1762   size_t len, shortlen;
1763   asection *tmp_sec;
1764   bfd_boolean matched;
1765
1766   if (h->versioned == unversioned || h->versioned == versioned_hidden)
1767     return TRUE;
1768
1769   /* If this symbol has a version, and it is the default version, we
1770      create an indirect symbol from the default name to the fully
1771      decorated name.  This will cause external references which do not
1772      specify a version to be bound to this version of the symbol.  */
1773   p = strchr (name, ELF_VER_CHR);
1774   if (h->versioned == unknown)
1775     {
1776       if (p == NULL)
1777         {
1778           h->versioned = unversioned;
1779           return TRUE;
1780         }
1781       else
1782         {
1783           if (p[1] != ELF_VER_CHR)
1784             {
1785               h->versioned = versioned_hidden;
1786               return TRUE;
1787             }
1788           else
1789             h->versioned = versioned;
1790         }
1791     }
1792   else
1793     {
1794       /* PR ld/19073: We may see an unversioned definition after the
1795          default version.  */
1796       if (p == NULL)
1797         return TRUE;
1798     }
1799
1800   bed = get_elf_backend_data (abfd);
1801   collect = bed->collect;
1802   dynamic = (abfd->flags & DYNAMIC) != 0;
1803
1804   shortlen = p - name;
1805   shortname = (char *) bfd_hash_allocate (&info->hash->table, shortlen + 1);
1806   if (shortname == NULL)
1807     return FALSE;
1808   memcpy (shortname, name, shortlen);
1809   shortname[shortlen] = '\0';
1810
1811   /* We are going to create a new symbol.  Merge it with any existing
1812      symbol with this name.  For the purposes of the merge, act as
1813      though we were defining the symbol we just defined, although we
1814      actually going to define an indirect symbol.  */
1815   type_change_ok = FALSE;
1816   size_change_ok = FALSE;
1817   matched = TRUE;
1818   tmp_sec = sec;
1819   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1820                               &hi, poldbfd, NULL, NULL, &skip, &override,
1821                               &type_change_ok, &size_change_ok, &matched))
1822     return FALSE;
1823
1824   if (skip)
1825     goto nondefault;
1826
1827   if (hi->def_regular)
1828     {
1829       /* If the undecorated symbol will have a version added by a
1830          script different to H, then don't indirect to/from the
1831          undecorated symbol.  This isn't ideal because we may not yet
1832          have seen symbol versions, if given by a script on the
1833          command line rather than via --version-script.  */
1834       if (hi->verinfo.vertree == NULL && info->version_info != NULL)
1835         {
1836           bfd_boolean hide;
1837
1838           hi->verinfo.vertree
1839             = bfd_find_version_for_sym (info->version_info,
1840                                         hi->root.root.string, &hide);
1841           if (hi->verinfo.vertree != NULL && hide)
1842             {
1843               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
1844               goto nondefault;
1845             }
1846         }
1847       if (hi->verinfo.vertree != NULL
1848           && strcmp (p + 1 + (p[1] == '@'), hi->verinfo.vertree->name) != 0)
1849         goto nondefault;
1850     }
1851
1852   if (! override)
1853     {
1854       /* Add the default symbol if not performing a relocatable link.  */
1855       if (! bfd_link_relocatable (info))
1856         {
1857           bh = &hi->root;
1858           if (! (_bfd_generic_link_add_one_symbol
1859                  (info, abfd, shortname, BSF_INDIRECT,
1860                   bfd_ind_section_ptr,
1861                   0, name, FALSE, collect, &bh)))
1862             return FALSE;
1863           hi = (struct elf_link_hash_entry *) bh;
1864         }
1865     }
1866   else
1867     {
1868       /* In this case the symbol named SHORTNAME is overriding the
1869          indirect symbol we want to add.  We were planning on making
1870          SHORTNAME an indirect symbol referring to NAME.  SHORTNAME
1871          is the name without a version.  NAME is the fully versioned
1872          name, and it is the default version.
1873
1874          Overriding means that we already saw a definition for the
1875          symbol SHORTNAME in a regular object, and it is overriding
1876          the symbol defined in the dynamic object.
1877
1878          When this happens, we actually want to change NAME, the
1879          symbol we just added, to refer to SHORTNAME.  This will cause
1880          references to NAME in the shared object to become references
1881          to SHORTNAME in the regular object.  This is what we expect
1882          when we override a function in a shared object: that the
1883          references in the shared object will be mapped to the
1884          definition in the regular object.  */
1885
1886       while (hi->root.type == bfd_link_hash_indirect
1887              || hi->root.type == bfd_link_hash_warning)
1888         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1889
1890       h->root.type = bfd_link_hash_indirect;
1891       h->root.u.i.link = (struct bfd_link_hash_entry *) hi;
1892       if (h->def_dynamic)
1893         {
1894           h->def_dynamic = 0;
1895           hi->ref_dynamic = 1;
1896           if (hi->ref_regular
1897               || hi->def_regular)
1898             {
1899               if (! bfd_elf_link_record_dynamic_symbol (info, hi))
1900                 return FALSE;
1901             }
1902         }
1903
1904       /* Now set HI to H, so that the following code will set the
1905          other fields correctly.  */
1906       hi = h;
1907     }
1908
1909   /* Check if HI is a warning symbol.  */
1910   if (hi->root.type == bfd_link_hash_warning)
1911     hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
1912
1913   /* If there is a duplicate definition somewhere, then HI may not
1914      point to an indirect symbol.  We will have reported an error to
1915      the user in that case.  */
1916
1917   if (hi->root.type == bfd_link_hash_indirect)
1918     {
1919       struct elf_link_hash_entry *ht;
1920
1921       ht = (struct elf_link_hash_entry *) hi->root.u.i.link;
1922       (*bed->elf_backend_copy_indirect_symbol) (info, ht, hi);
1923
1924       /* A reference to the SHORTNAME symbol from a dynamic library
1925          will be satisfied by the versioned symbol at runtime.  In
1926          effect, we have a reference to the versioned symbol.  */
1927       ht->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
1928       hi->dynamic_def |= ht->dynamic_def;
1929
1930       /* See if the new flags lead us to realize that the symbol must
1931          be dynamic.  */
1932       if (! *dynsym)
1933         {
1934           if (! dynamic)
1935             {
1936               if (! bfd_link_executable (info)
1937                   || hi->def_dynamic
1938                   || hi->ref_dynamic)
1939                 *dynsym = TRUE;
1940             }
1941           else
1942             {
1943               if (hi->ref_regular)
1944                 *dynsym = TRUE;
1945             }
1946         }
1947     }
1948
1949   /* We also need to define an indirection from the nondefault version
1950      of the symbol.  */
1951
1952 nondefault:
1953   len = strlen (name);
1954   shortname = (char *) bfd_hash_allocate (&info->hash->table, len);
1955   if (shortname == NULL)
1956     return FALSE;
1957   memcpy (shortname, name, shortlen);
1958   memcpy (shortname + shortlen, p + 1, len - shortlen);
1959
1960   /* Once again, merge with any existing symbol.  */
1961   type_change_ok = FALSE;
1962   size_change_ok = FALSE;
1963   tmp_sec = sec;
1964   if (!_bfd_elf_merge_symbol (abfd, info, shortname, sym, &tmp_sec, &value,
1965                               &hi, poldbfd, NULL, NULL, &skip, &override,
1966                               &type_change_ok, &size_change_ok, &matched))
1967     return FALSE;
1968
1969   if (skip)
1970     return TRUE;
1971
1972   if (override)
1973     {
1974       /* Here SHORTNAME is a versioned name, so we don't expect to see
1975          the type of override we do in the case above unless it is
1976          overridden by a versioned definition.  */
1977       if (hi->root.type != bfd_link_hash_defined
1978           && hi->root.type != bfd_link_hash_defweak)
1979         _bfd_error_handler
1980           /* xgettext:c-format */
1981           (_("%B: unexpected redefinition of indirect versioned symbol `%s'"),
1982            abfd, shortname);
1983     }
1984   else
1985     {
1986       bh = &hi->root;
1987       if (! (_bfd_generic_link_add_one_symbol
1988              (info, abfd, shortname, BSF_INDIRECT,
1989               bfd_ind_section_ptr, 0, name, FALSE, collect, &bh)))
1990         return FALSE;
1991       hi = (struct elf_link_hash_entry *) bh;
1992
1993       /* If there is a duplicate definition somewhere, then HI may not
1994          point to an indirect symbol.  We will have reported an error
1995          to the user in that case.  */
1996
1997       if (hi->root.type == bfd_link_hash_indirect)
1998         {
1999           (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
2000           h->ref_dynamic_nonweak |= hi->ref_dynamic_nonweak;
2001           hi->dynamic_def |= h->dynamic_def;
2002
2003           /* See if the new flags lead us to realize that the symbol
2004              must be dynamic.  */
2005           if (! *dynsym)
2006             {
2007               if (! dynamic)
2008                 {
2009                   if (! bfd_link_executable (info)
2010                       || hi->ref_dynamic)
2011                     *dynsym = TRUE;
2012                 }
2013               else
2014                 {
2015                   if (hi->ref_regular)
2016                     *dynsym = TRUE;
2017                 }
2018             }
2019         }
2020     }
2021
2022   return TRUE;
2023 }
2024 \f
2025 /* This routine is used to export all defined symbols into the dynamic
2026    symbol table.  It is called via elf_link_hash_traverse.  */
2027
2028 static bfd_boolean
2029 _bfd_elf_export_symbol (struct elf_link_hash_entry *h, void *data)
2030 {
2031   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2032
2033   /* Ignore indirect symbols.  These are added by the versioning code.  */
2034   if (h->root.type == bfd_link_hash_indirect)
2035     return TRUE;
2036
2037   /* Ignore this if we won't export it.  */
2038   if (!eif->info->export_dynamic && !h->dynamic)
2039     return TRUE;
2040
2041   if (h->dynindx == -1
2042       && (h->def_regular || h->ref_regular)
2043       && ! bfd_hide_sym_by_version (eif->info->version_info,
2044                                     h->root.root.string))
2045     {
2046       if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2047         {
2048           eif->failed = TRUE;
2049           return FALSE;
2050         }
2051     }
2052
2053   return TRUE;
2054 }
2055 \f
2056 /* Look through the symbols which are defined in other shared
2057    libraries and referenced here.  Update the list of version
2058    dependencies.  This will be put into the .gnu.version_r section.
2059    This function is called via elf_link_hash_traverse.  */
2060
2061 static bfd_boolean
2062 _bfd_elf_link_find_version_dependencies (struct elf_link_hash_entry *h,
2063                                          void *data)
2064 {
2065   struct elf_find_verdep_info *rinfo = (struct elf_find_verdep_info *) data;
2066   Elf_Internal_Verneed *t;
2067   Elf_Internal_Vernaux *a;
2068   bfd_size_type amt;
2069
2070   /* We only care about symbols defined in shared objects with version
2071      information.  */
2072   if (!h->def_dynamic
2073       || h->def_regular
2074       || h->dynindx == -1
2075       || h->verinfo.verdef == NULL
2076       || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
2077           & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
2078     return TRUE;
2079
2080   /* See if we already know about this version.  */
2081   for (t = elf_tdata (rinfo->info->output_bfd)->verref;
2082        t != NULL;
2083        t = t->vn_nextref)
2084     {
2085       if (t->vn_bfd != h->verinfo.verdef->vd_bfd)
2086         continue;
2087
2088       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
2089         if (a->vna_nodename == h->verinfo.verdef->vd_nodename)
2090           return TRUE;
2091
2092       break;
2093     }
2094
2095   /* This is a new version.  Add it to tree we are building.  */
2096
2097   if (t == NULL)
2098     {
2099       amt = sizeof *t;
2100       t = (Elf_Internal_Verneed *) bfd_zalloc (rinfo->info->output_bfd, amt);
2101       if (t == NULL)
2102         {
2103           rinfo->failed = TRUE;
2104           return FALSE;
2105         }
2106
2107       t->vn_bfd = h->verinfo.verdef->vd_bfd;
2108       t->vn_nextref = elf_tdata (rinfo->info->output_bfd)->verref;
2109       elf_tdata (rinfo->info->output_bfd)->verref = t;
2110     }
2111
2112   amt = sizeof *a;
2113   a = (Elf_Internal_Vernaux *) bfd_zalloc (rinfo->info->output_bfd, amt);
2114   if (a == NULL)
2115     {
2116       rinfo->failed = TRUE;
2117       return FALSE;
2118     }
2119
2120   /* Note that we are copying a string pointer here, and testing it
2121      above.  If bfd_elf_string_from_elf_section is ever changed to
2122      discard the string data when low in memory, this will have to be
2123      fixed.  */
2124   a->vna_nodename = h->verinfo.verdef->vd_nodename;
2125
2126   a->vna_flags = h->verinfo.verdef->vd_flags;
2127   a->vna_nextptr = t->vn_auxptr;
2128
2129   h->verinfo.verdef->vd_exp_refno = rinfo->vers;
2130   ++rinfo->vers;
2131
2132   a->vna_other = h->verinfo.verdef->vd_exp_refno + 1;
2133
2134   t->vn_auxptr = a;
2135
2136   return TRUE;
2137 }
2138
2139 /* Figure out appropriate versions for all the symbols.  We may not
2140    have the version number script until we have read all of the input
2141    files, so until that point we don't know which symbols should be
2142    local.  This function is called via elf_link_hash_traverse.  */
2143
2144 static bfd_boolean
2145 _bfd_elf_link_assign_sym_version (struct elf_link_hash_entry *h, void *data)
2146 {
2147   struct elf_info_failed *sinfo;
2148   struct bfd_link_info *info;
2149   const struct elf_backend_data *bed;
2150   struct elf_info_failed eif;
2151   char *p;
2152
2153   sinfo = (struct elf_info_failed *) data;
2154   info = sinfo->info;
2155
2156   /* Fix the symbol flags.  */
2157   eif.failed = FALSE;
2158   eif.info = info;
2159   if (! _bfd_elf_fix_symbol_flags (h, &eif))
2160     {
2161       if (eif.failed)
2162         sinfo->failed = TRUE;
2163       return FALSE;
2164     }
2165
2166   /* We only need version numbers for symbols defined in regular
2167      objects.  */
2168   if (!h->def_regular)
2169     return TRUE;
2170
2171   bed = get_elf_backend_data (info->output_bfd);
2172   p = strchr (h->root.root.string, ELF_VER_CHR);
2173   if (p != NULL && h->verinfo.vertree == NULL)
2174     {
2175       struct bfd_elf_version_tree *t;
2176
2177       ++p;
2178       if (*p == ELF_VER_CHR)
2179         ++p;
2180
2181       /* If there is no version string, we can just return out.  */
2182       if (*p == '\0')
2183         return TRUE;
2184
2185       /* Look for the version.  If we find it, it is no longer weak.  */
2186       for (t = sinfo->info->version_info; t != NULL; t = t->next)
2187         {
2188           if (strcmp (t->name, p) == 0)
2189             {
2190               size_t len;
2191               char *alc;
2192               struct bfd_elf_version_expr *d;
2193
2194               len = p - h->root.root.string;
2195               alc = (char *) bfd_malloc (len);
2196               if (alc == NULL)
2197                 {
2198                   sinfo->failed = TRUE;
2199                   return FALSE;
2200                 }
2201               memcpy (alc, h->root.root.string, len - 1);
2202               alc[len - 1] = '\0';
2203               if (alc[len - 2] == ELF_VER_CHR)
2204                 alc[len - 2] = '\0';
2205
2206               h->verinfo.vertree = t;
2207               t->used = TRUE;
2208               d = NULL;
2209
2210               if (t->globals.list != NULL)
2211                 d = (*t->match) (&t->globals, NULL, alc);
2212
2213               /* See if there is anything to force this symbol to
2214                  local scope.  */
2215               if (d == NULL && t->locals.list != NULL)
2216                 {
2217                   d = (*t->match) (&t->locals, NULL, alc);
2218                   if (d != NULL
2219                       && h->dynindx != -1
2220                       && ! info->export_dynamic)
2221                     (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2222                 }
2223
2224               free (alc);
2225               break;
2226             }
2227         }
2228
2229       /* If we are building an application, we need to create a
2230          version node for this version.  */
2231       if (t == NULL && bfd_link_executable (info))
2232         {
2233           struct bfd_elf_version_tree **pp;
2234           int version_index;
2235
2236           /* If we aren't going to export this symbol, we don't need
2237              to worry about it.  */
2238           if (h->dynindx == -1)
2239             return TRUE;
2240
2241           t = (struct bfd_elf_version_tree *) bfd_zalloc (info->output_bfd,
2242                                                           sizeof *t);
2243           if (t == NULL)
2244             {
2245               sinfo->failed = TRUE;
2246               return FALSE;
2247             }
2248
2249           t->name = p;
2250           t->name_indx = (unsigned int) -1;
2251           t->used = TRUE;
2252
2253           version_index = 1;
2254           /* Don't count anonymous version tag.  */
2255           if (sinfo->info->version_info != NULL
2256               && sinfo->info->version_info->vernum == 0)
2257             version_index = 0;
2258           for (pp = &sinfo->info->version_info;
2259                *pp != NULL;
2260                pp = &(*pp)->next)
2261             ++version_index;
2262           t->vernum = version_index;
2263
2264           *pp = t;
2265
2266           h->verinfo.vertree = t;
2267         }
2268       else if (t == NULL)
2269         {
2270           /* We could not find the version for a symbol when
2271              generating a shared archive.  Return an error.  */
2272           _bfd_error_handler
2273             /* xgettext:c-format */
2274             (_("%B: version node not found for symbol %s"),
2275              info->output_bfd, h->root.root.string);
2276           bfd_set_error (bfd_error_bad_value);
2277           sinfo->failed = TRUE;
2278           return FALSE;
2279         }
2280     }
2281
2282   /* If we don't have a version for this symbol, see if we can find
2283      something.  */
2284   if (h->verinfo.vertree == NULL && sinfo->info->version_info != NULL)
2285     {
2286       bfd_boolean hide;
2287
2288       h->verinfo.vertree
2289         = bfd_find_version_for_sym (sinfo->info->version_info,
2290                                     h->root.root.string, &hide);
2291       if (h->verinfo.vertree != NULL && hide)
2292         (*bed->elf_backend_hide_symbol) (info, h, TRUE);
2293     }
2294
2295   return TRUE;
2296 }
2297 \f
2298 /* Read and swap the relocs from the section indicated by SHDR.  This
2299    may be either a REL or a RELA section.  The relocations are
2300    translated into RELA relocations and stored in INTERNAL_RELOCS,
2301    which should have already been allocated to contain enough space.
2302    The EXTERNAL_RELOCS are a buffer where the external form of the
2303    relocations should be stored.
2304
2305    Returns FALSE if something goes wrong.  */
2306
2307 static bfd_boolean
2308 elf_link_read_relocs_from_section (bfd *abfd,
2309                                    asection *sec,
2310                                    Elf_Internal_Shdr *shdr,
2311                                    void *external_relocs,
2312                                    Elf_Internal_Rela *internal_relocs)
2313 {
2314   const struct elf_backend_data *bed;
2315   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
2316   const bfd_byte *erela;
2317   const bfd_byte *erelaend;
2318   Elf_Internal_Rela *irela;
2319   Elf_Internal_Shdr *symtab_hdr;
2320   size_t nsyms;
2321
2322   /* Position ourselves at the start of the section.  */
2323   if (bfd_seek (abfd, shdr->sh_offset, SEEK_SET) != 0)
2324     return FALSE;
2325
2326   /* Read the relocations.  */
2327   if (bfd_bread (external_relocs, shdr->sh_size, abfd) != shdr->sh_size)
2328     return FALSE;
2329
2330   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
2331   nsyms = NUM_SHDR_ENTRIES (symtab_hdr);
2332
2333   bed = get_elf_backend_data (abfd);
2334
2335   /* Convert the external relocations to the internal format.  */
2336   if (shdr->sh_entsize == bed->s->sizeof_rel)
2337     swap_in = bed->s->swap_reloc_in;
2338   else if (shdr->sh_entsize == bed->s->sizeof_rela)
2339     swap_in = bed->s->swap_reloca_in;
2340   else
2341     {
2342       bfd_set_error (bfd_error_wrong_format);
2343       return FALSE;
2344     }
2345
2346   erela = (const bfd_byte *) external_relocs;
2347   erelaend = erela + shdr->sh_size;
2348   irela = internal_relocs;
2349   while (erela < erelaend)
2350     {
2351       bfd_vma r_symndx;
2352
2353       (*swap_in) (abfd, erela, irela);
2354       r_symndx = ELF32_R_SYM (irela->r_info);
2355       if (bed->s->arch_size == 64)
2356         r_symndx >>= 24;
2357       if (nsyms > 0)
2358         {
2359           if ((size_t) r_symndx >= nsyms)
2360             {
2361               _bfd_error_handler
2362                 /* xgettext:c-format */
2363                 (_("%B: bad reloc symbol index (0x%lx >= 0x%lx)"
2364                    " for offset 0x%lx in section `%A'"),
2365                  abfd, sec,
2366                  (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2367               bfd_set_error (bfd_error_bad_value);
2368               return FALSE;
2369             }
2370         }
2371       else if (r_symndx != STN_UNDEF)
2372         {
2373           _bfd_error_handler
2374             /* xgettext:c-format */
2375             (_("%B: non-zero symbol index (0x%lx) for offset 0x%lx in section `%A'"
2376                " when the object file has no symbol table"),
2377              abfd, sec,
2378              (unsigned long) r_symndx, (unsigned long) nsyms, irela->r_offset);
2379           bfd_set_error (bfd_error_bad_value);
2380           return FALSE;
2381         }
2382       irela += bed->s->int_rels_per_ext_rel;
2383       erela += shdr->sh_entsize;
2384     }
2385
2386   return TRUE;
2387 }
2388
2389 /* Read and swap the relocs for a section O.  They may have been
2390    cached.  If the EXTERNAL_RELOCS and INTERNAL_RELOCS arguments are
2391    not NULL, they are used as buffers to read into.  They are known to
2392    be large enough.  If the INTERNAL_RELOCS relocs argument is NULL,
2393    the return value is allocated using either malloc or bfd_alloc,
2394    according to the KEEP_MEMORY argument.  If O has two relocation
2395    sections (both REL and RELA relocations), then the REL_HDR
2396    relocations will appear first in INTERNAL_RELOCS, followed by the
2397    RELA_HDR relocations.  */
2398
2399 Elf_Internal_Rela *
2400 _bfd_elf_link_read_relocs (bfd *abfd,
2401                            asection *o,
2402                            void *external_relocs,
2403                            Elf_Internal_Rela *internal_relocs,
2404                            bfd_boolean keep_memory)
2405 {
2406   void *alloc1 = NULL;
2407   Elf_Internal_Rela *alloc2 = NULL;
2408   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
2409   struct bfd_elf_section_data *esdo = elf_section_data (o);
2410   Elf_Internal_Rela *internal_rela_relocs;
2411
2412   if (esdo->relocs != NULL)
2413     return esdo->relocs;
2414
2415   if (o->reloc_count == 0)
2416     return NULL;
2417
2418   if (internal_relocs == NULL)
2419     {
2420       bfd_size_type size;
2421
2422       size = o->reloc_count;
2423       size *= bed->s->int_rels_per_ext_rel * sizeof (Elf_Internal_Rela);
2424       if (keep_memory)
2425         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_alloc (abfd, size);
2426       else
2427         internal_relocs = alloc2 = (Elf_Internal_Rela *) bfd_malloc (size);
2428       if (internal_relocs == NULL)
2429         goto error_return;
2430     }
2431
2432   if (external_relocs == NULL)
2433     {
2434       bfd_size_type size = 0;
2435
2436       if (esdo->rel.hdr)
2437         size += esdo->rel.hdr->sh_size;
2438       if (esdo->rela.hdr)
2439         size += esdo->rela.hdr->sh_size;
2440
2441       alloc1 = bfd_malloc (size);
2442       if (alloc1 == NULL)
2443         goto error_return;
2444       external_relocs = alloc1;
2445     }
2446
2447   internal_rela_relocs = internal_relocs;
2448   if (esdo->rel.hdr)
2449     {
2450       if (!elf_link_read_relocs_from_section (abfd, o, esdo->rel.hdr,
2451                                               external_relocs,
2452                                               internal_relocs))
2453         goto error_return;
2454       external_relocs = (((bfd_byte *) external_relocs)
2455                          + esdo->rel.hdr->sh_size);
2456       internal_rela_relocs += (NUM_SHDR_ENTRIES (esdo->rel.hdr)
2457                                * bed->s->int_rels_per_ext_rel);
2458     }
2459
2460   if (esdo->rela.hdr
2461       && (!elf_link_read_relocs_from_section (abfd, o, esdo->rela.hdr,
2462                                               external_relocs,
2463                                               internal_rela_relocs)))
2464     goto error_return;
2465
2466   /* Cache the results for next time, if we can.  */
2467   if (keep_memory)
2468     esdo->relocs = internal_relocs;
2469
2470   if (alloc1 != NULL)
2471     free (alloc1);
2472
2473   /* Don't free alloc2, since if it was allocated we are passing it
2474      back (under the name of internal_relocs).  */
2475
2476   return internal_relocs;
2477
2478  error_return:
2479   if (alloc1 != NULL)
2480     free (alloc1);
2481   if (alloc2 != NULL)
2482     {
2483       if (keep_memory)
2484         bfd_release (abfd, alloc2);
2485       else
2486         free (alloc2);
2487     }
2488   return NULL;
2489 }
2490
2491 /* Compute the size of, and allocate space for, REL_HDR which is the
2492    section header for a section containing relocations for O.  */
2493
2494 static bfd_boolean
2495 _bfd_elf_link_size_reloc_section (bfd *abfd,
2496                                   struct bfd_elf_section_reloc_data *reldata)
2497 {
2498   Elf_Internal_Shdr *rel_hdr = reldata->hdr;
2499
2500   /* That allows us to calculate the size of the section.  */
2501   rel_hdr->sh_size = rel_hdr->sh_entsize * reldata->count;
2502
2503   /* The contents field must last into write_object_contents, so we
2504      allocate it with bfd_alloc rather than malloc.  Also since we
2505      cannot be sure that the contents will actually be filled in,
2506      we zero the allocated space.  */
2507   rel_hdr->contents = (unsigned char *) bfd_zalloc (abfd, rel_hdr->sh_size);
2508   if (rel_hdr->contents == NULL && rel_hdr->sh_size != 0)
2509     return FALSE;
2510
2511   if (reldata->hashes == NULL && reldata->count)
2512     {
2513       struct elf_link_hash_entry **p;
2514
2515       p = ((struct elf_link_hash_entry **)
2516            bfd_zmalloc (reldata->count * sizeof (*p)));
2517       if (p == NULL)
2518         return FALSE;
2519
2520       reldata->hashes = p;
2521     }
2522
2523   return TRUE;
2524 }
2525
2526 /* Copy the relocations indicated by the INTERNAL_RELOCS (which
2527    originated from the section given by INPUT_REL_HDR) to the
2528    OUTPUT_BFD.  */
2529
2530 bfd_boolean
2531 _bfd_elf_link_output_relocs (bfd *output_bfd,
2532                              asection *input_section,
2533                              Elf_Internal_Shdr *input_rel_hdr,
2534                              Elf_Internal_Rela *internal_relocs,
2535                              struct elf_link_hash_entry **rel_hash
2536                                ATTRIBUTE_UNUSED)
2537 {
2538   Elf_Internal_Rela *irela;
2539   Elf_Internal_Rela *irelaend;
2540   bfd_byte *erel;
2541   struct bfd_elf_section_reloc_data *output_reldata;
2542   asection *output_section;
2543   const struct elf_backend_data *bed;
2544   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
2545   struct bfd_elf_section_data *esdo;
2546
2547   output_section = input_section->output_section;
2548
2549   bed = get_elf_backend_data (output_bfd);
2550   esdo = elf_section_data (output_section);
2551   if (esdo->rel.hdr && esdo->rel.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2552     {
2553       output_reldata = &esdo->rel;
2554       swap_out = bed->s->swap_reloc_out;
2555     }
2556   else if (esdo->rela.hdr
2557            && esdo->rela.hdr->sh_entsize == input_rel_hdr->sh_entsize)
2558     {
2559       output_reldata = &esdo->rela;
2560       swap_out = bed->s->swap_reloca_out;
2561     }
2562   else
2563     {
2564       _bfd_error_handler
2565         /* xgettext:c-format */
2566         (_("%B: relocation size mismatch in %B section %A"),
2567          output_bfd, input_section->owner, input_section);
2568       bfd_set_error (bfd_error_wrong_format);
2569       return FALSE;
2570     }
2571
2572   erel = output_reldata->hdr->contents;
2573   erel += output_reldata->count * input_rel_hdr->sh_entsize;
2574   irela = internal_relocs;
2575   irelaend = irela + (NUM_SHDR_ENTRIES (input_rel_hdr)
2576                       * bed->s->int_rels_per_ext_rel);
2577   while (irela < irelaend)
2578     {
2579       (*swap_out) (output_bfd, irela, erel);
2580       irela += bed->s->int_rels_per_ext_rel;
2581       erel += input_rel_hdr->sh_entsize;
2582     }
2583
2584   /* Bump the counter, so that we know where to add the next set of
2585      relocations.  */
2586   output_reldata->count += NUM_SHDR_ENTRIES (input_rel_hdr);
2587
2588   return TRUE;
2589 }
2590 \f
2591 /* Make weak undefined symbols in PIE dynamic.  */
2592
2593 bfd_boolean
2594 _bfd_elf_link_hash_fixup_symbol (struct bfd_link_info *info,
2595                                  struct elf_link_hash_entry *h)
2596 {
2597   if (bfd_link_pie (info)
2598       && h->dynindx == -1
2599       && h->root.type == bfd_link_hash_undefweak)
2600     return bfd_elf_link_record_dynamic_symbol (info, h);
2601
2602   return TRUE;
2603 }
2604
2605 /* Fix up the flags for a symbol.  This handles various cases which
2606    can only be fixed after all the input files are seen.  This is
2607    currently called by both adjust_dynamic_symbol and
2608    assign_sym_version, which is unnecessary but perhaps more robust in
2609    the face of future changes.  */
2610
2611 static bfd_boolean
2612 _bfd_elf_fix_symbol_flags (struct elf_link_hash_entry *h,
2613                            struct elf_info_failed *eif)
2614 {
2615   const struct elf_backend_data *bed;
2616
2617   /* If this symbol was mentioned in a non-ELF file, try to set
2618      DEF_REGULAR and REF_REGULAR correctly.  This is the only way to
2619      permit a non-ELF file to correctly refer to a symbol defined in
2620      an ELF dynamic object.  */
2621   if (h->non_elf)
2622     {
2623       while (h->root.type == bfd_link_hash_indirect)
2624         h = (struct elf_link_hash_entry *) h->root.u.i.link;
2625
2626       if (h->root.type != bfd_link_hash_defined
2627           && h->root.type != bfd_link_hash_defweak)
2628         {
2629           h->ref_regular = 1;
2630           h->ref_regular_nonweak = 1;
2631         }
2632       else
2633         {
2634           if (h->root.u.def.section->owner != NULL
2635               && (bfd_get_flavour (h->root.u.def.section->owner)
2636                   == bfd_target_elf_flavour))
2637             {
2638               h->ref_regular = 1;
2639               h->ref_regular_nonweak = 1;
2640             }
2641           else
2642             h->def_regular = 1;
2643         }
2644
2645       if (h->dynindx == -1
2646           && (h->def_dynamic
2647               || h->ref_dynamic))
2648         {
2649           if (! bfd_elf_link_record_dynamic_symbol (eif->info, h))
2650             {
2651               eif->failed = TRUE;
2652               return FALSE;
2653             }
2654         }
2655     }
2656   else
2657     {
2658       /* Unfortunately, NON_ELF is only correct if the symbol
2659          was first seen in a non-ELF file.  Fortunately, if the symbol
2660          was first seen in an ELF file, we're probably OK unless the
2661          symbol was defined in a non-ELF file.  Catch that case here.
2662          FIXME: We're still in trouble if the symbol was first seen in
2663          a dynamic object, and then later in a non-ELF regular object.  */
2664       if ((h->root.type == bfd_link_hash_defined
2665            || h->root.type == bfd_link_hash_defweak)
2666           && !h->def_regular
2667           && (h->root.u.def.section->owner != NULL
2668               ? (bfd_get_flavour (h->root.u.def.section->owner)
2669                  != bfd_target_elf_flavour)
2670               : (bfd_is_abs_section (h->root.u.def.section)
2671                  && !h->def_dynamic)))
2672         h->def_regular = 1;
2673     }
2674
2675   /* Backend specific symbol fixup.  */
2676   bed = get_elf_backend_data (elf_hash_table (eif->info)->dynobj);
2677   if (bed->elf_backend_fixup_symbol
2678       && !(*bed->elf_backend_fixup_symbol) (eif->info, h))
2679     return FALSE;
2680
2681   /* If this is a final link, and the symbol was defined as a common
2682      symbol in a regular object file, and there was no definition in
2683      any dynamic object, then the linker will have allocated space for
2684      the symbol in a common section but the DEF_REGULAR
2685      flag will not have been set.  */
2686   if (h->root.type == bfd_link_hash_defined
2687       && !h->def_regular
2688       && h->ref_regular
2689       && !h->def_dynamic
2690       && (h->root.u.def.section->owner->flags & (DYNAMIC | BFD_PLUGIN)) == 0)
2691     h->def_regular = 1;
2692
2693   /* If a weak undefined symbol has non-default visibility, we also
2694      hide it from the dynamic linker.  */
2695   if (ELF_ST_VISIBILITY (h->other) != STV_DEFAULT
2696       && h->root.type == bfd_link_hash_undefweak)
2697     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2698
2699   /* A hidden versioned symbol in executable should be forced local if
2700      it is is locally defined, not referenced by shared library and not
2701      exported.  */
2702   else if (bfd_link_executable (eif->info)
2703            && h->versioned == versioned_hidden
2704            && !eif->info->export_dynamic
2705            && !h->dynamic
2706            && !h->ref_dynamic
2707            && h->def_regular)
2708     (*bed->elf_backend_hide_symbol) (eif->info, h, TRUE);
2709
2710   /* If -Bsymbolic was used (which means to bind references to global
2711      symbols to the definition within the shared object), and this
2712      symbol was defined in a regular object, then it actually doesn't
2713      need a PLT entry.  Likewise, if the symbol has non-default
2714      visibility.  If the symbol has hidden or internal visibility, we
2715      will force it local.  */
2716   else if (h->needs_plt
2717            && bfd_link_pic (eif->info)
2718            && is_elf_hash_table (eif->info->hash)
2719            && (SYMBOLIC_BIND (eif->info, h)
2720                || ELF_ST_VISIBILITY (h->other) != STV_DEFAULT)
2721            && h->def_regular)
2722     {
2723       bfd_boolean force_local;
2724
2725       force_local = (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL
2726                      || ELF_ST_VISIBILITY (h->other) == STV_HIDDEN);
2727       (*bed->elf_backend_hide_symbol) (eif->info, h, force_local);
2728     }
2729
2730   /* If this is a weak defined symbol in a dynamic object, and we know
2731      the real definition in the dynamic object, copy interesting flags
2732      over to the real definition.  */
2733   if (h->u.weakdef != NULL)
2734     {
2735       /* If the real definition is defined by a regular object file,
2736          don't do anything special.  See the longer description in
2737          _bfd_elf_adjust_dynamic_symbol, below.  */
2738       if (h->u.weakdef->def_regular)
2739         h->u.weakdef = NULL;
2740       else
2741         {
2742           struct elf_link_hash_entry *weakdef = h->u.weakdef;
2743
2744           while (h->root.type == bfd_link_hash_indirect)
2745             h = (struct elf_link_hash_entry *) h->root.u.i.link;
2746
2747           BFD_ASSERT (h->root.type == bfd_link_hash_defined
2748                       || h->root.type == bfd_link_hash_defweak);
2749           BFD_ASSERT (weakdef->def_dynamic);
2750           BFD_ASSERT (weakdef->root.type == bfd_link_hash_defined
2751                       || weakdef->root.type == bfd_link_hash_defweak);
2752           (*bed->elf_backend_copy_indirect_symbol) (eif->info, weakdef, h);
2753         }
2754     }
2755
2756   return TRUE;
2757 }
2758
2759 /* Make the backend pick a good value for a dynamic symbol.  This is
2760    called via elf_link_hash_traverse, and also calls itself
2761    recursively.  */
2762
2763 static bfd_boolean
2764 _bfd_elf_adjust_dynamic_symbol (struct elf_link_hash_entry *h, void *data)
2765 {
2766   struct elf_info_failed *eif = (struct elf_info_failed *) data;
2767   bfd *dynobj;
2768   const struct elf_backend_data *bed;
2769
2770   if (! is_elf_hash_table (eif->info->hash))
2771     return FALSE;
2772
2773   /* Ignore indirect symbols.  These are added by the versioning code.  */
2774   if (h->root.type == bfd_link_hash_indirect)
2775     return TRUE;
2776
2777   /* Fix the symbol flags.  */
2778   if (! _bfd_elf_fix_symbol_flags (h, eif))
2779     return FALSE;
2780
2781   /* If this symbol does not require a PLT entry, and it is not
2782      defined by a dynamic object, or is not referenced by a regular
2783      object, ignore it.  We do have to handle a weak defined symbol,
2784      even if no regular object refers to it, if we decided to add it
2785      to the dynamic symbol table.  FIXME: Do we normally need to worry
2786      about symbols which are defined by one dynamic object and
2787      referenced by another one?  */
2788   if (!h->needs_plt
2789       && h->type != STT_GNU_IFUNC
2790       && (h->def_regular
2791           || !h->def_dynamic
2792           || (!h->ref_regular
2793               && (h->u.weakdef == NULL || h->u.weakdef->dynindx == -1))))
2794     {
2795       h->plt = elf_hash_table (eif->info)->init_plt_offset;
2796       return TRUE;
2797     }
2798
2799   /* If we've already adjusted this symbol, don't do it again.  This
2800      can happen via a recursive call.  */
2801   if (h->dynamic_adjusted)
2802     return TRUE;
2803
2804   /* Don't look at this symbol again.  Note that we must set this
2805      after checking the above conditions, because we may look at a
2806      symbol once, decide not to do anything, and then get called
2807      recursively later after REF_REGULAR is set below.  */
2808   h->dynamic_adjusted = 1;
2809
2810   /* If this is a weak definition, and we know a real definition, and
2811      the real symbol is not itself defined by a regular object file,
2812      then get a good value for the real definition.  We handle the
2813      real symbol first, for the convenience of the backend routine.
2814
2815      Note that there is a confusing case here.  If the real definition
2816      is defined by a regular object file, we don't get the real symbol
2817      from the dynamic object, but we do get the weak symbol.  If the
2818      processor backend uses a COPY reloc, then if some routine in the
2819      dynamic object changes the real symbol, we will not see that
2820      change in the corresponding weak symbol.  This is the way other
2821      ELF linkers work as well, and seems to be a result of the shared
2822      library model.
2823
2824      I will clarify this issue.  Most SVR4 shared libraries define the
2825      variable _timezone and define timezone as a weak synonym.  The
2826      tzset call changes _timezone.  If you write
2827        extern int timezone;
2828        int _timezone = 5;
2829        int main () { tzset (); printf ("%d %d\n", timezone, _timezone); }
2830      you might expect that, since timezone is a synonym for _timezone,
2831      the same number will print both times.  However, if the processor
2832      backend uses a COPY reloc, then actually timezone will be copied
2833      into your process image, and, since you define _timezone
2834      yourself, _timezone will not.  Thus timezone and _timezone will
2835      wind up at different memory locations.  The tzset call will set
2836      _timezone, leaving timezone unchanged.  */
2837
2838   if (h->u.weakdef != NULL)
2839     {
2840       /* If we get to this point, there is an implicit reference to
2841          H->U.WEAKDEF by a regular object file via the weak symbol H.  */
2842       h->u.weakdef->ref_regular = 1;
2843
2844       /* Ensure that the backend adjust_dynamic_symbol function sees
2845          H->U.WEAKDEF before H by recursively calling ourselves.  */
2846       if (! _bfd_elf_adjust_dynamic_symbol (h->u.weakdef, eif))
2847         return FALSE;
2848     }
2849
2850   /* If a symbol has no type and no size and does not require a PLT
2851      entry, then we are probably about to do the wrong thing here: we
2852      are probably going to create a COPY reloc for an empty object.
2853      This case can arise when a shared object is built with assembly
2854      code, and the assembly code fails to set the symbol type.  */
2855   if (h->size == 0
2856       && h->type == STT_NOTYPE
2857       && !h->needs_plt)
2858     _bfd_error_handler
2859       (_("warning: type and size of dynamic symbol `%s' are not defined"),
2860        h->root.root.string);
2861
2862   dynobj = elf_hash_table (eif->info)->dynobj;
2863   bed = get_elf_backend_data (dynobj);
2864
2865   if (! (*bed->elf_backend_adjust_dynamic_symbol) (eif->info, h))
2866     {
2867       eif->failed = TRUE;
2868       return FALSE;
2869     }
2870
2871   return TRUE;
2872 }
2873
2874 /* Adjust the dynamic symbol, H, for copy in the dynamic bss section,
2875    DYNBSS.  */
2876
2877 bfd_boolean
2878 _bfd_elf_adjust_dynamic_copy (struct bfd_link_info *info,
2879                               struct elf_link_hash_entry *h,
2880                               asection *dynbss)
2881 {
2882   unsigned int power_of_two;
2883   bfd_vma mask;
2884   asection *sec = h->root.u.def.section;
2885
2886   /* The section aligment of definition is the maximum alignment
2887      requirement of symbols defined in the section.  Since we don't
2888      know the symbol alignment requirement, we start with the
2889      maximum alignment and check low bits of the symbol address
2890      for the minimum alignment.  */
2891   power_of_two = bfd_get_section_alignment (sec->owner, sec);
2892   mask = ((bfd_vma) 1 << power_of_two) - 1;
2893   while ((h->root.u.def.value & mask) != 0)
2894     {
2895        mask >>= 1;
2896        --power_of_two;
2897     }
2898
2899   if (power_of_two > bfd_get_section_alignment (dynbss->owner,
2900                                                 dynbss))
2901     {
2902       /* Adjust the section alignment if needed.  */
2903       if (! bfd_set_section_alignment (dynbss->owner, dynbss,
2904                                        power_of_two))
2905         return FALSE;
2906     }
2907
2908   /* We make sure that the symbol will be aligned properly.  */
2909   dynbss->size = BFD_ALIGN (dynbss->size, mask + 1);
2910
2911   /* Define the symbol as being at this point in DYNBSS.  */
2912   h->root.u.def.section = dynbss;
2913   h->root.u.def.value = dynbss->size;
2914
2915   /* Increment the size of DYNBSS to make room for the symbol.  */
2916   dynbss->size += h->size;
2917
2918   /* No error if extern_protected_data is true.  */
2919   if (h->protected_def
2920       && (!info->extern_protected_data
2921           || (info->extern_protected_data < 0
2922               && !get_elf_backend_data (dynbss->owner)->extern_protected_data)))
2923     info->callbacks->einfo
2924       (_("%P: copy reloc against protected `%T' is dangerous\n"),
2925        h->root.root.string);
2926
2927   return TRUE;
2928 }
2929
2930 /* Adjust all external symbols pointing into SEC_MERGE sections
2931    to reflect the object merging within the sections.  */
2932
2933 static bfd_boolean
2934 _bfd_elf_link_sec_merge_syms (struct elf_link_hash_entry *h, void *data)
2935 {
2936   asection *sec;
2937
2938   if ((h->root.type == bfd_link_hash_defined
2939        || h->root.type == bfd_link_hash_defweak)
2940       && ((sec = h->root.u.def.section)->flags & SEC_MERGE)
2941       && sec->sec_info_type == SEC_INFO_TYPE_MERGE)
2942     {
2943       bfd *output_bfd = (bfd *) data;
2944
2945       h->root.u.def.value =
2946         _bfd_merged_section_offset (output_bfd,
2947                                     &h->root.u.def.section,
2948                                     elf_section_data (sec)->sec_info,
2949                                     h->root.u.def.value);
2950     }
2951
2952   return TRUE;
2953 }
2954
2955 /* Returns false if the symbol referred to by H should be considered
2956    to resolve local to the current module, and true if it should be
2957    considered to bind dynamically.  */
2958
2959 bfd_boolean
2960 _bfd_elf_dynamic_symbol_p (struct elf_link_hash_entry *h,
2961                            struct bfd_link_info *info,
2962                            bfd_boolean not_local_protected)
2963 {
2964   bfd_boolean binding_stays_local_p;
2965   const struct elf_backend_data *bed;
2966   struct elf_link_hash_table *hash_table;
2967
2968   if (h == NULL)
2969     return FALSE;
2970
2971   while (h->root.type == bfd_link_hash_indirect
2972          || h->root.type == bfd_link_hash_warning)
2973     h = (struct elf_link_hash_entry *) h->root.u.i.link;
2974
2975   /* If it was forced local, then clearly it's not dynamic.  */
2976   if (h->dynindx == -1)
2977     return FALSE;
2978   if (h->forced_local)
2979     return FALSE;
2980
2981   /* Identify the cases where name binding rules say that a
2982      visible symbol resolves locally.  */
2983   binding_stays_local_p = (bfd_link_executable (info)
2984                            || SYMBOLIC_BIND (info, h));
2985
2986   switch (ELF_ST_VISIBILITY (h->other))
2987     {
2988     case STV_INTERNAL:
2989     case STV_HIDDEN:
2990       return FALSE;
2991
2992     case STV_PROTECTED:
2993       hash_table = elf_hash_table (info);
2994       if (!is_elf_hash_table (hash_table))
2995         return FALSE;
2996
2997       bed = get_elf_backend_data (hash_table->dynobj);
2998
2999       /* Proper resolution for function pointer equality may require
3000          that these symbols perhaps be resolved dynamically, even though
3001          we should be resolving them to the current module.  */
3002       if (!not_local_protected || !bed->is_function_type (h->type))
3003         binding_stays_local_p = TRUE;
3004       break;
3005
3006     default:
3007       break;
3008     }
3009
3010   /* If it isn't defined locally, then clearly it's dynamic.  */
3011   if (!h->def_regular && !ELF_COMMON_DEF_P (h))
3012     return TRUE;
3013
3014   /* Otherwise, the symbol is dynamic if binding rules don't tell
3015      us that it remains local.  */
3016   return !binding_stays_local_p;
3017 }
3018
3019 /* Return true if the symbol referred to by H should be considered
3020    to resolve local to the current module, and false otherwise.  Differs
3021    from (the inverse of) _bfd_elf_dynamic_symbol_p in the treatment of
3022    undefined symbols.  The two functions are virtually identical except
3023    for the place where forced_local and dynindx == -1 are tested.  If
3024    either of those tests are true, _bfd_elf_dynamic_symbol_p will say
3025    the symbol is local, while _bfd_elf_symbol_refs_local_p will say
3026    the symbol is local only for defined symbols.
3027    It might seem that _bfd_elf_dynamic_symbol_p could be rewritten as
3028    !_bfd_elf_symbol_refs_local_p, except that targets differ in their
3029    treatment of undefined weak symbols.  For those that do not make
3030    undefined weak symbols dynamic, both functions may return false.  */
3031
3032 bfd_boolean
3033 _bfd_elf_symbol_refs_local_p (struct elf_link_hash_entry *h,
3034                               struct bfd_link_info *info,
3035                               bfd_boolean local_protected)
3036 {
3037   const struct elf_backend_data *bed;
3038   struct elf_link_hash_table *hash_table;
3039
3040   /* If it's a local sym, of course we resolve locally.  */
3041   if (h == NULL)
3042     return TRUE;
3043
3044   /* STV_HIDDEN or STV_INTERNAL ones must be local.  */
3045   if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN
3046       || ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
3047     return TRUE;
3048
3049   /* Common symbols that become definitions don't get the DEF_REGULAR
3050      flag set, so test it first, and don't bail out.  */
3051   if (ELF_COMMON_DEF_P (h))
3052     /* Do nothing.  */;
3053   /* If we don't have a definition in a regular file, then we can't
3054      resolve locally.  The sym is either undefined or dynamic.  */
3055   else if (!h->def_regular)
3056     return FALSE;
3057
3058   /* Forced local symbols resolve locally.  */
3059   if (h->forced_local)
3060     return TRUE;
3061
3062   /* As do non-dynamic symbols.  */
3063   if (h->dynindx == -1)
3064     return TRUE;
3065
3066   /* At this point, we know the symbol is defined and dynamic.  In an
3067      executable it must resolve locally, likewise when building symbolic
3068      shared libraries.  */
3069   if (bfd_link_executable (info) || SYMBOLIC_BIND (info, h))
3070     return TRUE;
3071
3072   /* Now deal with defined dynamic symbols in shared libraries.  Ones
3073      with default visibility might not resolve locally.  */
3074   if (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT)
3075     return FALSE;
3076
3077   hash_table = elf_hash_table (info);
3078   if (!is_elf_hash_table (hash_table))
3079     return TRUE;
3080
3081   bed = get_elf_backend_data (hash_table->dynobj);
3082
3083   /* If extern_protected_data is false, STV_PROTECTED non-function
3084      symbols are local.  */
3085   if ((!info->extern_protected_data
3086        || (info->extern_protected_data < 0
3087            && !bed->extern_protected_data))
3088       && !bed->is_function_type (h->type))
3089     return TRUE;
3090
3091   /* Function pointer equality tests may require that STV_PROTECTED
3092      symbols be treated as dynamic symbols.  If the address of a
3093      function not defined in an executable is set to that function's
3094      plt entry in the executable, then the address of the function in
3095      a shared library must also be the plt entry in the executable.  */
3096   return local_protected;
3097 }
3098
3099 /* Caches some TLS segment info, and ensures that the TLS segment vma is
3100    aligned.  Returns the first TLS output section.  */
3101
3102 struct bfd_section *
3103 _bfd_elf_tls_setup (bfd *obfd, struct bfd_link_info *info)
3104 {
3105   struct bfd_section *sec, *tls;
3106   unsigned int align = 0;
3107
3108   for (sec = obfd->sections; sec != NULL; sec = sec->next)
3109     if ((sec->flags & SEC_THREAD_LOCAL) != 0)
3110       break;
3111   tls = sec;
3112
3113   for (; sec != NULL && (sec->flags & SEC_THREAD_LOCAL) != 0; sec = sec->next)
3114     if (sec->alignment_power > align)
3115       align = sec->alignment_power;
3116
3117   elf_hash_table (info)->tls_sec = tls;
3118
3119   /* Ensure the alignment of the first section is the largest alignment,
3120      so that the tls segment starts aligned.  */
3121   if (tls != NULL)
3122     tls->alignment_power = align;
3123
3124   return tls;
3125 }
3126
3127 /* Return TRUE iff this is a non-common, definition of a non-function symbol.  */
3128 static bfd_boolean
3129 is_global_data_symbol_definition (bfd *abfd ATTRIBUTE_UNUSED,
3130                                   Elf_Internal_Sym *sym)
3131 {
3132   const struct elf_backend_data *bed;
3133
3134   /* Local symbols do not count, but target specific ones might.  */
3135   if (ELF_ST_BIND (sym->st_info) != STB_GLOBAL
3136       && ELF_ST_BIND (sym->st_info) < STB_LOOS)
3137     return FALSE;
3138
3139   bed = get_elf_backend_data (abfd);
3140   /* Function symbols do not count.  */
3141   if (bed->is_function_type (ELF_ST_TYPE (sym->st_info)))
3142     return FALSE;
3143
3144   /* If the section is undefined, then so is the symbol.  */
3145   if (sym->st_shndx == SHN_UNDEF)
3146     return FALSE;
3147
3148   /* If the symbol is defined in the common section, then
3149      it is a common definition and so does not count.  */
3150   if (bed->common_definition (sym))
3151     return FALSE;
3152
3153   /* If the symbol is in a target specific section then we
3154      must rely upon the backend to tell us what it is.  */
3155   if (sym->st_shndx >= SHN_LORESERVE && sym->st_shndx < SHN_ABS)
3156     /* FIXME - this function is not coded yet:
3157
3158        return _bfd_is_global_symbol_definition (abfd, sym);
3159
3160        Instead for now assume that the definition is not global,
3161        Even if this is wrong, at least the linker will behave
3162        in the same way that it used to do.  */
3163     return FALSE;
3164
3165   return TRUE;
3166 }
3167
3168 /* Search the symbol table of the archive element of the archive ABFD
3169    whose archive map contains a mention of SYMDEF, and determine if
3170    the symbol is defined in this element.  */
3171 static bfd_boolean
3172 elf_link_is_defined_archive_symbol (bfd * abfd, carsym * symdef)
3173 {
3174   Elf_Internal_Shdr * hdr;
3175   size_t symcount;
3176   size_t extsymcount;
3177   size_t extsymoff;
3178   Elf_Internal_Sym *isymbuf;
3179   Elf_Internal_Sym *isym;
3180   Elf_Internal_Sym *isymend;
3181   bfd_boolean result;
3182
3183   abfd = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
3184   if (abfd == NULL)
3185     return FALSE;
3186
3187   if (! bfd_check_format (abfd, bfd_object))
3188     return FALSE;
3189
3190   /* Select the appropriate symbol table.  If we don't know if the
3191      object file is an IR object, give linker LTO plugin a chance to
3192      get the correct symbol table.  */
3193   if (abfd->plugin_format == bfd_plugin_yes
3194 #if BFD_SUPPORTS_PLUGINS
3195       || (abfd->plugin_format == bfd_plugin_unknown
3196           && bfd_link_plugin_object_p (abfd))
3197 #endif
3198       )
3199     {
3200       /* Use the IR symbol table if the object has been claimed by
3201          plugin.  */
3202       abfd = abfd->plugin_dummy_bfd;
3203       hdr = &elf_tdata (abfd)->symtab_hdr;
3204     }
3205   else if ((abfd->flags & DYNAMIC) == 0 || elf_dynsymtab (abfd) == 0)
3206     hdr = &elf_tdata (abfd)->symtab_hdr;
3207   else
3208     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
3209
3210   symcount = hdr->sh_size / get_elf_backend_data (abfd)->s->sizeof_sym;
3211
3212   /* The sh_info field of the symtab header tells us where the
3213      external symbols start.  We don't care about the local symbols.  */
3214   if (elf_bad_symtab (abfd))
3215     {
3216       extsymcount = symcount;
3217       extsymoff = 0;
3218     }
3219   else
3220     {
3221       extsymcount = symcount - hdr->sh_info;
3222       extsymoff = hdr->sh_info;
3223     }
3224
3225   if (extsymcount == 0)
3226     return FALSE;
3227
3228   /* Read in the symbol table.  */
3229   isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
3230                                   NULL, NULL, NULL);
3231   if (isymbuf == NULL)
3232     return FALSE;
3233
3234   /* Scan the symbol table looking for SYMDEF.  */
3235   result = FALSE;
3236   for (isym = isymbuf, isymend = isymbuf + extsymcount; isym < isymend; isym++)
3237     {
3238       const char *name;
3239
3240       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
3241                                               isym->st_name);
3242       if (name == NULL)
3243         break;
3244
3245       if (strcmp (name, symdef->name) == 0)
3246         {
3247           result = is_global_data_symbol_definition (abfd, isym);
3248           break;
3249         }
3250     }
3251
3252   free (isymbuf);
3253
3254   return result;
3255 }
3256 \f
3257 /* Add an entry to the .dynamic table.  */
3258
3259 bfd_boolean
3260 _bfd_elf_add_dynamic_entry (struct bfd_link_info *info,
3261                             bfd_vma tag,
3262                             bfd_vma val)
3263 {
3264   struct elf_link_hash_table *hash_table;
3265   const struct elf_backend_data *bed;
3266   asection *s;
3267   bfd_size_type newsize;
3268   bfd_byte *newcontents;
3269   Elf_Internal_Dyn dyn;
3270
3271   hash_table = elf_hash_table (info);
3272   if (! is_elf_hash_table (hash_table))
3273     return FALSE;
3274
3275   bed = get_elf_backend_data (hash_table->dynobj);
3276   s = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3277   BFD_ASSERT (s != NULL);
3278
3279   newsize = s->size + bed->s->sizeof_dyn;
3280   newcontents = (bfd_byte *) bfd_realloc (s->contents, newsize);
3281   if (newcontents == NULL)
3282     return FALSE;
3283
3284   dyn.d_tag = tag;
3285   dyn.d_un.d_val = val;
3286   bed->s->swap_dyn_out (hash_table->dynobj, &dyn, newcontents + s->size);
3287
3288   s->size = newsize;
3289   s->contents = newcontents;
3290
3291   return TRUE;
3292 }
3293
3294 /* Add a DT_NEEDED entry for this dynamic object if DO_IT is true,
3295    otherwise just check whether one already exists.  Returns -1 on error,
3296    1 if a DT_NEEDED tag already exists, and 0 on success.  */
3297
3298 static int
3299 elf_add_dt_needed_tag (bfd *abfd,
3300                        struct bfd_link_info *info,
3301                        const char *soname,
3302                        bfd_boolean do_it)
3303 {
3304   struct elf_link_hash_table *hash_table;
3305   size_t strindex;
3306
3307   if (!_bfd_elf_link_create_dynstrtab (abfd, info))
3308     return -1;
3309
3310   hash_table = elf_hash_table (info);
3311   strindex = _bfd_elf_strtab_add (hash_table->dynstr, soname, FALSE);
3312   if (strindex == (size_t) -1)
3313     return -1;
3314
3315   if (_bfd_elf_strtab_refcount (hash_table->dynstr, strindex) != 1)
3316     {
3317       asection *sdyn;
3318       const struct elf_backend_data *bed;
3319       bfd_byte *extdyn;
3320
3321       bed = get_elf_backend_data (hash_table->dynobj);
3322       sdyn = bfd_get_linker_section (hash_table->dynobj, ".dynamic");
3323       if (sdyn != NULL)
3324         for (extdyn = sdyn->contents;
3325              extdyn < sdyn->contents + sdyn->size;
3326              extdyn += bed->s->sizeof_dyn)
3327           {
3328             Elf_Internal_Dyn dyn;
3329
3330             bed->s->swap_dyn_in (hash_table->dynobj, extdyn, &dyn);
3331             if (dyn.d_tag == DT_NEEDED
3332                 && dyn.d_un.d_val == strindex)
3333               {
3334                 _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3335                 return 1;
3336               }
3337           }
3338     }
3339
3340   if (do_it)
3341     {
3342       if (!_bfd_elf_link_create_dynamic_sections (hash_table->dynobj, info))
3343         return -1;
3344
3345       if (!_bfd_elf_add_dynamic_entry (info, DT_NEEDED, strindex))
3346         return -1;
3347     }
3348   else
3349     /* We were just checking for existence of the tag.  */
3350     _bfd_elf_strtab_delref (hash_table->dynstr, strindex);
3351
3352   return 0;
3353 }
3354
3355 /* Return true if SONAME is on the needed list between NEEDED and STOP
3356    (or the end of list if STOP is NULL), and needed by a library that
3357    will be loaded.  */
3358
3359 static bfd_boolean
3360 on_needed_list (const char *soname,
3361                 struct bfd_link_needed_list *needed,
3362                 struct bfd_link_needed_list *stop)
3363 {
3364   struct bfd_link_needed_list *look;
3365   for (look = needed; look != stop; look = look->next)
3366     if (strcmp (soname, look->name) == 0
3367         && ((elf_dyn_lib_class (look->by) & DYN_AS_NEEDED) == 0
3368             /* If needed by a library that itself is not directly
3369                needed, recursively check whether that library is
3370                indirectly needed.  Since we add DT_NEEDED entries to
3371                the end of the list, library dependencies appear after
3372                the library.  Therefore search prior to the current
3373                LOOK, preventing possible infinite recursion.  */
3374             || on_needed_list (elf_dt_name (look->by), needed, look)))
3375       return TRUE;
3376
3377   return FALSE;
3378 }
3379
3380 /* Sort symbol by value, section, and size.  */
3381 static int
3382 elf_sort_symbol (const void *arg1, const void *arg2)
3383 {
3384   const struct elf_link_hash_entry *h1;
3385   const struct elf_link_hash_entry *h2;
3386   bfd_signed_vma vdiff;
3387
3388   h1 = *(const struct elf_link_hash_entry **) arg1;
3389   h2 = *(const struct elf_link_hash_entry **) arg2;
3390   vdiff = h1->root.u.def.value - h2->root.u.def.value;
3391   if (vdiff != 0)
3392     return vdiff > 0 ? 1 : -1;
3393   else
3394     {
3395       int sdiff = h1->root.u.def.section->id - h2->root.u.def.section->id;
3396       if (sdiff != 0)
3397         return sdiff > 0 ? 1 : -1;
3398     }
3399   vdiff = h1->size - h2->size;
3400   return vdiff == 0 ? 0 : vdiff > 0 ? 1 : -1;
3401 }
3402
3403 /* This function is used to adjust offsets into .dynstr for
3404    dynamic symbols.  This is called via elf_link_hash_traverse.  */
3405
3406 static bfd_boolean
3407 elf_adjust_dynstr_offsets (struct elf_link_hash_entry *h, void *data)
3408 {
3409   struct elf_strtab_hash *dynstr = (struct elf_strtab_hash *) data;
3410
3411   if (h->dynindx != -1)
3412     h->dynstr_index = _bfd_elf_strtab_offset (dynstr, h->dynstr_index);
3413   return TRUE;
3414 }
3415
3416 /* Assign string offsets in .dynstr, update all structures referencing
3417    them.  */
3418
3419 static bfd_boolean
3420 elf_finalize_dynstr (bfd *output_bfd, struct bfd_link_info *info)
3421 {
3422   struct elf_link_hash_table *hash_table = elf_hash_table (info);
3423   struct elf_link_local_dynamic_entry *entry;
3424   struct elf_strtab_hash *dynstr = hash_table->dynstr;
3425   bfd *dynobj = hash_table->dynobj;
3426   asection *sdyn;
3427   bfd_size_type size;
3428   const struct elf_backend_data *bed;
3429   bfd_byte *extdyn;
3430
3431   _bfd_elf_strtab_finalize (dynstr);
3432   size = _bfd_elf_strtab_size (dynstr);
3433
3434   bed = get_elf_backend_data (dynobj);
3435   sdyn = bfd_get_linker_section (dynobj, ".dynamic");
3436   BFD_ASSERT (sdyn != NULL);
3437
3438   /* Update all .dynamic entries referencing .dynstr strings.  */
3439   for (extdyn = sdyn->contents;
3440        extdyn < sdyn->contents + sdyn->size;
3441        extdyn += bed->s->sizeof_dyn)
3442     {
3443       Elf_Internal_Dyn dyn;
3444
3445       bed->s->swap_dyn_in (dynobj, extdyn, &dyn);
3446       switch (dyn.d_tag)
3447         {
3448         case DT_STRSZ:
3449           dyn.d_un.d_val = size;
3450           break;
3451         case DT_NEEDED:
3452         case DT_SONAME:
3453         case DT_RPATH:
3454         case DT_RUNPATH:
3455         case DT_FILTER:
3456         case DT_AUXILIARY:
3457         case DT_AUDIT:
3458         case DT_DEPAUDIT:
3459           dyn.d_un.d_val = _bfd_elf_strtab_offset (dynstr, dyn.d_un.d_val);
3460           break;
3461         default:
3462           continue;
3463         }
3464       bed->s->swap_dyn_out (dynobj, &dyn, extdyn);
3465     }
3466
3467   /* Now update local dynamic symbols.  */
3468   for (entry = hash_table->dynlocal; entry ; entry = entry->next)
3469     entry->isym.st_name = _bfd_elf_strtab_offset (dynstr,
3470                                                   entry->isym.st_name);
3471
3472   /* And the rest of dynamic symbols.  */
3473   elf_link_hash_traverse (hash_table, elf_adjust_dynstr_offsets, dynstr);
3474
3475   /* Adjust version definitions.  */
3476   if (elf_tdata (output_bfd)->cverdefs)
3477     {
3478       asection *s;
3479       bfd_byte *p;
3480       size_t i;
3481       Elf_Internal_Verdef def;
3482       Elf_Internal_Verdaux defaux;
3483
3484       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
3485       p = s->contents;
3486       do
3487         {
3488           _bfd_elf_swap_verdef_in (output_bfd, (Elf_External_Verdef *) p,
3489                                    &def);
3490           p += sizeof (Elf_External_Verdef);
3491           if (def.vd_aux != sizeof (Elf_External_Verdef))
3492             continue;
3493           for (i = 0; i < def.vd_cnt; ++i)
3494             {
3495               _bfd_elf_swap_verdaux_in (output_bfd,
3496                                         (Elf_External_Verdaux *) p, &defaux);
3497               defaux.vda_name = _bfd_elf_strtab_offset (dynstr,
3498                                                         defaux.vda_name);
3499               _bfd_elf_swap_verdaux_out (output_bfd,
3500                                          &defaux, (Elf_External_Verdaux *) p);
3501               p += sizeof (Elf_External_Verdaux);
3502             }
3503         }
3504       while (def.vd_next);
3505     }
3506
3507   /* Adjust version references.  */
3508   if (elf_tdata (output_bfd)->verref)
3509     {
3510       asection *s;
3511       bfd_byte *p;
3512       size_t i;
3513       Elf_Internal_Verneed need;
3514       Elf_Internal_Vernaux needaux;
3515
3516       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
3517       p = s->contents;
3518       do
3519         {
3520           _bfd_elf_swap_verneed_in (output_bfd, (Elf_External_Verneed *) p,
3521                                     &need);
3522           need.vn_file = _bfd_elf_strtab_offset (dynstr, need.vn_file);
3523           _bfd_elf_swap_verneed_out (output_bfd, &need,
3524                                      (Elf_External_Verneed *) p);
3525           p += sizeof (Elf_External_Verneed);
3526           for (i = 0; i < need.vn_cnt; ++i)
3527             {
3528               _bfd_elf_swap_vernaux_in (output_bfd,
3529                                         (Elf_External_Vernaux *) p, &needaux);
3530               needaux.vna_name = _bfd_elf_strtab_offset (dynstr,
3531                                                          needaux.vna_name);
3532               _bfd_elf_swap_vernaux_out (output_bfd,
3533                                          &needaux,
3534                                          (Elf_External_Vernaux *) p);
3535               p += sizeof (Elf_External_Vernaux);
3536             }
3537         }
3538       while (need.vn_next);
3539     }
3540
3541   return TRUE;
3542 }
3543 \f
3544 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3545    The default is to only match when the INPUT and OUTPUT are exactly
3546    the same target.  */
3547
3548 bfd_boolean
3549 _bfd_elf_default_relocs_compatible (const bfd_target *input,
3550                                     const bfd_target *output)
3551 {
3552   return input == output;
3553 }
3554
3555 /* Return TRUE iff relocations for INPUT are compatible with OUTPUT.
3556    This version is used when different targets for the same architecture
3557    are virtually identical.  */
3558
3559 bfd_boolean
3560 _bfd_elf_relocs_compatible (const bfd_target *input,
3561                             const bfd_target *output)
3562 {
3563   const struct elf_backend_data *obed, *ibed;
3564
3565   if (input == output)
3566     return TRUE;
3567
3568   ibed = xvec_get_elf_backend_data (input);
3569   obed = xvec_get_elf_backend_data (output);
3570
3571   if (ibed->arch != obed->arch)
3572     return FALSE;
3573
3574   /* If both backends are using this function, deem them compatible.  */
3575   return ibed->relocs_compatible == obed->relocs_compatible;
3576 }
3577
3578 /* Make a special call to the linker "notice" function to tell it that
3579    we are about to handle an as-needed lib, or have finished
3580    processing the lib.  */
3581
3582 bfd_boolean
3583 _bfd_elf_notice_as_needed (bfd *ibfd,
3584                            struct bfd_link_info *info,
3585                            enum notice_asneeded_action act)
3586 {
3587   return (*info->callbacks->notice) (info, NULL, NULL, ibfd, NULL, act, 0);
3588 }
3589
3590 /* Check relocations an ELF object file.  */
3591
3592 bfd_boolean
3593 _bfd_elf_link_check_relocs (bfd *abfd, struct bfd_link_info *info)
3594 {
3595   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
3596   struct elf_link_hash_table *htab = elf_hash_table (info);
3597
3598   /* If this object is the same format as the output object, and it is
3599      not a shared library, then let the backend look through the
3600      relocs.
3601
3602      This is required to build global offset table entries and to
3603      arrange for dynamic relocs.  It is not required for the
3604      particular common case of linking non PIC code, even when linking
3605      against shared libraries, but unfortunately there is no way of
3606      knowing whether an object file has been compiled PIC or not.
3607      Looking through the relocs is not particularly time consuming.
3608      The problem is that we must either (1) keep the relocs in memory,
3609      which causes the linker to require additional runtime memory or
3610      (2) read the relocs twice from the input file, which wastes time.
3611      This would be a good case for using mmap.
3612
3613      I have no idea how to handle linking PIC code into a file of a
3614      different format.  It probably can't be done.  */
3615   if ((abfd->flags & DYNAMIC) == 0
3616       && is_elf_hash_table (htab)
3617       && bed->check_relocs != NULL
3618       && elf_object_id (abfd) == elf_hash_table_id (htab)
3619       && (*bed->relocs_compatible) (abfd->xvec, info->output_bfd->xvec))
3620     {
3621       asection *o;
3622
3623       for (o = abfd->sections; o != NULL; o = o->next)
3624         {
3625           Elf_Internal_Rela *internal_relocs;
3626           bfd_boolean ok;
3627
3628           /* Don't check relocations in excluded sections.  */
3629           if ((o->flags & SEC_RELOC) == 0
3630               || (o->flags & SEC_EXCLUDE) != 0
3631               || o->reloc_count == 0
3632               || ((info->strip == strip_all || info->strip == strip_debugger)
3633                   && (o->flags & SEC_DEBUGGING) != 0)
3634               || bfd_is_abs_section (o->output_section))
3635             continue;
3636
3637           internal_relocs = _bfd_elf_link_read_relocs (abfd, o, NULL, NULL,
3638                                                        info->keep_memory);
3639           if (internal_relocs == NULL)
3640             return FALSE;
3641
3642           ok = (*bed->check_relocs) (abfd, info, o, internal_relocs);
3643
3644           if (elf_section_data (o)->relocs != internal_relocs)
3645             free (internal_relocs);
3646
3647           if (! ok)
3648             return FALSE;
3649         }
3650     }
3651
3652   return TRUE;
3653 }
3654
3655 /* Add symbols from an ELF object file to the linker hash table.  */
3656
3657 static bfd_boolean
3658 elf_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3659 {
3660   Elf_Internal_Ehdr *ehdr;
3661   Elf_Internal_Shdr *hdr;
3662   size_t symcount;
3663   size_t extsymcount;
3664   size_t extsymoff;
3665   struct elf_link_hash_entry **sym_hash;
3666   bfd_boolean dynamic;
3667   Elf_External_Versym *extversym = NULL;
3668   Elf_External_Versym *ever;
3669   struct elf_link_hash_entry *weaks;
3670   struct elf_link_hash_entry **nondeflt_vers = NULL;
3671   size_t nondeflt_vers_cnt = 0;
3672   Elf_Internal_Sym *isymbuf = NULL;
3673   Elf_Internal_Sym *isym;
3674   Elf_Internal_Sym *isymend;
3675   const struct elf_backend_data *bed;
3676   bfd_boolean add_needed;
3677   struct elf_link_hash_table *htab;
3678   bfd_size_type amt;
3679   void *alloc_mark = NULL;
3680   struct bfd_hash_entry **old_table = NULL;
3681   unsigned int old_size = 0;
3682   unsigned int old_count = 0;
3683   void *old_tab = NULL;
3684   void *old_ent;
3685   struct bfd_link_hash_entry *old_undefs = NULL;
3686   struct bfd_link_hash_entry *old_undefs_tail = NULL;
3687   void *old_strtab = NULL;
3688   size_t tabsize = 0;
3689   asection *s;
3690   bfd_boolean just_syms;
3691
3692   htab = elf_hash_table (info);
3693   bed = get_elf_backend_data (abfd);
3694
3695   if ((abfd->flags & DYNAMIC) == 0)
3696     dynamic = FALSE;
3697   else
3698     {
3699       dynamic = TRUE;
3700
3701       /* You can't use -r against a dynamic object.  Also, there's no
3702          hope of using a dynamic object which does not exactly match
3703          the format of the output file.  */
3704       if (bfd_link_relocatable (info)
3705           || !is_elf_hash_table (htab)
3706           || info->output_bfd->xvec != abfd->xvec)
3707         {
3708           if (bfd_link_relocatable (info))
3709             bfd_set_error (bfd_error_invalid_operation);
3710           else
3711             bfd_set_error (bfd_error_wrong_format);
3712           goto error_return;
3713         }
3714     }
3715
3716   ehdr = elf_elfheader (abfd);
3717   if (info->warn_alternate_em
3718       && bed->elf_machine_code != ehdr->e_machine
3719       && ((bed->elf_machine_alt1 != 0
3720            && ehdr->e_machine == bed->elf_machine_alt1)
3721           || (bed->elf_machine_alt2 != 0
3722               && ehdr->e_machine == bed->elf_machine_alt2)))
3723     info->callbacks->einfo
3724       /* xgettext:c-format */
3725       (_("%P: alternate ELF machine code found (%d) in %B, expecting %d\n"),
3726        ehdr->e_machine, abfd, bed->elf_machine_code);
3727
3728   /* As a GNU extension, any input sections which are named
3729      .gnu.warning.SYMBOL are treated as warning symbols for the given
3730      symbol.  This differs from .gnu.warning sections, which generate
3731      warnings when they are included in an output file.  */
3732   /* PR 12761: Also generate this warning when building shared libraries.  */
3733   for (s = abfd->sections; s != NULL; s = s->next)
3734     {
3735       const char *name;
3736
3737       name = bfd_get_section_name (abfd, s);
3738       if (CONST_STRNEQ (name, ".gnu.warning."))
3739         {
3740           char *msg;
3741           bfd_size_type sz;
3742
3743           name += sizeof ".gnu.warning." - 1;
3744
3745           /* If this is a shared object, then look up the symbol
3746              in the hash table.  If it is there, and it is already
3747              been defined, then we will not be using the entry
3748              from this shared object, so we don't need to warn.
3749              FIXME: If we see the definition in a regular object
3750              later on, we will warn, but we shouldn't.  The only
3751              fix is to keep track of what warnings we are supposed
3752              to emit, and then handle them all at the end of the
3753              link.  */
3754           if (dynamic)
3755             {
3756               struct elf_link_hash_entry *h;
3757
3758               h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
3759
3760               /* FIXME: What about bfd_link_hash_common?  */
3761               if (h != NULL
3762                   && (h->root.type == bfd_link_hash_defined
3763                       || h->root.type == bfd_link_hash_defweak))
3764                 continue;
3765             }
3766
3767           sz = s->size;
3768           msg = (char *) bfd_alloc (abfd, sz + 1);
3769           if (msg == NULL)
3770             goto error_return;
3771
3772           if (! bfd_get_section_contents (abfd, s, msg, 0, sz))
3773             goto error_return;
3774
3775           msg[sz] = '\0';
3776
3777           if (! (_bfd_generic_link_add_one_symbol
3778                  (info, abfd, name, BSF_WARNING, s, 0, msg,
3779                   FALSE, bed->collect, NULL)))
3780             goto error_return;
3781
3782           if (bfd_link_executable (info))
3783             {
3784               /* Clobber the section size so that the warning does
3785                  not get copied into the output file.  */
3786               s->size = 0;
3787
3788               /* Also set SEC_EXCLUDE, so that symbols defined in
3789                  the warning section don't get copied to the output.  */
3790               s->flags |= SEC_EXCLUDE;
3791             }
3792         }
3793     }
3794
3795   just_syms = ((s = abfd->sections) != NULL
3796                && s->sec_info_type == SEC_INFO_TYPE_JUST_SYMS);
3797
3798   add_needed = TRUE;
3799   if (! dynamic)
3800     {
3801       /* If we are creating a shared library, create all the dynamic
3802          sections immediately.  We need to attach them to something,
3803          so we attach them to this BFD, provided it is the right
3804          format and is not from ld --just-symbols.  Always create the
3805          dynamic sections for -E/--dynamic-list.  FIXME: If there
3806          are no input BFD's of the same format as the output, we can't
3807          make a shared library.  */
3808       if (!just_syms
3809           && (bfd_link_pic (info)
3810               || (!bfd_link_relocatable (info)
3811                   && (info->export_dynamic || info->dynamic)))
3812           && is_elf_hash_table (htab)
3813           && info->output_bfd->xvec == abfd->xvec
3814           && !htab->dynamic_sections_created)
3815         {
3816           if (! _bfd_elf_link_create_dynamic_sections (abfd, info))
3817             goto error_return;
3818         }
3819     }
3820   else if (!is_elf_hash_table (htab))
3821     goto error_return;
3822   else
3823     {
3824       const char *soname = NULL;
3825       char *audit = NULL;
3826       struct bfd_link_needed_list *rpath = NULL, *runpath = NULL;
3827       const Elf_Internal_Phdr *phdr;
3828       int ret;
3829
3830       /* ld --just-symbols and dynamic objects don't mix very well.
3831          ld shouldn't allow it.  */
3832       if (just_syms)
3833         abort ();
3834
3835       /* If this dynamic lib was specified on the command line with
3836          --as-needed in effect, then we don't want to add a DT_NEEDED
3837          tag unless the lib is actually used.  Similary for libs brought
3838          in by another lib's DT_NEEDED.  When --no-add-needed is used
3839          on a dynamic lib, we don't want to add a DT_NEEDED entry for
3840          any dynamic library in DT_NEEDED tags in the dynamic lib at
3841          all.  */
3842       add_needed = (elf_dyn_lib_class (abfd)
3843                     & (DYN_AS_NEEDED | DYN_DT_NEEDED
3844                        | DYN_NO_NEEDED)) == 0;
3845
3846       s = bfd_get_section_by_name (abfd, ".dynamic");
3847       if (s != NULL)
3848         {
3849           bfd_byte *dynbuf;
3850           bfd_byte *extdyn;
3851           unsigned int elfsec;
3852           unsigned long shlink;
3853
3854           if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
3855             {
3856 error_free_dyn:
3857               free (dynbuf);
3858               goto error_return;
3859             }
3860
3861           elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
3862           if (elfsec == SHN_BAD)
3863             goto error_free_dyn;
3864           shlink = elf_elfsections (abfd)[elfsec]->sh_link;
3865
3866           for (extdyn = dynbuf;
3867                extdyn < dynbuf + s->size;
3868                extdyn += bed->s->sizeof_dyn)
3869             {
3870               Elf_Internal_Dyn dyn;
3871
3872               bed->s->swap_dyn_in (abfd, extdyn, &dyn);
3873               if (dyn.d_tag == DT_SONAME)
3874                 {
3875                   unsigned int tagv = dyn.d_un.d_val;
3876                   soname = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3877                   if (soname == NULL)
3878                     goto error_free_dyn;
3879                 }
3880               if (dyn.d_tag == DT_NEEDED)
3881                 {
3882                   struct bfd_link_needed_list *n, **pn;
3883                   char *fnm, *anm;
3884                   unsigned int tagv = dyn.d_un.d_val;
3885
3886                   amt = sizeof (struct bfd_link_needed_list);
3887                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3888                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3889                   if (n == NULL || fnm == NULL)
3890                     goto error_free_dyn;
3891                   amt = strlen (fnm) + 1;
3892                   anm = (char *) bfd_alloc (abfd, amt);
3893                   if (anm == NULL)
3894                     goto error_free_dyn;
3895                   memcpy (anm, fnm, amt);
3896                   n->name = anm;
3897                   n->by = abfd;
3898                   n->next = NULL;
3899                   for (pn = &htab->needed; *pn != NULL; pn = &(*pn)->next)
3900                     ;
3901                   *pn = n;
3902                 }
3903               if (dyn.d_tag == DT_RUNPATH)
3904                 {
3905                   struct bfd_link_needed_list *n, **pn;
3906                   char *fnm, *anm;
3907                   unsigned int tagv = dyn.d_un.d_val;
3908
3909                   amt = sizeof (struct bfd_link_needed_list);
3910                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3911                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3912                   if (n == NULL || fnm == NULL)
3913                     goto error_free_dyn;
3914                   amt = strlen (fnm) + 1;
3915                   anm = (char *) bfd_alloc (abfd, amt);
3916                   if (anm == NULL)
3917                     goto error_free_dyn;
3918                   memcpy (anm, fnm, amt);
3919                   n->name = anm;
3920                   n->by = abfd;
3921                   n->next = NULL;
3922                   for (pn = & runpath;
3923                        *pn != NULL;
3924                        pn = &(*pn)->next)
3925                     ;
3926                   *pn = n;
3927                 }
3928               /* Ignore DT_RPATH if we have seen DT_RUNPATH.  */
3929               if (!runpath && dyn.d_tag == DT_RPATH)
3930                 {
3931                   struct bfd_link_needed_list *n, **pn;
3932                   char *fnm, *anm;
3933                   unsigned int tagv = dyn.d_un.d_val;
3934
3935                   amt = sizeof (struct bfd_link_needed_list);
3936                   n = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
3937                   fnm = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3938                   if (n == NULL || fnm == NULL)
3939                     goto error_free_dyn;
3940                   amt = strlen (fnm) + 1;
3941                   anm = (char *) bfd_alloc (abfd, amt);
3942                   if (anm == NULL)
3943                     goto error_free_dyn;
3944                   memcpy (anm, fnm, amt);
3945                   n->name = anm;
3946                   n->by = abfd;
3947                   n->next = NULL;
3948                   for (pn = & rpath;
3949                        *pn != NULL;
3950                        pn = &(*pn)->next)
3951                     ;
3952                   *pn = n;
3953                 }
3954               if (dyn.d_tag == DT_AUDIT)
3955                 {
3956                   unsigned int tagv = dyn.d_un.d_val;
3957                   audit = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
3958                 }
3959             }
3960
3961           free (dynbuf);
3962         }
3963
3964       /* DT_RUNPATH overrides DT_RPATH.  Do _NOT_ bfd_release, as that
3965          frees all more recently bfd_alloc'd blocks as well.  */
3966       if (runpath)
3967         rpath = runpath;
3968
3969       if (rpath)
3970         {
3971           struct bfd_link_needed_list **pn;
3972           for (pn = &htab->runpath; *pn != NULL; pn = &(*pn)->next)
3973             ;
3974           *pn = rpath;
3975         }
3976
3977       /* If we have a PT_GNU_RELRO program header, mark as read-only
3978          all sections contained fully therein.  This makes relro
3979          shared library sections appear as they will at run-time.  */
3980       phdr = elf_tdata (abfd)->phdr + elf_elfheader (abfd)->e_phnum;
3981       while (--phdr >= elf_tdata (abfd)->phdr)
3982         if (phdr->p_type == PT_GNU_RELRO)
3983           {
3984             for (s = abfd->sections; s != NULL; s = s->next)
3985               if ((s->flags & SEC_ALLOC) != 0
3986                   && s->vma >= phdr->p_vaddr
3987                   && s->vma + s->size <= phdr->p_vaddr + phdr->p_memsz)
3988                 s->flags |= SEC_READONLY;
3989             break;
3990           }
3991
3992       /* We do not want to include any of the sections in a dynamic
3993          object in the output file.  We hack by simply clobbering the
3994          list of sections in the BFD.  This could be handled more
3995          cleanly by, say, a new section flag; the existing
3996          SEC_NEVER_LOAD flag is not the one we want, because that one
3997          still implies that the section takes up space in the output
3998          file.  */
3999       bfd_section_list_clear (abfd);
4000
4001       /* Find the name to use in a DT_NEEDED entry that refers to this
4002          object.  If the object has a DT_SONAME entry, we use it.
4003          Otherwise, if the generic linker stuck something in
4004          elf_dt_name, we use that.  Otherwise, we just use the file
4005          name.  */
4006       if (soname == NULL || *soname == '\0')
4007         {
4008           soname = elf_dt_name (abfd);
4009           if (soname == NULL || *soname == '\0')
4010             soname = bfd_get_filename (abfd);
4011         }
4012
4013       /* Save the SONAME because sometimes the linker emulation code
4014          will need to know it.  */
4015       elf_dt_name (abfd) = soname;
4016
4017       ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4018       if (ret < 0)
4019         goto error_return;
4020
4021       /* If we have already included this dynamic object in the
4022          link, just ignore it.  There is no reason to include a
4023          particular dynamic object more than once.  */
4024       if (ret > 0)
4025         return TRUE;
4026
4027       /* Save the DT_AUDIT entry for the linker emulation code. */
4028       elf_dt_audit (abfd) = audit;
4029     }
4030
4031   /* If this is a dynamic object, we always link against the .dynsym
4032      symbol table, not the .symtab symbol table.  The dynamic linker
4033      will only see the .dynsym symbol table, so there is no reason to
4034      look at .symtab for a dynamic object.  */
4035
4036   if (! dynamic || elf_dynsymtab (abfd) == 0)
4037     hdr = &elf_tdata (abfd)->symtab_hdr;
4038   else
4039     hdr = &elf_tdata (abfd)->dynsymtab_hdr;
4040
4041   symcount = hdr->sh_size / bed->s->sizeof_sym;
4042
4043   /* The sh_info field of the symtab header tells us where the
4044      external symbols start.  We don't care about the local symbols at
4045      this point.  */
4046   if (elf_bad_symtab (abfd))
4047     {
4048       extsymcount = symcount;
4049       extsymoff = 0;
4050     }
4051   else
4052     {
4053       extsymcount = symcount - hdr->sh_info;
4054       extsymoff = hdr->sh_info;
4055     }
4056
4057   sym_hash = elf_sym_hashes (abfd);
4058   if (extsymcount != 0)
4059     {
4060       isymbuf = bfd_elf_get_elf_syms (abfd, hdr, extsymcount, extsymoff,
4061                                       NULL, NULL, NULL);
4062       if (isymbuf == NULL)
4063         goto error_return;
4064
4065       if (sym_hash == NULL)
4066         {
4067           /* We store a pointer to the hash table entry for each
4068              external symbol.  */
4069           amt = extsymcount;
4070           amt *= sizeof (struct elf_link_hash_entry *);
4071           sym_hash = (struct elf_link_hash_entry **) bfd_zalloc (abfd, amt);
4072           if (sym_hash == NULL)
4073             goto error_free_sym;
4074           elf_sym_hashes (abfd) = sym_hash;
4075         }
4076     }
4077
4078   if (dynamic)
4079     {
4080       /* Read in any version definitions.  */
4081       if (!_bfd_elf_slurp_version_tables (abfd,
4082                                           info->default_imported_symver))
4083         goto error_free_sym;
4084
4085       /* Read in the symbol versions, but don't bother to convert them
4086          to internal format.  */
4087       if (elf_dynversym (abfd) != 0)
4088         {
4089           Elf_Internal_Shdr *versymhdr;
4090
4091           versymhdr = &elf_tdata (abfd)->dynversym_hdr;
4092           extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
4093           if (extversym == NULL)
4094             goto error_free_sym;
4095           amt = versymhdr->sh_size;
4096           if (bfd_seek (abfd, versymhdr->sh_offset, SEEK_SET) != 0
4097               || bfd_bread (extversym, amt, abfd) != amt)
4098             goto error_free_vers;
4099         }
4100     }
4101
4102   /* If we are loading an as-needed shared lib, save the symbol table
4103      state before we start adding symbols.  If the lib turns out
4104      to be unneeded, restore the state.  */
4105   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4106     {
4107       unsigned int i;
4108       size_t entsize;
4109
4110       for (entsize = 0, i = 0; i < htab->root.table.size; i++)
4111         {
4112           struct bfd_hash_entry *p;
4113           struct elf_link_hash_entry *h;
4114
4115           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4116             {
4117               h = (struct elf_link_hash_entry *) p;
4118               entsize += htab->root.table.entsize;
4119               if (h->root.type == bfd_link_hash_warning)
4120                 entsize += htab->root.table.entsize;
4121             }
4122         }
4123
4124       tabsize = htab->root.table.size * sizeof (struct bfd_hash_entry *);
4125       old_tab = bfd_malloc (tabsize + entsize);
4126       if (old_tab == NULL)
4127         goto error_free_vers;
4128
4129       /* Remember the current objalloc pointer, so that all mem for
4130          symbols added can later be reclaimed.  */
4131       alloc_mark = bfd_hash_allocate (&htab->root.table, 1);
4132       if (alloc_mark == NULL)
4133         goto error_free_vers;
4134
4135       /* Make a special call to the linker "notice" function to
4136          tell it that we are about to handle an as-needed lib.  */
4137       if (!(*bed->notice_as_needed) (abfd, info, notice_as_needed))
4138         goto error_free_vers;
4139
4140       /* Clone the symbol table.  Remember some pointers into the
4141          symbol table, and dynamic symbol count.  */
4142       old_ent = (char *) old_tab + tabsize;
4143       memcpy (old_tab, htab->root.table.table, tabsize);
4144       old_undefs = htab->root.undefs;
4145       old_undefs_tail = htab->root.undefs_tail;
4146       old_table = htab->root.table.table;
4147       old_size = htab->root.table.size;
4148       old_count = htab->root.table.count;
4149       old_strtab = _bfd_elf_strtab_save (htab->dynstr);
4150       if (old_strtab == NULL)
4151         goto error_free_vers;
4152
4153       for (i = 0; i < htab->root.table.size; i++)
4154         {
4155           struct bfd_hash_entry *p;
4156           struct elf_link_hash_entry *h;
4157
4158           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4159             {
4160               memcpy (old_ent, p, htab->root.table.entsize);
4161               old_ent = (char *) old_ent + htab->root.table.entsize;
4162               h = (struct elf_link_hash_entry *) p;
4163               if (h->root.type == bfd_link_hash_warning)
4164                 {
4165                   memcpy (old_ent, h->root.u.i.link, htab->root.table.entsize);
4166                   old_ent = (char *) old_ent + htab->root.table.entsize;
4167                 }
4168             }
4169         }
4170     }
4171
4172   weaks = NULL;
4173   ever = extversym != NULL ? extversym + extsymoff : NULL;
4174   for (isym = isymbuf, isymend = isymbuf + extsymcount;
4175        isym < isymend;
4176        isym++, sym_hash++, ever = (ever != NULL ? ever + 1 : NULL))
4177     {
4178       int bind;
4179       bfd_vma value;
4180       asection *sec, *new_sec;
4181       flagword flags;
4182       const char *name;
4183       struct elf_link_hash_entry *h;
4184       struct elf_link_hash_entry *hi;
4185       bfd_boolean definition;
4186       bfd_boolean size_change_ok;
4187       bfd_boolean type_change_ok;
4188       bfd_boolean new_weakdef;
4189       bfd_boolean new_weak;
4190       bfd_boolean old_weak;
4191       bfd_boolean override;
4192       bfd_boolean common;
4193       bfd_boolean discarded;
4194       unsigned int old_alignment;
4195       bfd *old_bfd;
4196       bfd_boolean matched;
4197
4198       override = FALSE;
4199
4200       flags = BSF_NO_FLAGS;
4201       sec = NULL;
4202       value = isym->st_value;
4203       common = bed->common_definition (isym);
4204       discarded = FALSE;
4205
4206       bind = ELF_ST_BIND (isym->st_info);
4207       switch (bind)
4208         {
4209         case STB_LOCAL:
4210           /* This should be impossible, since ELF requires that all
4211              global symbols follow all local symbols, and that sh_info
4212              point to the first global symbol.  Unfortunately, Irix 5
4213              screws this up.  */
4214           continue;
4215
4216         case STB_GLOBAL:
4217           if (isym->st_shndx != SHN_UNDEF && !common)
4218             flags = BSF_GLOBAL;
4219           break;
4220
4221         case STB_WEAK:
4222           flags = BSF_WEAK;
4223           break;
4224
4225         case STB_GNU_UNIQUE:
4226           flags = BSF_GNU_UNIQUE;
4227           break;
4228
4229         default:
4230           /* Leave it up to the processor backend.  */
4231           break;
4232         }
4233
4234       if (isym->st_shndx == SHN_UNDEF)
4235         sec = bfd_und_section_ptr;
4236       else if (isym->st_shndx == SHN_ABS)
4237         sec = bfd_abs_section_ptr;
4238       else if (isym->st_shndx == SHN_COMMON)
4239         {
4240           sec = bfd_com_section_ptr;
4241           /* What ELF calls the size we call the value.  What ELF
4242              calls the value we call the alignment.  */
4243           value = isym->st_size;
4244         }
4245       else
4246         {
4247           sec = bfd_section_from_elf_index (abfd, isym->st_shndx);
4248           if (sec == NULL)
4249             sec = bfd_abs_section_ptr;
4250           else if (discarded_section (sec))
4251             {
4252               /* Symbols from discarded section are undefined.  We keep
4253                  its visibility.  */
4254               sec = bfd_und_section_ptr;
4255               discarded = TRUE;
4256               isym->st_shndx = SHN_UNDEF;
4257             }
4258           else if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
4259             value -= sec->vma;
4260         }
4261
4262       name = bfd_elf_string_from_elf_section (abfd, hdr->sh_link,
4263                                               isym->st_name);
4264       if (name == NULL)
4265         goto error_free_vers;
4266
4267       if (isym->st_shndx == SHN_COMMON
4268           && (abfd->flags & BFD_PLUGIN) != 0)
4269         {
4270           asection *xc = bfd_get_section_by_name (abfd, "COMMON");
4271
4272           if (xc == NULL)
4273             {
4274               flagword sflags = (SEC_ALLOC | SEC_IS_COMMON | SEC_KEEP
4275                                  | SEC_EXCLUDE);
4276               xc = bfd_make_section_with_flags (abfd, "COMMON", sflags);
4277               if (xc == NULL)
4278                 goto error_free_vers;
4279             }
4280           sec = xc;
4281         }
4282       else if (isym->st_shndx == SHN_COMMON
4283                && ELF_ST_TYPE (isym->st_info) == STT_TLS
4284                && !bfd_link_relocatable (info))
4285         {
4286           asection *tcomm = bfd_get_section_by_name (abfd, ".tcommon");
4287
4288           if (tcomm == NULL)
4289             {
4290               flagword sflags = (SEC_ALLOC | SEC_THREAD_LOCAL | SEC_IS_COMMON
4291                                  | SEC_LINKER_CREATED);
4292               tcomm = bfd_make_section_with_flags (abfd, ".tcommon", sflags);
4293               if (tcomm == NULL)
4294                 goto error_free_vers;
4295             }
4296           sec = tcomm;
4297         }
4298       else if (bed->elf_add_symbol_hook)
4299         {
4300           if (! (*bed->elf_add_symbol_hook) (abfd, info, isym, &name, &flags,
4301                                              &sec, &value))
4302             goto error_free_vers;
4303
4304           /* The hook function sets the name to NULL if this symbol
4305              should be skipped for some reason.  */
4306           if (name == NULL)
4307             continue;
4308         }
4309
4310       /* Sanity check that all possibilities were handled.  */
4311       if (sec == NULL)
4312         {
4313           bfd_set_error (bfd_error_bad_value);
4314           goto error_free_vers;
4315         }
4316
4317       /* Silently discard TLS symbols from --just-syms.  There's
4318          no way to combine a static TLS block with a new TLS block
4319          for this executable.  */
4320       if (ELF_ST_TYPE (isym->st_info) == STT_TLS
4321           && sec->sec_info_type == SEC_INFO_TYPE_JUST_SYMS)
4322         continue;
4323
4324       if (bfd_is_und_section (sec)
4325           || bfd_is_com_section (sec))
4326         definition = FALSE;
4327       else
4328         definition = TRUE;
4329
4330       size_change_ok = FALSE;
4331       type_change_ok = bed->type_change_ok;
4332       old_weak = FALSE;
4333       matched = FALSE;
4334       old_alignment = 0;
4335       old_bfd = NULL;
4336       new_sec = sec;
4337
4338       if (is_elf_hash_table (htab))
4339         {
4340           Elf_Internal_Versym iver;
4341           unsigned int vernum = 0;
4342           bfd_boolean skip;
4343
4344           if (ever == NULL)
4345             {
4346               if (info->default_imported_symver)
4347                 /* Use the default symbol version created earlier.  */
4348                 iver.vs_vers = elf_tdata (abfd)->cverdefs;
4349               else
4350                 iver.vs_vers = 0;
4351             }
4352           else
4353             _bfd_elf_swap_versym_in (abfd, ever, &iver);
4354
4355           vernum = iver.vs_vers & VERSYM_VERSION;
4356
4357           /* If this is a hidden symbol, or if it is not version
4358              1, we append the version name to the symbol name.
4359              However, we do not modify a non-hidden absolute symbol
4360              if it is not a function, because it might be the version
4361              symbol itself.  FIXME: What if it isn't?  */
4362           if ((iver.vs_vers & VERSYM_HIDDEN) != 0
4363               || (vernum > 1
4364                   && (!bfd_is_abs_section (sec)
4365                       || bed->is_function_type (ELF_ST_TYPE (isym->st_info)))))
4366             {
4367               const char *verstr;
4368               size_t namelen, verlen, newlen;
4369               char *newname, *p;
4370
4371               if (isym->st_shndx != SHN_UNDEF)
4372                 {
4373                   if (vernum > elf_tdata (abfd)->cverdefs)
4374                     verstr = NULL;
4375                   else if (vernum > 1)
4376                     verstr =
4377                       elf_tdata (abfd)->verdef[vernum - 1].vd_nodename;
4378                   else
4379                     verstr = "";
4380
4381                   if (verstr == NULL)
4382                     {
4383                       _bfd_error_handler
4384                         /* xgettext:c-format */
4385                         (_("%B: %s: invalid version %u (max %d)"),
4386                          abfd, name, vernum,
4387                          elf_tdata (abfd)->cverdefs);
4388                       bfd_set_error (bfd_error_bad_value);
4389                       goto error_free_vers;
4390                     }
4391                 }
4392               else
4393                 {
4394                   /* We cannot simply test for the number of
4395                      entries in the VERNEED section since the
4396                      numbers for the needed versions do not start
4397                      at 0.  */
4398                   Elf_Internal_Verneed *t;
4399
4400                   verstr = NULL;
4401                   for (t = elf_tdata (abfd)->verref;
4402                        t != NULL;
4403                        t = t->vn_nextref)
4404                     {
4405                       Elf_Internal_Vernaux *a;
4406
4407                       for (a = t->vn_auxptr; a != NULL; a = a->vna_nextptr)
4408                         {
4409                           if (a->vna_other == vernum)
4410                             {
4411                               verstr = a->vna_nodename;
4412                               break;
4413                             }
4414                         }
4415                       if (a != NULL)
4416                         break;
4417                     }
4418                   if (verstr == NULL)
4419                     {
4420                       _bfd_error_handler
4421                         /* xgettext:c-format */
4422                         (_("%B: %s: invalid needed version %d"),
4423                          abfd, name, vernum);
4424                       bfd_set_error (bfd_error_bad_value);
4425                       goto error_free_vers;
4426                     }
4427                 }
4428
4429               namelen = strlen (name);
4430               verlen = strlen (verstr);
4431               newlen = namelen + verlen + 2;
4432               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4433                   && isym->st_shndx != SHN_UNDEF)
4434                 ++newlen;
4435
4436               newname = (char *) bfd_hash_allocate (&htab->root.table, newlen);
4437               if (newname == NULL)
4438                 goto error_free_vers;
4439               memcpy (newname, name, namelen);
4440               p = newname + namelen;
4441               *p++ = ELF_VER_CHR;
4442               /* If this is a defined non-hidden version symbol,
4443                  we add another @ to the name.  This indicates the
4444                  default version of the symbol.  */
4445               if ((iver.vs_vers & VERSYM_HIDDEN) == 0
4446                   && isym->st_shndx != SHN_UNDEF)
4447                 *p++ = ELF_VER_CHR;
4448               memcpy (p, verstr, verlen + 1);
4449
4450               name = newname;
4451             }
4452
4453           /* If this symbol has default visibility and the user has
4454              requested we not re-export it, then mark it as hidden.  */
4455           if (!bfd_is_und_section (sec)
4456               && !dynamic
4457               && abfd->no_export
4458               && ELF_ST_VISIBILITY (isym->st_other) != STV_INTERNAL)
4459             isym->st_other = (STV_HIDDEN
4460                               | (isym->st_other & ~ELF_ST_VISIBILITY (-1)));
4461
4462           if (!_bfd_elf_merge_symbol (abfd, info, name, isym, &sec, &value,
4463                                       sym_hash, &old_bfd, &old_weak,
4464                                       &old_alignment, &skip, &override,
4465                                       &type_change_ok, &size_change_ok,
4466                                       &matched))
4467             goto error_free_vers;
4468
4469           if (skip)
4470             continue;
4471
4472           /* Override a definition only if the new symbol matches the
4473              existing one.  */
4474           if (override && matched)
4475             definition = FALSE;
4476
4477           h = *sym_hash;
4478           while (h->root.type == bfd_link_hash_indirect
4479                  || h->root.type == bfd_link_hash_warning)
4480             h = (struct elf_link_hash_entry *) h->root.u.i.link;
4481
4482           if (elf_tdata (abfd)->verdef != NULL
4483               && vernum > 1
4484               && definition)
4485             h->verinfo.verdef = &elf_tdata (abfd)->verdef[vernum - 1];
4486         }
4487
4488       if (! (_bfd_generic_link_add_one_symbol
4489              (info, abfd, name, flags, sec, value, NULL, FALSE, bed->collect,
4490               (struct bfd_link_hash_entry **) sym_hash)))
4491         goto error_free_vers;
4492
4493       if ((flags & BSF_GNU_UNIQUE)
4494           && (abfd->flags & DYNAMIC) == 0
4495           && bfd_get_flavour (info->output_bfd) == bfd_target_elf_flavour)
4496         elf_tdata (info->output_bfd)->has_gnu_symbols |= elf_gnu_symbol_unique;
4497
4498       h = *sym_hash;
4499       /* We need to make sure that indirect symbol dynamic flags are
4500          updated.  */
4501       hi = h;
4502       while (h->root.type == bfd_link_hash_indirect
4503              || h->root.type == bfd_link_hash_warning)
4504         h = (struct elf_link_hash_entry *) h->root.u.i.link;
4505
4506       /* Setting the index to -3 tells elf_link_output_extsym that
4507          this symbol is defined in a discarded section.  */
4508       if (discarded)
4509         h->indx = -3;
4510
4511       *sym_hash = h;
4512
4513       new_weak = (flags & BSF_WEAK) != 0;
4514       new_weakdef = FALSE;
4515       if (dynamic
4516           && definition
4517           && new_weak
4518           && !bed->is_function_type (ELF_ST_TYPE (isym->st_info))
4519           && is_elf_hash_table (htab)
4520           && h->u.weakdef == NULL)
4521         {
4522           /* Keep a list of all weak defined non function symbols from
4523              a dynamic object, using the weakdef field.  Later in this
4524              function we will set the weakdef field to the correct
4525              value.  We only put non-function symbols from dynamic
4526              objects on this list, because that happens to be the only
4527              time we need to know the normal symbol corresponding to a
4528              weak symbol, and the information is time consuming to
4529              figure out.  If the weakdef field is not already NULL,
4530              then this symbol was already defined by some previous
4531              dynamic object, and we will be using that previous
4532              definition anyhow.  */
4533
4534           h->u.weakdef = weaks;
4535           weaks = h;
4536           new_weakdef = TRUE;
4537         }
4538
4539       /* Set the alignment of a common symbol.  */
4540       if ((common || bfd_is_com_section (sec))
4541           && h->root.type == bfd_link_hash_common)
4542         {
4543           unsigned int align;
4544
4545           if (common)
4546             align = bfd_log2 (isym->st_value);
4547           else
4548             {
4549               /* The new symbol is a common symbol in a shared object.
4550                  We need to get the alignment from the section.  */
4551               align = new_sec->alignment_power;
4552             }
4553           if (align > old_alignment)
4554             h->root.u.c.p->alignment_power = align;
4555           else
4556             h->root.u.c.p->alignment_power = old_alignment;
4557         }
4558
4559       if (is_elf_hash_table (htab))
4560         {
4561           /* Set a flag in the hash table entry indicating the type of
4562              reference or definition we just found.  A dynamic symbol
4563              is one which is referenced or defined by both a regular
4564              object and a shared object.  */
4565           bfd_boolean dynsym = FALSE;
4566
4567           /* Plugin symbols aren't normal.  Don't set def_regular or
4568              ref_regular for them, or make them dynamic.  */
4569           if ((abfd->flags & BFD_PLUGIN) != 0)
4570             ;
4571           else if (! dynamic)
4572             {
4573               if (! definition)
4574                 {
4575                   h->ref_regular = 1;
4576                   if (bind != STB_WEAK)
4577                     h->ref_regular_nonweak = 1;
4578                 }
4579               else
4580                 {
4581                   h->def_regular = 1;
4582                   if (h->def_dynamic)
4583                     {
4584                       h->def_dynamic = 0;
4585                       h->ref_dynamic = 1;
4586                     }
4587                 }
4588
4589               /* If the indirect symbol has been forced local, don't
4590                  make the real symbol dynamic.  */
4591               if ((h == hi || !hi->forced_local)
4592                   && (bfd_link_dll (info)
4593                       || h->def_dynamic
4594                       || h->ref_dynamic))
4595                 dynsym = TRUE;
4596             }
4597           else
4598             {
4599               if (! definition)
4600                 {
4601                   h->ref_dynamic = 1;
4602                   hi->ref_dynamic = 1;
4603                 }
4604               else
4605                 {
4606                   h->def_dynamic = 1;
4607                   hi->def_dynamic = 1;
4608                 }
4609
4610               /* If the indirect symbol has been forced local, don't
4611                  make the real symbol dynamic.  */
4612               if ((h == hi || !hi->forced_local)
4613                   && (h->def_regular
4614                       || h->ref_regular
4615                       || (h->u.weakdef != NULL
4616                           && ! new_weakdef
4617                           && h->u.weakdef->dynindx != -1)))
4618                 dynsym = TRUE;
4619             }
4620
4621           /* Check to see if we need to add an indirect symbol for
4622              the default name.  */
4623           if (definition
4624               || (!override && h->root.type == bfd_link_hash_common))
4625             if (!_bfd_elf_add_default_symbol (abfd, info, h, name, isym,
4626                                               sec, value, &old_bfd, &dynsym))
4627               goto error_free_vers;
4628
4629           /* Check the alignment when a common symbol is involved. This
4630              can change when a common symbol is overridden by a normal
4631              definition or a common symbol is ignored due to the old
4632              normal definition. We need to make sure the maximum
4633              alignment is maintained.  */
4634           if ((old_alignment || common)
4635               && h->root.type != bfd_link_hash_common)
4636             {
4637               unsigned int common_align;
4638               unsigned int normal_align;
4639               unsigned int symbol_align;
4640               bfd *normal_bfd;
4641               bfd *common_bfd;
4642
4643               BFD_ASSERT (h->root.type == bfd_link_hash_defined
4644                           || h->root.type == bfd_link_hash_defweak);
4645
4646               symbol_align = ffs (h->root.u.def.value) - 1;
4647               if (h->root.u.def.section->owner != NULL
4648                   && (h->root.u.def.section->owner->flags
4649                        & (DYNAMIC | BFD_PLUGIN)) == 0)
4650                 {
4651                   normal_align = h->root.u.def.section->alignment_power;
4652                   if (normal_align > symbol_align)
4653                     normal_align = symbol_align;
4654                 }
4655               else
4656                 normal_align = symbol_align;
4657
4658               if (old_alignment)
4659                 {
4660                   common_align = old_alignment;
4661                   common_bfd = old_bfd;
4662                   normal_bfd = abfd;
4663                 }
4664               else
4665                 {
4666                   common_align = bfd_log2 (isym->st_value);
4667                   common_bfd = abfd;
4668                   normal_bfd = old_bfd;
4669                 }
4670
4671               if (normal_align < common_align)
4672                 {
4673                   /* PR binutils/2735 */
4674                   if (normal_bfd == NULL)
4675                     _bfd_error_handler
4676                       /* xgettext:c-format */
4677                       (_("Warning: alignment %u of common symbol `%s' in %B is"
4678                          " greater than the alignment (%u) of its section %A"),
4679                        common_bfd, h->root.u.def.section,
4680                        1 << common_align, name, 1 << normal_align);
4681                   else
4682                     _bfd_error_handler
4683                       /* xgettext:c-format */
4684                       (_("Warning: alignment %u of symbol `%s' in %B"
4685                          " is smaller than %u in %B"),
4686                        normal_bfd, common_bfd,
4687                        1 << normal_align, name, 1 << common_align);
4688                 }
4689             }
4690
4691           /* Remember the symbol size if it isn't undefined.  */
4692           if (isym->st_size != 0
4693               && isym->st_shndx != SHN_UNDEF
4694               && (definition || h->size == 0))
4695             {
4696               if (h->size != 0
4697                   && h->size != isym->st_size
4698                   && ! size_change_ok)
4699                 _bfd_error_handler
4700                   /* xgettext:c-format */
4701                   (_("Warning: size of symbol `%s' changed"
4702                      " from %lu in %B to %lu in %B"),
4703                    old_bfd, abfd,
4704                    name, (unsigned long) h->size,
4705                    (unsigned long) isym->st_size);
4706
4707               h->size = isym->st_size;
4708             }
4709
4710           /* If this is a common symbol, then we always want H->SIZE
4711              to be the size of the common symbol.  The code just above
4712              won't fix the size if a common symbol becomes larger.  We
4713              don't warn about a size change here, because that is
4714              covered by --warn-common.  Allow changes between different
4715              function types.  */
4716           if (h->root.type == bfd_link_hash_common)
4717             h->size = h->root.u.c.size;
4718
4719           if (ELF_ST_TYPE (isym->st_info) != STT_NOTYPE
4720               && ((definition && !new_weak)
4721                   || (old_weak && h->root.type == bfd_link_hash_common)
4722                   || h->type == STT_NOTYPE))
4723             {
4724               unsigned int type = ELF_ST_TYPE (isym->st_info);
4725
4726               /* Turn an IFUNC symbol from a DSO into a normal FUNC
4727                  symbol.  */
4728               if (type == STT_GNU_IFUNC
4729                   && (abfd->flags & DYNAMIC) != 0)
4730                 type = STT_FUNC;
4731
4732               if (h->type != type)
4733                 {
4734                   if (h->type != STT_NOTYPE && ! type_change_ok)
4735                     /* xgettext:c-format */
4736                     _bfd_error_handler
4737                       (_("Warning: type of symbol `%s' changed"
4738                          " from %d to %d in %B"),
4739                        abfd, name, h->type, type);
4740
4741                   h->type = type;
4742                 }
4743             }
4744
4745           /* Merge st_other field.  */
4746           elf_merge_st_other (abfd, h, isym, sec, definition, dynamic);
4747
4748           /* We don't want to make debug symbol dynamic.  */
4749           if (definition
4750               && (sec->flags & SEC_DEBUGGING)
4751               && !bfd_link_relocatable (info))
4752             dynsym = FALSE;
4753
4754           /* Nor should we make plugin symbols dynamic.  */
4755           if ((abfd->flags & BFD_PLUGIN) != 0)
4756             dynsym = FALSE;
4757
4758           if (definition)
4759             {
4760               h->target_internal = isym->st_target_internal;
4761               h->unique_global = (flags & BSF_GNU_UNIQUE) != 0;
4762             }
4763
4764           if (definition && !dynamic)
4765             {
4766               char *p = strchr (name, ELF_VER_CHR);
4767               if (p != NULL && p[1] != ELF_VER_CHR)
4768                 {
4769                   /* Queue non-default versions so that .symver x, x@FOO
4770                      aliases can be checked.  */
4771                   if (!nondeflt_vers)
4772                     {
4773                       amt = ((isymend - isym + 1)
4774                              * sizeof (struct elf_link_hash_entry *));
4775                       nondeflt_vers
4776                         = (struct elf_link_hash_entry **) bfd_malloc (amt);
4777                       if (!nondeflt_vers)
4778                         goto error_free_vers;
4779                     }
4780                   nondeflt_vers[nondeflt_vers_cnt++] = h;
4781                 }
4782             }
4783
4784           if (dynsym && h->dynindx == -1)
4785             {
4786               if (! bfd_elf_link_record_dynamic_symbol (info, h))
4787                 goto error_free_vers;
4788               if (h->u.weakdef != NULL
4789                   && ! new_weakdef
4790                   && h->u.weakdef->dynindx == -1)
4791                 {
4792                   if (!bfd_elf_link_record_dynamic_symbol (info, h->u.weakdef))
4793                     goto error_free_vers;
4794                 }
4795             }
4796           else if (h->dynindx != -1)
4797             /* If the symbol already has a dynamic index, but
4798                visibility says it should not be visible, turn it into
4799                a local symbol.  */
4800             switch (ELF_ST_VISIBILITY (h->other))
4801               {
4802               case STV_INTERNAL:
4803               case STV_HIDDEN:
4804                 (*bed->elf_backend_hide_symbol) (info, h, TRUE);
4805                 dynsym = FALSE;
4806                 break;
4807               }
4808
4809           /* Don't add DT_NEEDED for references from the dummy bfd nor
4810              for unmatched symbol.  */
4811           if (!add_needed
4812               && matched
4813               && definition
4814               && ((dynsym
4815                    && h->ref_regular_nonweak
4816                    && (old_bfd == NULL
4817                        || (old_bfd->flags & BFD_PLUGIN) == 0))
4818                   || (h->ref_dynamic_nonweak
4819                       && (elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0
4820                       && !on_needed_list (elf_dt_name (abfd),
4821                                           htab->needed, NULL))))
4822             {
4823               int ret;
4824               const char *soname = elf_dt_name (abfd);
4825
4826               info->callbacks->minfo ("%!", soname, old_bfd,
4827                                       h->root.root.string);
4828
4829               /* A symbol from a library loaded via DT_NEEDED of some
4830                  other library is referenced by a regular object.
4831                  Add a DT_NEEDED entry for it.  Issue an error if
4832                  --no-add-needed is used and the reference was not
4833                  a weak one.  */
4834               if (old_bfd != NULL
4835                   && (elf_dyn_lib_class (abfd) & DYN_NO_NEEDED) != 0)
4836                 {
4837                   _bfd_error_handler
4838                     /* xgettext:c-format */
4839                     (_("%B: undefined reference to symbol '%s'"),
4840                      old_bfd, name);
4841                   bfd_set_error (bfd_error_missing_dso);
4842                   goto error_free_vers;
4843                 }
4844
4845               elf_dyn_lib_class (abfd) = (enum dynamic_lib_link_class)
4846                 (elf_dyn_lib_class (abfd) & ~DYN_AS_NEEDED);
4847
4848               add_needed = TRUE;
4849               ret = elf_add_dt_needed_tag (abfd, info, soname, add_needed);
4850               if (ret < 0)
4851                 goto error_free_vers;
4852
4853               BFD_ASSERT (ret == 0);
4854             }
4855         }
4856     }
4857
4858   if (extversym != NULL)
4859     {
4860       free (extversym);
4861       extversym = NULL;
4862     }
4863
4864   if (isymbuf != NULL)
4865     {
4866       free (isymbuf);
4867       isymbuf = NULL;
4868     }
4869
4870   if ((elf_dyn_lib_class (abfd) & DYN_AS_NEEDED) != 0)
4871     {
4872       unsigned int i;
4873
4874       /* Restore the symbol table.  */
4875       old_ent = (char *) old_tab + tabsize;
4876       memset (elf_sym_hashes (abfd), 0,
4877               extsymcount * sizeof (struct elf_link_hash_entry *));
4878       htab->root.table.table = old_table;
4879       htab->root.table.size = old_size;
4880       htab->root.table.count = old_count;
4881       memcpy (htab->root.table.table, old_tab, tabsize);
4882       htab->root.undefs = old_undefs;
4883       htab->root.undefs_tail = old_undefs_tail;
4884       _bfd_elf_strtab_restore (htab->dynstr, old_strtab);
4885       free (old_strtab);
4886       old_strtab = NULL;
4887       for (i = 0; i < htab->root.table.size; i++)
4888         {
4889           struct bfd_hash_entry *p;
4890           struct elf_link_hash_entry *h;
4891           bfd_size_type size;
4892           unsigned int alignment_power;
4893
4894           for (p = htab->root.table.table[i]; p != NULL; p = p->next)
4895             {
4896               h = (struct elf_link_hash_entry *) p;
4897               if (h->root.type == bfd_link_hash_warning)
4898                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
4899
4900               /* Preserve the maximum alignment and size for common
4901                  symbols even if this dynamic lib isn't on DT_NEEDED
4902                  since it can still be loaded at run time by another
4903                  dynamic lib.  */
4904               if (h->root.type == bfd_link_hash_common)
4905                 {
4906                   size = h->root.u.c.size;
4907                   alignment_power = h->root.u.c.p->alignment_power;
4908                 }
4909               else
4910                 {
4911                   size = 0;
4912                   alignment_power = 0;
4913                 }
4914               memcpy (p, old_ent, htab->root.table.entsize);
4915               old_ent = (char *) old_ent + htab->root.table.entsize;
4916               h = (struct elf_link_hash_entry *) p;
4917               if (h->root.type == bfd_link_hash_warning)
4918                 {
4919                   memcpy (h->root.u.i.link, old_ent, htab->root.table.entsize);
4920                   old_ent = (char *) old_ent + htab->root.table.entsize;
4921                   h = (struct elf_link_hash_entry *) h->root.u.i.link;
4922                 }
4923               if (h->root.type == bfd_link_hash_common)
4924                 {
4925                   if (size > h->root.u.c.size)
4926                     h->root.u.c.size = size;
4927                   if (alignment_power > h->root.u.c.p->alignment_power)
4928                     h->root.u.c.p->alignment_power = alignment_power;
4929                 }
4930             }
4931         }
4932
4933       /* Make a special call to the linker "notice" function to
4934          tell it that symbols added for crefs may need to be removed.  */
4935       if (!(*bed->notice_as_needed) (abfd, info, notice_not_needed))
4936         goto error_free_vers;
4937
4938       free (old_tab);
4939       objalloc_free_block ((struct objalloc *) htab->root.table.memory,
4940                            alloc_mark);
4941       if (nondeflt_vers != NULL)
4942         free (nondeflt_vers);
4943       return TRUE;
4944     }
4945
4946   if (old_tab != NULL)
4947     {
4948       if (!(*bed->notice_as_needed) (abfd, info, notice_needed))
4949         goto error_free_vers;
4950       free (old_tab);
4951       old_tab = NULL;
4952     }
4953
4954   /* Now that all the symbols from this input file are created, if
4955      not performing a relocatable link, handle .symver foo, foo@BAR
4956      such that any relocs against foo become foo@BAR.  */
4957   if (!bfd_link_relocatable (info) && nondeflt_vers != NULL)
4958     {
4959       size_t cnt, symidx;
4960
4961       for (cnt = 0; cnt < nondeflt_vers_cnt; ++cnt)
4962         {
4963           struct elf_link_hash_entry *h = nondeflt_vers[cnt], *hi;
4964           char *shortname, *p;
4965
4966           p = strchr (h->root.root.string, ELF_VER_CHR);
4967           if (p == NULL
4968               || (h->root.type != bfd_link_hash_defined
4969                   && h->root.type != bfd_link_hash_defweak))
4970             continue;
4971
4972           amt = p - h->root.root.string;
4973           shortname = (char *) bfd_malloc (amt + 1);
4974           if (!shortname)
4975             goto error_free_vers;
4976           memcpy (shortname, h->root.root.string, amt);
4977           shortname[amt] = '\0';
4978
4979           hi = (struct elf_link_hash_entry *)
4980                bfd_link_hash_lookup (&htab->root, shortname,
4981                                      FALSE, FALSE, FALSE);
4982           if (hi != NULL
4983               && hi->root.type == h->root.type
4984               && hi->root.u.def.value == h->root.u.def.value
4985               && hi->root.u.def.section == h->root.u.def.section)
4986             {
4987               (*bed->elf_backend_hide_symbol) (info, hi, TRUE);
4988               hi->root.type = bfd_link_hash_indirect;
4989               hi->root.u.i.link = (struct bfd_link_hash_entry *) h;
4990               (*bed->elf_backend_copy_indirect_symbol) (info, h, hi);
4991               sym_hash = elf_sym_hashes (abfd);
4992               if (sym_hash)
4993                 for (symidx = 0; symidx < extsymcount; ++symidx)
4994                   if (sym_hash[symidx] == hi)
4995                     {
4996                       sym_hash[symidx] = h;
4997                       break;
4998                     }
4999             }
5000           free (shortname);
5001         }
5002       free (nondeflt_vers);
5003       nondeflt_vers = NULL;
5004     }
5005
5006   /* Now set the weakdefs field correctly for all the weak defined
5007      symbols we found.  The only way to do this is to search all the
5008      symbols.  Since we only need the information for non functions in
5009      dynamic objects, that's the only time we actually put anything on
5010      the list WEAKS.  We need this information so that if a regular
5011      object refers to a symbol defined weakly in a dynamic object, the
5012      real symbol in the dynamic object is also put in the dynamic
5013      symbols; we also must arrange for both symbols to point to the
5014      same memory location.  We could handle the general case of symbol
5015      aliasing, but a general symbol alias can only be generated in
5016      assembler code, handling it correctly would be very time
5017      consuming, and other ELF linkers don't handle general aliasing
5018      either.  */
5019   if (weaks != NULL)
5020     {
5021       struct elf_link_hash_entry **hpp;
5022       struct elf_link_hash_entry **hppend;
5023       struct elf_link_hash_entry **sorted_sym_hash;
5024       struct elf_link_hash_entry *h;
5025       size_t sym_count;
5026
5027       /* Since we have to search the whole symbol list for each weak
5028          defined symbol, search time for N weak defined symbols will be
5029          O(N^2). Binary search will cut it down to O(NlogN).  */
5030       amt = extsymcount;
5031       amt *= sizeof (struct elf_link_hash_entry *);
5032       sorted_sym_hash = (struct elf_link_hash_entry **) bfd_malloc (amt);
5033       if (sorted_sym_hash == NULL)
5034         goto error_return;
5035       sym_hash = sorted_sym_hash;
5036       hpp = elf_sym_hashes (abfd);
5037       hppend = hpp + extsymcount;
5038       sym_count = 0;
5039       for (; hpp < hppend; hpp++)
5040         {
5041           h = *hpp;
5042           if (h != NULL
5043               && h->root.type == bfd_link_hash_defined
5044               && !bed->is_function_type (h->type))
5045             {
5046               *sym_hash = h;
5047               sym_hash++;
5048               sym_count++;
5049             }
5050         }
5051
5052       qsort (sorted_sym_hash, sym_count,
5053              sizeof (struct elf_link_hash_entry *),
5054              elf_sort_symbol);
5055
5056       while (weaks != NULL)
5057         {
5058           struct elf_link_hash_entry *hlook;
5059           asection *slook;
5060           bfd_vma vlook;
5061           size_t i, j, idx = 0;
5062
5063           hlook = weaks;
5064           weaks = hlook->u.weakdef;
5065           hlook->u.weakdef = NULL;
5066
5067           BFD_ASSERT (hlook->root.type == bfd_link_hash_defined
5068                       || hlook->root.type == bfd_link_hash_defweak
5069                       || hlook->root.type == bfd_link_hash_common
5070                       || hlook->root.type == bfd_link_hash_indirect);
5071           slook = hlook->root.u.def.section;
5072           vlook = hlook->root.u.def.value;
5073
5074           i = 0;
5075           j = sym_count;
5076           while (i != j)
5077             {
5078               bfd_signed_vma vdiff;
5079               idx = (i + j) / 2;
5080               h = sorted_sym_hash[idx];
5081               vdiff = vlook - h->root.u.def.value;
5082               if (vdiff < 0)
5083                 j = idx;
5084               else if (vdiff > 0)
5085                 i = idx + 1;
5086               else
5087                 {
5088                   int sdiff = slook->id - h->root.u.def.section->id;
5089                   if (sdiff < 0)
5090                     j = idx;
5091                   else if (sdiff > 0)
5092                     i = idx + 1;
5093                   else
5094                     break;
5095                 }
5096             }
5097
5098           /* We didn't find a value/section match.  */
5099           if (i == j)
5100             continue;
5101
5102           /* With multiple aliases, or when the weak symbol is already
5103              strongly defined, we have multiple matching symbols and
5104              the binary search above may land on any of them.  Step
5105              one past the matching symbol(s).  */
5106           while (++idx != j)
5107             {
5108               h = sorted_sym_hash[idx];
5109               if (h->root.u.def.section != slook
5110                   || h->root.u.def.value != vlook)
5111                 break;
5112             }
5113
5114           /* Now look back over the aliases.  Since we sorted by size
5115              as well as value and section, we'll choose the one with
5116              the largest size.  */
5117           while (idx-- != i)
5118             {
5119               h = sorted_sym_hash[idx];
5120
5121               /* Stop if value or section doesn't match.  */
5122               if (h->root.u.def.section != slook
5123                   || h->root.u.def.value != vlook)
5124                 break;
5125               else if (h != hlook)
5126                 {
5127                   hlook->u.weakdef = h;
5128
5129                   /* If the weak definition is in the list of dynamic
5130                      symbols, make sure the real definition is put
5131                      there as well.  */
5132                   if (hlook->dynindx != -1 && h->dynindx == -1)
5133                     {
5134                       if (! bfd_elf_link_record_dynamic_symbol (info, h))
5135                         {
5136                         err_free_sym_hash:
5137                           free (sorted_sym_hash);
5138                           goto error_return;
5139                         }
5140                     }
5141
5142                   /* If the real definition is in the list of dynamic
5143                      symbols, make sure the weak definition is put
5144                      there as well.  If we don't do this, then the
5145                      dynamic loader might not merge the entries for the
5146                      real definition and the weak definition.  */
5147                   if (h->dynindx != -1 && hlook->dynindx == -1)
5148                     {
5149                       if (! bfd_elf_link_record_dynamic_symbol (info, hlook))
5150                         goto err_free_sym_hash;
5151                     }
5152                   break;
5153                 }
5154             }
5155         }
5156
5157       free (sorted_sym_hash);
5158     }
5159
5160   if (bed->check_directives
5161       && !(*bed->check_directives) (abfd, info))
5162     return FALSE;
5163
5164   if (!info->check_relocs_after_open_input
5165       && !_bfd_elf_link_check_relocs (abfd, info))
5166     return FALSE;
5167
5168   /* If this is a non-traditional link, try to optimize the handling
5169      of the .stab/.stabstr sections.  */
5170   if (! dynamic
5171       && ! info->traditional_format
5172       && is_elf_hash_table (htab)
5173       && (info->strip != strip_all && info->strip != strip_debugger))
5174     {
5175       asection *stabstr;
5176
5177       stabstr = bfd_get_section_by_name (abfd, ".stabstr");
5178       if (stabstr != NULL)
5179         {
5180           bfd_size_type string_offset = 0;
5181           asection *stab;
5182
5183           for (stab = abfd->sections; stab; stab = stab->next)
5184             if (CONST_STRNEQ (stab->name, ".stab")
5185                 && (!stab->name[5] ||
5186                     (stab->name[5] == '.' && ISDIGIT (stab->name[6])))
5187                 && (stab->flags & SEC_MERGE) == 0
5188                 && !bfd_is_abs_section (stab->output_section))
5189               {
5190                 struct bfd_elf_section_data *secdata;
5191
5192                 secdata = elf_section_data (stab);
5193                 if (! _bfd_link_section_stabs (abfd, &htab->stab_info, stab,
5194                                                stabstr, &secdata->sec_info,
5195                                                &string_offset))
5196                   goto error_return;
5197                 if (secdata->sec_info)
5198                   stab->sec_info_type = SEC_INFO_TYPE_STABS;
5199             }
5200         }
5201     }
5202
5203   if (is_elf_hash_table (htab) && add_needed)
5204     {
5205       /* Add this bfd to the loaded list.  */
5206       struct elf_link_loaded_list *n;
5207
5208       n = (struct elf_link_loaded_list *) bfd_alloc (abfd, sizeof (*n));
5209       if (n == NULL)
5210         goto error_return;
5211       n->abfd = abfd;
5212       n->next = htab->loaded;
5213       htab->loaded = n;
5214     }
5215
5216   return TRUE;
5217
5218  error_free_vers:
5219   if (old_tab != NULL)
5220     free (old_tab);
5221   if (old_strtab != NULL)
5222     free (old_strtab);
5223   if (nondeflt_vers != NULL)
5224     free (nondeflt_vers);
5225   if (extversym != NULL)
5226     free (extversym);
5227  error_free_sym:
5228   if (isymbuf != NULL)
5229     free (isymbuf);
5230  error_return:
5231   return FALSE;
5232 }
5233
5234 /* Return the linker hash table entry of a symbol that might be
5235    satisfied by an archive symbol.  Return -1 on error.  */
5236
5237 struct elf_link_hash_entry *
5238 _bfd_elf_archive_symbol_lookup (bfd *abfd,
5239                                 struct bfd_link_info *info,
5240                                 const char *name)
5241 {
5242   struct elf_link_hash_entry *h;
5243   char *p, *copy;
5244   size_t len, first;
5245
5246   h = elf_link_hash_lookup (elf_hash_table (info), name, FALSE, FALSE, TRUE);
5247   if (h != NULL)
5248     return h;
5249
5250   /* If this is a default version (the name contains @@), look up the
5251      symbol again with only one `@' as well as without the version.
5252      The effect is that references to the symbol with and without the
5253      version will be matched by the default symbol in the archive.  */
5254
5255   p = strchr (name, ELF_VER_CHR);
5256   if (p == NULL || p[1] != ELF_VER_CHR)
5257     return h;
5258
5259   /* First check with only one `@'.  */
5260   len = strlen (name);
5261   copy = (char *) bfd_alloc (abfd, len);
5262   if (copy == NULL)
5263     return (struct elf_link_hash_entry *) 0 - 1;
5264
5265   first = p - name + 1;
5266   memcpy (copy, name, first);
5267   memcpy (copy + first, name + first + 1, len - first);
5268
5269   h = elf_link_hash_lookup (elf_hash_table (info), copy, FALSE, FALSE, TRUE);
5270   if (h == NULL)
5271     {
5272       /* We also need to check references to the symbol without the
5273          version.  */
5274       copy[first - 1] = '\0';
5275       h = elf_link_hash_lookup (elf_hash_table (info), copy,
5276                                 FALSE, FALSE, TRUE);
5277     }
5278
5279   bfd_release (abfd, copy);
5280   return h;
5281 }
5282
5283 /* Add symbols from an ELF archive file to the linker hash table.  We
5284    don't use _bfd_generic_link_add_archive_symbols because we need to
5285    handle versioned symbols.
5286
5287    Fortunately, ELF archive handling is simpler than that done by
5288    _bfd_generic_link_add_archive_symbols, which has to allow for a.out
5289    oddities.  In ELF, if we find a symbol in the archive map, and the
5290    symbol is currently undefined, we know that we must pull in that
5291    object file.
5292
5293    Unfortunately, we do have to make multiple passes over the symbol
5294    table until nothing further is resolved.  */
5295
5296 static bfd_boolean
5297 elf_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
5298 {
5299   symindex c;
5300   unsigned char *included = NULL;
5301   carsym *symdefs;
5302   bfd_boolean loop;
5303   bfd_size_type amt;
5304   const struct elf_backend_data *bed;
5305   struct elf_link_hash_entry * (*archive_symbol_lookup)
5306     (bfd *, struct bfd_link_info *, const char *);
5307
5308   if (! bfd_has_map (abfd))
5309     {
5310       /* An empty archive is a special case.  */
5311       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
5312         return TRUE;
5313       bfd_set_error (bfd_error_no_armap);
5314       return FALSE;
5315     }
5316
5317   /* Keep track of all symbols we know to be already defined, and all
5318      files we know to be already included.  This is to speed up the
5319      second and subsequent passes.  */
5320   c = bfd_ardata (abfd)->symdef_count;
5321   if (c == 0)
5322     return TRUE;
5323   amt = c;
5324   amt *= sizeof (*included);
5325   included = (unsigned char *) bfd_zmalloc (amt);
5326   if (included == NULL)
5327     return FALSE;
5328
5329   symdefs = bfd_ardata (abfd)->symdefs;
5330   bed = get_elf_backend_data (abfd);
5331   archive_symbol_lookup = bed->elf_backend_archive_symbol_lookup;
5332
5333   do
5334     {
5335       file_ptr last;
5336       symindex i;
5337       carsym *symdef;
5338       carsym *symdefend;
5339
5340       loop = FALSE;
5341       last = -1;
5342
5343       symdef = symdefs;
5344       symdefend = symdef + c;
5345       for (i = 0; symdef < symdefend; symdef++, i++)
5346         {
5347           struct elf_link_hash_entry *h;
5348           bfd *element;
5349           struct bfd_link_hash_entry *undefs_tail;
5350           symindex mark;
5351
5352           if (included[i])
5353             continue;
5354           if (symdef->file_offset == last)
5355             {
5356               included[i] = TRUE;
5357               continue;
5358             }
5359
5360           h = archive_symbol_lookup (abfd, info, symdef->name);
5361           if (h == (struct elf_link_hash_entry *) 0 - 1)
5362             goto error_return;
5363
5364           if (h == NULL)
5365             continue;
5366
5367           if (h->root.type == bfd_link_hash_common)
5368             {
5369               /* We currently have a common symbol.  The archive map contains
5370                  a reference to this symbol, so we may want to include it.  We
5371                  only want to include it however, if this archive element
5372                  contains a definition of the symbol, not just another common
5373                  declaration of it.
5374
5375                  Unfortunately some archivers (including GNU ar) will put
5376                  declarations of common symbols into their archive maps, as
5377                  well as real definitions, so we cannot just go by the archive
5378                  map alone.  Instead we must read in the element's symbol
5379                  table and check that to see what kind of symbol definition
5380                  this is.  */
5381               if (! elf_link_is_defined_archive_symbol (abfd, symdef))
5382                 continue;
5383             }
5384           else if (h->root.type != bfd_link_hash_undefined)
5385             {
5386               if (h->root.type != bfd_link_hash_undefweak)
5387                 /* Symbol must be defined.  Don't check it again.  */
5388                 included[i] = TRUE;
5389               continue;
5390             }
5391
5392           /* We need to include this archive member.  */
5393           element = _bfd_get_elt_at_filepos (abfd, symdef->file_offset);
5394           if (element == NULL)
5395             goto error_return;
5396
5397           if (! bfd_check_format (element, bfd_object))
5398             goto error_return;
5399
5400           undefs_tail = info->hash->undefs_tail;
5401
5402           if (!(*info->callbacks
5403                 ->add_archive_element) (info, element, symdef->name, &element))
5404             continue;
5405           if (!bfd_link_add_symbols (element, info))
5406             goto error_return;
5407
5408           /* If there are any new undefined symbols, we need to make
5409              another pass through the archive in order to see whether
5410              they can be defined.  FIXME: This isn't perfect, because
5411              common symbols wind up on undefs_tail and because an
5412              undefined symbol which is defined later on in this pass
5413              does not require another pass.  This isn't a bug, but it
5414              does make the code less efficient than it could be.  */
5415           if (undefs_tail != info->hash->undefs_tail)
5416             loop = TRUE;
5417
5418           /* Look backward to mark all symbols from this object file
5419              which we have already seen in this pass.  */
5420           mark = i;
5421           do
5422             {
5423               included[mark] = TRUE;
5424               if (mark == 0)
5425                 break;
5426               --mark;
5427             }
5428           while (symdefs[mark].file_offset == symdef->file_offset);
5429
5430           /* We mark subsequent symbols from this object file as we go
5431              on through the loop.  */
5432           last = symdef->file_offset;
5433         }
5434     }
5435   while (loop);
5436
5437   free (included);
5438
5439   return TRUE;
5440
5441  error_return:
5442   if (included != NULL)
5443     free (included);
5444   return FALSE;
5445 }
5446
5447 /* Given an ELF BFD, add symbols to the global hash table as
5448    appropriate.  */
5449
5450 bfd_boolean
5451 bfd_elf_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
5452 {
5453   switch (bfd_get_format (abfd))
5454     {
5455     case bfd_object:
5456       return elf_link_add_object_symbols (abfd, info);
5457     case bfd_archive:
5458       return elf_link_add_archive_symbols (abfd, info);
5459     default:
5460       bfd_set_error (bfd_error_wrong_format);
5461       return FALSE;
5462     }
5463 }
5464 \f
5465 struct hash_codes_info
5466 {
5467   unsigned long *hashcodes;
5468   bfd_boolean error;
5469 };
5470
5471 /* This function will be called though elf_link_hash_traverse to store
5472    all hash value of the exported symbols in an array.  */
5473
5474 static bfd_boolean
5475 elf_collect_hash_codes (struct elf_link_hash_entry *h, void *data)
5476 {
5477   struct hash_codes_info *inf = (struct hash_codes_info *) data;
5478   const char *name;
5479   unsigned long ha;
5480   char *alc = NULL;
5481
5482   /* Ignore indirect symbols.  These are added by the versioning code.  */
5483   if (h->dynindx == -1)
5484     return TRUE;
5485
5486   name = h->root.root.string;
5487   if (h->versioned >= versioned)
5488     {
5489       char *p = strchr (name, ELF_VER_CHR);
5490       if (p != NULL)
5491         {
5492           alc = (char *) bfd_malloc (p - name + 1);
5493           if (alc == NULL)
5494             {
5495               inf->error = TRUE;
5496               return FALSE;
5497             }
5498           memcpy (alc, name, p - name);
5499           alc[p - name] = '\0';
5500           name = alc;
5501         }
5502     }
5503
5504   /* Compute the hash value.  */
5505   ha = bfd_elf_hash (name);
5506
5507   /* Store the found hash value in the array given as the argument.  */
5508   *(inf->hashcodes)++ = ha;
5509
5510   /* And store it in the struct so that we can put it in the hash table
5511      later.  */
5512   h->u.elf_hash_value = ha;
5513
5514   if (alc != NULL)
5515     free (alc);
5516
5517   return TRUE;
5518 }
5519
5520 struct collect_gnu_hash_codes
5521 {
5522   bfd *output_bfd;
5523   const struct elf_backend_data *bed;
5524   unsigned long int nsyms;
5525   unsigned long int maskbits;
5526   unsigned long int *hashcodes;
5527   unsigned long int *hashval;
5528   unsigned long int *indx;
5529   unsigned long int *counts;
5530   bfd_vma *bitmask;
5531   bfd_byte *contents;
5532   long int min_dynindx;
5533   unsigned long int bucketcount;
5534   unsigned long int symindx;
5535   long int local_indx;
5536   long int shift1, shift2;
5537   unsigned long int mask;
5538   bfd_boolean error;
5539 };
5540
5541 /* This function will be called though elf_link_hash_traverse to store
5542    all hash value of the exported symbols in an array.  */
5543
5544 static bfd_boolean
5545 elf_collect_gnu_hash_codes (struct elf_link_hash_entry *h, void *data)
5546 {
5547   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5548   const char *name;
5549   unsigned long ha;
5550   char *alc = NULL;
5551
5552   /* Ignore indirect symbols.  These are added by the versioning code.  */
5553   if (h->dynindx == -1)
5554     return TRUE;
5555
5556   /* Ignore also local symbols and undefined symbols.  */
5557   if (! (*s->bed->elf_hash_symbol) (h))
5558     return TRUE;
5559
5560   name = h->root.root.string;
5561   if (h->versioned >= versioned)
5562     {
5563       char *p = strchr (name, ELF_VER_CHR);
5564       if (p != NULL)
5565         {
5566           alc = (char *) bfd_malloc (p - name + 1);
5567           if (alc == NULL)
5568             {
5569               s->error = TRUE;
5570               return FALSE;
5571             }
5572           memcpy (alc, name, p - name);
5573           alc[p - name] = '\0';
5574           name = alc;
5575         }
5576     }
5577
5578   /* Compute the hash value.  */
5579   ha = bfd_elf_gnu_hash (name);
5580
5581   /* Store the found hash value in the array for compute_bucket_count,
5582      and also for .dynsym reordering purposes.  */
5583   s->hashcodes[s->nsyms] = ha;
5584   s->hashval[h->dynindx] = ha;
5585   ++s->nsyms;
5586   if (s->min_dynindx < 0 || s->min_dynindx > h->dynindx)
5587     s->min_dynindx = h->dynindx;
5588
5589   if (alc != NULL)
5590     free (alc);
5591
5592   return TRUE;
5593 }
5594
5595 /* This function will be called though elf_link_hash_traverse to do
5596    final dynaminc symbol renumbering.  */
5597
5598 static bfd_boolean
5599 elf_renumber_gnu_hash_syms (struct elf_link_hash_entry *h, void *data)
5600 {
5601   struct collect_gnu_hash_codes *s = (struct collect_gnu_hash_codes *) data;
5602   unsigned long int bucket;
5603   unsigned long int val;
5604
5605   /* Ignore indirect symbols.  */
5606   if (h->dynindx == -1)
5607     return TRUE;
5608
5609   /* Ignore also local symbols and undefined symbols.  */
5610   if (! (*s->bed->elf_hash_symbol) (h))
5611     {
5612       if (h->dynindx >= s->min_dynindx)
5613         h->dynindx = s->local_indx++;
5614       return TRUE;
5615     }
5616
5617   bucket = s->hashval[h->dynindx] % s->bucketcount;
5618   val = (s->hashval[h->dynindx] >> s->shift1)
5619         & ((s->maskbits >> s->shift1) - 1);
5620   s->bitmask[val] |= ((bfd_vma) 1) << (s->hashval[h->dynindx] & s->mask);
5621   s->bitmask[val]
5622     |= ((bfd_vma) 1) << ((s->hashval[h->dynindx] >> s->shift2) & s->mask);
5623   val = s->hashval[h->dynindx] & ~(unsigned long int) 1;
5624   if (s->counts[bucket] == 1)
5625     /* Last element terminates the chain.  */
5626     val |= 1;
5627   bfd_put_32 (s->output_bfd, val,
5628               s->contents + (s->indx[bucket] - s->symindx) * 4);
5629   --s->counts[bucket];
5630   h->dynindx = s->indx[bucket]++;
5631   return TRUE;
5632 }
5633
5634 /* Return TRUE if symbol should be hashed in the `.gnu.hash' section.  */
5635
5636 bfd_boolean
5637 _bfd_elf_hash_symbol (struct elf_link_hash_entry *h)
5638 {
5639   return !(h->forced_local
5640            || h->root.type == bfd_link_hash_undefined
5641            || h->root.type == bfd_link_hash_undefweak
5642            || ((h->root.type == bfd_link_hash_defined
5643                 || h->root.type == bfd_link_hash_defweak)
5644                && h->root.u.def.section->output_section == NULL));
5645 }
5646
5647 /* Array used to determine the number of hash table buckets to use
5648    based on the number of symbols there are.  If there are fewer than
5649    3 symbols we use 1 bucket, fewer than 17 symbols we use 3 buckets,
5650    fewer than 37 we use 17 buckets, and so forth.  We never use more
5651    than 32771 buckets.  */
5652
5653 static const size_t elf_buckets[] =
5654 {
5655   1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
5656   16411, 32771, 0
5657 };
5658
5659 /* Compute bucket count for hashing table.  We do not use a static set
5660    of possible tables sizes anymore.  Instead we determine for all
5661    possible reasonable sizes of the table the outcome (i.e., the
5662    number of collisions etc) and choose the best solution.  The
5663    weighting functions are not too simple to allow the table to grow
5664    without bounds.  Instead one of the weighting factors is the size.
5665    Therefore the result is always a good payoff between few collisions
5666    (= short chain lengths) and table size.  */
5667 static size_t
5668 compute_bucket_count (struct bfd_link_info *info ATTRIBUTE_UNUSED,
5669                       unsigned long int *hashcodes ATTRIBUTE_UNUSED,
5670                       unsigned long int nsyms,
5671                       int gnu_hash)
5672 {
5673   size_t best_size = 0;
5674   unsigned long int i;
5675
5676   /* We have a problem here.  The following code to optimize the table
5677      size requires an integer type with more the 32 bits.  If
5678      BFD_HOST_U_64_BIT is set we know about such a type.  */
5679 #ifdef BFD_HOST_U_64_BIT
5680   if (info->optimize)
5681     {
5682       size_t minsize;
5683       size_t maxsize;
5684       BFD_HOST_U_64_BIT best_chlen = ~((BFD_HOST_U_64_BIT) 0);
5685       bfd *dynobj = elf_hash_table (info)->dynobj;
5686       size_t dynsymcount = elf_hash_table (info)->dynsymcount;
5687       const struct elf_backend_data *bed = get_elf_backend_data (dynobj);
5688       unsigned long int *counts;
5689       bfd_size_type amt;
5690       unsigned int no_improvement_count = 0;
5691
5692       /* Possible optimization parameters: if we have NSYMS symbols we say
5693          that the hashing table must at least have NSYMS/4 and at most
5694          2*NSYMS buckets.  */
5695       minsize = nsyms / 4;
5696       if (minsize == 0)
5697         minsize = 1;
5698       best_size = maxsize = nsyms * 2;
5699       if (gnu_hash)
5700         {
5701           if (minsize < 2)
5702             minsize = 2;
5703           if ((best_size & 31) == 0)
5704             ++best_size;
5705         }
5706
5707       /* Create array where we count the collisions in.  We must use bfd_malloc
5708          since the size could be large.  */
5709       amt = maxsize;
5710       amt *= sizeof (unsigned long int);
5711       counts = (unsigned long int *) bfd_malloc (amt);
5712       if (counts == NULL)
5713         return 0;
5714
5715       /* Compute the "optimal" size for the hash table.  The criteria is a
5716          minimal chain length.  The minor criteria is (of course) the size
5717          of the table.  */
5718       for (i = minsize; i < maxsize; ++i)
5719         {
5720           /* Walk through the array of hashcodes and count the collisions.  */
5721           BFD_HOST_U_64_BIT max;
5722           unsigned long int j;
5723           unsigned long int fact;
5724
5725           if (gnu_hash && (i & 31) == 0)
5726             continue;
5727
5728           memset (counts, '\0', i * sizeof (unsigned long int));
5729
5730           /* Determine how often each hash bucket is used.  */
5731           for (j = 0; j < nsyms; ++j)
5732             ++counts[hashcodes[j] % i];
5733
5734           /* For the weight function we need some information about the
5735              pagesize on the target.  This is information need not be 100%
5736              accurate.  Since this information is not available (so far) we
5737              define it here to a reasonable default value.  If it is crucial
5738              to have a better value some day simply define this value.  */
5739 # ifndef BFD_TARGET_PAGESIZE
5740 #  define BFD_TARGET_PAGESIZE   (4096)
5741 # endif
5742
5743           /* We in any case need 2 + DYNSYMCOUNT entries for the size values
5744              and the chains.  */
5745           max = (2 + dynsymcount) * bed->s->sizeof_hash_entry;
5746
5747 # if 1
5748           /* Variant 1: optimize for short chains.  We add the squares
5749              of all the chain lengths (which favors many small chain
5750              over a few long chains).  */
5751           for (j = 0; j < i; ++j)
5752             max += counts[j] * counts[j];
5753
5754           /* This adds penalties for the overall size of the table.  */
5755           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5756           max *= fact * fact;
5757 # else
5758           /* Variant 2: Optimize a lot more for small table.  Here we
5759              also add squares of the size but we also add penalties for
5760              empty slots (the +1 term).  */
5761           for (j = 0; j < i; ++j)
5762             max += (1 + counts[j]) * (1 + counts[j]);
5763
5764           /* The overall size of the table is considered, but not as
5765              strong as in variant 1, where it is squared.  */
5766           fact = i / (BFD_TARGET_PAGESIZE / bed->s->sizeof_hash_entry) + 1;
5767           max *= fact;
5768 # endif
5769
5770           /* Compare with current best results.  */
5771           if (max < best_chlen)
5772             {
5773               best_chlen = max;
5774               best_size = i;
5775               no_improvement_count = 0;
5776             }
5777           /* PR 11843: Avoid futile long searches for the best bucket size
5778              when there are a large number of symbols.  */
5779           else if (++no_improvement_count == 100)
5780             break;
5781         }
5782
5783       free (counts);
5784     }
5785   else
5786 #endif /* defined (BFD_HOST_U_64_BIT) */
5787     {
5788       /* This is the fallback solution if no 64bit type is available or if we
5789          are not supposed to spend much time on optimizations.  We select the
5790          bucket count using a fixed set of numbers.  */
5791       for (i = 0; elf_buckets[i] != 0; i++)
5792         {
5793           best_size = elf_buckets[i];
5794           if (nsyms < elf_buckets[i + 1])
5795             break;
5796         }
5797       if (gnu_hash && best_size < 2)
5798         best_size = 2;
5799     }
5800
5801   return best_size;
5802 }
5803
5804 /* Size any SHT_GROUP section for ld -r.  */
5805
5806 bfd_boolean
5807 _bfd_elf_size_group_sections (struct bfd_link_info *info)
5808 {
5809   bfd *ibfd;
5810
5811   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
5812     if (bfd_get_flavour (ibfd) == bfd_target_elf_flavour
5813         && !_bfd_elf_fixup_group_sections (ibfd, bfd_abs_section_ptr))
5814       return FALSE;
5815   return TRUE;
5816 }
5817
5818 /* Set a default stack segment size.  The value in INFO wins.  If it
5819    is unset, LEGACY_SYMBOL's value is used, and if that symbol is
5820    undefined it is initialized.  */
5821
5822 bfd_boolean
5823 bfd_elf_stack_segment_size (bfd *output_bfd,
5824                             struct bfd_link_info *info,
5825                             const char *legacy_symbol,
5826                             bfd_vma default_size)
5827 {
5828   struct elf_link_hash_entry *h = NULL;
5829
5830   /* Look for legacy symbol.  */
5831   if (legacy_symbol)
5832     h = elf_link_hash_lookup (elf_hash_table (info), legacy_symbol,
5833                               FALSE, FALSE, FALSE);
5834   if (h && (h->root.type == bfd_link_hash_defined
5835             || h->root.type == bfd_link_hash_defweak)
5836       && h->def_regular
5837       && (h->type == STT_NOTYPE || h->type == STT_OBJECT))
5838     {
5839       /* The symbol has no type if specified on the command line.  */
5840       h->type = STT_OBJECT;
5841       if (info->stacksize)
5842         /* xgettext:c-format */
5843         _bfd_error_handler (_("%B: stack size specified and %s set"),
5844                             output_bfd, legacy_symbol);
5845       else if (h->root.u.def.section != bfd_abs_section_ptr)
5846         /* xgettext:c-format */
5847         _bfd_error_handler (_("%B: %s not absolute"),
5848                             output_bfd, legacy_symbol);
5849       else
5850         info->stacksize = h->root.u.def.value;
5851     }
5852
5853   if (!info->stacksize)
5854     /* If the user didn't set a size, or explicitly inhibit the
5855        size, set it now.  */
5856     info->stacksize = default_size;
5857
5858   /* Provide the legacy symbol, if it is referenced.  */
5859   if (h && (h->root.type == bfd_link_hash_undefined
5860             || h->root.type == bfd_link_hash_undefweak))
5861     {
5862       struct bfd_link_hash_entry *bh = NULL;
5863
5864       if (!(_bfd_generic_link_add_one_symbol
5865             (info, output_bfd, legacy_symbol,
5866              BSF_GLOBAL, bfd_abs_section_ptr,
5867              info->stacksize >= 0 ? info->stacksize : 0,
5868              NULL, FALSE, get_elf_backend_data (output_bfd)->collect, &bh)))
5869         return FALSE;
5870
5871       h = (struct elf_link_hash_entry *) bh;
5872       h->def_regular = 1;
5873       h->type = STT_OBJECT;
5874     }
5875
5876   return TRUE;
5877 }
5878
5879 /* Sweep symbols in swept sections.  Called via elf_link_hash_traverse.  */
5880
5881 struct elf_gc_sweep_symbol_info
5882 {
5883   struct bfd_link_info *info;
5884   void (*hide_symbol) (struct bfd_link_info *, struct elf_link_hash_entry *,
5885                        bfd_boolean);
5886 };
5887
5888 static bfd_boolean
5889 elf_gc_sweep_symbol (struct elf_link_hash_entry *h, void *data)
5890 {
5891   if (!h->mark
5892       && (((h->root.type == bfd_link_hash_defined
5893             || h->root.type == bfd_link_hash_defweak)
5894            && !((h->def_regular || ELF_COMMON_DEF_P (h))
5895                 && h->root.u.def.section->gc_mark))
5896           || h->root.type == bfd_link_hash_undefined
5897           || h->root.type == bfd_link_hash_undefweak))
5898     {
5899       struct elf_gc_sweep_symbol_info *inf;
5900
5901       inf = (struct elf_gc_sweep_symbol_info *) data;
5902       (*inf->hide_symbol) (inf->info, h, TRUE);
5903       h->def_regular = 0;
5904       h->ref_regular = 0;
5905       h->ref_regular_nonweak = 0;
5906     }
5907
5908   return TRUE;
5909 }
5910
5911 /* Set up the sizes and contents of the ELF dynamic sections.  This is
5912    called by the ELF linker emulation before_allocation routine.  We
5913    must set the sizes of the sections before the linker sets the
5914    addresses of the various sections.  */
5915
5916 bfd_boolean
5917 bfd_elf_size_dynamic_sections (bfd *output_bfd,
5918                                const char *soname,
5919                                const char *rpath,
5920                                const char *filter_shlib,
5921                                const char *audit,
5922                                const char *depaudit,
5923                                const char * const *auxiliary_filters,
5924                                struct bfd_link_info *info,
5925                                asection **sinterpptr)
5926 {
5927   size_t soname_indx;
5928   bfd *dynobj;
5929   const struct elf_backend_data *bed;
5930
5931   *sinterpptr = NULL;
5932
5933   soname_indx = (size_t) -1;
5934
5935   if (!is_elf_hash_table (info->hash))
5936     return TRUE;
5937
5938   dynobj = elf_hash_table (info)->dynobj;
5939
5940   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
5941     {
5942       struct bfd_elf_version_tree *verdefs;
5943       struct elf_info_failed asvinfo;
5944       struct bfd_elf_version_tree *t;
5945       struct bfd_elf_version_expr *d;
5946       struct elf_info_failed eif;
5947       bfd_boolean all_defined;
5948       asection *s;
5949
5950       eif.info = info;
5951       eif.failed = FALSE;
5952
5953       /* If we are supposed to export all symbols into the dynamic symbol
5954          table (this is not the normal case), then do so.  */
5955       if (info->export_dynamic
5956           || (bfd_link_executable (info) && info->dynamic))
5957         {
5958           elf_link_hash_traverse (elf_hash_table (info),
5959                                   _bfd_elf_export_symbol,
5960                                   &eif);
5961           if (eif.failed)
5962             return FALSE;
5963         }
5964
5965       /* Make all global versions with definition.  */
5966       for (t = info->version_info; t != NULL; t = t->next)
5967         for (d = t->globals.list; d != NULL; d = d->next)
5968           if (!d->symver && d->literal)
5969             {
5970               const char *verstr, *name;
5971               size_t namelen, verlen, newlen;
5972               char *newname, *p, leading_char;
5973               struct elf_link_hash_entry *newh;
5974
5975               leading_char = bfd_get_symbol_leading_char (output_bfd);
5976               name = d->pattern;
5977               namelen = strlen (name) + (leading_char != '\0');
5978               verstr = t->name;
5979               verlen = strlen (verstr);
5980               newlen = namelen + verlen + 3;
5981
5982               newname = (char *) bfd_malloc (newlen);
5983               if (newname == NULL)
5984                 return FALSE;
5985               newname[0] = leading_char;
5986               memcpy (newname + (leading_char != '\0'), name, namelen);
5987
5988               /* Check the hidden versioned definition.  */
5989               p = newname + namelen;
5990               *p++ = ELF_VER_CHR;
5991               memcpy (p, verstr, verlen + 1);
5992               newh = elf_link_hash_lookup (elf_hash_table (info),
5993                                            newname, FALSE, FALSE,
5994                                            FALSE);
5995               if (newh == NULL
5996                   || (newh->root.type != bfd_link_hash_defined
5997                       && newh->root.type != bfd_link_hash_defweak))
5998                 {
5999                   /* Check the default versioned definition.  */
6000                   *p++ = ELF_VER_CHR;
6001                   memcpy (p, verstr, verlen + 1);
6002                   newh = elf_link_hash_lookup (elf_hash_table (info),
6003                                                newname, FALSE, FALSE,
6004                                                FALSE);
6005                 }
6006               free (newname);
6007
6008               /* Mark this version if there is a definition and it is
6009                  not defined in a shared object.  */
6010               if (newh != NULL
6011                   && !newh->def_dynamic
6012                   && (newh->root.type == bfd_link_hash_defined
6013                       || newh->root.type == bfd_link_hash_defweak))
6014                 d->symver = 1;
6015             }
6016
6017       /* Attach all the symbols to their version information.  */
6018       asvinfo.info = info;
6019       asvinfo.failed = FALSE;
6020
6021       elf_link_hash_traverse (elf_hash_table (info),
6022                               _bfd_elf_link_assign_sym_version,
6023                               &asvinfo);
6024       if (asvinfo.failed)
6025         return FALSE;
6026
6027       if (!info->allow_undefined_version)
6028         {
6029           /* Check if all global versions have a definition.  */
6030           all_defined = TRUE;
6031           for (t = info->version_info; t != NULL; t = t->next)
6032             for (d = t->globals.list; d != NULL; d = d->next)
6033               if (d->literal && !d->symver && !d->script)
6034                 {
6035                   _bfd_error_handler
6036                     (_("%s: undefined version: %s"),
6037                      d->pattern, t->name);
6038                   all_defined = FALSE;
6039                 }
6040
6041           if (!all_defined)
6042             {
6043               bfd_set_error (bfd_error_bad_value);
6044               return FALSE;
6045             }
6046         }
6047
6048       /* Set up the version definition section.  */
6049       s = bfd_get_linker_section (dynobj, ".gnu.version_d");
6050       BFD_ASSERT (s != NULL);
6051
6052       /* We may have created additional version definitions if we are
6053          just linking a regular application.  */
6054       verdefs = info->version_info;
6055
6056       /* Skip anonymous version tag.  */
6057       if (verdefs != NULL && verdefs->vernum == 0)
6058         verdefs = verdefs->next;
6059
6060       if (verdefs == NULL && !info->create_default_symver)
6061         s->flags |= SEC_EXCLUDE;
6062       else
6063         {
6064           unsigned int cdefs;
6065           bfd_size_type size;
6066           bfd_byte *p;
6067           Elf_Internal_Verdef def;
6068           Elf_Internal_Verdaux defaux;
6069           struct bfd_link_hash_entry *bh;
6070           struct elf_link_hash_entry *h;
6071           const char *name;
6072
6073           cdefs = 0;
6074           size = 0;
6075
6076           /* Make space for the base version.  */
6077           size += sizeof (Elf_External_Verdef);
6078           size += sizeof (Elf_External_Verdaux);
6079           ++cdefs;
6080
6081           /* Make space for the default version.  */
6082           if (info->create_default_symver)
6083             {
6084               size += sizeof (Elf_External_Verdef);
6085               ++cdefs;
6086             }
6087
6088           for (t = verdefs; t != NULL; t = t->next)
6089             {
6090               struct bfd_elf_version_deps *n;
6091
6092               /* Don't emit base version twice.  */
6093               if (t->vernum == 0)
6094                 continue;
6095
6096               size += sizeof (Elf_External_Verdef);
6097               size += sizeof (Elf_External_Verdaux);
6098               ++cdefs;
6099
6100               for (n = t->deps; n != NULL; n = n->next)
6101                 size += sizeof (Elf_External_Verdaux);
6102             }
6103
6104           s->size = size;
6105           s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6106           if (s->contents == NULL && s->size != 0)
6107             return FALSE;
6108
6109           /* Fill in the version definition section.  */
6110
6111           p = s->contents;
6112
6113           def.vd_version = VER_DEF_CURRENT;
6114           def.vd_flags = VER_FLG_BASE;
6115           def.vd_ndx = 1;
6116           def.vd_cnt = 1;
6117           if (info->create_default_symver)
6118             {
6119               def.vd_aux = 2 * sizeof (Elf_External_Verdef);
6120               def.vd_next = sizeof (Elf_External_Verdef);
6121             }
6122           else
6123             {
6124               def.vd_aux = sizeof (Elf_External_Verdef);
6125               def.vd_next = (sizeof (Elf_External_Verdef)
6126                              + sizeof (Elf_External_Verdaux));
6127             }
6128
6129           if (soname_indx != (size_t) -1)
6130             {
6131               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6132                                       soname_indx);
6133               def.vd_hash = bfd_elf_hash (soname);
6134               defaux.vda_name = soname_indx;
6135               name = soname;
6136             }
6137           else
6138             {
6139               size_t indx;
6140
6141               name = lbasename (output_bfd->filename);
6142               def.vd_hash = bfd_elf_hash (name);
6143               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6144                                           name, FALSE);
6145               if (indx == (size_t) -1)
6146                 return FALSE;
6147               defaux.vda_name = indx;
6148             }
6149           defaux.vda_next = 0;
6150
6151           _bfd_elf_swap_verdef_out (output_bfd, &def,
6152                                     (Elf_External_Verdef *) p);
6153           p += sizeof (Elf_External_Verdef);
6154           if (info->create_default_symver)
6155             {
6156               /* Add a symbol representing this version.  */
6157               bh = NULL;
6158               if (! (_bfd_generic_link_add_one_symbol
6159                      (info, dynobj, name, BSF_GLOBAL, bfd_abs_section_ptr,
6160                       0, NULL, FALSE,
6161                       get_elf_backend_data (dynobj)->collect, &bh)))
6162                 return FALSE;
6163               h = (struct elf_link_hash_entry *) bh;
6164               h->non_elf = 0;
6165               h->def_regular = 1;
6166               h->type = STT_OBJECT;
6167               h->verinfo.vertree = NULL;
6168
6169               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6170                 return FALSE;
6171
6172               /* Create a duplicate of the base version with the same
6173                  aux block, but different flags.  */
6174               def.vd_flags = 0;
6175               def.vd_ndx = 2;
6176               def.vd_aux = sizeof (Elf_External_Verdef);
6177               if (verdefs)
6178                 def.vd_next = (sizeof (Elf_External_Verdef)
6179                                + sizeof (Elf_External_Verdaux));
6180               else
6181                 def.vd_next = 0;
6182               _bfd_elf_swap_verdef_out (output_bfd, &def,
6183                                         (Elf_External_Verdef *) p);
6184               p += sizeof (Elf_External_Verdef);
6185             }
6186           _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6187                                      (Elf_External_Verdaux *) p);
6188           p += sizeof (Elf_External_Verdaux);
6189
6190           for (t = verdefs; t != NULL; t = t->next)
6191             {
6192               unsigned int cdeps;
6193               struct bfd_elf_version_deps *n;
6194
6195               /* Don't emit the base version twice.  */
6196               if (t->vernum == 0)
6197                 continue;
6198
6199               cdeps = 0;
6200               for (n = t->deps; n != NULL; n = n->next)
6201                 ++cdeps;
6202
6203               /* Add a symbol representing this version.  */
6204               bh = NULL;
6205               if (! (_bfd_generic_link_add_one_symbol
6206                      (info, dynobj, t->name, BSF_GLOBAL, bfd_abs_section_ptr,
6207                       0, NULL, FALSE,
6208                       get_elf_backend_data (dynobj)->collect, &bh)))
6209                 return FALSE;
6210               h = (struct elf_link_hash_entry *) bh;
6211               h->non_elf = 0;
6212               h->def_regular = 1;
6213               h->type = STT_OBJECT;
6214               h->verinfo.vertree = t;
6215
6216               if (! bfd_elf_link_record_dynamic_symbol (info, h))
6217                 return FALSE;
6218
6219               def.vd_version = VER_DEF_CURRENT;
6220               def.vd_flags = 0;
6221               if (t->globals.list == NULL
6222                   && t->locals.list == NULL
6223                   && ! t->used)
6224                 def.vd_flags |= VER_FLG_WEAK;
6225               def.vd_ndx = t->vernum + (info->create_default_symver ? 2 : 1);
6226               def.vd_cnt = cdeps + 1;
6227               def.vd_hash = bfd_elf_hash (t->name);
6228               def.vd_aux = sizeof (Elf_External_Verdef);
6229               def.vd_next = 0;
6230
6231               /* If a basever node is next, it *must* be the last node in
6232                  the chain, otherwise Verdef construction breaks.  */
6233               if (t->next != NULL && t->next->vernum == 0)
6234                 BFD_ASSERT (t->next->next == NULL);
6235
6236               if (t->next != NULL && t->next->vernum != 0)
6237                 def.vd_next = (sizeof (Elf_External_Verdef)
6238                                + (cdeps + 1) * sizeof (Elf_External_Verdaux));
6239
6240               _bfd_elf_swap_verdef_out (output_bfd, &def,
6241                                         (Elf_External_Verdef *) p);
6242               p += sizeof (Elf_External_Verdef);
6243
6244               defaux.vda_name = h->dynstr_index;
6245               _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6246                                       h->dynstr_index);
6247               defaux.vda_next = 0;
6248               if (t->deps != NULL)
6249                 defaux.vda_next = sizeof (Elf_External_Verdaux);
6250               t->name_indx = defaux.vda_name;
6251
6252               _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6253                                          (Elf_External_Verdaux *) p);
6254               p += sizeof (Elf_External_Verdaux);
6255
6256               for (n = t->deps; n != NULL; n = n->next)
6257                 {
6258                   if (n->version_needed == NULL)
6259                     {
6260                       /* This can happen if there was an error in the
6261                          version script.  */
6262                       defaux.vda_name = 0;
6263                     }
6264                   else
6265                     {
6266                       defaux.vda_name = n->version_needed->name_indx;
6267                       _bfd_elf_strtab_addref (elf_hash_table (info)->dynstr,
6268                                               defaux.vda_name);
6269                     }
6270                   if (n->next == NULL)
6271                     defaux.vda_next = 0;
6272                   else
6273                     defaux.vda_next = sizeof (Elf_External_Verdaux);
6274
6275                   _bfd_elf_swap_verdaux_out (output_bfd, &defaux,
6276                                              (Elf_External_Verdaux *) p);
6277                   p += sizeof (Elf_External_Verdaux);
6278                 }
6279             }
6280
6281           elf_tdata (output_bfd)->cverdefs = cdefs;
6282         }
6283
6284       /* Work out the size of the version reference section.  */
6285
6286       s = bfd_get_linker_section (dynobj, ".gnu.version_r");
6287       BFD_ASSERT (s != NULL);
6288       {
6289         struct elf_find_verdep_info sinfo;
6290
6291         sinfo.info = info;
6292         sinfo.vers = elf_tdata (output_bfd)->cverdefs;
6293         if (sinfo.vers == 0)
6294           sinfo.vers = 1;
6295         sinfo.failed = FALSE;
6296
6297         elf_link_hash_traverse (elf_hash_table (info),
6298                                 _bfd_elf_link_find_version_dependencies,
6299                                 &sinfo);
6300         if (sinfo.failed)
6301           return FALSE;
6302
6303         if (elf_tdata (output_bfd)->verref == NULL)
6304           s->flags |= SEC_EXCLUDE;
6305         else
6306           {
6307             Elf_Internal_Verneed *vn;
6308             unsigned int size;
6309             unsigned int crefs;
6310             bfd_byte *p;
6311
6312             /* Build the version dependency section.  */
6313             size = 0;
6314             crefs = 0;
6315             for (vn = elf_tdata (output_bfd)->verref;
6316                  vn != NULL;
6317                  vn = vn->vn_nextref)
6318               {
6319                 Elf_Internal_Vernaux *a;
6320
6321                 size += sizeof (Elf_External_Verneed);
6322                 ++crefs;
6323                 for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6324                   size += sizeof (Elf_External_Vernaux);
6325               }
6326
6327             s->size = size;
6328             s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6329             if (s->contents == NULL)
6330               return FALSE;
6331
6332             p = s->contents;
6333             for (vn = elf_tdata (output_bfd)->verref;
6334                  vn != NULL;
6335                  vn = vn->vn_nextref)
6336               {
6337                 unsigned int caux;
6338                 Elf_Internal_Vernaux *a;
6339                 size_t indx;
6340
6341                 caux = 0;
6342                 for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6343                   ++caux;
6344
6345                 vn->vn_version = VER_NEED_CURRENT;
6346                 vn->vn_cnt = caux;
6347                 indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6348                                             elf_dt_name (vn->vn_bfd) != NULL
6349                                             ? elf_dt_name (vn->vn_bfd)
6350                                             : lbasename (vn->vn_bfd->filename),
6351                                             FALSE);
6352                 if (indx == (size_t) -1)
6353                   return FALSE;
6354                 vn->vn_file = indx;
6355                 vn->vn_aux = sizeof (Elf_External_Verneed);
6356                 if (vn->vn_nextref == NULL)
6357                   vn->vn_next = 0;
6358                 else
6359                   vn->vn_next = (sizeof (Elf_External_Verneed)
6360                                 + caux * sizeof (Elf_External_Vernaux));
6361
6362                 _bfd_elf_swap_verneed_out (output_bfd, vn,
6363                                            (Elf_External_Verneed *) p);
6364                 p += sizeof (Elf_External_Verneed);
6365
6366                 for (a = vn->vn_auxptr; a != NULL; a = a->vna_nextptr)
6367                   {
6368                     a->vna_hash = bfd_elf_hash (a->vna_nodename);
6369                     indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6370                                                 a->vna_nodename, FALSE);
6371                     if (indx == (size_t) -1)
6372                       return FALSE;
6373                     a->vna_name = indx;
6374                     if (a->vna_nextptr == NULL)
6375                       a->vna_next = 0;
6376                     else
6377                       a->vna_next = sizeof (Elf_External_Vernaux);
6378
6379                     _bfd_elf_swap_vernaux_out (output_bfd, a,
6380                                                (Elf_External_Vernaux *) p);
6381                     p += sizeof (Elf_External_Vernaux);
6382                   }
6383               }
6384
6385             elf_tdata (output_bfd)->cverrefs = crefs;
6386           }
6387       }
6388     }
6389
6390   bed = get_elf_backend_data (output_bfd);
6391
6392   if (info->gc_sections && bed->can_gc_sections)
6393     {
6394       struct elf_gc_sweep_symbol_info sweep_info;
6395       unsigned long section_sym_count;
6396
6397       /* Remove the symbols that were in the swept sections from the
6398          dynamic symbol table.  GCFIXME: Anyone know how to get them
6399          out of the static symbol table as well?  */
6400       sweep_info.info = info;
6401       sweep_info.hide_symbol = bed->elf_backend_hide_symbol;
6402       elf_link_hash_traverse (elf_hash_table (info), elf_gc_sweep_symbol,
6403                               &sweep_info);
6404
6405       _bfd_elf_link_renumber_dynsyms (output_bfd, info, &section_sym_count);
6406     }
6407
6408   /* Any syms created from now on start with -1 in
6409      got.refcount/offset and plt.refcount/offset.  */
6410   elf_hash_table (info)->init_got_refcount
6411     = elf_hash_table (info)->init_got_offset;
6412   elf_hash_table (info)->init_plt_refcount
6413     = elf_hash_table (info)->init_plt_offset;
6414
6415   if (bfd_link_relocatable (info)
6416       && !_bfd_elf_size_group_sections (info))
6417     return FALSE;
6418
6419   /* The backend may have to create some sections regardless of whether
6420      we're dynamic or not.  */
6421   if (bed->elf_backend_always_size_sections
6422       && ! (*bed->elf_backend_always_size_sections) (output_bfd, info))
6423     return FALSE;
6424
6425   /* Determine any GNU_STACK segment requirements, after the backend
6426      has had a chance to set a default segment size.  */
6427   if (info->execstack)
6428     elf_stack_flags (output_bfd) = PF_R | PF_W | PF_X;
6429   else if (info->noexecstack)
6430     elf_stack_flags (output_bfd) = PF_R | PF_W;
6431   else
6432     {
6433       bfd *inputobj;
6434       asection *notesec = NULL;
6435       int exec = 0;
6436
6437       for (inputobj = info->input_bfds;
6438            inputobj;
6439            inputobj = inputobj->link.next)
6440         {
6441           asection *s;
6442
6443           if (inputobj->flags
6444               & (DYNAMIC | EXEC_P | BFD_PLUGIN | BFD_LINKER_CREATED))
6445             continue;
6446           s = bfd_get_section_by_name (inputobj, ".note.GNU-stack");
6447           if (s)
6448             {
6449               if (s->flags & SEC_CODE)
6450                 exec = PF_X;
6451               notesec = s;
6452             }
6453           else if (bed->default_execstack)
6454             exec = PF_X;
6455         }
6456       if (notesec || info->stacksize > 0)
6457         elf_stack_flags (output_bfd) = PF_R | PF_W | exec;
6458       if (notesec && exec && bfd_link_relocatable (info)
6459           && notesec->output_section != bfd_abs_section_ptr)
6460         notesec->output_section->flags |= SEC_CODE;
6461     }
6462
6463   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6464     {
6465       struct elf_info_failed eif;
6466       struct elf_link_hash_entry *h;
6467       asection *dynstr;
6468       asection *s;
6469
6470       *sinterpptr = bfd_get_linker_section (dynobj, ".interp");
6471       BFD_ASSERT (*sinterpptr != NULL || !bfd_link_executable (info) || info->nointerp);
6472
6473       if (soname != NULL)
6474         {
6475           soname_indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6476                                              soname, TRUE);
6477           if (soname_indx == (size_t) -1
6478               || !_bfd_elf_add_dynamic_entry (info, DT_SONAME, soname_indx))
6479             return FALSE;
6480         }
6481
6482       if (info->symbolic)
6483         {
6484           if (!_bfd_elf_add_dynamic_entry (info, DT_SYMBOLIC, 0))
6485             return FALSE;
6486           info->flags |= DF_SYMBOLIC;
6487         }
6488
6489       if (rpath != NULL)
6490         {
6491           size_t indx;
6492           bfd_vma tag;
6493
6494           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, rpath,
6495                                       TRUE);
6496           if (indx == (size_t) -1)
6497             return FALSE;
6498
6499           tag = info->new_dtags ? DT_RUNPATH : DT_RPATH;
6500           if (!_bfd_elf_add_dynamic_entry (info, tag, indx))
6501             return FALSE;
6502         }
6503
6504       if (filter_shlib != NULL)
6505         {
6506           size_t indx;
6507
6508           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6509                                       filter_shlib, TRUE);
6510           if (indx == (size_t) -1
6511               || !_bfd_elf_add_dynamic_entry (info, DT_FILTER, indx))
6512             return FALSE;
6513         }
6514
6515       if (auxiliary_filters != NULL)
6516         {
6517           const char * const *p;
6518
6519           for (p = auxiliary_filters; *p != NULL; p++)
6520             {
6521               size_t indx;
6522
6523               indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr,
6524                                           *p, TRUE);
6525               if (indx == (size_t) -1
6526                   || !_bfd_elf_add_dynamic_entry (info, DT_AUXILIARY, indx))
6527                 return FALSE;
6528             }
6529         }
6530
6531       if (audit != NULL)
6532         {
6533           size_t indx;
6534
6535           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, audit,
6536                                       TRUE);
6537           if (indx == (size_t) -1
6538               || !_bfd_elf_add_dynamic_entry (info, DT_AUDIT, indx))
6539             return FALSE;
6540         }
6541
6542       if (depaudit != NULL)
6543         {
6544           size_t indx;
6545
6546           indx = _bfd_elf_strtab_add (elf_hash_table (info)->dynstr, depaudit,
6547                                       TRUE);
6548           if (indx == (size_t) -1
6549               || !_bfd_elf_add_dynamic_entry (info, DT_DEPAUDIT, indx))
6550             return FALSE;
6551         }
6552
6553       eif.info = info;
6554       eif.failed = FALSE;
6555
6556       /* Find all symbols which were defined in a dynamic object and make
6557          the backend pick a reasonable value for them.  */
6558       elf_link_hash_traverse (elf_hash_table (info),
6559                               _bfd_elf_adjust_dynamic_symbol,
6560                               &eif);
6561       if (eif.failed)
6562         return FALSE;
6563
6564       /* Add some entries to the .dynamic section.  We fill in some of the
6565          values later, in bfd_elf_final_link, but we must add the entries
6566          now so that we know the final size of the .dynamic section.  */
6567
6568       /* If there are initialization and/or finalization functions to
6569          call then add the corresponding DT_INIT/DT_FINI entries.  */
6570       h = (info->init_function
6571            ? elf_link_hash_lookup (elf_hash_table (info),
6572                                    info->init_function, FALSE,
6573                                    FALSE, FALSE)
6574            : NULL);
6575       if (h != NULL
6576           && (h->ref_regular
6577               || h->def_regular))
6578         {
6579           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT, 0))
6580             return FALSE;
6581         }
6582       h = (info->fini_function
6583            ? elf_link_hash_lookup (elf_hash_table (info),
6584                                    info->fini_function, FALSE,
6585                                    FALSE, FALSE)
6586            : NULL);
6587       if (h != NULL
6588           && (h->ref_regular
6589               || h->def_regular))
6590         {
6591           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI, 0))
6592             return FALSE;
6593         }
6594
6595       s = bfd_get_section_by_name (output_bfd, ".preinit_array");
6596       if (s != NULL && s->linker_has_input)
6597         {
6598           /* DT_PREINIT_ARRAY is not allowed in shared library.  */
6599           if (! bfd_link_executable (info))
6600             {
6601               bfd *sub;
6602               asection *o;
6603
6604               for (sub = info->input_bfds; sub != NULL;
6605                    sub = sub->link.next)
6606                 if (bfd_get_flavour (sub) == bfd_target_elf_flavour)
6607                   for (o = sub->sections; o != NULL; o = o->next)
6608                     if (elf_section_data (o)->this_hdr.sh_type
6609                         == SHT_PREINIT_ARRAY)
6610                       {
6611                         _bfd_error_handler
6612                           (_("%B: .preinit_array section is not allowed in DSO"),
6613                            sub);
6614                         break;
6615                       }
6616
6617               bfd_set_error (bfd_error_nonrepresentable_section);
6618               return FALSE;
6619             }
6620
6621           if (!_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAY, 0)
6622               || !_bfd_elf_add_dynamic_entry (info, DT_PREINIT_ARRAYSZ, 0))
6623             return FALSE;
6624         }
6625       s = bfd_get_section_by_name (output_bfd, ".init_array");
6626       if (s != NULL && s->linker_has_input)
6627         {
6628           if (!_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAY, 0)
6629               || !_bfd_elf_add_dynamic_entry (info, DT_INIT_ARRAYSZ, 0))
6630             return FALSE;
6631         }
6632       s = bfd_get_section_by_name (output_bfd, ".fini_array");
6633       if (s != NULL && s->linker_has_input)
6634         {
6635           if (!_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAY, 0)
6636               || !_bfd_elf_add_dynamic_entry (info, DT_FINI_ARRAYSZ, 0))
6637             return FALSE;
6638         }
6639
6640       dynstr = bfd_get_linker_section (dynobj, ".dynstr");
6641       /* If .dynstr is excluded from the link, we don't want any of
6642          these tags.  Strictly, we should be checking each section
6643          individually;  This quick check covers for the case where
6644          someone does a /DISCARD/ : { *(*) }.  */
6645       if (dynstr != NULL && dynstr->output_section != bfd_abs_section_ptr)
6646         {
6647           bfd_size_type strsize;
6648
6649           strsize = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
6650           if ((info->emit_hash
6651                && !_bfd_elf_add_dynamic_entry (info, DT_HASH, 0))
6652               || (info->emit_gnu_hash
6653                   && !_bfd_elf_add_dynamic_entry (info, DT_GNU_HASH, 0))
6654               || !_bfd_elf_add_dynamic_entry (info, DT_STRTAB, 0)
6655               || !_bfd_elf_add_dynamic_entry (info, DT_SYMTAB, 0)
6656               || !_bfd_elf_add_dynamic_entry (info, DT_STRSZ, strsize)
6657               || !_bfd_elf_add_dynamic_entry (info, DT_SYMENT,
6658                                               bed->s->sizeof_sym))
6659             return FALSE;
6660         }
6661     }
6662
6663   if (! _bfd_elf_maybe_strip_eh_frame_hdr (info))
6664     return FALSE;
6665
6666   /* The backend must work out the sizes of all the other dynamic
6667      sections.  */
6668   if (dynobj != NULL
6669       && bed->elf_backend_size_dynamic_sections != NULL
6670       && ! (*bed->elf_backend_size_dynamic_sections) (output_bfd, info))
6671     return FALSE;
6672
6673   if (dynobj != NULL && elf_hash_table (info)->dynamic_sections_created)
6674     {
6675       unsigned long section_sym_count;
6676
6677       if (elf_tdata (output_bfd)->cverdefs)
6678         {
6679           unsigned int crefs = elf_tdata (output_bfd)->cverdefs;
6680
6681           if (!_bfd_elf_add_dynamic_entry (info, DT_VERDEF, 0)
6682               || !_bfd_elf_add_dynamic_entry (info, DT_VERDEFNUM, crefs))
6683             return FALSE;
6684         }
6685
6686       if ((info->new_dtags && info->flags) || (info->flags & DF_STATIC_TLS))
6687         {
6688           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS, info->flags))
6689             return FALSE;
6690         }
6691       else if (info->flags & DF_BIND_NOW)
6692         {
6693           if (!_bfd_elf_add_dynamic_entry (info, DT_BIND_NOW, 0))
6694             return FALSE;
6695         }
6696
6697       if (info->flags_1)
6698         {
6699           if (bfd_link_executable (info))
6700             info->flags_1 &= ~ (DF_1_INITFIRST
6701                                 | DF_1_NODELETE
6702                                 | DF_1_NOOPEN);
6703           if (!_bfd_elf_add_dynamic_entry (info, DT_FLAGS_1, info->flags_1))
6704             return FALSE;
6705         }
6706
6707       if (elf_tdata (output_bfd)->cverrefs)
6708         {
6709           unsigned int crefs = elf_tdata (output_bfd)->cverrefs;
6710
6711           if (!_bfd_elf_add_dynamic_entry (info, DT_VERNEED, 0)
6712               || !_bfd_elf_add_dynamic_entry (info, DT_VERNEEDNUM, crefs))
6713             return FALSE;
6714         }
6715
6716       if ((elf_tdata (output_bfd)->cverrefs == 0
6717            && elf_tdata (output_bfd)->cverdefs == 0)
6718           || _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6719                                              &section_sym_count) == 0)
6720         {
6721           asection *s;
6722
6723           s = bfd_get_linker_section (dynobj, ".gnu.version");
6724           s->flags |= SEC_EXCLUDE;
6725         }
6726     }
6727   return TRUE;
6728 }
6729
6730 /* Find the first non-excluded output section.  We'll use its
6731    section symbol for some emitted relocs.  */
6732 void
6733 _bfd_elf_init_1_index_section (bfd *output_bfd, struct bfd_link_info *info)
6734 {
6735   asection *s;
6736
6737   for (s = output_bfd->sections; s != NULL; s = s->next)
6738     if ((s->flags & (SEC_EXCLUDE | SEC_ALLOC)) == SEC_ALLOC
6739         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6740       {
6741         elf_hash_table (info)->text_index_section = s;
6742         break;
6743       }
6744 }
6745
6746 /* Find two non-excluded output sections, one for code, one for data.
6747    We'll use their section symbols for some emitted relocs.  */
6748 void
6749 _bfd_elf_init_2_index_sections (bfd *output_bfd, struct bfd_link_info *info)
6750 {
6751   asection *s;
6752
6753   /* Data first, since setting text_index_section changes
6754      _bfd_elf_link_omit_section_dynsym.  */
6755   for (s = output_bfd->sections; s != NULL; s = s->next)
6756     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY)) == SEC_ALLOC)
6757         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6758       {
6759         elf_hash_table (info)->data_index_section = s;
6760         break;
6761       }
6762
6763   for (s = output_bfd->sections; s != NULL; s = s->next)
6764     if (((s->flags & (SEC_EXCLUDE | SEC_ALLOC | SEC_READONLY))
6765          == (SEC_ALLOC | SEC_READONLY))
6766         && !_bfd_elf_link_omit_section_dynsym (output_bfd, info, s))
6767       {
6768         elf_hash_table (info)->text_index_section = s;
6769         break;
6770       }
6771
6772   if (elf_hash_table (info)->text_index_section == NULL)
6773     elf_hash_table (info)->text_index_section
6774       = elf_hash_table (info)->data_index_section;
6775 }
6776
6777 bfd_boolean
6778 bfd_elf_size_dynsym_hash_dynstr (bfd *output_bfd, struct bfd_link_info *info)
6779 {
6780   const struct elf_backend_data *bed;
6781
6782   if (!is_elf_hash_table (info->hash))
6783     return TRUE;
6784
6785   bed = get_elf_backend_data (output_bfd);
6786   (*bed->elf_backend_init_index_section) (output_bfd, info);
6787
6788   if (elf_hash_table (info)->dynamic_sections_created)
6789     {
6790       bfd *dynobj;
6791       asection *s;
6792       bfd_size_type dynsymcount;
6793       unsigned long section_sym_count;
6794       unsigned int dtagcount;
6795
6796       dynobj = elf_hash_table (info)->dynobj;
6797
6798       /* Assign dynsym indicies.  In a shared library we generate a
6799          section symbol for each output section, which come first.
6800          Next come all of the back-end allocated local dynamic syms,
6801          followed by the rest of the global symbols.  */
6802
6803       dynsymcount = _bfd_elf_link_renumber_dynsyms (output_bfd, info,
6804                                                     &section_sym_count);
6805
6806       /* Work out the size of the symbol version section.  */
6807       s = bfd_get_linker_section (dynobj, ".gnu.version");
6808       BFD_ASSERT (s != NULL);
6809       if ((s->flags & SEC_EXCLUDE) == 0)
6810         {
6811           s->size = dynsymcount * sizeof (Elf_External_Versym);
6812           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6813           if (s->contents == NULL)
6814             return FALSE;
6815
6816           if (!_bfd_elf_add_dynamic_entry (info, DT_VERSYM, 0))
6817             return FALSE;
6818         }
6819
6820       /* Set the size of the .dynsym and .hash sections.  We counted
6821          the number of dynamic symbols in elf_link_add_object_symbols.
6822          We will build the contents of .dynsym and .hash when we build
6823          the final symbol table, because until then we do not know the
6824          correct value to give the symbols.  We built the .dynstr
6825          section as we went along in elf_link_add_object_symbols.  */
6826       s = elf_hash_table (info)->dynsym;
6827       BFD_ASSERT (s != NULL);
6828       s->size = dynsymcount * bed->s->sizeof_sym;
6829
6830       s->contents = (unsigned char *) bfd_alloc (output_bfd, s->size);
6831       if (s->contents == NULL)
6832         return FALSE;
6833
6834       /* The first entry in .dynsym is a dummy symbol.  Clear all the
6835          section syms, in case we don't output them all.  */
6836       ++section_sym_count;
6837       memset (s->contents, 0, section_sym_count * bed->s->sizeof_sym);
6838
6839       elf_hash_table (info)->bucketcount = 0;
6840
6841       /* Compute the size of the hashing table.  As a side effect this
6842          computes the hash values for all the names we export.  */
6843       if (info->emit_hash)
6844         {
6845           unsigned long int *hashcodes;
6846           struct hash_codes_info hashinf;
6847           bfd_size_type amt;
6848           unsigned long int nsyms;
6849           size_t bucketcount;
6850           size_t hash_entry_size;
6851
6852           /* Compute the hash values for all exported symbols.  At the same
6853              time store the values in an array so that we could use them for
6854              optimizations.  */
6855           amt = dynsymcount * sizeof (unsigned long int);
6856           hashcodes = (unsigned long int *) bfd_malloc (amt);
6857           if (hashcodes == NULL)
6858             return FALSE;
6859           hashinf.hashcodes = hashcodes;
6860           hashinf.error = FALSE;
6861
6862           /* Put all hash values in HASHCODES.  */
6863           elf_link_hash_traverse (elf_hash_table (info),
6864                                   elf_collect_hash_codes, &hashinf);
6865           if (hashinf.error)
6866             {
6867               free (hashcodes);
6868               return FALSE;
6869             }
6870
6871           nsyms = hashinf.hashcodes - hashcodes;
6872           bucketcount
6873             = compute_bucket_count (info, hashcodes, nsyms, 0);
6874           free (hashcodes);
6875
6876           if (bucketcount == 0)
6877             return FALSE;
6878
6879           elf_hash_table (info)->bucketcount = bucketcount;
6880
6881           s = bfd_get_linker_section (dynobj, ".hash");
6882           BFD_ASSERT (s != NULL);
6883           hash_entry_size = elf_section_data (s)->this_hdr.sh_entsize;
6884           s->size = ((2 + bucketcount + dynsymcount) * hash_entry_size);
6885           s->contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6886           if (s->contents == NULL)
6887             return FALSE;
6888
6889           bfd_put (8 * hash_entry_size, output_bfd, bucketcount, s->contents);
6890           bfd_put (8 * hash_entry_size, output_bfd, dynsymcount,
6891                    s->contents + hash_entry_size);
6892         }
6893
6894       if (info->emit_gnu_hash)
6895         {
6896           size_t i, cnt;
6897           unsigned char *contents;
6898           struct collect_gnu_hash_codes cinfo;
6899           bfd_size_type amt;
6900           size_t bucketcount;
6901
6902           memset (&cinfo, 0, sizeof (cinfo));
6903
6904           /* Compute the hash values for all exported symbols.  At the same
6905              time store the values in an array so that we could use them for
6906              optimizations.  */
6907           amt = dynsymcount * 2 * sizeof (unsigned long int);
6908           cinfo.hashcodes = (long unsigned int *) bfd_malloc (amt);
6909           if (cinfo.hashcodes == NULL)
6910             return FALSE;
6911
6912           cinfo.hashval = cinfo.hashcodes + dynsymcount;
6913           cinfo.min_dynindx = -1;
6914           cinfo.output_bfd = output_bfd;
6915           cinfo.bed = bed;
6916
6917           /* Put all hash values in HASHCODES.  */
6918           elf_link_hash_traverse (elf_hash_table (info),
6919                                   elf_collect_gnu_hash_codes, &cinfo);
6920           if (cinfo.error)
6921             {
6922               free (cinfo.hashcodes);
6923               return FALSE;
6924             }
6925
6926           bucketcount
6927             = compute_bucket_count (info, cinfo.hashcodes, cinfo.nsyms, 1);
6928
6929           if (bucketcount == 0)
6930             {
6931               free (cinfo.hashcodes);
6932               return FALSE;
6933             }
6934
6935           s = bfd_get_linker_section (dynobj, ".gnu.hash");
6936           BFD_ASSERT (s != NULL);
6937
6938           if (cinfo.nsyms == 0)
6939             {
6940               /* Empty .gnu.hash section is special.  */
6941               BFD_ASSERT (cinfo.min_dynindx == -1);
6942               free (cinfo.hashcodes);
6943               s->size = 5 * 4 + bed->s->arch_size / 8;
6944               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
6945               if (contents == NULL)
6946                 return FALSE;
6947               s->contents = contents;
6948               /* 1 empty bucket.  */
6949               bfd_put_32 (output_bfd, 1, contents);
6950               /* SYMIDX above the special symbol 0.  */
6951               bfd_put_32 (output_bfd, 1, contents + 4);
6952               /* Just one word for bitmask.  */
6953               bfd_put_32 (output_bfd, 1, contents + 8);
6954               /* Only hash fn bloom filter.  */
6955               bfd_put_32 (output_bfd, 0, contents + 12);
6956               /* No hashes are valid - empty bitmask.  */
6957               bfd_put (bed->s->arch_size, output_bfd, 0, contents + 16);
6958               /* No hashes in the only bucket.  */
6959               bfd_put_32 (output_bfd, 0,
6960                           contents + 16 + bed->s->arch_size / 8);
6961             }
6962           else
6963             {
6964               unsigned long int maskwords, maskbitslog2, x;
6965               BFD_ASSERT (cinfo.min_dynindx != -1);
6966
6967               x = cinfo.nsyms;
6968               maskbitslog2 = 1;
6969               while ((x >>= 1) != 0)
6970                 ++maskbitslog2;
6971               if (maskbitslog2 < 3)
6972                 maskbitslog2 = 5;
6973               else if ((1 << (maskbitslog2 - 2)) & cinfo.nsyms)
6974                 maskbitslog2 = maskbitslog2 + 3;
6975               else
6976                 maskbitslog2 = maskbitslog2 + 2;
6977               if (bed->s->arch_size == 64)
6978                 {
6979                   if (maskbitslog2 == 5)
6980                     maskbitslog2 = 6;
6981                   cinfo.shift1 = 6;
6982                 }
6983               else
6984                 cinfo.shift1 = 5;
6985               cinfo.mask = (1 << cinfo.shift1) - 1;
6986               cinfo.shift2 = maskbitslog2;
6987               cinfo.maskbits = 1 << maskbitslog2;
6988               maskwords = 1 << (maskbitslog2 - cinfo.shift1);
6989               amt = bucketcount * sizeof (unsigned long int) * 2;
6990               amt += maskwords * sizeof (bfd_vma);
6991               cinfo.bitmask = (bfd_vma *) bfd_malloc (amt);
6992               if (cinfo.bitmask == NULL)
6993                 {
6994                   free (cinfo.hashcodes);
6995                   return FALSE;
6996                 }
6997
6998               cinfo.counts = (long unsigned int *) (cinfo.bitmask + maskwords);
6999               cinfo.indx = cinfo.counts + bucketcount;
7000               cinfo.symindx = dynsymcount - cinfo.nsyms;
7001               memset (cinfo.bitmask, 0, maskwords * sizeof (bfd_vma));
7002
7003               /* Determine how often each hash bucket is used.  */
7004               memset (cinfo.counts, 0, bucketcount * sizeof (cinfo.counts[0]));
7005               for (i = 0; i < cinfo.nsyms; ++i)
7006                 ++cinfo.counts[cinfo.hashcodes[i] % bucketcount];
7007
7008               for (i = 0, cnt = cinfo.symindx; i < bucketcount; ++i)
7009                 if (cinfo.counts[i] != 0)
7010                   {
7011                     cinfo.indx[i] = cnt;
7012                     cnt += cinfo.counts[i];
7013                   }
7014               BFD_ASSERT (cnt == dynsymcount);
7015               cinfo.bucketcount = bucketcount;
7016               cinfo.local_indx = cinfo.min_dynindx;
7017
7018               s->size = (4 + bucketcount + cinfo.nsyms) * 4;
7019               s->size += cinfo.maskbits / 8;
7020               contents = (unsigned char *) bfd_zalloc (output_bfd, s->size);
7021               if (contents == NULL)
7022                 {
7023                   free (cinfo.bitmask);
7024                   free (cinfo.hashcodes);
7025                   return FALSE;
7026                 }
7027
7028               s->contents = contents;
7029               bfd_put_32 (output_bfd, bucketcount, contents);
7030               bfd_put_32 (output_bfd, cinfo.symindx, contents + 4);
7031               bfd_put_32 (output_bfd, maskwords, contents + 8);
7032               bfd_put_32 (output_bfd, cinfo.shift2, contents + 12);
7033               contents += 16 + cinfo.maskbits / 8;
7034
7035               for (i = 0; i < bucketcount; ++i)
7036                 {
7037                   if (cinfo.counts[i] == 0)
7038                     bfd_put_32 (output_bfd, 0, contents);
7039                   else
7040                     bfd_put_32 (output_bfd, cinfo.indx[i], contents);
7041                   contents += 4;
7042                 }
7043
7044               cinfo.contents = contents;
7045
7046               /* Renumber dynamic symbols, populate .gnu.hash section.  */
7047               elf_link_hash_traverse (elf_hash_table (info),
7048                                       elf_renumber_gnu_hash_syms, &cinfo);
7049
7050               contents = s->contents + 16;
7051               for (i = 0; i < maskwords; ++i)
7052                 {
7053                   bfd_put (bed->s->arch_size, output_bfd, cinfo.bitmask[i],
7054                            contents);
7055                   contents += bed->s->arch_size / 8;
7056                 }
7057
7058               free (cinfo.bitmask);
7059               free (cinfo.hashcodes);
7060             }
7061         }
7062
7063       s = bfd_get_linker_section (dynobj, ".dynstr");
7064       BFD_ASSERT (s != NULL);
7065
7066       elf_finalize_dynstr (output_bfd, info);
7067
7068       s->size = _bfd_elf_strtab_size (elf_hash_table (info)->dynstr);
7069
7070       for (dtagcount = 0; dtagcount <= info->spare_dynamic_tags; ++dtagcount)
7071         if (!_bfd_elf_add_dynamic_entry (info, DT_NULL, 0))
7072           return FALSE;
7073     }
7074
7075   return TRUE;
7076 }
7077 \f
7078 /* Make sure sec_info_type is cleared if sec_info is cleared too.  */
7079
7080 static void
7081 merge_sections_remove_hook (bfd *abfd ATTRIBUTE_UNUSED,
7082                             asection *sec)
7083 {
7084   BFD_ASSERT (sec->sec_info_type == SEC_INFO_TYPE_MERGE);
7085   sec->sec_info_type = SEC_INFO_TYPE_NONE;
7086 }
7087
7088 /* Finish SHF_MERGE section merging.  */
7089
7090 bfd_boolean
7091 _bfd_elf_merge_sections (bfd *obfd, struct bfd_link_info *info)
7092 {
7093   bfd *ibfd;
7094   asection *sec;
7095
7096   if (!is_elf_hash_table (info->hash))
7097     return FALSE;
7098
7099   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
7100     if ((ibfd->flags & DYNAMIC) == 0
7101         && bfd_get_flavour (ibfd) == bfd_target_elf_flavour
7102         && (elf_elfheader (ibfd)->e_ident[EI_CLASS]
7103             == get_elf_backend_data (obfd)->s->elfclass))
7104       for (sec = ibfd->sections; sec != NULL; sec = sec->next)
7105         if ((sec->flags & SEC_MERGE) != 0
7106             && !bfd_is_abs_section (sec->output_section))
7107           {
7108             struct bfd_elf_section_data *secdata;
7109
7110             secdata = elf_section_data (sec);
7111             if (! _bfd_add_merge_section (obfd,
7112                                           &elf_hash_table (info)->merge_info,
7113                                           sec, &secdata->sec_info))
7114               return FALSE;
7115             else if (secdata->sec_info)
7116               sec->sec_info_type = SEC_INFO_TYPE_MERGE;
7117           }
7118
7119   if (elf_hash_table (info)->merge_info != NULL)
7120     _bfd_merge_sections (obfd, info, elf_hash_table (info)->merge_info,
7121                          merge_sections_remove_hook);
7122   return TRUE;
7123 }
7124
7125 /* Create an entry in an ELF linker hash table.  */
7126
7127 struct bfd_hash_entry *
7128 _bfd_elf_link_hash_newfunc (struct bfd_hash_entry *entry,
7129                             struct bfd_hash_table *table,
7130                             const char *string)
7131 {
7132   /* Allocate the structure if it has not already been allocated by a
7133      subclass.  */
7134   if (entry == NULL)
7135     {
7136       entry = (struct bfd_hash_entry *)
7137         bfd_hash_allocate (table, sizeof (struct elf_link_hash_entry));
7138       if (entry == NULL)
7139         return entry;
7140     }
7141
7142   /* Call the allocation method of the superclass.  */
7143   entry = _bfd_link_hash_newfunc (entry, table, string);
7144   if (entry != NULL)
7145     {
7146       struct elf_link_hash_entry *ret = (struct elf_link_hash_entry *) entry;
7147       struct elf_link_hash_table *htab = (struct elf_link_hash_table *) table;
7148
7149       /* Set local fields.  */
7150       ret->indx = -1;
7151       ret->dynindx = -1;
7152       ret->got = htab->init_got_refcount;
7153       ret->plt = htab->init_plt_refcount;
7154       memset (&ret->size, 0, (sizeof (struct elf_link_hash_entry)
7155                               - offsetof (struct elf_link_hash_entry, size)));
7156       /* Assume that we have been called by a non-ELF symbol reader.
7157          This flag is then reset by the code which reads an ELF input
7158          file.  This ensures that a symbol created by a non-ELF symbol
7159          reader will have the flag set correctly.  */
7160       ret->non_elf = 1;
7161     }
7162
7163   return entry;
7164 }
7165
7166 /* Copy data from an indirect symbol to its direct symbol, hiding the
7167    old indirect symbol.  Also used for copying flags to a weakdef.  */
7168
7169 void
7170 _bfd_elf_link_hash_copy_indirect (struct bfd_link_info *info,
7171                                   struct elf_link_hash_entry *dir,
7172                                   struct elf_link_hash_entry *ind)
7173 {
7174   struct elf_link_hash_table *htab;
7175
7176   /* Copy down any references that we may have already seen to the
7177      symbol which just became indirect.  */
7178
7179   if (dir->versioned != versioned_hidden)
7180     dir->ref_dynamic |= ind->ref_dynamic;
7181   dir->ref_regular |= ind->ref_regular;
7182   dir->ref_regular_nonweak |= ind->ref_regular_nonweak;
7183   dir->non_got_ref |= ind->non_got_ref;
7184   dir->needs_plt |= ind->needs_plt;
7185   dir->pointer_equality_needed |= ind->pointer_equality_needed;
7186
7187   if (ind->root.type != bfd_link_hash_indirect)
7188     return;
7189
7190   /* Copy over the global and procedure linkage table refcount entries.
7191      These may have been already set up by a check_relocs routine.  */
7192   htab = elf_hash_table (info);
7193   if (ind->got.refcount > htab->init_got_refcount.refcount)
7194     {
7195       if (dir->got.refcount < 0)
7196         dir->got.refcount = 0;
7197       dir->got.refcount += ind->got.refcount;
7198       ind->got.refcount = htab->init_got_refcount.refcount;
7199     }
7200
7201   if (ind->plt.refcount > htab->init_plt_refcount.refcount)
7202     {
7203       if (dir->plt.refcount < 0)
7204         dir->plt.refcount = 0;
7205       dir->plt.refcount += ind->plt.refcount;
7206       ind->plt.refcount = htab->init_plt_refcount.refcount;
7207     }
7208
7209   if (ind->dynindx != -1)
7210     {
7211       if (dir->dynindx != -1)
7212         _bfd_elf_strtab_delref (htab->dynstr, dir->dynstr_index);
7213       dir->dynindx = ind->dynindx;
7214       dir->dynstr_index = ind->dynstr_index;
7215       ind->dynindx = -1;
7216       ind->dynstr_index = 0;
7217     }
7218 }
7219
7220 void
7221 _bfd_elf_link_hash_hide_symbol (struct bfd_link_info *info,
7222                                 struct elf_link_hash_entry *h,
7223                                 bfd_boolean force_local)
7224 {
7225   /* STT_GNU_IFUNC symbol must go through PLT.  */
7226   if (h->type != STT_GNU_IFUNC)
7227     {
7228       h->plt = elf_hash_table (info)->init_plt_offset;
7229       h->needs_plt = 0;
7230     }
7231   if (force_local)
7232     {
7233       h->forced_local = 1;
7234       if (h->dynindx != -1)
7235         {
7236           h->dynindx = -1;
7237           _bfd_elf_strtab_delref (elf_hash_table (info)->dynstr,
7238                                   h->dynstr_index);
7239         }
7240     }
7241 }
7242
7243 /* Initialize an ELF linker hash table.  *TABLE has been zeroed by our
7244    caller.  */
7245
7246 bfd_boolean
7247 _bfd_elf_link_hash_table_init
7248   (struct elf_link_hash_table *table,
7249    bfd *abfd,
7250    struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
7251                                       struct bfd_hash_table *,
7252                                       const char *),
7253    unsigned int entsize,
7254    enum elf_target_id target_id)
7255 {
7256   bfd_boolean ret;
7257   int can_refcount = get_elf_backend_data (abfd)->can_refcount;
7258
7259   table->init_got_refcount.refcount = can_refcount - 1;
7260   table->init_plt_refcount.refcount = can_refcount - 1;
7261   table->init_got_offset.offset = -(bfd_vma) 1;
7262   table->init_plt_offset.offset = -(bfd_vma) 1;
7263   /* The first dynamic symbol is a dummy.  */
7264   table->dynsymcount = 1;
7265
7266   ret = _bfd_link_hash_table_init (&table->root, abfd, newfunc, entsize);
7267
7268   table->root.type = bfd_link_elf_hash_table;
7269   table->hash_table_id = target_id;
7270
7271   return ret;
7272 }
7273
7274 /* Create an ELF linker hash table.  */
7275
7276 struct bfd_link_hash_table *
7277 _bfd_elf_link_hash_table_create (bfd *abfd)
7278 {
7279   struct elf_link_hash_table *ret;
7280   bfd_size_type amt = sizeof (struct elf_link_hash_table);
7281
7282   ret = (struct elf_link_hash_table *) bfd_zmalloc (amt);
7283   if (ret == NULL)
7284     return NULL;
7285
7286   if (! _bfd_elf_link_hash_table_init (ret, abfd, _bfd_elf_link_hash_newfunc,
7287                                        sizeof (struct elf_link_hash_entry),
7288                                        GENERIC_ELF_DATA))
7289     {
7290       free (ret);
7291       return NULL;
7292     }
7293   ret->root.hash_table_free = _bfd_elf_link_hash_table_free;
7294
7295   return &ret->root;
7296 }
7297
7298 /* Destroy an ELF linker hash table.  */
7299
7300 void
7301 _bfd_elf_link_hash_table_free (bfd *obfd)
7302 {
7303   struct elf_link_hash_table *htab;
7304
7305   htab = (struct elf_link_hash_table *) obfd->link.hash;
7306   if (htab->dynstr != NULL)
7307     _bfd_elf_strtab_free (htab->dynstr);
7308   _bfd_merge_sections_free (htab->merge_info);
7309   _bfd_generic_link_hash_table_free (obfd);
7310 }
7311
7312 /* This is a hook for the ELF emulation code in the generic linker to
7313    tell the backend linker what file name to use for the DT_NEEDED
7314    entry for a dynamic object.  */
7315
7316 void
7317 bfd_elf_set_dt_needed_name (bfd *abfd, const char *name)
7318 {
7319   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7320       && bfd_get_format (abfd) == bfd_object)
7321     elf_dt_name (abfd) = name;
7322 }
7323
7324 int
7325 bfd_elf_get_dyn_lib_class (bfd *abfd)
7326 {
7327   int lib_class;
7328   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7329       && bfd_get_format (abfd) == bfd_object)
7330     lib_class = elf_dyn_lib_class (abfd);
7331   else
7332     lib_class = 0;
7333   return lib_class;
7334 }
7335
7336 void
7337 bfd_elf_set_dyn_lib_class (bfd *abfd, enum dynamic_lib_link_class lib_class)
7338 {
7339   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7340       && bfd_get_format (abfd) == bfd_object)
7341     elf_dyn_lib_class (abfd) = lib_class;
7342 }
7343
7344 /* Get the list of DT_NEEDED entries for a link.  This is a hook for
7345    the linker ELF emulation code.  */
7346
7347 struct bfd_link_needed_list *
7348 bfd_elf_get_needed_list (bfd *abfd ATTRIBUTE_UNUSED,
7349                          struct bfd_link_info *info)
7350 {
7351   if (! is_elf_hash_table (info->hash))
7352     return NULL;
7353   return elf_hash_table (info)->needed;
7354 }
7355
7356 /* Get the list of DT_RPATH/DT_RUNPATH entries for a link.  This is a
7357    hook for the linker ELF emulation code.  */
7358
7359 struct bfd_link_needed_list *
7360 bfd_elf_get_runpath_list (bfd *abfd ATTRIBUTE_UNUSED,
7361                           struct bfd_link_info *info)
7362 {
7363   if (! is_elf_hash_table (info->hash))
7364     return NULL;
7365   return elf_hash_table (info)->runpath;
7366 }
7367
7368 /* Get the name actually used for a dynamic object for a link.  This
7369    is the SONAME entry if there is one.  Otherwise, it is the string
7370    passed to bfd_elf_set_dt_needed_name, or it is the filename.  */
7371
7372 const char *
7373 bfd_elf_get_dt_soname (bfd *abfd)
7374 {
7375   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour
7376       && bfd_get_format (abfd) == bfd_object)
7377     return elf_dt_name (abfd);
7378   return NULL;
7379 }
7380
7381 /* Get the list of DT_NEEDED entries from a BFD.  This is a hook for
7382    the ELF linker emulation code.  */
7383
7384 bfd_boolean
7385 bfd_elf_get_bfd_needed_list (bfd *abfd,
7386                              struct bfd_link_needed_list **pneeded)
7387 {
7388   asection *s;
7389   bfd_byte *dynbuf = NULL;
7390   unsigned int elfsec;
7391   unsigned long shlink;
7392   bfd_byte *extdyn, *extdynend;
7393   size_t extdynsize;
7394   void (*swap_dyn_in) (bfd *, const void *, Elf_Internal_Dyn *);
7395
7396   *pneeded = NULL;
7397
7398   if (bfd_get_flavour (abfd) != bfd_target_elf_flavour
7399       || bfd_get_format (abfd) != bfd_object)
7400     return TRUE;
7401
7402   s = bfd_get_section_by_name (abfd, ".dynamic");
7403   if (s == NULL || s->size == 0)
7404     return TRUE;
7405
7406   if (!bfd_malloc_and_get_section (abfd, s, &dynbuf))
7407     goto error_return;
7408
7409   elfsec = _bfd_elf_section_from_bfd_section (abfd, s);
7410   if (elfsec == SHN_BAD)
7411     goto error_return;
7412
7413   shlink = elf_elfsections (abfd)[elfsec]->sh_link;
7414
7415   extdynsize = get_elf_backend_data (abfd)->s->sizeof_dyn;
7416   swap_dyn_in = get_elf_backend_data (abfd)->s->swap_dyn_in;
7417
7418   extdyn = dynbuf;
7419   extdynend = extdyn + s->size;
7420   for (; extdyn < extdynend; extdyn += extdynsize)
7421     {
7422       Elf_Internal_Dyn dyn;
7423
7424       (*swap_dyn_in) (abfd, extdyn, &dyn);
7425
7426       if (dyn.d_tag == DT_NULL)
7427         break;
7428
7429       if (dyn.d_tag == DT_NEEDED)
7430         {
7431           const char *string;
7432           struct bfd_link_needed_list *l;
7433           unsigned int tagv = dyn.d_un.d_val;
7434           bfd_size_type amt;
7435
7436           string = bfd_elf_string_from_elf_section (abfd, shlink, tagv);
7437           if (string == NULL)
7438             goto error_return;
7439
7440           amt = sizeof *l;
7441           l = (struct bfd_link_needed_list *) bfd_alloc (abfd, amt);
7442           if (l == NULL)
7443             goto error_return;
7444
7445           l->by = abfd;
7446           l->name = string;
7447           l->next = *pneeded;
7448           *pneeded = l;
7449         }
7450     }
7451
7452   free (dynbuf);
7453
7454   return TRUE;
7455
7456  error_return:
7457   if (dynbuf != NULL)
7458     free (dynbuf);
7459   return FALSE;
7460 }
7461
7462 struct elf_symbuf_symbol
7463 {
7464   unsigned long st_name;        /* Symbol name, index in string tbl */
7465   unsigned char st_info;        /* Type and binding attributes */
7466   unsigned char st_other;       /* Visibilty, and target specific */
7467 };
7468
7469 struct elf_symbuf_head
7470 {
7471   struct elf_symbuf_symbol *ssym;
7472   size_t count;
7473   unsigned int st_shndx;
7474 };
7475
7476 struct elf_symbol
7477 {
7478   union
7479     {
7480       Elf_Internal_Sym *isym;
7481       struct elf_symbuf_symbol *ssym;
7482     } u;
7483   const char *name;
7484 };
7485
7486 /* Sort references to symbols by ascending section number.  */
7487
7488 static int
7489 elf_sort_elf_symbol (const void *arg1, const void *arg2)
7490 {
7491   const Elf_Internal_Sym *s1 = *(const Elf_Internal_Sym **) arg1;
7492   const Elf_Internal_Sym *s2 = *(const Elf_Internal_Sym **) arg2;
7493
7494   return s1->st_shndx - s2->st_shndx;
7495 }
7496
7497 static int
7498 elf_sym_name_compare (const void *arg1, const void *arg2)
7499 {
7500   const struct elf_symbol *s1 = (const struct elf_symbol *) arg1;
7501   const struct elf_symbol *s2 = (const struct elf_symbol *) arg2;
7502   return strcmp (s1->name, s2->name);
7503 }
7504
7505 static struct elf_symbuf_head *
7506 elf_create_symbuf (size_t symcount, Elf_Internal_Sym *isymbuf)
7507 {
7508   Elf_Internal_Sym **ind, **indbufend, **indbuf;
7509   struct elf_symbuf_symbol *ssym;
7510   struct elf_symbuf_head *ssymbuf, *ssymhead;
7511   size_t i, shndx_count, total_size;
7512
7513   indbuf = (Elf_Internal_Sym **) bfd_malloc2 (symcount, sizeof (*indbuf));
7514   if (indbuf == NULL)
7515     return NULL;
7516
7517   for (ind = indbuf, i = 0; i < symcount; i++)
7518     if (isymbuf[i].st_shndx != SHN_UNDEF)
7519       *ind++ = &isymbuf[i];
7520   indbufend = ind;
7521
7522   qsort (indbuf, indbufend - indbuf, sizeof (Elf_Internal_Sym *),
7523          elf_sort_elf_symbol);
7524
7525   shndx_count = 0;
7526   if (indbufend > indbuf)
7527     for (ind = indbuf, shndx_count++; ind < indbufend - 1; ind++)
7528       if (ind[0]->st_shndx != ind[1]->st_shndx)
7529         shndx_count++;
7530
7531   total_size = ((shndx_count + 1) * sizeof (*ssymbuf)
7532                 + (indbufend - indbuf) * sizeof (*ssym));
7533   ssymbuf = (struct elf_symbuf_head *) bfd_malloc (total_size);
7534   if (ssymbuf == NULL)
7535     {
7536       free (indbuf);
7537       return NULL;
7538     }
7539
7540   ssym = (struct elf_symbuf_symbol *) (ssymbuf + shndx_count + 1);
7541   ssymbuf->ssym = NULL;
7542   ssymbuf->count = shndx_count;
7543   ssymbuf->st_shndx = 0;
7544   for (ssymhead = ssymbuf, ind = indbuf; ind < indbufend; ssym++, ind++)
7545     {
7546       if (ind == indbuf || ssymhead->st_shndx != (*ind)->st_shndx)
7547         {
7548           ssymhead++;
7549           ssymhead->ssym = ssym;
7550           ssymhead->count = 0;
7551           ssymhead->st_shndx = (*ind)->st_shndx;
7552         }
7553       ssym->st_name = (*ind)->st_name;
7554       ssym->st_info = (*ind)->st_info;
7555       ssym->st_other = (*ind)->st_other;
7556       ssymhead->count++;
7557     }
7558   BFD_ASSERT ((size_t) (ssymhead - ssymbuf) == shndx_count
7559               && (((bfd_hostptr_t) ssym - (bfd_hostptr_t) ssymbuf)
7560                   == total_size));
7561
7562   free (indbuf);
7563   return ssymbuf;
7564 }
7565
7566 /* Check if 2 sections define the same set of local and global
7567    symbols.  */
7568
7569 static bfd_boolean
7570 bfd_elf_match_symbols_in_sections (asection *sec1, asection *sec2,
7571                                    struct bfd_link_info *info)
7572 {
7573   bfd *bfd1, *bfd2;
7574   const struct elf_backend_data *bed1, *bed2;
7575   Elf_Internal_Shdr *hdr1, *hdr2;
7576   size_t symcount1, symcount2;
7577   Elf_Internal_Sym *isymbuf1, *isymbuf2;
7578   struct elf_symbuf_head *ssymbuf1, *ssymbuf2;
7579   Elf_Internal_Sym *isym, *isymend;
7580   struct elf_symbol *symtable1 = NULL, *symtable2 = NULL;
7581   size_t count1, count2, i;
7582   unsigned int shndx1, shndx2;
7583   bfd_boolean result;
7584
7585   bfd1 = sec1->owner;
7586   bfd2 = sec2->owner;
7587
7588   /* Both sections have to be in ELF.  */
7589   if (bfd_get_flavour (bfd1) != bfd_target_elf_flavour
7590       || bfd_get_flavour (bfd2) != bfd_target_elf_flavour)
7591     return FALSE;
7592
7593   if (elf_section_type (sec1) != elf_section_type (sec2))
7594     return FALSE;
7595
7596   shndx1 = _bfd_elf_section_from_bfd_section (bfd1, sec1);
7597   shndx2 = _bfd_elf_section_from_bfd_section (bfd2, sec2);
7598   if (shndx1 == SHN_BAD || shndx2 == SHN_BAD)
7599     return FALSE;
7600
7601   bed1 = get_elf_backend_data (bfd1);
7602   bed2 = get_elf_backend_data (bfd2);
7603   hdr1 = &elf_tdata (bfd1)->symtab_hdr;
7604   symcount1 = hdr1->sh_size / bed1->s->sizeof_sym;
7605   hdr2 = &elf_tdata (bfd2)->symtab_hdr;
7606   symcount2 = hdr2->sh_size / bed2->s->sizeof_sym;
7607
7608   if (symcount1 == 0 || symcount2 == 0)
7609     return FALSE;
7610
7611   result = FALSE;
7612   isymbuf1 = NULL;
7613   isymbuf2 = NULL;
7614   ssymbuf1 = (struct elf_symbuf_head *) elf_tdata (bfd1)->symbuf;
7615   ssymbuf2 = (struct elf_symbuf_head *) elf_tdata (bfd2)->symbuf;
7616
7617   if (ssymbuf1 == NULL)
7618     {
7619       isymbuf1 = bfd_elf_get_elf_syms (bfd1, hdr1, symcount1, 0,
7620                                        NULL, NULL, NULL);
7621       if (isymbuf1 == NULL)
7622         goto done;
7623
7624       if (!info->reduce_memory_overheads)
7625         elf_tdata (bfd1)->symbuf = ssymbuf1
7626           = elf_create_symbuf (symcount1, isymbuf1);
7627     }
7628
7629   if (ssymbuf1 == NULL || ssymbuf2 == NULL)
7630     {
7631       isymbuf2 = bfd_elf_get_elf_syms (bfd2, hdr2, symcount2, 0,
7632                                        NULL, NULL, NULL);
7633       if (isymbuf2 == NULL)
7634         goto done;
7635
7636       if (ssymbuf1 != NULL && !info->reduce_memory_overheads)
7637         elf_tdata (bfd2)->symbuf = ssymbuf2
7638           = elf_create_symbuf (symcount2, isymbuf2);
7639     }
7640
7641   if (ssymbuf1 != NULL && ssymbuf2 != NULL)
7642     {
7643       /* Optimized faster version.  */
7644       size_t lo, hi, mid;
7645       struct elf_symbol *symp;
7646       struct elf_symbuf_symbol *ssym, *ssymend;
7647
7648       lo = 0;
7649       hi = ssymbuf1->count;
7650       ssymbuf1++;
7651       count1 = 0;
7652       while (lo < hi)
7653         {
7654           mid = (lo + hi) / 2;
7655           if (shndx1 < ssymbuf1[mid].st_shndx)
7656             hi = mid;
7657           else if (shndx1 > ssymbuf1[mid].st_shndx)
7658             lo = mid + 1;
7659           else
7660             {
7661               count1 = ssymbuf1[mid].count;
7662               ssymbuf1 += mid;
7663               break;
7664             }
7665         }
7666
7667       lo = 0;
7668       hi = ssymbuf2->count;
7669       ssymbuf2++;
7670       count2 = 0;
7671       while (lo < hi)
7672         {
7673           mid = (lo + hi) / 2;
7674           if (shndx2 < ssymbuf2[mid].st_shndx)
7675             hi = mid;
7676           else if (shndx2 > ssymbuf2[mid].st_shndx)
7677             lo = mid + 1;
7678           else
7679             {
7680               count2 = ssymbuf2[mid].count;
7681               ssymbuf2 += mid;
7682               break;
7683             }
7684         }
7685
7686       if (count1 == 0 || count2 == 0 || count1 != count2)
7687         goto done;
7688
7689       symtable1
7690         = (struct elf_symbol *) bfd_malloc (count1 * sizeof (*symtable1));
7691       symtable2
7692         = (struct elf_symbol *) bfd_malloc (count2 * sizeof (*symtable2));
7693       if (symtable1 == NULL || symtable2 == NULL)
7694         goto done;
7695
7696       symp = symtable1;
7697       for (ssym = ssymbuf1->ssym, ssymend = ssym + count1;
7698            ssym < ssymend; ssym++, symp++)
7699         {
7700           symp->u.ssym = ssym;
7701           symp->name = bfd_elf_string_from_elf_section (bfd1,
7702                                                         hdr1->sh_link,
7703                                                         ssym->st_name);
7704         }
7705
7706       symp = symtable2;
7707       for (ssym = ssymbuf2->ssym, ssymend = ssym + count2;
7708            ssym < ssymend; ssym++, symp++)
7709         {
7710           symp->u.ssym = ssym;
7711           symp->name = bfd_elf_string_from_elf_section (bfd2,
7712                                                         hdr2->sh_link,
7713                                                         ssym->st_name);
7714         }
7715
7716       /* Sort symbol by name.  */
7717       qsort (symtable1, count1, sizeof (struct elf_symbol),
7718              elf_sym_name_compare);
7719       qsort (symtable2, count1, sizeof (struct elf_symbol),
7720              elf_sym_name_compare);
7721
7722       for (i = 0; i < count1; i++)
7723         /* Two symbols must have the same binding, type and name.  */
7724         if (symtable1 [i].u.ssym->st_info != symtable2 [i].u.ssym->st_info
7725             || symtable1 [i].u.ssym->st_other != symtable2 [i].u.ssym->st_other
7726             || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7727           goto done;
7728
7729       result = TRUE;
7730       goto done;
7731     }
7732
7733   symtable1 = (struct elf_symbol *)
7734       bfd_malloc (symcount1 * sizeof (struct elf_symbol));
7735   symtable2 = (struct elf_symbol *)
7736       bfd_malloc (symcount2 * sizeof (struct elf_symbol));
7737   if (symtable1 == NULL || symtable2 == NULL)
7738     goto done;
7739
7740   /* Count definitions in the section.  */
7741   count1 = 0;
7742   for (isym = isymbuf1, isymend = isym + symcount1; isym < isymend; isym++)
7743     if (isym->st_shndx == shndx1)
7744       symtable1[count1++].u.isym = isym;
7745
7746   count2 = 0;
7747   for (isym = isymbuf2, isymend = isym + symcount2; isym < isymend; isym++)
7748     if (isym->st_shndx == shndx2)
7749       symtable2[count2++].u.isym = isym;
7750
7751   if (count1 == 0 || count2 == 0 || count1 != count2)
7752     goto done;
7753
7754   for (i = 0; i < count1; i++)
7755     symtable1[i].name
7756       = bfd_elf_string_from_elf_section (bfd1, hdr1->sh_link,
7757                                          symtable1[i].u.isym->st_name);
7758
7759   for (i = 0; i < count2; i++)
7760     symtable2[i].name
7761       = bfd_elf_string_from_elf_section (bfd2, hdr2->sh_link,
7762                                          symtable2[i].u.isym->st_name);
7763
7764   /* Sort symbol by name.  */
7765   qsort (symtable1, count1, sizeof (struct elf_symbol),
7766          elf_sym_name_compare);
7767   qsort (symtable2, count1, sizeof (struct elf_symbol),
7768          elf_sym_name_compare);
7769
7770   for (i = 0; i < count1; i++)
7771     /* Two symbols must have the same binding, type and name.  */
7772     if (symtable1 [i].u.isym->st_info != symtable2 [i].u.isym->st_info
7773         || symtable1 [i].u.isym->st_other != symtable2 [i].u.isym->st_other
7774         || strcmp (symtable1 [i].name, symtable2 [i].name) != 0)
7775       goto done;
7776
7777   result = TRUE;
7778
7779 done:
7780   if (symtable1)
7781     free (symtable1);
7782   if (symtable2)
7783     free (symtable2);
7784   if (isymbuf1)
7785     free (isymbuf1);
7786   if (isymbuf2)
7787     free (isymbuf2);
7788
7789   return result;
7790 }
7791
7792 /* Return TRUE if 2 section types are compatible.  */
7793
7794 bfd_boolean
7795 _bfd_elf_match_sections_by_type (bfd *abfd, const asection *asec,
7796                                  bfd *bbfd, const asection *bsec)
7797 {
7798   if (asec == NULL
7799       || bsec == NULL
7800       || abfd->xvec->flavour != bfd_target_elf_flavour
7801       || bbfd->xvec->flavour != bfd_target_elf_flavour)
7802     return TRUE;
7803
7804   return elf_section_type (asec) == elf_section_type (bsec);
7805 }
7806 \f
7807 /* Final phase of ELF linker.  */
7808
7809 /* A structure we use to avoid passing large numbers of arguments.  */
7810
7811 struct elf_final_link_info
7812 {
7813   /* General link information.  */
7814   struct bfd_link_info *info;
7815   /* Output BFD.  */
7816   bfd *output_bfd;
7817   /* Symbol string table.  */
7818   struct elf_strtab_hash *symstrtab;
7819   /* .hash section.  */
7820   asection *hash_sec;
7821   /* symbol version section (.gnu.version).  */
7822   asection *symver_sec;
7823   /* Buffer large enough to hold contents of any section.  */
7824   bfd_byte *contents;
7825   /* Buffer large enough to hold external relocs of any section.  */
7826   void *external_relocs;
7827   /* Buffer large enough to hold internal relocs of any section.  */
7828   Elf_Internal_Rela *internal_relocs;
7829   /* Buffer large enough to hold external local symbols of any input
7830      BFD.  */
7831   bfd_byte *external_syms;
7832   /* And a buffer for symbol section indices.  */
7833   Elf_External_Sym_Shndx *locsym_shndx;
7834   /* Buffer large enough to hold internal local symbols of any input
7835      BFD.  */
7836   Elf_Internal_Sym *internal_syms;
7837   /* Array large enough to hold a symbol index for each local symbol
7838      of any input BFD.  */
7839   long *indices;
7840   /* Array large enough to hold a section pointer for each local
7841      symbol of any input BFD.  */
7842   asection **sections;
7843   /* Buffer for SHT_SYMTAB_SHNDX section.  */
7844   Elf_External_Sym_Shndx *symshndxbuf;
7845   /* Number of STT_FILE syms seen.  */
7846   size_t filesym_count;
7847 };
7848
7849 /* This struct is used to pass information to elf_link_output_extsym.  */
7850
7851 struct elf_outext_info
7852 {
7853   bfd_boolean failed;
7854   bfd_boolean localsyms;
7855   bfd_boolean file_sym_done;
7856   struct elf_final_link_info *flinfo;
7857 };
7858
7859
7860 /* Support for evaluating a complex relocation.
7861
7862    Complex relocations are generalized, self-describing relocations.  The
7863    implementation of them consists of two parts: complex symbols, and the
7864    relocations themselves.
7865
7866    The relocations are use a reserved elf-wide relocation type code (R_RELC
7867    external / BFD_RELOC_RELC internal) and an encoding of relocation field
7868    information (start bit, end bit, word width, etc) into the addend.  This
7869    information is extracted from CGEN-generated operand tables within gas.
7870
7871    Complex symbols are mangled symbols (BSF_RELC external / STT_RELC
7872    internal) representing prefix-notation expressions, including but not
7873    limited to those sorts of expressions normally encoded as addends in the
7874    addend field.  The symbol mangling format is:
7875
7876    <node> := <literal>
7877           |  <unary-operator> ':' <node>
7878           |  <binary-operator> ':' <node> ':' <node>
7879           ;
7880
7881    <literal> := 's' <digits=N> ':' <N character symbol name>
7882              |  'S' <digits=N> ':' <N character section name>
7883              |  '#' <hexdigits>
7884              ;
7885
7886    <binary-operator> := as in C
7887    <unary-operator> := as in C, plus "0-" for unambiguous negation.  */
7888
7889 static void
7890 set_symbol_value (bfd *bfd_with_globals,
7891                   Elf_Internal_Sym *isymbuf,
7892                   size_t locsymcount,
7893                   size_t symidx,
7894                   bfd_vma val)
7895 {
7896   struct elf_link_hash_entry **sym_hashes;
7897   struct elf_link_hash_entry *h;
7898   size_t extsymoff = locsymcount;
7899
7900   if (symidx < locsymcount)
7901     {
7902       Elf_Internal_Sym *sym;
7903
7904       sym = isymbuf + symidx;
7905       if (ELF_ST_BIND (sym->st_info) == STB_LOCAL)
7906         {
7907           /* It is a local symbol: move it to the
7908              "absolute" section and give it a value.  */
7909           sym->st_shndx = SHN_ABS;
7910           sym->st_value = val;
7911           return;
7912         }
7913       BFD_ASSERT (elf_bad_symtab (bfd_with_globals));
7914       extsymoff = 0;
7915     }
7916
7917   /* It is a global symbol: set its link type
7918      to "defined" and give it a value.  */
7919
7920   sym_hashes = elf_sym_hashes (bfd_with_globals);
7921   h = sym_hashes [symidx - extsymoff];
7922   while (h->root.type == bfd_link_hash_indirect
7923          || h->root.type == bfd_link_hash_warning)
7924     h = (struct elf_link_hash_entry *) h->root.u.i.link;
7925   h->root.type = bfd_link_hash_defined;
7926   h->root.u.def.value = val;
7927   h->root.u.def.section = bfd_abs_section_ptr;
7928 }
7929
7930 static bfd_boolean
7931 resolve_symbol (const char *name,
7932                 bfd *input_bfd,
7933                 struct elf_final_link_info *flinfo,
7934                 bfd_vma *result,
7935                 Elf_Internal_Sym *isymbuf,
7936                 size_t locsymcount)
7937 {
7938   Elf_Internal_Sym *sym;
7939   struct bfd_link_hash_entry *global_entry;
7940   const char *candidate = NULL;
7941   Elf_Internal_Shdr *symtab_hdr;
7942   size_t i;
7943
7944   symtab_hdr = & elf_tdata (input_bfd)->symtab_hdr;
7945
7946   for (i = 0; i < locsymcount; ++ i)
7947     {
7948       sym = isymbuf + i;
7949
7950       if (ELF_ST_BIND (sym->st_info) != STB_LOCAL)
7951         continue;
7952
7953       candidate = bfd_elf_string_from_elf_section (input_bfd,
7954                                                    symtab_hdr->sh_link,
7955                                                    sym->st_name);
7956 #ifdef DEBUG
7957       printf ("Comparing string: '%s' vs. '%s' = 0x%lx\n",
7958               name, candidate, (unsigned long) sym->st_value);
7959 #endif
7960       if (candidate && strcmp (candidate, name) == 0)
7961         {
7962           asection *sec = flinfo->sections [i];
7963
7964           *result = _bfd_elf_rel_local_sym (input_bfd, sym, &sec, 0);
7965           *result += sec->output_offset + sec->output_section->vma;
7966 #ifdef DEBUG
7967           printf ("Found symbol with value %8.8lx\n",
7968                   (unsigned long) *result);
7969 #endif
7970           return TRUE;
7971         }
7972     }
7973
7974   /* Hmm, haven't found it yet. perhaps it is a global.  */
7975   global_entry = bfd_link_hash_lookup (flinfo->info->hash, name,
7976                                        FALSE, FALSE, TRUE);
7977   if (!global_entry)
7978     return FALSE;
7979
7980   if (global_entry->type == bfd_link_hash_defined
7981       || global_entry->type == bfd_link_hash_defweak)
7982     {
7983       *result = (global_entry->u.def.value
7984                  + global_entry->u.def.section->output_section->vma
7985                  + global_entry->u.def.section->output_offset);
7986 #ifdef DEBUG
7987       printf ("Found GLOBAL symbol '%s' with value %8.8lx\n",
7988               global_entry->root.string, (unsigned long) *result);
7989 #endif
7990       return TRUE;
7991     }
7992
7993   return FALSE;
7994 }
7995
7996 /* Looks up NAME in SECTIONS.  If found sets RESULT to NAME's address (in
7997    bytes) and returns TRUE, otherwise returns FALSE.  Accepts pseudo-section
7998    names like "foo.end" which is the end address of section "foo".  */
7999    
8000 static bfd_boolean
8001 resolve_section (const char *name,
8002                  asection *sections,
8003                  bfd_vma *result,
8004                  bfd * abfd)
8005 {
8006   asection *curr;
8007   unsigned int len;
8008
8009   for (curr = sections; curr; curr = curr->next)
8010     if (strcmp (curr->name, name) == 0)
8011       {
8012         *result = curr->vma;
8013         return TRUE;
8014       }
8015
8016   /* Hmm. still haven't found it. try pseudo-section names.  */
8017   /* FIXME: This could be coded more efficiently...  */
8018   for (curr = sections; curr; curr = curr->next)
8019     {
8020       len = strlen (curr->name);
8021       if (len > strlen (name))
8022         continue;
8023
8024       if (strncmp (curr->name, name, len) == 0)
8025         {
8026           if (strncmp (".end", name + len, 4) == 0)
8027             {
8028               *result = curr->vma + curr->size / bfd_octets_per_byte (abfd);
8029               return TRUE;
8030             }
8031
8032           /* Insert more pseudo-section names here, if you like.  */
8033         }
8034     }
8035
8036   return FALSE;
8037 }
8038
8039 static void
8040 undefined_reference (const char *reftype, const char *name)
8041 {
8042   /* xgettext:c-format */
8043   _bfd_error_handler (_("undefined %s reference in complex symbol: %s"),
8044                       reftype, name);
8045 }
8046
8047 static bfd_boolean
8048 eval_symbol (bfd_vma *result,
8049              const char **symp,
8050              bfd *input_bfd,
8051              struct elf_final_link_info *flinfo,
8052              bfd_vma dot,
8053              Elf_Internal_Sym *isymbuf,
8054              size_t locsymcount,
8055              int signed_p)
8056 {
8057   size_t len;
8058   size_t symlen;
8059   bfd_vma a;
8060   bfd_vma b;
8061   char symbuf[4096];
8062   const char *sym = *symp;
8063   const char *symend;
8064   bfd_boolean symbol_is_section = FALSE;
8065
8066   len = strlen (sym);
8067   symend = sym + len;
8068
8069   if (len < 1 || len > sizeof (symbuf))
8070     {
8071       bfd_set_error (bfd_error_invalid_operation);
8072       return FALSE;
8073     }
8074
8075   switch (* sym)
8076     {
8077     case '.':
8078       *result = dot;
8079       *symp = sym + 1;
8080       return TRUE;
8081
8082     case '#':
8083       ++sym;
8084       *result = strtoul (sym, (char **) symp, 16);
8085       return TRUE;
8086
8087     case 'S':
8088       symbol_is_section = TRUE;
8089       /* Fall through.  */
8090     case 's':
8091       ++sym;
8092       symlen = strtol (sym, (char **) symp, 10);
8093       sym = *symp + 1; /* Skip the trailing ':'.  */
8094
8095       if (symend < sym || symlen + 1 > sizeof (symbuf))
8096         {
8097           bfd_set_error (bfd_error_invalid_operation);
8098           return FALSE;
8099         }
8100
8101       memcpy (symbuf, sym, symlen);
8102       symbuf[symlen] = '\0';
8103       *symp = sym + symlen;
8104
8105       /* Is it always possible, with complex symbols, that gas "mis-guessed"
8106          the symbol as a section, or vice-versa. so we're pretty liberal in our
8107          interpretation here; section means "try section first", not "must be a
8108          section", and likewise with symbol.  */
8109
8110       if (symbol_is_section)
8111         {
8112           if (!resolve_section (symbuf, flinfo->output_bfd->sections, result, input_bfd)
8113               && !resolve_symbol (symbuf, input_bfd, flinfo, result,
8114                                   isymbuf, locsymcount))
8115             {
8116               undefined_reference ("section", symbuf);
8117               return FALSE;
8118             }
8119         }
8120       else
8121         {
8122           if (!resolve_symbol (symbuf, input_bfd, flinfo, result,
8123                                isymbuf, locsymcount)
8124               && !resolve_section (symbuf, flinfo->output_bfd->sections,
8125                                    result, input_bfd))
8126             {
8127               undefined_reference ("symbol", symbuf);
8128               return FALSE;
8129             }
8130         }
8131
8132       return TRUE;
8133
8134       /* All that remains are operators.  */
8135
8136 #define UNARY_OP(op)                                            \
8137   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8138     {                                                           \
8139       sym += strlen (#op);                                      \
8140       if (*sym == ':')                                          \
8141         ++sym;                                                  \
8142       *symp = sym;                                              \
8143       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8144                         isymbuf, locsymcount, signed_p))        \
8145         return FALSE;                                           \
8146       if (signed_p)                                             \
8147         *result = op ((bfd_signed_vma) a);                      \
8148       else                                                      \
8149         *result = op a;                                         \
8150       return TRUE;                                              \
8151     }
8152
8153 #define BINARY_OP(op)                                           \
8154   if (strncmp (sym, #op, strlen (#op)) == 0)                    \
8155     {                                                           \
8156       sym += strlen (#op);                                      \
8157       if (*sym == ':')                                          \
8158         ++sym;                                                  \
8159       *symp = sym;                                              \
8160       if (!eval_symbol (&a, symp, input_bfd, flinfo, dot,       \
8161                         isymbuf, locsymcount, signed_p))        \
8162         return FALSE;                                           \
8163       ++*symp;                                                  \
8164       if (!eval_symbol (&b, symp, input_bfd, flinfo, dot,       \
8165                         isymbuf, locsymcount, signed_p))        \
8166         return FALSE;                                           \
8167       if (signed_p)                                             \
8168         *result = ((bfd_signed_vma) a) op ((bfd_signed_vma) b); \
8169       else                                                      \
8170         *result = a op b;                                       \
8171       return TRUE;                                              \
8172     }
8173
8174     default:
8175       UNARY_OP  (0-);
8176       BINARY_OP (<<);
8177       BINARY_OP (>>);
8178       BINARY_OP (==);
8179       BINARY_OP (!=);
8180       BINARY_OP (<=);
8181       BINARY_OP (>=);
8182       BINARY_OP (&&);
8183       BINARY_OP (||);
8184       UNARY_OP  (~);
8185       UNARY_OP  (!);
8186       BINARY_OP (*);
8187       BINARY_OP (/);
8188       BINARY_OP (%);
8189       BINARY_OP (^);
8190       BINARY_OP (|);
8191       BINARY_OP (&);
8192       BINARY_OP (+);
8193       BINARY_OP (-);
8194       BINARY_OP (<);
8195       BINARY_OP (>);
8196 #undef UNARY_OP
8197 #undef BINARY_OP
8198       _bfd_error_handler (_("unknown operator '%c' in complex symbol"), * sym);
8199       bfd_set_error (bfd_error_invalid_operation);
8200       return FALSE;
8201     }
8202 }
8203
8204 static void
8205 put_value (bfd_vma size,
8206            unsigned long chunksz,
8207            bfd *input_bfd,
8208            bfd_vma x,
8209            bfd_byte *location)
8210 {
8211   location += (size - chunksz);
8212
8213   for (; size; size -= chunksz, location -= chunksz)
8214     {
8215       switch (chunksz)
8216         {
8217         case 1:
8218           bfd_put_8 (input_bfd, x, location);
8219           x >>= 8;
8220           break;
8221         case 2:
8222           bfd_put_16 (input_bfd, x, location);
8223           x >>= 16;
8224           break;
8225         case 4:
8226           bfd_put_32 (input_bfd, x, location);
8227           /* Computed this way because x >>= 32 is undefined if x is a 32-bit value.  */
8228           x >>= 16;
8229           x >>= 16;
8230           break;
8231 #ifdef BFD64
8232         case 8:
8233           bfd_put_64 (input_bfd, x, location);
8234           /* Computed this way because x >>= 64 is undefined if x is a 64-bit value.  */
8235           x >>= 32;
8236           x >>= 32;
8237           break;
8238 #endif
8239         default:
8240           abort ();
8241           break;
8242         }
8243     }
8244 }
8245
8246 static bfd_vma
8247 get_value (bfd_vma size,
8248            unsigned long chunksz,
8249            bfd *input_bfd,
8250            bfd_byte *location)
8251 {
8252   int shift;
8253   bfd_vma x = 0;
8254
8255   /* Sanity checks.  */
8256   BFD_ASSERT (chunksz <= sizeof (x)
8257               && size >= chunksz
8258               && chunksz != 0
8259               && (size % chunksz) == 0
8260               && input_bfd != NULL
8261               && location != NULL);
8262
8263   if (chunksz == sizeof (x))
8264     {
8265       BFD_ASSERT (size == chunksz);
8266
8267       /* Make sure that we do not perform an undefined shift operation.
8268          We know that size == chunksz so there will only be one iteration
8269          of the loop below.  */
8270       shift = 0;
8271     }
8272   else
8273     shift = 8 * chunksz;
8274
8275   for (; size; size -= chunksz, location += chunksz)
8276     {
8277       switch (chunksz)
8278         {
8279         case 1:
8280           x = (x << shift) | bfd_get_8 (input_bfd, location);
8281           break;
8282         case 2:
8283           x = (x << shift) | bfd_get_16 (input_bfd, location);
8284           break;
8285         case 4:
8286           x = (x << shift) | bfd_get_32 (input_bfd, location);
8287           break;
8288 #ifdef BFD64
8289         case 8:
8290           x = (x << shift) | bfd_get_64 (input_bfd, location);
8291           break;
8292 #endif
8293         default:
8294           abort ();
8295         }
8296     }
8297   return x;
8298 }
8299
8300 static void
8301 decode_complex_addend (unsigned long *start,   /* in bits */
8302                        unsigned long *oplen,   /* in bits */
8303                        unsigned long *len,     /* in bits */
8304                        unsigned long *wordsz,  /* in bytes */
8305                        unsigned long *chunksz, /* in bytes */
8306                        unsigned long *lsb0_p,
8307                        unsigned long *signed_p,
8308                        unsigned long *trunc_p,
8309                        unsigned long encoded)
8310 {
8311   * start     =  encoded        & 0x3F;
8312   * len       = (encoded >>  6) & 0x3F;
8313   * oplen     = (encoded >> 12) & 0x3F;
8314   * wordsz    = (encoded >> 18) & 0xF;
8315   * chunksz   = (encoded >> 22) & 0xF;
8316   * lsb0_p    = (encoded >> 27) & 1;
8317   * signed_p  = (encoded >> 28) & 1;
8318   * trunc_p   = (encoded >> 29) & 1;
8319 }
8320
8321 bfd_reloc_status_type
8322 bfd_elf_perform_complex_relocation (bfd *input_bfd,
8323                                     asection *input_section ATTRIBUTE_UNUSED,
8324                                     bfd_byte *contents,
8325                                     Elf_Internal_Rela *rel,
8326                                     bfd_vma relocation)
8327 {
8328   bfd_vma shift, x, mask;
8329   unsigned long start, oplen, len, wordsz, chunksz, lsb0_p, signed_p, trunc_p;
8330   bfd_reloc_status_type r;
8331
8332   /*  Perform this reloc, since it is complex.
8333       (this is not to say that it necessarily refers to a complex
8334       symbol; merely that it is a self-describing CGEN based reloc.
8335       i.e. the addend has the complete reloc information (bit start, end,
8336       word size, etc) encoded within it.).  */
8337
8338   decode_complex_addend (&start, &oplen, &len, &wordsz,
8339                          &chunksz, &lsb0_p, &signed_p,
8340                          &trunc_p, rel->r_addend);
8341
8342   mask = (((1L << (len - 1)) - 1) << 1) | 1;
8343
8344   if (lsb0_p)
8345     shift = (start + 1) - len;
8346   else
8347     shift = (8 * wordsz) - (start + len);
8348
8349   x = get_value (wordsz, chunksz, input_bfd,
8350                  contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8351
8352 #ifdef DEBUG
8353   printf ("Doing complex reloc: "
8354           "lsb0? %ld, signed? %ld, trunc? %ld, wordsz %ld, "
8355           "chunksz %ld, start %ld, len %ld, oplen %ld\n"
8356           "    dest: %8.8lx, mask: %8.8lx, reloc: %8.8lx\n",
8357           lsb0_p, signed_p, trunc_p, wordsz, chunksz, start, len,
8358           oplen, (unsigned long) x, (unsigned long) mask,
8359           (unsigned long) relocation);
8360 #endif
8361
8362   r = bfd_reloc_ok;
8363   if (! trunc_p)
8364     /* Now do an overflow check.  */
8365     r = bfd_check_overflow ((signed_p
8366                              ? complain_overflow_signed
8367                              : complain_overflow_unsigned),
8368                             len, 0, (8 * wordsz),
8369                             relocation);
8370
8371   /* Do the deed.  */
8372   x = (x & ~(mask << shift)) | ((relocation & mask) << shift);
8373
8374 #ifdef DEBUG
8375   printf ("           relocation: %8.8lx\n"
8376           "         shifted mask: %8.8lx\n"
8377           " shifted/masked reloc: %8.8lx\n"
8378           "               result: %8.8lx\n",
8379           (unsigned long) relocation, (unsigned long) (mask << shift),
8380           (unsigned long) ((relocation & mask) << shift), (unsigned long) x);
8381 #endif
8382   put_value (wordsz, chunksz, input_bfd, x,
8383              contents + rel->r_offset * bfd_octets_per_byte (input_bfd));
8384   return r;
8385 }
8386
8387 /* Functions to read r_offset from external (target order) reloc
8388    entry.  Faster than bfd_getl32 et al, because we let the compiler
8389    know the value is aligned.  */
8390
8391 static bfd_vma
8392 ext32l_r_offset (const void *p)
8393 {
8394   union aligned32
8395   {
8396     uint32_t v;
8397     unsigned char c[4];
8398   };
8399   const union aligned32 *a
8400     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8401
8402   uint32_t aval = (  (uint32_t) a->c[0]
8403                    | (uint32_t) a->c[1] << 8
8404                    | (uint32_t) a->c[2] << 16
8405                    | (uint32_t) a->c[3] << 24);
8406   return aval;
8407 }
8408
8409 static bfd_vma
8410 ext32b_r_offset (const void *p)
8411 {
8412   union aligned32
8413   {
8414     uint32_t v;
8415     unsigned char c[4];
8416   };
8417   const union aligned32 *a
8418     = (const union aligned32 *) &((const Elf32_External_Rel *) p)->r_offset;
8419
8420   uint32_t aval = (  (uint32_t) a->c[0] << 24
8421                    | (uint32_t) a->c[1] << 16
8422                    | (uint32_t) a->c[2] << 8
8423                    | (uint32_t) a->c[3]);
8424   return aval;
8425 }
8426
8427 #ifdef BFD_HOST_64_BIT
8428 static bfd_vma
8429 ext64l_r_offset (const void *p)
8430 {
8431   union aligned64
8432   {
8433     uint64_t v;
8434     unsigned char c[8];
8435   };
8436   const union aligned64 *a
8437     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8438
8439   uint64_t aval = (  (uint64_t) a->c[0]
8440                    | (uint64_t) a->c[1] << 8
8441                    | (uint64_t) a->c[2] << 16
8442                    | (uint64_t) a->c[3] << 24
8443                    | (uint64_t) a->c[4] << 32
8444                    | (uint64_t) a->c[5] << 40
8445                    | (uint64_t) a->c[6] << 48
8446                    | (uint64_t) a->c[7] << 56);
8447   return aval;
8448 }
8449
8450 static bfd_vma
8451 ext64b_r_offset (const void *p)
8452 {
8453   union aligned64
8454   {
8455     uint64_t v;
8456     unsigned char c[8];
8457   };
8458   const union aligned64 *a
8459     = (const union aligned64 *) &((const Elf64_External_Rel *) p)->r_offset;
8460
8461   uint64_t aval = (  (uint64_t) a->c[0] << 56
8462                    | (uint64_t) a->c[1] << 48
8463                    | (uint64_t) a->c[2] << 40
8464                    | (uint64_t) a->c[3] << 32
8465                    | (uint64_t) a->c[4] << 24
8466                    | (uint64_t) a->c[5] << 16
8467                    | (uint64_t) a->c[6] << 8
8468                    | (uint64_t) a->c[7]);
8469   return aval;
8470 }
8471 #endif
8472
8473 /* When performing a relocatable link, the input relocations are
8474    preserved.  But, if they reference global symbols, the indices
8475    referenced must be updated.  Update all the relocations found in
8476    RELDATA.  */
8477
8478 static bfd_boolean
8479 elf_link_adjust_relocs (bfd *abfd,
8480                         asection *sec,
8481                         struct bfd_elf_section_reloc_data *reldata,
8482                         bfd_boolean sort)
8483 {
8484   unsigned int i;
8485   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8486   bfd_byte *erela;
8487   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8488   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8489   bfd_vma r_type_mask;
8490   int r_sym_shift;
8491   unsigned int count = reldata->count;
8492   struct elf_link_hash_entry **rel_hash = reldata->hashes;
8493
8494   if (reldata->hdr->sh_entsize == bed->s->sizeof_rel)
8495     {
8496       swap_in = bed->s->swap_reloc_in;
8497       swap_out = bed->s->swap_reloc_out;
8498     }
8499   else if (reldata->hdr->sh_entsize == bed->s->sizeof_rela)
8500     {
8501       swap_in = bed->s->swap_reloca_in;
8502       swap_out = bed->s->swap_reloca_out;
8503     }
8504   else
8505     abort ();
8506
8507   if (bed->s->int_rels_per_ext_rel > MAX_INT_RELS_PER_EXT_REL)
8508     abort ();
8509
8510   if (bed->s->arch_size == 32)
8511     {
8512       r_type_mask = 0xff;
8513       r_sym_shift = 8;
8514     }
8515   else
8516     {
8517       r_type_mask = 0xffffffff;
8518       r_sym_shift = 32;
8519     }
8520
8521   erela = reldata->hdr->contents;
8522   for (i = 0; i < count; i++, rel_hash++, erela += reldata->hdr->sh_entsize)
8523     {
8524       Elf_Internal_Rela irela[MAX_INT_RELS_PER_EXT_REL];
8525       unsigned int j;
8526
8527       if (*rel_hash == NULL)
8528         continue;
8529
8530       BFD_ASSERT ((*rel_hash)->indx >= 0);
8531
8532       (*swap_in) (abfd, erela, irela);
8533       for (j = 0; j < bed->s->int_rels_per_ext_rel; j++)
8534         irela[j].r_info = ((bfd_vma) (*rel_hash)->indx << r_sym_shift
8535                            | (irela[j].r_info & r_type_mask));
8536       (*swap_out) (abfd, irela, erela);
8537     }
8538
8539   if (bed->elf_backend_update_relocs)
8540     (*bed->elf_backend_update_relocs) (sec, reldata);
8541
8542   if (sort && count != 0)
8543     {
8544       bfd_vma (*ext_r_off) (const void *);
8545       bfd_vma r_off;
8546       size_t elt_size;
8547       bfd_byte *base, *end, *p, *loc;
8548       bfd_byte *buf = NULL;
8549
8550       if (bed->s->arch_size == 32)
8551         {
8552           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8553             ext_r_off = ext32l_r_offset;
8554           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8555             ext_r_off = ext32b_r_offset;
8556           else
8557             abort ();
8558         }
8559       else
8560         {
8561 #ifdef BFD_HOST_64_BIT
8562           if (abfd->xvec->header_byteorder == BFD_ENDIAN_LITTLE)
8563             ext_r_off = ext64l_r_offset;
8564           else if (abfd->xvec->header_byteorder == BFD_ENDIAN_BIG)
8565             ext_r_off = ext64b_r_offset;
8566           else
8567 #endif
8568             abort ();
8569         }
8570
8571       /*  Must use a stable sort here.  A modified insertion sort,
8572           since the relocs are mostly sorted already.  */
8573       elt_size = reldata->hdr->sh_entsize;
8574       base = reldata->hdr->contents;
8575       end = base + count * elt_size;
8576       if (elt_size > sizeof (Elf64_External_Rela))
8577         abort ();
8578
8579       /* Ensure the first element is lowest.  This acts as a sentinel,
8580          speeding the main loop below.  */
8581       r_off = (*ext_r_off) (base);
8582       for (p = loc = base; (p += elt_size) < end; )
8583         {
8584           bfd_vma r_off2 = (*ext_r_off) (p);
8585           if (r_off > r_off2)
8586             {
8587               r_off = r_off2;
8588               loc = p;
8589             }
8590         }
8591       if (loc != base)
8592         {
8593           /* Don't just swap *base and *loc as that changes the order
8594              of the original base[0] and base[1] if they happen to
8595              have the same r_offset.  */
8596           bfd_byte onebuf[sizeof (Elf64_External_Rela)];
8597           memcpy (onebuf, loc, elt_size);
8598           memmove (base + elt_size, base, loc - base);
8599           memcpy (base, onebuf, elt_size);
8600         }
8601
8602       for (p = base + elt_size; (p += elt_size) < end; )
8603         {
8604           /* base to p is sorted, *p is next to insert.  */
8605           r_off = (*ext_r_off) (p);
8606           /* Search the sorted region for location to insert.  */
8607           loc = p - elt_size;
8608           while (r_off < (*ext_r_off) (loc))
8609             loc -= elt_size;
8610           loc += elt_size;
8611           if (loc != p)
8612             {
8613               /* Chances are there is a run of relocs to insert here,
8614                  from one of more input files.  Files are not always
8615                  linked in order due to the way elf_link_input_bfd is
8616                  called.  See pr17666.  */
8617               size_t sortlen = p - loc;
8618               bfd_vma r_off2 = (*ext_r_off) (loc);
8619               size_t runlen = elt_size;
8620               size_t buf_size = 96 * 1024;
8621               while (p + runlen < end
8622                      && (sortlen <= buf_size
8623                          || runlen + elt_size <= buf_size)
8624                      && r_off2 > (*ext_r_off) (p + runlen))
8625                 runlen += elt_size;
8626               if (buf == NULL)
8627                 {
8628                   buf = bfd_malloc (buf_size);
8629                   if (buf == NULL)
8630                     return FALSE;
8631                 }
8632               if (runlen < sortlen)
8633                 {
8634                   memcpy (buf, p, runlen);
8635                   memmove (loc + runlen, loc, sortlen);
8636                   memcpy (loc, buf, runlen);
8637                 }
8638               else
8639                 {
8640                   memcpy (buf, loc, sortlen);
8641                   memmove (loc, p, runlen);
8642                   memcpy (loc + runlen, buf, sortlen);
8643                 }
8644               p += runlen - elt_size;
8645             }
8646         }
8647       /* Hashes are no longer valid.  */
8648       free (reldata->hashes);
8649       reldata->hashes = NULL;
8650       free (buf);
8651     }
8652   return TRUE;
8653 }
8654
8655 struct elf_link_sort_rela
8656 {
8657   union {
8658     bfd_vma offset;
8659     bfd_vma sym_mask;
8660   } u;
8661   enum elf_reloc_type_class type;
8662   /* We use this as an array of size int_rels_per_ext_rel.  */
8663   Elf_Internal_Rela rela[1];
8664 };
8665
8666 static int
8667 elf_link_sort_cmp1 (const void *A, const void *B)
8668 {
8669   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8670   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8671   int relativea, relativeb;
8672
8673   relativea = a->type == reloc_class_relative;
8674   relativeb = b->type == reloc_class_relative;
8675
8676   if (relativea < relativeb)
8677     return 1;
8678   if (relativea > relativeb)
8679     return -1;
8680   if ((a->rela->r_info & a->u.sym_mask) < (b->rela->r_info & b->u.sym_mask))
8681     return -1;
8682   if ((a->rela->r_info & a->u.sym_mask) > (b->rela->r_info & b->u.sym_mask))
8683     return 1;
8684   if (a->rela->r_offset < b->rela->r_offset)
8685     return -1;
8686   if (a->rela->r_offset > b->rela->r_offset)
8687     return 1;
8688   return 0;
8689 }
8690
8691 static int
8692 elf_link_sort_cmp2 (const void *A, const void *B)
8693 {
8694   const struct elf_link_sort_rela *a = (const struct elf_link_sort_rela *) A;
8695   const struct elf_link_sort_rela *b = (const struct elf_link_sort_rela *) B;
8696
8697   if (a->type < b->type)
8698     return -1;
8699   if (a->type > b->type)
8700     return 1;
8701   if (a->u.offset < b->u.offset)
8702     return -1;
8703   if (a->u.offset > b->u.offset)
8704     return 1;
8705   if (a->rela->r_offset < b->rela->r_offset)
8706     return -1;
8707   if (a->rela->r_offset > b->rela->r_offset)
8708     return 1;
8709   return 0;
8710 }
8711
8712 static size_t
8713 elf_link_sort_relocs (bfd *abfd, struct bfd_link_info *info, asection **psec)
8714 {
8715   asection *dynamic_relocs;
8716   asection *rela_dyn;
8717   asection *rel_dyn;
8718   bfd_size_type count, size;
8719   size_t i, ret, sort_elt, ext_size;
8720   bfd_byte *sort, *s_non_relative, *p;
8721   struct elf_link_sort_rela *sq;
8722   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
8723   int i2e = bed->s->int_rels_per_ext_rel;
8724   unsigned int opb = bfd_octets_per_byte (abfd);
8725   void (*swap_in) (bfd *, const bfd_byte *, Elf_Internal_Rela *);
8726   void (*swap_out) (bfd *, const Elf_Internal_Rela *, bfd_byte *);
8727   struct bfd_link_order *lo;
8728   bfd_vma r_sym_mask;
8729   bfd_boolean use_rela;
8730
8731   /* Find a dynamic reloc section.  */
8732   rela_dyn = bfd_get_section_by_name (abfd, ".rela.dyn");
8733   rel_dyn  = bfd_get_section_by_name (abfd, ".rel.dyn");
8734   if (rela_dyn != NULL && rela_dyn->size > 0
8735       && rel_dyn != NULL && rel_dyn->size > 0)
8736     {
8737       bfd_boolean use_rela_initialised = FALSE;
8738
8739       /* This is just here to stop gcc from complaining.
8740          Its initialization checking code is not perfect.  */
8741       use_rela = TRUE;
8742
8743       /* Both sections are present.  Examine the sizes
8744          of the indirect sections to help us choose.  */
8745       for (lo = rela_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8746         if (lo->type == bfd_indirect_link_order)
8747           {
8748             asection *o = lo->u.indirect.section;
8749
8750             if ((o->size % bed->s->sizeof_rela) == 0)
8751               {
8752                 if ((o->size % bed->s->sizeof_rel) == 0)
8753                   /* Section size is divisible by both rel and rela sizes.
8754                      It is of no help to us.  */
8755                   ;
8756                 else
8757                   {
8758                     /* Section size is only divisible by rela.  */
8759                     if (use_rela_initialised && (use_rela == FALSE))
8760                       {
8761                         _bfd_error_handler (_("%B: Unable to sort relocs - "
8762                                               "they are in more than one size"),
8763                                             abfd);
8764                         bfd_set_error (bfd_error_invalid_operation);
8765                         return 0;
8766                       }
8767                     else
8768                       {
8769                         use_rela = TRUE;
8770                         use_rela_initialised = TRUE;
8771                       }
8772                   }
8773               }
8774             else if ((o->size % bed->s->sizeof_rel) == 0)
8775               {
8776                 /* Section size is only divisible by rel.  */
8777                 if (use_rela_initialised && (use_rela == TRUE))
8778                   {
8779                     _bfd_error_handler (_("%B: Unable to sort relocs - "
8780                                           "they are in more than one size"),
8781                                         abfd);
8782                     bfd_set_error (bfd_error_invalid_operation);
8783                     return 0;
8784                   }
8785                 else
8786                   {
8787                     use_rela = FALSE;
8788                     use_rela_initialised = TRUE;
8789                   }
8790               }
8791             else
8792               {
8793                 /* The section size is not divisible by either -
8794                    something is wrong.  */
8795                 _bfd_error_handler (_("%B: Unable to sort relocs - "
8796                                       "they are of an unknown size"), abfd);
8797                 bfd_set_error (bfd_error_invalid_operation);
8798                 return 0;
8799               }
8800           }
8801
8802       for (lo = rel_dyn->map_head.link_order; lo != NULL; lo = lo->next)
8803         if (lo->type == bfd_indirect_link_order)
8804           {
8805             asection *o = lo->u.indirect.section;
8806
8807             if ((o->size % bed->s->sizeof_rela) == 0)
8808               {
8809                 if ((o->size % bed->s->sizeof_rel) == 0)
8810                   /* Section size is divisible by both rel and rela sizes.
8811                      It is of no help to us.  */
8812                   ;
8813                 else
8814                   {
8815                     /* Section size is only divisible by rela.  */
8816                     if (use_rela_initialised && (use_rela == FALSE))
8817                       {
8818                         _bfd_error_handler (_("%B: Unable to sort relocs - "
8819                                               "they are in more than one size"),
8820                                             abfd);
8821                         bfd_set_error (bfd_error_invalid_operation);
8822                         return 0;
8823                       }
8824                     else
8825                       {
8826                         use_rela = TRUE;
8827                         use_rela_initialised = TRUE;
8828                       }
8829                   }
8830               }
8831             else if ((o->size % bed->s->sizeof_rel) == 0)
8832               {
8833                 /* Section size is only divisible by rel.  */
8834                 if (use_rela_initialised && (use_rela == TRUE))
8835                   {
8836                     _bfd_error_handler (_("%B: Unable to sort relocs - "
8837                                           "they are in more than one size"),
8838                                         abfd);
8839                     bfd_set_error (bfd_error_invalid_operation);
8840                     return 0;
8841                   }
8842                 else
8843                   {
8844                     use_rela = FALSE;
8845                     use_rela_initialised = TRUE;
8846                   }
8847               }
8848             else
8849               {
8850                 /* The section size is not divisible by either -
8851                    something is wrong.  */
8852                 _bfd_error_handler (_("%B: Unable to sort relocs - "
8853                                       "they are of an unknown size"), abfd);
8854                 bfd_set_error (bfd_error_invalid_operation);
8855                 return 0;
8856               }
8857           }
8858
8859       if (! use_rela_initialised)
8860         /* Make a guess.  */
8861         use_rela = TRUE;
8862     }
8863   else if (rela_dyn != NULL && rela_dyn->size > 0)
8864     use_rela = TRUE;
8865   else if (rel_dyn != NULL && rel_dyn->size > 0)
8866     use_rela = FALSE;
8867   else
8868     return 0;
8869
8870   if (use_rela)
8871     {
8872       dynamic_relocs = rela_dyn;
8873       ext_size = bed->s->sizeof_rela;
8874       swap_in = bed->s->swap_reloca_in;
8875       swap_out = bed->s->swap_reloca_out;
8876     }
8877   else
8878     {
8879       dynamic_relocs = rel_dyn;
8880       ext_size = bed->s->sizeof_rel;
8881       swap_in = bed->s->swap_reloc_in;
8882       swap_out = bed->s->swap_reloc_out;
8883     }
8884
8885   size = 0;
8886   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8887     if (lo->type == bfd_indirect_link_order)
8888       size += lo->u.indirect.section->size;
8889
8890   if (size != dynamic_relocs->size)
8891     return 0;
8892
8893   sort_elt = (sizeof (struct elf_link_sort_rela)
8894               + (i2e - 1) * sizeof (Elf_Internal_Rela));
8895
8896   count = dynamic_relocs->size / ext_size;
8897   if (count == 0)
8898     return 0;
8899   sort = (bfd_byte *) bfd_zmalloc (sort_elt * count);
8900
8901   if (sort == NULL)
8902     {
8903       (*info->callbacks->warning)
8904         (info, _("Not enough memory to sort relocations"), 0, abfd, 0, 0);
8905       return 0;
8906     }
8907
8908   if (bed->s->arch_size == 32)
8909     r_sym_mask = ~(bfd_vma) 0xff;
8910   else
8911     r_sym_mask = ~(bfd_vma) 0xffffffff;
8912
8913   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8914     if (lo->type == bfd_indirect_link_order)
8915       {
8916         bfd_byte *erel, *erelend;
8917         asection *o = lo->u.indirect.section;
8918
8919         if (o->contents == NULL && o->size != 0)
8920           {
8921             /* This is a reloc section that is being handled as a normal
8922                section.  See bfd_section_from_shdr.  We can't combine
8923                relocs in this case.  */
8924             free (sort);
8925             return 0;
8926           }
8927         erel = o->contents;
8928         erelend = o->contents + o->size;
8929         p = sort + o->output_offset * opb / ext_size * sort_elt;
8930
8931         while (erel < erelend)
8932           {
8933             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8934
8935             (*swap_in) (abfd, erel, s->rela);
8936             s->type = (*bed->elf_backend_reloc_type_class) (info, o, s->rela);
8937             s->u.sym_mask = r_sym_mask;
8938             p += sort_elt;
8939             erel += ext_size;
8940           }
8941       }
8942
8943   qsort (sort, count, sort_elt, elf_link_sort_cmp1);
8944
8945   for (i = 0, p = sort; i < count; i++, p += sort_elt)
8946     {
8947       struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
8948       if (s->type != reloc_class_relative)
8949         break;
8950     }
8951   ret = i;
8952   s_non_relative = p;
8953
8954   sq = (struct elf_link_sort_rela *) s_non_relative;
8955   for (; i < count; i++, p += sort_elt)
8956     {
8957       struct elf_link_sort_rela *sp = (struct elf_link_sort_rela *) p;
8958       if (((sp->rela->r_info ^ sq->rela->r_info) & r_sym_mask) != 0)
8959         sq = sp;
8960       sp->u.offset = sq->rela->r_offset;
8961     }
8962
8963   qsort (s_non_relative, count - ret, sort_elt, elf_link_sort_cmp2);
8964
8965   struct elf_link_hash_table *htab = elf_hash_table (info);
8966   if (htab->srelplt && htab->srelplt->output_section == dynamic_relocs)
8967     {
8968       /* We have plt relocs in .rela.dyn.  */
8969       sq = (struct elf_link_sort_rela *) sort;
8970       for (i = 0; i < count; i++)
8971         if (sq[count - i - 1].type != reloc_class_plt)
8972           break;
8973       if (i != 0 && htab->srelplt->size == i * ext_size)
8974         {
8975           struct bfd_link_order **plo;
8976           /* Put srelplt link_order last.  This is so the output_offset
8977              set in the next loop is correct for DT_JMPREL.  */
8978           for (plo = &dynamic_relocs->map_head.link_order; *plo != NULL; )
8979             if ((*plo)->type == bfd_indirect_link_order
8980                 && (*plo)->u.indirect.section == htab->srelplt)
8981               {
8982                 lo = *plo;
8983                 *plo = lo->next;
8984               }
8985             else
8986               plo = &(*plo)->next;
8987           *plo = lo;
8988           lo->next = NULL;
8989           dynamic_relocs->map_tail.link_order = lo;
8990         }
8991     }
8992
8993   p = sort;
8994   for (lo = dynamic_relocs->map_head.link_order; lo != NULL; lo = lo->next)
8995     if (lo->type == bfd_indirect_link_order)
8996       {
8997         bfd_byte *erel, *erelend;
8998         asection *o = lo->u.indirect.section;
8999
9000         erel = o->contents;
9001         erelend = o->contents + o->size;
9002         o->output_offset = (p - sort) / sort_elt * ext_size / opb;
9003         while (erel < erelend)
9004           {
9005             struct elf_link_sort_rela *s = (struct elf_link_sort_rela *) p;
9006             (*swap_out) (abfd, s->rela, erel);
9007             p += sort_elt;
9008             erel += ext_size;
9009           }
9010       }
9011
9012   free (sort);
9013   *psec = dynamic_relocs;
9014   return ret;
9015 }
9016
9017 /* Add a symbol to the output symbol string table.  */
9018
9019 static int
9020 elf_link_output_symstrtab (struct elf_final_link_info *flinfo,
9021                            const char *name,
9022                            Elf_Internal_Sym *elfsym,
9023                            asection *input_sec,
9024                            struct elf_link_hash_entry *h)
9025 {
9026   int (*output_symbol_hook)
9027     (struct bfd_link_info *, const char *, Elf_Internal_Sym *, asection *,
9028      struct elf_link_hash_entry *);
9029   struct elf_link_hash_table *hash_table;
9030   const struct elf_backend_data *bed;
9031   bfd_size_type strtabsize;
9032
9033   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9034
9035   bed = get_elf_backend_data (flinfo->output_bfd);
9036   output_symbol_hook = bed->elf_backend_link_output_symbol_hook;
9037   if (output_symbol_hook != NULL)
9038     {
9039       int ret = (*output_symbol_hook) (flinfo->info, name, elfsym, input_sec, h);
9040       if (ret != 1)
9041         return ret;
9042     }
9043
9044   if (name == NULL
9045       || *name == '\0'
9046       || (input_sec->flags & SEC_EXCLUDE))
9047     elfsym->st_name = (unsigned long) -1;
9048   else
9049     {
9050       /* Call _bfd_elf_strtab_offset after _bfd_elf_strtab_finalize
9051          to get the final offset for st_name.  */
9052       elfsym->st_name
9053         = (unsigned long) _bfd_elf_strtab_add (flinfo->symstrtab,
9054                                                name, FALSE);
9055       if (elfsym->st_name == (unsigned long) -1)
9056         return 0;
9057     }
9058
9059   hash_table = elf_hash_table (flinfo->info);
9060   strtabsize = hash_table->strtabsize;
9061   if (strtabsize <= hash_table->strtabcount)
9062     {
9063       strtabsize += strtabsize;
9064       hash_table->strtabsize = strtabsize;
9065       strtabsize *= sizeof (*hash_table->strtab);
9066       hash_table->strtab
9067         = (struct elf_sym_strtab *) bfd_realloc (hash_table->strtab,
9068                                                  strtabsize);
9069       if (hash_table->strtab == NULL)
9070         return 0;
9071     }
9072   hash_table->strtab[hash_table->strtabcount].sym = *elfsym;
9073   hash_table->strtab[hash_table->strtabcount].dest_index
9074     = hash_table->strtabcount;
9075   hash_table->strtab[hash_table->strtabcount].destshndx_index
9076     = flinfo->symshndxbuf ? bfd_get_symcount (flinfo->output_bfd) : 0;
9077
9078   bfd_get_symcount (flinfo->output_bfd) += 1;
9079   hash_table->strtabcount += 1;
9080
9081   return 1;
9082 }
9083
9084 /* Swap symbols out to the symbol table and flush the output symbols to
9085    the file.  */
9086
9087 static bfd_boolean
9088 elf_link_swap_symbols_out (struct elf_final_link_info *flinfo)
9089 {
9090   struct elf_link_hash_table *hash_table = elf_hash_table (flinfo->info);
9091   bfd_size_type amt;
9092   size_t i;
9093   const struct elf_backend_data *bed;
9094   bfd_byte *symbuf;
9095   Elf_Internal_Shdr *hdr;
9096   file_ptr pos;
9097   bfd_boolean ret;
9098
9099   if (!hash_table->strtabcount)
9100     return TRUE;
9101
9102   BFD_ASSERT (elf_onesymtab (flinfo->output_bfd));
9103
9104   bed = get_elf_backend_data (flinfo->output_bfd);
9105
9106   amt = bed->s->sizeof_sym * hash_table->strtabcount;
9107   symbuf = (bfd_byte *) bfd_malloc (amt);
9108   if (symbuf == NULL)
9109     return FALSE;
9110
9111   if (flinfo->symshndxbuf)
9112     {
9113       amt = sizeof (Elf_External_Sym_Shndx);
9114       amt *= bfd_get_symcount (flinfo->output_bfd);
9115       flinfo->symshndxbuf = (Elf_External_Sym_Shndx *) bfd_zmalloc (amt);
9116       if (flinfo->symshndxbuf == NULL)
9117         {
9118           free (symbuf);
9119           return FALSE;
9120         }
9121     }
9122
9123   for (i = 0; i < hash_table->strtabcount; i++)
9124     {
9125       struct elf_sym_strtab *elfsym = &hash_table->strtab[i];
9126       if (elfsym->sym.st_name == (unsigned long) -1)
9127         elfsym->sym.st_name = 0;
9128       else
9129         elfsym->sym.st_name
9130           = (unsigned long) _bfd_elf_strtab_offset (flinfo->symstrtab,
9131                                                     elfsym->sym.st_name);
9132       bed->s->swap_symbol_out (flinfo->output_bfd, &elfsym->sym,
9133                                ((bfd_byte *) symbuf
9134                                 + (elfsym->dest_index
9135                                    * bed->s->sizeof_sym)),
9136                                (flinfo->symshndxbuf
9137                                 + elfsym->destshndx_index));
9138     }
9139
9140   hdr = &elf_tdata (flinfo->output_bfd)->symtab_hdr;
9141   pos = hdr->sh_offset + hdr->sh_size;
9142   amt = hash_table->strtabcount * bed->s->sizeof_sym;
9143   if (bfd_seek (flinfo->output_bfd, pos, SEEK_SET) == 0
9144       && bfd_bwrite (symbuf, amt, flinfo->output_bfd) == amt)
9145     {
9146       hdr->sh_size += amt;
9147       ret = TRUE;
9148     }
9149   else
9150     ret = FALSE;
9151
9152   free (symbuf);
9153
9154   free (hash_table->strtab);
9155   hash_table->strtab = NULL;
9156
9157   return ret;
9158 }
9159
9160 /* Return TRUE if the dynamic symbol SYM in ABFD is supported.  */
9161
9162 static bfd_boolean
9163 check_dynsym (bfd *abfd, Elf_Internal_Sym *sym)
9164 {
9165   if (sym->st_shndx >= (SHN_LORESERVE & 0xffff)
9166       && sym->st_shndx < SHN_LORESERVE)
9167     {
9168       /* The gABI doesn't support dynamic symbols in output sections
9169          beyond 64k.  */
9170       _bfd_error_handler
9171         /* xgettext:c-format */
9172         (_("%B: Too many sections: %d (>= %d)"),
9173          abfd, bfd_count_sections (abfd), SHN_LORESERVE & 0xffff);
9174       bfd_set_error (bfd_error_nonrepresentable_section);
9175       return FALSE;
9176     }
9177   return TRUE;
9178 }
9179
9180 /* For DSOs loaded in via a DT_NEEDED entry, emulate ld.so in
9181    allowing an unsatisfied unversioned symbol in the DSO to match a
9182    versioned symbol that would normally require an explicit version.
9183    We also handle the case that a DSO references a hidden symbol
9184    which may be satisfied by a versioned symbol in another DSO.  */
9185
9186 static bfd_boolean
9187 elf_link_check_versioned_symbol (struct bfd_link_info *info,
9188                                  const struct elf_backend_data *bed,
9189                                  struct elf_link_hash_entry *h)
9190 {
9191   bfd *abfd;
9192   struct elf_link_loaded_list *loaded;
9193
9194   if (!is_elf_hash_table (info->hash))
9195     return FALSE;
9196
9197   /* Check indirect symbol.  */
9198   while (h->root.type == bfd_link_hash_indirect)
9199     h = (struct elf_link_hash_entry *) h->root.u.i.link;
9200
9201   switch (h->root.type)
9202     {
9203     default:
9204       abfd = NULL;
9205       break;
9206
9207     case bfd_link_hash_undefined:
9208     case bfd_link_hash_undefweak:
9209       abfd = h->root.u.undef.abfd;
9210       if (abfd == NULL
9211           || (abfd->flags & DYNAMIC) == 0
9212           || (elf_dyn_lib_class (abfd) & DYN_DT_NEEDED) == 0)
9213         return FALSE;
9214       break;
9215
9216     case bfd_link_hash_defined:
9217     case bfd_link_hash_defweak:
9218       abfd = h->root.u.def.section->owner;
9219       break;
9220
9221     case bfd_link_hash_common:
9222       abfd = h->root.u.c.p->section->owner;
9223       break;
9224     }
9225   BFD_ASSERT (abfd != NULL);
9226
9227   for (loaded = elf_hash_table (info)->loaded;
9228        loaded != NULL;
9229        loaded = loaded->next)
9230     {
9231       bfd *input;
9232       Elf_Internal_Shdr *hdr;
9233       size_t symcount;
9234       size_t extsymcount;
9235       size_t extsymoff;
9236       Elf_Internal_Shdr *versymhdr;
9237       Elf_Internal_Sym *isym;
9238       Elf_Internal_Sym *isymend;
9239       Elf_Internal_Sym *isymbuf;
9240       Elf_External_Versym *ever;
9241       Elf_External_Versym *extversym;
9242
9243       input = loaded->abfd;
9244
9245       /* We check each DSO for a possible hidden versioned definition.  */
9246       if (input == abfd
9247           || (input->flags & DYNAMIC) == 0
9248           || elf_dynversym (input) == 0)
9249         continue;
9250
9251       hdr = &elf_tdata (input)->dynsymtab_hdr;
9252
9253       symcount = hdr->sh_size / bed->s->sizeof_sym;
9254       if (elf_bad_symtab (input))
9255         {
9256           extsymcount = symcount;
9257           extsymoff = 0;
9258         }
9259       else
9260         {
9261           extsymcount = symcount - hdr->sh_info;
9262           extsymoff = hdr->sh_info;
9263         }
9264
9265       if (extsymcount == 0)
9266         continue;
9267
9268       isymbuf = bfd_elf_get_elf_syms (input, hdr, extsymcount, extsymoff,
9269                                       NULL, NULL, NULL);
9270       if (isymbuf == NULL)
9271         return FALSE;
9272
9273       /* Read in any version definitions.  */
9274       versymhdr = &elf_tdata (input)->dynversym_hdr;
9275       extversym = (Elf_External_Versym *) bfd_malloc (versymhdr->sh_size);
9276       if (extversym == NULL)
9277         goto error_ret;
9278
9279       if (bfd_seek (input, versymhdr->sh_offset, SEEK_SET) != 0
9280           || (bfd_bread (extversym, versymhdr->sh_size, input)
9281               != versymhdr->sh_size))
9282         {
9283           free (extversym);
9284         error_ret:
9285           free (isymbuf);
9286           return FALSE;
9287         }
9288
9289       ever = extversym + extsymoff;
9290       isymend = isymbuf + extsymcount;
9291       for (isym = isymbuf; isym < isymend; isym++, ever++)
9292         {
9293           const char *name;
9294           Elf_Internal_Versym iver;
9295           unsigned short version_index;
9296
9297           if (ELF_ST_BIND (isym->st_info) == STB_LOCAL
9298               || isym->st_shndx == SHN_UNDEF)
9299             continue;
9300
9301           name = bfd_elf_string_from_elf_section (input,
9302                                                   hdr->sh_link,
9303                                                   isym->st_name);
9304           if (strcmp (name, h->root.root.string) != 0)
9305             continue;
9306
9307           _bfd_elf_swap_versym_in (input, ever, &iver);
9308
9309           if ((iver.vs_vers & VERSYM_HIDDEN) == 0
9310               && !(h->def_regular
9311                    && h->forced_local))
9312             {
9313               /* If we have a non-hidden versioned sym, then it should
9314                  have provided a definition for the undefined sym unless
9315                  it is defined in a non-shared object and forced local.
9316                */
9317               abort ();
9318             }
9319
9320           version_index = iver.vs_vers & VERSYM_VERSION;
9321           if (version_index == 1 || version_index == 2)
9322             {
9323               /* This is the base or first version.  We can use it.  */
9324               free (extversym);
9325               free (isymbuf);
9326               return TRUE;
9327             }
9328         }
9329
9330       free (extversym);
9331       free (isymbuf);
9332     }
9333
9334   return FALSE;
9335 }
9336
9337 /* Convert ELF common symbol TYPE.  */
9338
9339 static int
9340 elf_link_convert_common_type (struct bfd_link_info *info, int type)
9341 {
9342   /* Commom symbol can only appear in relocatable link.  */
9343   if (!bfd_link_relocatable (info))
9344     abort ();
9345   switch (info->elf_stt_common)
9346     {
9347     case unchanged:
9348       break;
9349     case elf_stt_common:
9350       type = STT_COMMON;
9351       break;
9352     case no_elf_stt_common:
9353       type = STT_OBJECT;
9354       break;
9355     }
9356   return type;
9357 }
9358
9359 /* Add an external symbol to the symbol table.  This is called from
9360    the hash table traversal routine.  When generating a shared object,
9361    we go through the symbol table twice.  The first time we output
9362    anything that might have been forced to local scope in a version
9363    script.  The second time we output the symbols that are still
9364    global symbols.  */
9365
9366 static bfd_boolean
9367 elf_link_output_extsym (struct bfd_hash_entry *bh, void *data)
9368 {
9369   struct elf_link_hash_entry *h = (struct elf_link_hash_entry *) bh;
9370   struct elf_outext_info *eoinfo = (struct elf_outext_info *) data;
9371   struct elf_final_link_info *flinfo = eoinfo->flinfo;
9372   bfd_boolean strip;
9373   Elf_Internal_Sym sym;
9374   asection *input_sec;
9375   const struct elf_backend_data *bed;
9376   long indx;
9377   int ret;
9378   unsigned int type;
9379
9380   if (h->root.type == bfd_link_hash_warning)
9381     {
9382       h = (struct elf_link_hash_entry *) h->root.u.i.link;
9383       if (h->root.type == bfd_link_hash_new)
9384         return TRUE;
9385     }
9386
9387   /* Decide whether to output this symbol in this pass.  */
9388   if (eoinfo->localsyms)
9389     {
9390       if (!h->forced_local)
9391         return TRUE;
9392     }
9393   else
9394     {
9395       if (h->forced_local)
9396         return TRUE;
9397     }
9398
9399   bed = get_elf_backend_data (flinfo->output_bfd);
9400
9401   if (h->root.type == bfd_link_hash_undefined)
9402     {
9403       /* If we have an undefined symbol reference here then it must have
9404          come from a shared library that is being linked in.  (Undefined
9405          references in regular files have already been handled unless
9406          they are in unreferenced sections which are removed by garbage
9407          collection).  */
9408       bfd_boolean ignore_undef = FALSE;
9409
9410       /* Some symbols may be special in that the fact that they're
9411          undefined can be safely ignored - let backend determine that.  */
9412       if (bed->elf_backend_ignore_undef_symbol)
9413         ignore_undef = bed->elf_backend_ignore_undef_symbol (h);
9414
9415       /* If we are reporting errors for this situation then do so now.  */
9416       if (!ignore_undef
9417           && h->ref_dynamic
9418           && (!h->ref_regular || flinfo->info->gc_sections)
9419           && !elf_link_check_versioned_symbol (flinfo->info, bed, h)
9420           && flinfo->info->unresolved_syms_in_shared_libs != RM_IGNORE)
9421         (*flinfo->info->callbacks->undefined_symbol)
9422           (flinfo->info, h->root.root.string,
9423            h->ref_regular ? NULL : h->root.u.undef.abfd,
9424            NULL, 0,
9425            flinfo->info->unresolved_syms_in_shared_libs == RM_GENERATE_ERROR);
9426
9427       /* Strip a global symbol defined in a discarded section.  */
9428       if (h->indx == -3)
9429         return TRUE;
9430     }
9431
9432   /* We should also warn if a forced local symbol is referenced from
9433      shared libraries.  */
9434   if (bfd_link_executable (flinfo->info)
9435       && h->forced_local
9436       && h->ref_dynamic
9437       && h->def_regular
9438       && !h->dynamic_def
9439       && h->ref_dynamic_nonweak
9440       && !elf_link_check_versioned_symbol (flinfo->info, bed, h))
9441     {
9442       bfd *def_bfd;
9443       const char *msg;
9444       struct elf_link_hash_entry *hi = h;
9445
9446       /* Check indirect symbol.  */
9447       while (hi->root.type == bfd_link_hash_indirect)
9448         hi = (struct elf_link_hash_entry *) hi->root.u.i.link;
9449
9450       if (ELF_ST_VISIBILITY (h->other) == STV_INTERNAL)
9451         /* xgettext:c-format */
9452         msg = _("%B: internal symbol `%s' in %B is referenced by DSO");
9453       else if (ELF_ST_VISIBILITY (h->other) == STV_HIDDEN)
9454         /* xgettext:c-format */
9455         msg = _("%B: hidden symbol `%s' in %B is referenced by DSO");
9456       else
9457         /* xgettext:c-format */
9458         msg = _("%B: local symbol `%s' in %B is referenced by DSO");
9459       def_bfd = flinfo->output_bfd;
9460       if (hi->root.u.def.section != bfd_abs_section_ptr)
9461         def_bfd = hi->root.u.def.section->owner;
9462       _bfd_error_handler (msg, flinfo->output_bfd, def_bfd,
9463                           h->root.root.string);
9464       bfd_set_error (bfd_error_bad_value);
9465       eoinfo->failed = TRUE;
9466       return FALSE;
9467     }
9468
9469   /* We don't want to output symbols that have never been mentioned by
9470      a regular file, or that we have been told to strip.  However, if
9471      h->indx is set to -2, the symbol is used by a reloc and we must
9472      output it.  */
9473   strip = FALSE;
9474   if (h->indx == -2)
9475     ;
9476   else if ((h->def_dynamic
9477             || h->ref_dynamic
9478             || h->root.type == bfd_link_hash_new)
9479            && !h->def_regular
9480            && !h->ref_regular)
9481     strip = TRUE;
9482   else if (flinfo->info->strip == strip_all)
9483     strip = TRUE;
9484   else if (flinfo->info->strip == strip_some
9485            && bfd_hash_lookup (flinfo->info->keep_hash,
9486                                h->root.root.string, FALSE, FALSE) == NULL)
9487     strip = TRUE;
9488   else if ((h->root.type == bfd_link_hash_defined
9489             || h->root.type == bfd_link_hash_defweak)
9490            && ((flinfo->info->strip_discarded
9491                 && discarded_section (h->root.u.def.section))
9492                || ((h->root.u.def.section->flags & SEC_LINKER_CREATED) == 0
9493                    && h->root.u.def.section->owner != NULL
9494                    && (h->root.u.def.section->owner->flags & BFD_PLUGIN) != 0)))
9495     strip = TRUE;
9496   else if ((h->root.type == bfd_link_hash_undefined
9497             || h->root.type == bfd_link_hash_undefweak)
9498            && h->root.u.undef.abfd != NULL
9499            && (h->root.u.undef.abfd->flags & BFD_PLUGIN) != 0)
9500     strip = TRUE;
9501
9502   type = h->type;
9503
9504   /* If we're stripping it, and it's not a dynamic symbol, there's
9505      nothing else to do.   However, if it is a forced local symbol or
9506      an ifunc symbol we need to give the backend finish_dynamic_symbol
9507      function a chance to make it dynamic.  */
9508   if (strip
9509       && h->dynindx == -1
9510       && type != STT_GNU_IFUNC
9511       && !h->forced_local)
9512     return TRUE;
9513
9514   sym.st_value = 0;
9515   sym.st_size = h->size;
9516   sym.st_other = h->other;
9517   switch (h->root.type)
9518     {
9519     default:
9520     case bfd_link_hash_new:
9521     case bfd_link_hash_warning:
9522       abort ();
9523       return FALSE;
9524
9525     case bfd_link_hash_undefined:
9526     case bfd_link_hash_undefweak:
9527       input_sec = bfd_und_section_ptr;
9528       sym.st_shndx = SHN_UNDEF;
9529       break;
9530
9531     case bfd_link_hash_defined:
9532     case bfd_link_hash_defweak:
9533       {
9534         input_sec = h->root.u.def.section;
9535         if (input_sec->output_section != NULL)
9536           {
9537             sym.st_shndx =
9538               _bfd_elf_section_from_bfd_section (flinfo->output_bfd,
9539                                                  input_sec->output_section);
9540             if (sym.st_shndx == SHN_BAD)
9541               {
9542                 _bfd_error_handler
9543                   /* xgettext:c-format */
9544                   (_("%B: could not find output section %A for input section %A"),
9545                    flinfo->output_bfd, input_sec->output_section, input_sec);
9546                 bfd_set_error (bfd_error_nonrepresentable_section);
9547                 eoinfo->failed = TRUE;
9548                 return FALSE;
9549               }
9550
9551             /* ELF symbols in relocatable files are section relative,
9552                but in nonrelocatable files they are virtual
9553                addresses.  */
9554             sym.st_value = h->root.u.def.value + input_sec->output_offset;
9555             if (!bfd_link_relocatable (flinfo->info))
9556               {
9557                 sym.st_value += input_sec->output_section->vma;
9558                 if (h->type == STT_TLS)
9559                   {
9560                     asection *tls_sec = elf_hash_table (flinfo->info)->tls_sec;
9561                     if (tls_sec != NULL)
9562                       sym.st_value -= tls_sec->vma;
9563                   }
9564               }
9565           }
9566         else
9567           {
9568             BFD_ASSERT (input_sec->owner == NULL
9569                         || (input_sec->owner->flags & DYNAMIC) != 0);
9570             sym.st_shndx = SHN_UNDEF;
9571             input_sec = bfd_und_section_ptr;
9572           }
9573       }
9574       break;
9575
9576     case bfd_link_hash_common:
9577       input_sec = h->root.u.c.p->section;
9578       sym.st_shndx = bed->common_section_index (input_sec);
9579       sym.st_value = 1 << h->root.u.c.p->alignment_power;
9580       break;
9581
9582     case bfd_link_hash_indirect:
9583       /* These symbols are created by symbol versioning.  They point
9584          to the decorated version of the name.  For example, if the
9585          symbol foo@@GNU_1.2 is the default, which should be used when
9586          foo is used with no version, then we add an indirect symbol
9587          foo which points to foo@@GNU_1.2.  We ignore these symbols,
9588          since the indirected symbol is already in the hash table.  */
9589       return TRUE;
9590     }
9591
9592   if (type == STT_COMMON || type == STT_OBJECT)
9593     switch (h->root.type)
9594       {
9595       case bfd_link_hash_common:
9596         type = elf_link_convert_common_type (flinfo->info, type);
9597         break;
9598       case bfd_link_hash_defined:
9599       case bfd_link_hash_defweak:
9600         if (bed->common_definition (&sym))
9601           type = elf_link_convert_common_type (flinfo->info, type);
9602         else
9603           type = STT_OBJECT;
9604         break;
9605       case bfd_link_hash_undefined:
9606       case bfd_link_hash_undefweak:
9607         break;
9608       default:
9609         abort ();
9610       }
9611
9612   if (h->forced_local)
9613     {
9614       sym.st_info = ELF_ST_INFO (STB_LOCAL, type);
9615       /* Turn off visibility on local symbol.  */
9616       sym.st_other &= ~ELF_ST_VISIBILITY (-1);
9617     }
9618   /* Set STB_GNU_UNIQUE only if symbol is defined in regular object.  */
9619   else if (h->unique_global && h->def_regular)
9620     sym.st_info = ELF_ST_INFO (STB_GNU_UNIQUE, type);
9621   else if (h->root.type == bfd_link_hash_undefweak
9622            || h->root.type == bfd_link_hash_defweak)
9623     sym.st_info = ELF_ST_INFO (STB_WEAK, type);
9624   else
9625     sym.st_info = ELF_ST_INFO (STB_GLOBAL, type);
9626   sym.st_target_internal = h->target_internal;
9627
9628   /* Give the processor backend a chance to tweak the symbol value,
9629      and also to finish up anything that needs to be done for this
9630      symbol.  FIXME: Not calling elf_backend_finish_dynamic_symbol for
9631      forced local syms when non-shared is due to a historical quirk.
9632      STT_GNU_IFUNC symbol must go through PLT.  */
9633   if ((h->type == STT_GNU_IFUNC
9634        && h->def_regular
9635        && !bfd_link_relocatable (flinfo->info))
9636       || ((h->dynindx != -1
9637            || h->forced_local)
9638           && ((bfd_link_pic (flinfo->info)
9639                && (ELF_ST_VISIBILITY (h->other) == STV_DEFAULT
9640                    || h->root.type != bfd_link_hash_undefweak))
9641               || !h->forced_local)
9642           && elf_hash_table (flinfo->info)->dynamic_sections_created))
9643     {
9644       if (! ((*bed->elf_backend_finish_dynamic_symbol)
9645              (flinfo->output_bfd, flinfo->info, h, &sym)))
9646         {
9647           eoinfo->failed = TRUE;
9648           return FALSE;
9649         }
9650     }
9651
9652   /* If we are marking the symbol as undefined, and there are no
9653      non-weak references to this symbol from a regular object, then
9654      mark the symbol as weak undefined; if there are non-weak
9655      references, mark the symbol as strong.  We can't do this earlier,
9656      because it might not be marked as undefined until the
9657      finish_dynamic_symbol routine gets through with it.  */
9658   if (sym.st_shndx == SHN_UNDEF
9659       && h->ref_regular
9660       && (ELF_ST_BIND (sym.st_info) == STB_GLOBAL
9661           || ELF_ST_BIND (sym.st_info) == STB_WEAK))
9662     {
9663       int bindtype;
9664       type = ELF_ST_TYPE (sym.st_info);
9665
9666       /* Turn an undefined IFUNC symbol into a normal FUNC symbol. */
9667       if (type == STT_GNU_IFUNC)
9668         type = STT_FUNC;
9669
9670       if (h->ref_regular_nonweak)
9671         bindtype = STB_GLOBAL;
9672       else
9673         bindtype = STB_WEAK;
9674       sym.st_info = ELF_ST_INFO (bindtype, type);
9675     }
9676
9677   /* If this is a symbol defined in a dynamic library, don't use the
9678      symbol size from the dynamic library.  Relinking an executable
9679      against a new library may introduce gratuitous changes in the
9680      executable's symbols if we keep the size.  */
9681   if (sym.st_shndx == SHN_UNDEF
9682       && !h->def_regular
9683       && h->def_dynamic)
9684     sym.st_size = 0;
9685
9686   /* If a non-weak symbol with non-default visibility is not defined
9687      locally, it is a fatal error.  */
9688   if (!bfd_link_relocatable (flinfo->info)
9689       && ELF_ST_VISIBILITY (sym.st_other) != STV_DEFAULT
9690       && ELF_ST_BIND (sym.st_info) != STB_WEAK
9691       && h->root.type == bfd_link_hash_undefined
9692       && !h->def_regular)
9693     {
9694       const char *msg;
9695
9696       if (ELF_ST_VISIBILITY (sym.st_other) == STV_PROTECTED)
9697         /* xgettext:c-format */
9698         msg = _("%B: protected symbol `%s' isn't defined");
9699       else if (ELF_ST_VISIBILITY (sym.st_other) == STV_INTERNAL)
9700         /* xgettext:c-format */
9701         msg = _("%B: internal symbol `%s' isn't defined");
9702       else
9703         /* xgettext:c-format */
9704         msg = _("%B: hidden symbol `%s' isn't defined");
9705       _bfd_error_handler (msg, flinfo->output_bfd, h->root.root.string);
9706       bfd_set_error (bfd_error_bad_value);
9707       eoinfo->failed = TRUE;
9708       return FALSE;
9709     }
9710
9711   /* If this symbol should be put in the .dynsym section, then put it
9712      there now.  We already know the symbol index.  We also fill in
9713      the entry in the .hash section.  */
9714   if (elf_hash_table (flinfo->info)->dynsym != NULL
9715       && h->dynindx != -1
9716       && elf_hash_table (flinfo->info)->dynamic_sections_created)
9717     {
9718       bfd_byte *esym;
9719
9720       /* Since there is no version information in the dynamic string,
9721          if there is no version info in symbol version section, we will
9722          have a run-time problem if not linking executable, referenced
9723          by shared library, or not bound locally.  */
9724       if (h->verinfo.verdef == NULL
9725           && (!bfd_link_executable (flinfo->info)
9726               || h->ref_dynamic
9727               || !h->def_regular))
9728         {
9729           char *p = strrchr (h->root.root.string, ELF_VER_CHR);
9730
9731           if (p && p [1] != '\0')
9732             {
9733               _bfd_error_handler
9734                 /* xgettext:c-format */
9735                 (_("%B: No symbol version section for versioned symbol `%s'"),
9736                  flinfo->output_bfd, h->root.root.string);
9737               eoinfo->failed = TRUE;
9738               return FALSE;
9739             }
9740         }
9741
9742       sym.st_name = h->dynstr_index;
9743       esym = (elf_hash_table (flinfo->info)->dynsym->contents
9744               + h->dynindx * bed->s->sizeof_sym);
9745       if (!check_dynsym (flinfo->output_bfd, &sym))
9746         {
9747           eoinfo->failed = TRUE;
9748           return FALSE;
9749         }
9750       bed->s->swap_symbol_out (flinfo->output_bfd, &sym, esym, 0);
9751
9752       if (flinfo->hash_sec != NULL)
9753         {
9754           size_t hash_entry_size;
9755           bfd_byte *bucketpos;
9756           bfd_vma chain;
9757           size_t bucketcount;
9758           size_t bucket;
9759
9760           bucketcount = elf_hash_table (flinfo->info)->bucketcount;
9761           bucket = h->u.elf_hash_value % bucketcount;
9762
9763           hash_entry_size
9764             = elf_section_data (flinfo->hash_sec)->this_hdr.sh_entsize;
9765           bucketpos = ((bfd_byte *) flinfo->hash_sec->contents
9766                        + (bucket + 2) * hash_entry_size);
9767           chain = bfd_get (8 * hash_entry_size, flinfo->output_bfd, bucketpos);
9768           bfd_put (8 * hash_entry_size, flinfo->output_bfd, h->dynindx,
9769                    bucketpos);
9770           bfd_put (8 * hash_entry_size, flinfo->output_bfd, chain,
9771                    ((bfd_byte *) flinfo->hash_sec->contents
9772                     + (bucketcount + 2 + h->dynindx) * hash_entry_size));
9773         }
9774
9775       if (flinfo->symver_sec != NULL && flinfo->symver_sec->contents != NULL)
9776         {
9777           Elf_Internal_Versym iversym;
9778           Elf_External_Versym *eversym;
9779
9780           if (!h->def_regular)
9781             {
9782               if (h->verinfo.verdef == NULL
9783                   || (elf_dyn_lib_class (h->verinfo.verdef->vd_bfd)
9784                       & (DYN_AS_NEEDED | DYN_DT_NEEDED | DYN_NO_NEEDED)))
9785                 iversym.vs_vers = 0;
9786               else
9787                 iversym.vs_vers = h->verinfo.verdef->vd_exp_refno + 1;
9788             }
9789           else
9790             {
9791               if (h->verinfo.vertree == NULL)
9792                 iversym.vs_vers = 1;
9793               else
9794                 iversym.vs_vers = h->verinfo.vertree->vernum + 1;
9795               if (flinfo->info->create_default_symver)
9796                 iversym.vs_vers++;
9797             }
9798
9799           /* Turn on VERSYM_HIDDEN only if the hidden versioned symbol is
9800              defined locally.  */
9801           if (h->versioned == versioned_hidden && h->def_regular)
9802             iversym.vs_vers |= VERSYM_HIDDEN;
9803
9804           eversym = (Elf_External_Versym *) flinfo->symver_sec->contents;
9805           eversym += h->dynindx;
9806           _bfd_elf_swap_versym_out (flinfo->output_bfd, &iversym, eversym);
9807         }
9808     }
9809
9810   /* If the symbol is undefined, and we didn't output it to .dynsym,
9811      strip it from .symtab too.  Obviously we can't do this for
9812      relocatable output or when needed for --emit-relocs.  */
9813   else if (input_sec == bfd_und_section_ptr
9814            && h->indx != -2
9815            && !bfd_link_relocatable (flinfo->info))
9816     return TRUE;
9817   /* Also strip others that we couldn't earlier due to dynamic symbol
9818      processing.  */
9819   if (strip)
9820     return TRUE;
9821   if ((input_sec->flags & SEC_EXCLUDE) != 0)
9822     return TRUE;
9823
9824   /* Output a FILE symbol so that following locals are not associated
9825      with the wrong input file.  We need one for forced local symbols
9826      if we've seen more than one FILE symbol or when we have exactly
9827      one FILE symbol but global symbols are present in a file other
9828      than the one with the FILE symbol.  We also need one if linker
9829      defined symbols are present.  In practice these conditions are
9830      always met, so just emit the FILE symbol unconditionally.  */
9831   if (eoinfo->localsyms
9832       && !eoinfo->file_sym_done
9833       && eoinfo->flinfo->filesym_count != 0)
9834     {
9835       Elf_Internal_Sym fsym;
9836
9837       memset (&fsym, 0, sizeof (fsym));
9838       fsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
9839       fsym.st_shndx = SHN_ABS;
9840       if (!elf_link_output_symstrtab (eoinfo->flinfo, NULL, &fsym,
9841                                       bfd_und_section_ptr, NULL))
9842         return FALSE;
9843
9844       eoinfo->file_sym_done = TRUE;
9845     }
9846
9847   indx = bfd_get_symcount (flinfo->output_bfd);
9848   ret = elf_link_output_symstrtab (flinfo, h->root.root.string, &sym,
9849                                    input_sec, h);
9850   if (ret == 0)
9851     {
9852       eoinfo->failed = TRUE;
9853       return FALSE;
9854     }
9855   else if (ret == 1)
9856     h->indx = indx;
9857   else if (h->indx == -2)
9858     abort();
9859
9860   return TRUE;
9861 }
9862
9863 /* Return TRUE if special handling is done for relocs in SEC against
9864    symbols defined in discarded sections.  */
9865
9866 static bfd_boolean
9867 elf_section_ignore_discarded_relocs (asection *sec)
9868 {
9869   const struct elf_backend_data *bed;
9870
9871   switch (sec->sec_info_type)
9872     {
9873     case SEC_INFO_TYPE_STABS:
9874     case SEC_INFO_TYPE_EH_FRAME:
9875     case SEC_INFO_TYPE_EH_FRAME_ENTRY:
9876       return TRUE;
9877     default:
9878       break;
9879     }
9880
9881   bed = get_elf_backend_data (sec->owner);
9882   if (bed->elf_backend_ignore_discarded_relocs != NULL
9883       && (*bed->elf_backend_ignore_discarded_relocs) (sec))
9884     return TRUE;
9885
9886   return FALSE;
9887 }
9888
9889 /* Return a mask saying how ld should treat relocations in SEC against
9890    symbols defined in discarded sections.  If this function returns
9891    COMPLAIN set, ld will issue a warning message.  If this function
9892    returns PRETEND set, and the discarded section was link-once and the
9893    same size as the kept link-once section, ld will pretend that the
9894    symbol was actually defined in the kept section.  Otherwise ld will
9895    zero the reloc (at least that is the intent, but some cooperation by
9896    the target dependent code is needed, particularly for REL targets).  */
9897
9898 unsigned int
9899 _bfd_elf_default_action_discarded (asection *sec)
9900 {
9901   if (sec->flags & SEC_DEBUGGING)
9902     return PRETEND;
9903
9904   if (strcmp (".eh_frame", sec->name) == 0)
9905     return 0;
9906
9907   if (strcmp (".gcc_except_table", sec->name) == 0)
9908     return 0;
9909
9910   return COMPLAIN | PRETEND;
9911 }
9912
9913 /* Find a match between a section and a member of a section group.  */
9914
9915 static asection *
9916 match_group_member (asection *sec, asection *group,
9917                     struct bfd_link_info *info)
9918 {
9919   asection *first = elf_next_in_group (group);
9920   asection *s = first;
9921
9922   while (s != NULL)
9923     {
9924       if (bfd_elf_match_symbols_in_sections (s, sec, info))
9925         return s;
9926
9927       s = elf_next_in_group (s);
9928       if (s == first)
9929         break;
9930     }
9931
9932   return NULL;
9933 }
9934
9935 /* Check if the kept section of a discarded section SEC can be used
9936    to replace it.  Return the replacement if it is OK.  Otherwise return
9937    NULL.  */
9938
9939 asection *
9940 _bfd_elf_check_kept_section (asection *sec, struct bfd_link_info *info)
9941 {
9942   asection *kept;
9943
9944   kept = sec->kept_section;
9945   if (kept != NULL)
9946     {
9947       if ((kept->flags & SEC_GROUP) != 0)
9948         kept = match_group_member (sec, kept, info);
9949       if (kept != NULL
9950           && ((sec->rawsize != 0 ? sec->rawsize : sec->size)
9951               != (kept->rawsize != 0 ? kept->rawsize : kept->size)))
9952         kept = NULL;
9953       sec->kept_section = kept;
9954     }
9955   return kept;
9956 }
9957
9958 /* Link an input file into the linker output file.  This function
9959    handles all the sections and relocations of the input file at once.
9960    This is so that we only have to read the local symbols once, and
9961    don't have to keep them in memory.  */
9962
9963 static bfd_boolean
9964 elf_link_input_bfd (struct elf_final_link_info *flinfo, bfd *input_bfd)
9965 {
9966   int (*relocate_section)
9967     (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
9968      Elf_Internal_Rela *, Elf_Internal_Sym *, asection **);
9969   bfd *output_bfd;
9970   Elf_Internal_Shdr *symtab_hdr;
9971   size_t locsymcount;
9972   size_t extsymoff;
9973   Elf_Internal_Sym *isymbuf;
9974   Elf_Internal_Sym *isym;
9975   Elf_Internal_Sym *isymend;
9976   long *pindex;
9977   asection **ppsection;
9978   asection *o;
9979   const struct elf_backend_data *bed;
9980   struct elf_link_hash_entry **sym_hashes;
9981   bfd_size_type address_size;
9982   bfd_vma r_type_mask;
9983   int r_sym_shift;
9984   bfd_boolean have_file_sym = FALSE;
9985
9986   output_bfd = flinfo->output_bfd;
9987   bed = get_elf_backend_data (output_bfd);
9988   relocate_section = bed->elf_backend_relocate_section;
9989
9990   /* If this is a dynamic object, we don't want to do anything here:
9991      we don't want the local symbols, and we don't want the section
9992      contents.  */
9993   if ((input_bfd->flags & DYNAMIC) != 0)
9994     return TRUE;
9995
9996   symtab_hdr = &elf_tdata (input_bfd)->symtab_hdr;
9997   if (elf_bad_symtab (input_bfd))
9998     {
9999       locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
10000       extsymoff = 0;
10001     }
10002   else
10003     {
10004       locsymcount = symtab_hdr->sh_info;
10005       extsymoff = symtab_hdr->sh_info;
10006     }
10007
10008   /* Read the local symbols.  */
10009   isymbuf = (Elf_Internal_Sym *) symtab_hdr->contents;
10010   if (isymbuf == NULL && locsymcount != 0)
10011     {
10012       isymbuf = bfd_elf_get_elf_syms (input_bfd, symtab_hdr, locsymcount, 0,
10013                                       flinfo->internal_syms,
10014                                       flinfo->external_syms,
10015                                       flinfo->locsym_shndx);
10016       if (isymbuf == NULL)
10017         return FALSE;
10018     }
10019
10020   /* Find local symbol sections and adjust values of symbols in
10021      SEC_MERGE sections.  Write out those local symbols we know are
10022      going into the output file.  */
10023   isymend = isymbuf + locsymcount;
10024   for (isym = isymbuf, pindex = flinfo->indices, ppsection = flinfo->sections;
10025        isym < isymend;
10026        isym++, pindex++, ppsection++)
10027     {
10028       asection *isec;
10029       const char *name;
10030       Elf_Internal_Sym osym;
10031       long indx;
10032       int ret;
10033
10034       *pindex = -1;
10035
10036       if (elf_bad_symtab (input_bfd))
10037         {
10038           if (ELF_ST_BIND (isym->st_info) != STB_LOCAL)
10039             {
10040               *ppsection = NULL;
10041               continue;
10042             }
10043         }
10044
10045       if (isym->st_shndx == SHN_UNDEF)
10046         isec = bfd_und_section_ptr;
10047       else if (isym->st_shndx == SHN_ABS)
10048         isec = bfd_abs_section_ptr;
10049       else if (isym->st_shndx == SHN_COMMON)
10050         isec = bfd_com_section_ptr;
10051       else
10052         {
10053           isec = bfd_section_from_elf_index (input_bfd, isym->st_shndx);
10054           if (isec == NULL)
10055             {
10056               /* Don't attempt to output symbols with st_shnx in the
10057                  reserved range other than SHN_ABS and SHN_COMMON.  */
10058               *ppsection = NULL;
10059               continue;
10060             }
10061           else if (isec->sec_info_type == SEC_INFO_TYPE_MERGE
10062                    && ELF_ST_TYPE (isym->st_info) != STT_SECTION)
10063             isym->st_value =
10064               _bfd_merged_section_offset (output_bfd, &isec,
10065                                           elf_section_data (isec)->sec_info,
10066                                           isym->st_value);
10067         }
10068
10069       *ppsection = isec;
10070
10071       /* Don't output the first, undefined, symbol.  In fact, don't
10072          output any undefined local symbol.  */
10073       if (isec == bfd_und_section_ptr)
10074         continue;
10075
10076       if (ELF_ST_TYPE (isym->st_info) == STT_SECTION)
10077         {
10078           /* We never output section symbols.  Instead, we use the
10079              section symbol of the corresponding section in the output
10080              file.  */
10081           continue;
10082         }
10083
10084       /* If we are stripping all symbols, we don't want to output this
10085          one.  */
10086       if (flinfo->info->strip == strip_all)
10087         continue;
10088
10089       /* If we are discarding all local symbols, we don't want to
10090          output this one.  If we are generating a relocatable output
10091          file, then some of the local symbols may be required by
10092          relocs; we output them below as we discover that they are
10093          needed.  */
10094       if (flinfo->info->discard == discard_all)
10095         continue;
10096
10097       /* If this symbol is defined in a section which we are
10098          discarding, we don't need to keep it.  */
10099       if (isym->st_shndx != SHN_UNDEF
10100           && isym->st_shndx < SHN_LORESERVE
10101           && bfd_section_removed_from_list (output_bfd,
10102                                             isec->output_section))
10103         continue;
10104
10105       /* Get the name of the symbol.  */
10106       name = bfd_elf_string_from_elf_section (input_bfd, symtab_hdr->sh_link,
10107                                               isym->st_name);
10108       if (name == NULL)
10109         return FALSE;
10110
10111       /* See if we are discarding symbols with this name.  */
10112       if ((flinfo->info->strip == strip_some
10113            && (bfd_hash_lookup (flinfo->info->keep_hash, name, FALSE, FALSE)
10114                == NULL))
10115           || (((flinfo->info->discard == discard_sec_merge
10116                 && (isec->flags & SEC_MERGE)
10117                 && !bfd_link_relocatable (flinfo->info))
10118                || flinfo->info->discard == discard_l)
10119               && bfd_is_local_label_name (input_bfd, name)))
10120         continue;
10121
10122       if (ELF_ST_TYPE (isym->st_info) == STT_FILE)
10123         {
10124           if (input_bfd->lto_output)
10125             /* -flto puts a temp file name here.  This means builds
10126                are not reproducible.  Discard the symbol.  */
10127             continue;
10128           have_file_sym = TRUE;
10129           flinfo->filesym_count += 1;
10130         }
10131       if (!have_file_sym)
10132         {
10133           /* In the absence of debug info, bfd_find_nearest_line uses
10134              FILE symbols to determine the source file for local
10135              function symbols.  Provide a FILE symbol here if input
10136              files lack such, so that their symbols won't be
10137              associated with a previous input file.  It's not the
10138              source file, but the best we can do.  */
10139           have_file_sym = TRUE;
10140           flinfo->filesym_count += 1;
10141           memset (&osym, 0, sizeof (osym));
10142           osym.st_info = ELF_ST_INFO (STB_LOCAL, STT_FILE);
10143           osym.st_shndx = SHN_ABS;
10144           if (!elf_link_output_symstrtab (flinfo,
10145                                           (input_bfd->lto_output ? NULL
10146                                            : input_bfd->filename),
10147                                           &osym, bfd_abs_section_ptr,
10148                                           NULL))
10149             return FALSE;
10150         }
10151
10152       osym = *isym;
10153
10154       /* Adjust the section index for the output file.  */
10155       osym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10156                                                          isec->output_section);
10157       if (osym.st_shndx == SHN_BAD)
10158         return FALSE;
10159
10160       /* ELF symbols in relocatable files are section relative, but
10161          in executable files they are virtual addresses.  Note that
10162          this code assumes that all ELF sections have an associated
10163          BFD section with a reasonable value for output_offset; below
10164          we assume that they also have a reasonable value for
10165          output_section.  Any special sections must be set up to meet
10166          these requirements.  */
10167       osym.st_value += isec->output_offset;
10168       if (!bfd_link_relocatable (flinfo->info))
10169         {
10170           osym.st_value += isec->output_section->vma;
10171           if (ELF_ST_TYPE (osym.st_info) == STT_TLS)
10172             {
10173               /* STT_TLS symbols are relative to PT_TLS segment base.  */
10174               BFD_ASSERT (elf_hash_table (flinfo->info)->tls_sec != NULL);
10175               osym.st_value -= elf_hash_table (flinfo->info)->tls_sec->vma;
10176             }
10177         }
10178
10179       indx = bfd_get_symcount (output_bfd);
10180       ret = elf_link_output_symstrtab (flinfo, name, &osym, isec, NULL);
10181       if (ret == 0)
10182         return FALSE;
10183       else if (ret == 1)
10184         *pindex = indx;
10185     }
10186
10187   if (bed->s->arch_size == 32)
10188     {
10189       r_type_mask = 0xff;
10190       r_sym_shift = 8;
10191       address_size = 4;
10192     }
10193   else
10194     {
10195       r_type_mask = 0xffffffff;
10196       r_sym_shift = 32;
10197       address_size = 8;
10198     }
10199
10200   /* Relocate the contents of each section.  */
10201   sym_hashes = elf_sym_hashes (input_bfd);
10202   for (o = input_bfd->sections; o != NULL; o = o->next)
10203     {
10204       bfd_byte *contents;
10205
10206       if (! o->linker_mark)
10207         {
10208           /* This section was omitted from the link.  */
10209           continue;
10210         }
10211
10212       if (bfd_link_relocatable (flinfo->info)
10213           && (o->flags & (SEC_LINKER_CREATED | SEC_GROUP)) == SEC_GROUP)
10214         {
10215           /* Deal with the group signature symbol.  */
10216           struct bfd_elf_section_data *sec_data = elf_section_data (o);
10217           unsigned long symndx = sec_data->this_hdr.sh_info;
10218           asection *osec = o->output_section;
10219
10220           if (symndx >= locsymcount
10221               || (elf_bad_symtab (input_bfd)
10222                   && flinfo->sections[symndx] == NULL))
10223             {
10224               struct elf_link_hash_entry *h = sym_hashes[symndx - extsymoff];
10225               while (h->root.type == bfd_link_hash_indirect
10226                      || h->root.type == bfd_link_hash_warning)
10227                 h = (struct elf_link_hash_entry *) h->root.u.i.link;
10228               /* Arrange for symbol to be output.  */
10229               h->indx = -2;
10230               elf_section_data (osec)->this_hdr.sh_info = -2;
10231             }
10232           else if (ELF_ST_TYPE (isymbuf[symndx].st_info) == STT_SECTION)
10233             {
10234               /* We'll use the output section target_index.  */
10235               asection *sec = flinfo->sections[symndx]->output_section;
10236               elf_section_data (osec)->this_hdr.sh_info = sec->target_index;
10237             }
10238           else
10239             {
10240               if (flinfo->indices[symndx] == -1)
10241                 {
10242                   /* Otherwise output the local symbol now.  */
10243                   Elf_Internal_Sym sym = isymbuf[symndx];
10244                   asection *sec = flinfo->sections[symndx]->output_section;
10245                   const char *name;
10246                   long indx;
10247                   int ret;
10248
10249                   name = bfd_elf_string_from_elf_section (input_bfd,
10250                                                           symtab_hdr->sh_link,
10251                                                           sym.st_name);
10252                   if (name == NULL)
10253                     return FALSE;
10254
10255                   sym.st_shndx = _bfd_elf_section_from_bfd_section (output_bfd,
10256                                                                     sec);
10257                   if (sym.st_shndx == SHN_BAD)
10258                     return FALSE;
10259
10260                   sym.st_value += o->output_offset;
10261
10262                   indx = bfd_get_symcount (output_bfd);
10263                   ret = elf_link_output_symstrtab (flinfo, name, &sym, o,
10264                                                    NULL);
10265                   if (ret == 0)
10266                     return FALSE;
10267                   else if (ret == 1)
10268                     flinfo->indices[symndx] = indx;
10269                   else
10270                     abort ();
10271                 }
10272               elf_section_data (osec)->this_hdr.sh_info
10273                 = flinfo->indices[symndx];
10274             }
10275         }
10276
10277       if ((o->flags & SEC_HAS_CONTENTS) == 0
10278           || (o->size == 0 && (o->flags & SEC_RELOC) == 0))
10279         continue;
10280
10281       if ((o->flags & SEC_LINKER_CREATED) != 0)
10282         {
10283           /* Section was created by _bfd_elf_link_create_dynamic_sections
10284              or somesuch.  */
10285           continue;
10286         }
10287
10288       /* Get the contents of the section.  They have been cached by a
10289          relaxation routine.  Note that o is a section in an input
10290          file, so the contents field will not have been set by any of
10291          the routines which work on output files.  */
10292       if (elf_section_data (o)->this_hdr.contents != NULL)
10293         {
10294           contents = elf_section_data (o)->this_hdr.contents;
10295           if (bed->caches_rawsize
10296               && o->rawsize != 0
10297               && o->rawsize < o->size)
10298             {
10299               memcpy (flinfo->contents, contents, o->rawsize);
10300               contents = flinfo->contents;
10301             }
10302         }
10303       else
10304         {
10305           contents = flinfo->contents;
10306           if (! bfd_get_full_section_contents (input_bfd, o, &contents))
10307             return FALSE;
10308         }
10309
10310       if ((o->flags & SEC_RELOC) != 0)
10311         {
10312           Elf_Internal_Rela *internal_relocs;
10313           Elf_Internal_Rela *rel, *relend;
10314           int action_discarded;
10315           int ret;
10316
10317           /* Get the swapped relocs.  */
10318           internal_relocs
10319             = _bfd_elf_link_read_relocs (input_bfd, o, flinfo->external_relocs,
10320                                          flinfo->internal_relocs, FALSE);
10321           if (internal_relocs == NULL
10322               && o->reloc_count > 0)
10323             return FALSE;
10324
10325           /* We need to reverse-copy input .ctors/.dtors sections if
10326              they are placed in .init_array/.finit_array for output.  */
10327           if (o->size > address_size
10328               && ((strncmp (o->name, ".ctors", 6) == 0
10329                    && strcmp (o->output_section->name,
10330                               ".init_array") == 0)
10331                   || (strncmp (o->name, ".dtors", 6) == 0
10332                       && strcmp (o->output_section->name,
10333                                  ".fini_array") == 0))
10334               && (o->name[6] == 0 || o->name[6] == '.'))
10335             {
10336               if (o->size != o->reloc_count * address_size)
10337                 {
10338                   _bfd_error_handler
10339                     /* xgettext:c-format */
10340                     (_("error: %B: size of section %A is not "
10341                        "multiple of address size"),
10342                      input_bfd, o);
10343                   bfd_set_error (bfd_error_on_input);
10344                   return FALSE;
10345                 }
10346               o->flags |= SEC_ELF_REVERSE_COPY;
10347             }
10348
10349           action_discarded = -1;
10350           if (!elf_section_ignore_discarded_relocs (o))
10351             action_discarded = (*bed->action_discarded) (o);
10352
10353           /* Run through the relocs evaluating complex reloc symbols and
10354              looking for relocs against symbols from discarded sections
10355              or section symbols from removed link-once sections.
10356              Complain about relocs against discarded sections.  Zero
10357              relocs against removed link-once sections.  */
10358
10359           rel = internal_relocs;
10360           relend = rel + o->reloc_count * bed->s->int_rels_per_ext_rel;
10361           for ( ; rel < relend; rel++)
10362             {
10363               unsigned long r_symndx = rel->r_info >> r_sym_shift;
10364               unsigned int s_type;
10365               asection **ps, *sec;
10366               struct elf_link_hash_entry *h = NULL;
10367               const char *sym_name;
10368
10369               if (r_symndx == STN_UNDEF)
10370                 continue;
10371
10372               if (r_symndx >= locsymcount
10373                   || (elf_bad_symtab (input_bfd)
10374                       && flinfo->sections[r_symndx] == NULL))
10375                 {
10376                   h = sym_hashes[r_symndx - extsymoff];
10377
10378                   /* Badly formatted input files can contain relocs that
10379                      reference non-existant symbols.  Check here so that
10380                      we do not seg fault.  */
10381                   if (h == NULL)
10382                     {
10383                       char buffer [32];
10384
10385                       sprintf_vma (buffer, rel->r_info);
10386                       _bfd_error_handler
10387                         /* xgettext:c-format */
10388                         (_("error: %B contains a reloc (0x%s) for section %A "
10389                            "that references a non-existent global symbol"),
10390                          input_bfd, o, buffer);
10391                       bfd_set_error (bfd_error_bad_value);
10392                       return FALSE;
10393                     }
10394
10395                   while (h->root.type == bfd_link_hash_indirect
10396                          || h->root.type == bfd_link_hash_warning)
10397                     h = (struct elf_link_hash_entry *) h->root.u.i.link;
10398
10399                   s_type = h->type;
10400
10401                   /* If a plugin symbol is referenced from a non-IR file,
10402                      mark the symbol as undefined.  Note that the
10403                      linker may attach linker created dynamic sections
10404                      to the plugin bfd.  Symbols defined in linker
10405                      created sections are not plugin symbols.  */
10406                   if (h->root.non_ir_ref
10407                       && (h->root.type == bfd_link_hash_defined
10408                           || h->root.type == bfd_link_hash_defweak)
10409                       && (h->root.u.def.section->flags
10410                           & SEC_LINKER_CREATED) == 0
10411                       && h->root.u.def.section->owner != NULL
10412                       && (h->root.u.def.section->owner->flags
10413                           & BFD_PLUGIN) != 0)
10414                     {
10415                       h->root.type = bfd_link_hash_undefined;
10416                       h->root.u.undef.abfd = h->root.u.def.section->owner;
10417                     }
10418
10419                   ps = NULL;
10420                   if (h->root.type == bfd_link_hash_defined
10421                       || h->root.type == bfd_link_hash_defweak)
10422                     ps = &h->root.u.def.section;
10423
10424                   sym_name = h->root.root.string;
10425                 }
10426               else
10427                 {
10428                   Elf_Internal_Sym *sym = isymbuf + r_symndx;
10429
10430                   s_type = ELF_ST_TYPE (sym->st_info);
10431                   ps = &flinfo->sections[r_symndx];
10432                   sym_name = bfd_elf_sym_name (input_bfd, symtab_hdr,
10433                                                sym, *ps);
10434                 }
10435
10436               if ((s_type == STT_RELC || s_type == STT_SRELC)
10437                   && !bfd_link_relocatable (flinfo->info))
10438                 {
10439                   bfd_vma val;
10440                   bfd_vma dot = (rel->r_offset
10441                                  + o->output_offset + o->output_section->vma);
10442 #ifdef DEBUG
10443                   printf ("Encountered a complex symbol!");
10444                   printf (" (input_bfd %s, section %s, reloc %ld\n",
10445                           input_bfd->filename, o->name,
10446                           (long) (rel - internal_relocs));
10447                   printf (" symbol: idx  %8.8lx, name %s\n",
10448                           r_symndx, sym_name);
10449                   printf (" reloc : info %8.8lx, addr %8.8lx\n",
10450                           (unsigned long) rel->r_info,
10451                           (unsigned long) rel->r_offset);
10452 #endif
10453                   if (!eval_symbol (&val, &sym_name, input_bfd, flinfo, dot,
10454                                     isymbuf, locsymcount, s_type == STT_SRELC))
10455                     return FALSE;
10456
10457                   /* Symbol evaluated OK.  Update to absolute value.  */
10458                   set_symbol_value (input_bfd, isymbuf, locsymcount,
10459                                     r_symndx, val);
10460                   continue;
10461                 }
10462
10463               if (action_discarded != -1 && ps != NULL)
10464                 {
10465                   /* Complain if the definition comes from a
10466                      discarded section.  */
10467                   if ((sec = *ps) != NULL && discarded_section (sec))
10468                     {
10469                       BFD_ASSERT (r_symndx != STN_UNDEF);
10470                       if (action_discarded & COMPLAIN)
10471                         (*flinfo->info->callbacks->einfo)
10472                           /* xgettext:c-format */
10473                           (_("%X`%s' referenced in section `%A' of %B: "
10474                              "defined in discarded section `%A' of %B\n"),
10475                            sym_name, o, input_bfd, sec, sec->owner);
10476
10477                       /* Try to do the best we can to support buggy old
10478                          versions of gcc.  Pretend that the symbol is
10479                          really defined in the kept linkonce section.
10480                          FIXME: This is quite broken.  Modifying the
10481                          symbol here means we will be changing all later
10482                          uses of the symbol, not just in this section.  */
10483                       if (action_discarded & PRETEND)
10484                         {
10485                           asection *kept;
10486
10487                           kept = _bfd_elf_check_kept_section (sec,
10488                                                               flinfo->info);
10489                           if (kept != NULL)
10490                             {
10491                               *ps = kept;
10492                               continue;
10493                             }
10494                         }
10495                     }
10496                 }
10497             }
10498
10499           /* Relocate the section by invoking a back end routine.
10500
10501              The back end routine is responsible for adjusting the
10502              section contents as necessary, and (if using Rela relocs
10503              and generating a relocatable output file) adjusting the
10504              reloc addend as necessary.
10505
10506              The back end routine does not have to worry about setting
10507              the reloc address or the reloc symbol index.
10508
10509              The back end routine is given a pointer to the swapped in
10510              internal symbols, and can access the hash table entries
10511              for the external symbols via elf_sym_hashes (input_bfd).
10512
10513              When generating relocatable output, the back end routine
10514              must handle STB_LOCAL/STT_SECTION symbols specially.  The
10515              output symbol is going to be a section symbol
10516              corresponding to the output section, which will require
10517              the addend to be adjusted.  */
10518
10519           ret = (*relocate_section) (output_bfd, flinfo->info,
10520                                      input_bfd, o, contents,
10521                                      internal_relocs,
10522                                      isymbuf,
10523                                      flinfo->sections);
10524           if (!ret)
10525             return FALSE;
10526
10527           if (ret == 2
10528               || bfd_link_relocatable (flinfo->info)
10529               || flinfo->info->emitrelocations)
10530             {
10531               Elf_Internal_Rela *irela;
10532               Elf_Internal_Rela *irelaend, *irelamid;
10533               bfd_vma last_offset;
10534               struct elf_link_hash_entry **rel_hash;
10535               struct elf_link_hash_entry **rel_hash_list, **rela_hash_list;
10536               Elf_Internal_Shdr *input_rel_hdr, *input_rela_hdr;
10537               unsigned int next_erel;
10538               bfd_boolean rela_normal;
10539               struct bfd_elf_section_data *esdi, *esdo;
10540
10541               esdi = elf_section_data (o);
10542               esdo = elf_section_data (o->output_section);
10543               rela_normal = FALSE;
10544
10545               /* Adjust the reloc addresses and symbol indices.  */
10546
10547               irela = internal_relocs;
10548               irelaend = irela + o->reloc_count * bed->s->int_rels_per_ext_rel;
10549               rel_hash = esdo->rel.hashes + esdo->rel.count;
10550               /* We start processing the REL relocs, if any.  When we reach
10551                  IRELAMID in the loop, we switch to the RELA relocs.  */
10552               irelamid = irela;
10553               if (esdi->rel.hdr != NULL)
10554                 irelamid += (NUM_SHDR_ENTRIES (esdi->rel.hdr)
10555                              * bed->s->int_rels_per_ext_rel);
10556               rel_hash_list = rel_hash;
10557               rela_hash_list = NULL;
10558               last_offset = o->output_offset;
10559               if (!bfd_link_relocatable (flinfo->info))
10560                 last_offset += o->output_section->vma;
10561               for (next_erel = 0; irela < irelaend; irela++, next_erel++)
10562                 {
10563                   unsigned long r_symndx;
10564                   asection *sec;
10565                   Elf_Internal_Sym sym;
10566
10567                   if (next_erel == bed->s->int_rels_per_ext_rel)
10568                     {
10569                       rel_hash++;
10570                       next_erel = 0;
10571                     }
10572
10573                   if (irela == irelamid)
10574                     {
10575                       rel_hash = esdo->rela.hashes + esdo->rela.count;
10576                       rela_hash_list = rel_hash;
10577                       rela_normal = bed->rela_normal;
10578                     }
10579
10580                   irela->r_offset = _bfd_elf_section_offset (output_bfd,
10581                                                              flinfo->info, o,
10582                                                              irela->r_offset);
10583                   if (irela->r_offset >= (bfd_vma) -2)
10584                     {
10585                       /* This is a reloc for a deleted entry or somesuch.
10586                          Turn it into an R_*_NONE reloc, at the same
10587                          offset as the last reloc.  elf_eh_frame.c and
10588                          bfd_elf_discard_info rely on reloc offsets
10589                          being ordered.  */
10590                       irela->r_offset = last_offset;
10591                       irela->r_info = 0;
10592                       irela->r_addend = 0;
10593                       continue;
10594                     }
10595
10596                   irela->r_offset += o->output_offset;
10597
10598                   /* Relocs in an executable have to be virtual addresses.  */
10599                   if (!bfd_link_relocatable (flinfo->info))
10600                     irela->r_offset += o->output_section->vma;
10601
10602                   last_offset = irela->r_offset;
10603
10604                   r_symndx = irela->r_info >> r_sym_shift;
10605                   if (r_symndx == STN_UNDEF)
10606                     continue;
10607
10608                   if (r_symndx >= locsymcount
10609                       || (elf_bad_symtab (input_bfd)
10610                           && flinfo->sections[r_symndx] == NULL))
10611                     {
10612                       struct elf_link_hash_entry *rh;
10613                       unsigned long indx;
10614
10615                       /* This is a reloc against a global symbol.  We
10616                          have not yet output all the local symbols, so
10617                          we do not know the symbol index of any global
10618                          symbol.  We set the rel_hash entry for this
10619                          reloc to point to the global hash table entry
10620                          for this symbol.  The symbol index is then
10621                          set at the end of bfd_elf_final_link.  */
10622                       indx = r_symndx - extsymoff;
10623                       rh = elf_sym_hashes (input_bfd)[indx];
10624                       while (rh->root.type == bfd_link_hash_indirect
10625                              || rh->root.type == bfd_link_hash_warning)
10626                         rh = (struct elf_link_hash_entry *) rh->root.u.i.link;
10627
10628                       /* Setting the index to -2 tells
10629                          elf_link_output_extsym that this symbol is
10630                          used by a reloc.  */
10631                       BFD_ASSERT (rh->indx < 0);
10632                       rh->indx = -2;
10633
10634                       *rel_hash = rh;
10635
10636                       continue;
10637                     }
10638
10639                   /* This is a reloc against a local symbol.  */
10640
10641                   *rel_hash = NULL;
10642                   sym = isymbuf[r_symndx];
10643                   sec = flinfo->sections[r_symndx];
10644                   if (ELF_ST_TYPE (sym.st_info) == STT_SECTION)
10645                     {
10646                       /* I suppose the backend ought to fill in the
10647                          section of any STT_SECTION symbol against a
10648                          processor specific section.  */
10649                       r_symndx = STN_UNDEF;
10650                       if (bfd_is_abs_section (sec))
10651                         ;
10652                       else if (sec == NULL || sec->owner == NULL)
10653                         {
10654                           bfd_set_error (bfd_error_bad_value);
10655                           return FALSE;
10656                         }
10657                       else
10658                         {
10659                           asection *osec = sec->output_section;
10660
10661                           /* If we have discarded a section, the output
10662                              section will be the absolute section.  In
10663                              case of discarded SEC_MERGE sections, use
10664                              the kept section.  relocate_section should
10665                              have already handled discarded linkonce
10666                              sections.  */
10667                           if (bfd_is_abs_section (osec)
10668                               && sec->kept_section != NULL
10669                               && sec->kept_section->output_section != NULL)
10670                             {
10671                               osec = sec->kept_section->output_section;
10672                               irela->r_addend -= osec->vma;
10673                             }
10674
10675                           if (!bfd_is_abs_section (osec))
10676                             {
10677                               r_symndx = osec->target_index;
10678                               if (r_symndx == STN_UNDEF)
10679                                 {
10680                                   irela->r_addend += osec->vma;
10681                                   osec = _bfd_nearby_section (output_bfd, osec,
10682                                                               osec->vma);
10683                                   irela->r_addend -= osec->vma;
10684                                   r_symndx = osec->target_index;
10685                                 }
10686                             }
10687                         }
10688
10689                       /* Adjust the addend according to where the
10690                          section winds up in the output section.  */
10691                       if (rela_normal)
10692                         irela->r_addend += sec->output_offset;
10693                     }
10694                   else
10695                     {
10696                       if (flinfo->indices[r_symndx] == -1)
10697                         {
10698                           unsigned long shlink;
10699                           const char *name;
10700                           asection *osec;
10701                           long indx;
10702
10703                           if (flinfo->info->strip == strip_all)
10704                             {
10705                               /* You can't do ld -r -s.  */
10706                               bfd_set_error (bfd_error_invalid_operation);
10707                               return FALSE;
10708                             }
10709
10710                           /* This symbol was skipped earlier, but
10711                              since it is needed by a reloc, we
10712                              must output it now.  */
10713                           shlink = symtab_hdr->sh_link;
10714                           name = (bfd_elf_string_from_elf_section
10715                                   (input_bfd, shlink, sym.st_name));
10716                           if (name == NULL)
10717                             return FALSE;
10718
10719                           osec = sec->output_section;
10720                           sym.st_shndx =
10721                             _bfd_elf_section_from_bfd_section (output_bfd,
10722                                                                osec);
10723                           if (sym.st_shndx == SHN_BAD)
10724                             return FALSE;
10725
10726                           sym.st_value += sec->output_offset;
10727                           if (!bfd_link_relocatable (flinfo->info))
10728                             {
10729                               sym.st_value += osec->vma;
10730                               if (ELF_ST_TYPE (sym.st_info) == STT_TLS)
10731                                 {
10732                                   /* STT_TLS symbols are relative to PT_TLS
10733                                      segment base.  */
10734                                   BFD_ASSERT (elf_hash_table (flinfo->info)
10735                                               ->tls_sec != NULL);
10736                                   sym.st_value -= (elf_hash_table (flinfo->info)
10737                                                    ->tls_sec->vma);
10738                                 }
10739                             }
10740
10741                           indx = bfd_get_symcount (output_bfd);
10742                           ret = elf_link_output_symstrtab (flinfo, name,
10743                                                            &sym, sec,
10744                                                            NULL);
10745                           if (ret == 0)
10746                             return FALSE;
10747                           else if (ret == 1)
10748                             flinfo->indices[r_symndx] = indx;
10749                           else
10750                             abort ();
10751                         }
10752
10753                       r_symndx = flinfo->indices[r_symndx];
10754                     }
10755
10756                   irela->r_info = ((bfd_vma) r_symndx << r_sym_shift
10757                                    | (irela->r_info & r_type_mask));
10758                 }
10759
10760               /* Swap out the relocs.  */
10761               input_rel_hdr = esdi->rel.hdr;
10762               if (input_rel_hdr && input_rel_hdr->sh_size != 0)
10763                 {
10764                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10765                                                      input_rel_hdr,
10766                                                      internal_relocs,
10767                                                      rel_hash_list))
10768                     return FALSE;
10769                   internal_relocs += (NUM_SHDR_ENTRIES (input_rel_hdr)
10770                                       * bed->s->int_rels_per_ext_rel);
10771                   rel_hash_list += NUM_SHDR_ENTRIES (input_rel_hdr);
10772                 }
10773
10774               input_rela_hdr = esdi->rela.hdr;
10775               if (input_rela_hdr && input_rela_hdr->sh_size != 0)
10776                 {
10777                   if (!bed->elf_backend_emit_relocs (output_bfd, o,
10778                                                      input_rela_hdr,
10779                                                      internal_relocs,
10780                                                      rela_hash_list))
10781                     return FALSE;
10782                 }
10783             }
10784         }
10785
10786       /* Write out the modified section contents.  */
10787       if (bed->elf_backend_write_section
10788           && (*bed->elf_backend_write_section) (output_bfd, flinfo->info, o,
10789                                                 contents))
10790         {
10791           /* Section written out.  */
10792         }
10793       else switch (o->sec_info_type)
10794         {
10795         case SEC_INFO_TYPE_STABS:
10796           if (! (_bfd_write_section_stabs
10797                  (output_bfd,
10798                   &elf_hash_table (flinfo->info)->stab_info,
10799                   o, &elf_section_data (o)->sec_info, contents)))
10800             return FALSE;
10801           break;
10802         case SEC_INFO_TYPE_MERGE:
10803           if (! _bfd_write_merged_section (output_bfd, o,
10804                                            elf_section_data (o)->sec_info))
10805             return FALSE;
10806           break;
10807         case SEC_INFO_TYPE_EH_FRAME:
10808           {
10809             if (! _bfd_elf_write_section_eh_frame (output_bfd, flinfo->info,
10810                                                    o, contents))
10811               return FALSE;
10812           }
10813           break;
10814         case SEC_INFO_TYPE_EH_FRAME_ENTRY:
10815           {
10816             if (! _bfd_elf_write_section_eh_frame_entry (output_bfd,
10817                                                          flinfo->info,
10818                                                          o, contents))
10819               return FALSE;
10820           }
10821           break;
10822         default:
10823           {
10824             if (! (o->flags & SEC_EXCLUDE))
10825               {
10826                 file_ptr offset = (file_ptr) o->output_offset;
10827                 bfd_size_type todo = o->size;
10828
10829                 offset *= bfd_octets_per_byte (output_bfd);
10830
10831                 if ((o->flags & SEC_ELF_REVERSE_COPY))
10832                   {
10833                     /* Reverse-copy input section to output.  */
10834                     do
10835                       {
10836                         todo -= address_size;
10837                         if (! bfd_set_section_contents (output_bfd,
10838                                                         o->output_section,
10839                                                         contents + todo,
10840                                                         offset,
10841                                                         address_size))
10842                           return FALSE;
10843                         if (todo == 0)
10844                           break;
10845                         offset += address_size;
10846                       }
10847                     while (1);
10848                   }
10849                 else if (! bfd_set_section_contents (output_bfd,
10850                                                      o->output_section,
10851                                                      contents,
10852                                                      offset, todo))
10853                   return FALSE;
10854               }
10855           }
10856           break;
10857         }
10858     }
10859
10860   return TRUE;
10861 }
10862
10863 /* Generate a reloc when linking an ELF file.  This is a reloc
10864    requested by the linker, and does not come from any input file.  This
10865    is used to build constructor and destructor tables when linking
10866    with -Ur.  */
10867
10868 static bfd_boolean
10869 elf_reloc_link_order (bfd *output_bfd,
10870                       struct bfd_link_info *info,
10871                       asection *output_section,
10872                       struct bfd_link_order *link_order)
10873 {
10874   reloc_howto_type *howto;
10875   long indx;
10876   bfd_vma offset;
10877   bfd_vma addend;
10878   struct bfd_elf_section_reloc_data *reldata;
10879   struct elf_link_hash_entry **rel_hash_ptr;
10880   Elf_Internal_Shdr *rel_hdr;
10881   const struct elf_backend_data *bed = get_elf_backend_data (output_bfd);
10882   Elf_Internal_Rela irel[MAX_INT_RELS_PER_EXT_REL];
10883   bfd_byte *erel;
10884   unsigned int i;
10885   struct bfd_elf_section_data *esdo = elf_section_data (output_section);
10886
10887   howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
10888   if (howto == NULL)
10889     {
10890       bfd_set_error (bfd_error_bad_value);
10891       return FALSE;
10892     }
10893
10894   addend = link_order->u.reloc.p->addend;
10895
10896   if (esdo->rel.hdr)
10897     reldata = &esdo->rel;
10898   else if (esdo->rela.hdr)
10899     reldata = &esdo->rela;
10900   else
10901     {
10902       reldata = NULL;
10903       BFD_ASSERT (0);
10904     }
10905
10906   /* Figure out the symbol index.  */
10907   rel_hash_ptr = reldata->hashes + reldata->count;
10908   if (link_order->type == bfd_section_reloc_link_order)
10909     {
10910       indx = link_order->u.reloc.p->u.section->target_index;
10911       BFD_ASSERT (indx != 0);
10912       *rel_hash_ptr = NULL;
10913     }
10914   else
10915     {
10916       struct elf_link_hash_entry *h;
10917
10918       /* Treat a reloc against a defined symbol as though it were
10919          actually against the section.  */
10920       h = ((struct elf_link_hash_entry *)
10921            bfd_wrapped_link_hash_lookup (output_bfd, info,
10922                                          link_order->u.reloc.p->u.name,
10923                                          FALSE, FALSE, TRUE));
10924       if (h != NULL
10925           && (h->root.type == bfd_link_hash_defined
10926               || h->root.type == bfd_link_hash_defweak))
10927         {
10928           asection *section;
10929
10930           section = h->root.u.def.section;
10931           indx = section->output_section->target_index;
10932           *rel_hash_ptr = NULL;
10933           /* It seems that we ought to add the symbol value to the
10934              addend here, but in practice it has already been added
10935              because it was passed to constructor_callback.  */
10936           addend += section->output_section->vma + section->output_offset;
10937         }
10938       else if (h != NULL)
10939         {
10940           /* Setting the index to -2 tells elf_link_output_extsym that
10941              this symbol is used by a reloc.  */
10942           h->indx = -2;
10943           *rel_hash_ptr = h;
10944           indx = 0;
10945         }
10946       else
10947         {
10948           (*info->callbacks->unattached_reloc)
10949             (info, link_order->u.reloc.p->u.name, NULL, NULL, 0);
10950           indx = 0;
10951         }
10952     }
10953
10954   /* If this is an inplace reloc, we must write the addend into the
10955      object file.  */
10956   if (howto->partial_inplace && addend != 0)
10957     {
10958       bfd_size_type size;
10959       bfd_reloc_status_type rstat;
10960       bfd_byte *buf;
10961       bfd_boolean ok;
10962       const char *sym_name;
10963
10964       size = (bfd_size_type) bfd_get_reloc_size (howto);
10965       buf = (bfd_byte *) bfd_zmalloc (size);
10966       if (buf == NULL && size != 0)
10967         return FALSE;
10968       rstat = _bfd_relocate_contents (howto, output_bfd, addend, buf);
10969       switch (rstat)
10970         {
10971         case bfd_reloc_ok:
10972           break;
10973
10974         default:
10975         case bfd_reloc_outofrange:
10976           abort ();
10977
10978         case bfd_reloc_overflow:
10979           if (link_order->type == bfd_section_reloc_link_order)
10980             sym_name = bfd_section_name (output_bfd,
10981                                          link_order->u.reloc.p->u.section);
10982           else
10983             sym_name = link_order->u.reloc.p->u.name;
10984           (*info->callbacks->reloc_overflow) (info, NULL, sym_name,
10985                                               howto->name, addend, NULL, NULL,
10986                                               (bfd_vma) 0);
10987           break;
10988         }
10989
10990       ok = bfd_set_section_contents (output_bfd, output_section, buf,
10991                                      link_order->offset
10992                                      * bfd_octets_per_byte (output_bfd),
10993                                      size);
10994       free (buf);
10995       if (! ok)
10996         return FALSE;
10997     }
10998
10999   /* The address of a reloc is relative to the section in a
11000      relocatable file, and is a virtual address in an executable
11001      file.  */
11002   offset = link_order->offset;
11003   if (! bfd_link_relocatable (info))
11004     offset += output_section->vma;
11005
11006   for (i = 0; i < bed->s->int_rels_per_ext_rel; i++)
11007     {
11008       irel[i].r_offset = offset;
11009       irel[i].r_info = 0;
11010       irel[i].r_addend = 0;
11011     }
11012   if (bed->s->arch_size == 32)
11013     irel[0].r_info = ELF32_R_INFO (indx, howto->type);
11014   else
11015     irel[0].r_info = ELF64_R_INFO (indx, howto->type);
11016
11017   rel_hdr = reldata->hdr;
11018   erel = rel_hdr->contents;
11019   if (rel_hdr->sh_type == SHT_REL)
11020     {
11021       erel += reldata->count * bed->s->sizeof_rel;
11022       (*bed->s->swap_reloc_out) (output_bfd, irel, erel);
11023     }
11024   else
11025     {
11026       irel[0].r_addend = addend;
11027       erel += reldata->count * bed->s->sizeof_rela;
11028       (*bed->s->swap_reloca_out) (output_bfd, irel, erel);
11029     }
11030
11031   ++reldata->count;
11032
11033   return TRUE;
11034 }
11035
11036
11037 /* Get the output vma of the section pointed to by the sh_link field.  */
11038
11039 static bfd_vma
11040 elf_get_linked_section_vma (struct bfd_link_order *p)
11041 {
11042   Elf_Internal_Shdr **elf_shdrp;
11043   asection *s;
11044   int elfsec;
11045
11046   s = p->u.indirect.section;
11047   elf_shdrp = elf_elfsections (s->owner);
11048   elfsec = _bfd_elf_section_from_bfd_section (s->owner, s);
11049   elfsec = elf_shdrp[elfsec]->sh_link;
11050   /* PR 290:
11051      The Intel C compiler generates SHT_IA_64_UNWIND with
11052      SHF_LINK_ORDER.  But it doesn't set the sh_link or
11053      sh_info fields.  Hence we could get the situation
11054      where elfsec is 0.  */
11055   if (elfsec == 0)
11056     {
11057       const struct elf_backend_data *bed
11058         = get_elf_backend_data (s->owner);
11059       if (bed->link_order_error_handler)
11060         bed->link_order_error_handler
11061           /* xgettext:c-format */
11062           (_("%B: warning: sh_link not set for section `%A'"), s->owner, s);
11063       return 0;
11064     }
11065   else
11066     {
11067       s = elf_shdrp[elfsec]->bfd_section;
11068       return s->output_section->vma + s->output_offset;
11069     }
11070 }
11071
11072
11073 /* Compare two sections based on the locations of the sections they are
11074    linked to.  Used by elf_fixup_link_order.  */
11075
11076 static int
11077 compare_link_order (const void * a, const void * b)
11078 {
11079   bfd_vma apos;
11080   bfd_vma bpos;
11081
11082   apos = elf_get_linked_section_vma (*(struct bfd_link_order **)a);
11083   bpos = elf_get_linked_section_vma (*(struct bfd_link_order **)b);
11084   if (apos < bpos)
11085     return -1;
11086   return apos > bpos;
11087 }
11088
11089
11090 /* Looks for sections with SHF_LINK_ORDER set.  Rearranges them into the same
11091    order as their linked sections.  Returns false if this could not be done
11092    because an output section includes both ordered and unordered
11093    sections.  Ideally we'd do this in the linker proper.  */
11094
11095 static bfd_boolean
11096 elf_fixup_link_order (bfd *abfd, asection *o)
11097 {
11098   int seen_linkorder;
11099   int seen_other;
11100   int n;
11101   struct bfd_link_order *p;
11102   bfd *sub;
11103   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11104   unsigned elfsec;
11105   struct bfd_link_order **sections;
11106   asection *s, *other_sec, *linkorder_sec;
11107   bfd_vma offset;
11108
11109   other_sec = NULL;
11110   linkorder_sec = NULL;
11111   seen_other = 0;
11112   seen_linkorder = 0;
11113   for (p = o->map_head.link_order; p != NULL; p = p->next)
11114     {
11115       if (p->type == bfd_indirect_link_order)
11116         {
11117           s = p->u.indirect.section;
11118           sub = s->owner;
11119           if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11120               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass
11121               && (elfsec = _bfd_elf_section_from_bfd_section (sub, s))
11122               && elfsec < elf_numsections (sub)
11123               && elf_elfsections (sub)[elfsec]->sh_flags & SHF_LINK_ORDER
11124               && elf_elfsections (sub)[elfsec]->sh_link < elf_numsections (sub))
11125             {
11126               seen_linkorder++;
11127               linkorder_sec = s;
11128             }
11129           else
11130             {
11131               seen_other++;
11132               other_sec = s;
11133             }
11134         }
11135       else
11136         seen_other++;
11137
11138       if (seen_other && seen_linkorder)
11139         {
11140           if (other_sec && linkorder_sec)
11141             _bfd_error_handler
11142               /* xgettext:c-format */
11143               (_("%A has both ordered [`%A' in %B] "
11144                  "and unordered [`%A' in %B] sections"),
11145                o, linkorder_sec,
11146                linkorder_sec->owner, other_sec,
11147                other_sec->owner);
11148           else
11149             _bfd_error_handler
11150               (_("%A has both ordered and unordered sections"), o);
11151           bfd_set_error (bfd_error_bad_value);
11152           return FALSE;
11153         }
11154     }
11155
11156   if (!seen_linkorder)
11157     return TRUE;
11158
11159   sections = (struct bfd_link_order **)
11160     bfd_malloc (seen_linkorder * sizeof (struct bfd_link_order *));
11161   if (sections == NULL)
11162     return FALSE;
11163   seen_linkorder = 0;
11164
11165   for (p = o->map_head.link_order; p != NULL; p = p->next)
11166     {
11167       sections[seen_linkorder++] = p;
11168     }
11169   /* Sort the input sections in the order of their linked section.  */
11170   qsort (sections, seen_linkorder, sizeof (struct bfd_link_order *),
11171          compare_link_order);
11172
11173   /* Change the offsets of the sections.  */
11174   offset = 0;
11175   for (n = 0; n < seen_linkorder; n++)
11176     {
11177       s = sections[n]->u.indirect.section;
11178       offset &= ~(bfd_vma) 0 << s->alignment_power;
11179       s->output_offset = offset / bfd_octets_per_byte (abfd);
11180       sections[n]->offset = offset;
11181       offset += sections[n]->size;
11182     }
11183
11184   free (sections);
11185   return TRUE;
11186 }
11187
11188 /* Generate an import library in INFO->implib_bfd from symbols in ABFD.
11189    Returns TRUE upon success, FALSE otherwise.  */
11190
11191 static bfd_boolean
11192 elf_output_implib (bfd *abfd, struct bfd_link_info *info)
11193 {
11194   bfd_boolean ret = FALSE;
11195   bfd *implib_bfd;
11196   const struct elf_backend_data *bed;
11197   flagword flags;
11198   enum bfd_architecture arch;
11199   unsigned int mach;
11200   asymbol **sympp = NULL;
11201   long symsize;
11202   long symcount;
11203   long src_count;
11204   elf_symbol_type *osymbuf;
11205
11206   implib_bfd = info->out_implib_bfd;
11207   bed = get_elf_backend_data (abfd);
11208
11209   if (!bfd_set_format (implib_bfd, bfd_object))
11210     return FALSE;
11211
11212   flags = bfd_get_file_flags (abfd);
11213   flags &= ~HAS_RELOC;
11214   if (!bfd_set_start_address (implib_bfd, 0)
11215       || !bfd_set_file_flags (implib_bfd, flags))
11216     return FALSE;
11217
11218   /* Copy architecture of output file to import library file.  */
11219   arch = bfd_get_arch (abfd);
11220   mach = bfd_get_mach (abfd);
11221   if (!bfd_set_arch_mach (implib_bfd, arch, mach)
11222       && (abfd->target_defaulted
11223           || bfd_get_arch (abfd) != bfd_get_arch (implib_bfd)))
11224     return FALSE;
11225
11226   /* Get symbol table size.  */
11227   symsize = bfd_get_symtab_upper_bound (abfd);
11228   if (symsize < 0)
11229     return FALSE;
11230
11231   /* Read in the symbol table.  */
11232   sympp = (asymbol **) xmalloc (symsize);
11233   symcount = bfd_canonicalize_symtab (abfd, sympp);
11234   if (symcount < 0)
11235     goto free_sym_buf;
11236
11237   /* Allow the BFD backend to copy any private header data it
11238      understands from the output BFD to the import library BFD.  */
11239   if (! bfd_copy_private_header_data (abfd, implib_bfd))
11240     goto free_sym_buf;
11241
11242   /* Filter symbols to appear in the import library.  */
11243   if (bed->elf_backend_filter_implib_symbols)
11244     symcount = bed->elf_backend_filter_implib_symbols (abfd, info, sympp,
11245                                                        symcount);
11246   else
11247     symcount = _bfd_elf_filter_global_symbols (abfd, info, sympp, symcount);
11248   if (symcount == 0)
11249     {
11250       bfd_set_error (bfd_error_no_symbols);
11251       _bfd_error_handler (_("%B: no symbol found for import library"),
11252                           implib_bfd);
11253       goto free_sym_buf;
11254     }
11255
11256
11257   /* Make symbols absolute.  */
11258   osymbuf = (elf_symbol_type *) bfd_alloc2 (implib_bfd, symcount,
11259                                             sizeof (*osymbuf));
11260   for (src_count = 0; src_count < symcount; src_count++)
11261     {
11262       memcpy (&osymbuf[src_count], (elf_symbol_type *) sympp[src_count],
11263               sizeof (*osymbuf));
11264       osymbuf[src_count].symbol.section = bfd_abs_section_ptr;
11265       osymbuf[src_count].internal_elf_sym.st_shndx = SHN_ABS;
11266       osymbuf[src_count].symbol.value += sympp[src_count]->section->vma;
11267       osymbuf[src_count].internal_elf_sym.st_value =
11268         osymbuf[src_count].symbol.value;
11269       sympp[src_count] = &osymbuf[src_count].symbol;
11270     }
11271
11272   bfd_set_symtab (implib_bfd, sympp, symcount);
11273
11274   /* Allow the BFD backend to copy any private data it understands
11275      from the output BFD to the import library BFD.  This is done last
11276      to permit the routine to look at the filtered symbol table.  */
11277   if (! bfd_copy_private_bfd_data (abfd, implib_bfd))
11278     goto free_sym_buf;
11279
11280   if (!bfd_close (implib_bfd))
11281     goto free_sym_buf;
11282
11283   ret = TRUE;
11284
11285 free_sym_buf:
11286   free (sympp);
11287   return ret;
11288 }
11289
11290 static void
11291 elf_final_link_free (bfd *obfd, struct elf_final_link_info *flinfo)
11292 {
11293   asection *o;
11294
11295   if (flinfo->symstrtab != NULL)
11296     _bfd_elf_strtab_free (flinfo->symstrtab);
11297   if (flinfo->contents != NULL)
11298     free (flinfo->contents);
11299   if (flinfo->external_relocs != NULL)
11300     free (flinfo->external_relocs);
11301   if (flinfo->internal_relocs != NULL)
11302     free (flinfo->internal_relocs);
11303   if (flinfo->external_syms != NULL)
11304     free (flinfo->external_syms);
11305   if (flinfo->locsym_shndx != NULL)
11306     free (flinfo->locsym_shndx);
11307   if (flinfo->internal_syms != NULL)
11308     free (flinfo->internal_syms);
11309   if (flinfo->indices != NULL)
11310     free (flinfo->indices);
11311   if (flinfo->sections != NULL)
11312     free (flinfo->sections);
11313   if (flinfo->symshndxbuf != NULL)
11314     free (flinfo->symshndxbuf);
11315   for (o = obfd->sections; o != NULL; o = o->next)
11316     {
11317       struct bfd_elf_section_data *esdo = elf_section_data (o);
11318       if ((o->flags & SEC_RELOC) != 0 && esdo->rel.hashes != NULL)
11319         free (esdo->rel.hashes);
11320       if ((o->flags & SEC_RELOC) != 0 && esdo->rela.hashes != NULL)
11321         free (esdo->rela.hashes);
11322     }
11323 }
11324
11325 /* Do the final step of an ELF link.  */
11326
11327 bfd_boolean
11328 bfd_elf_final_link (bfd *abfd, struct bfd_link_info *info)
11329 {
11330   bfd_boolean dynamic;
11331   bfd_boolean emit_relocs;
11332   bfd *dynobj;
11333   struct elf_final_link_info flinfo;
11334   asection *o;
11335   struct bfd_link_order *p;
11336   bfd *sub;
11337   bfd_size_type max_contents_size;
11338   bfd_size_type max_external_reloc_size;
11339   bfd_size_type max_internal_reloc_count;
11340   bfd_size_type max_sym_count;
11341   bfd_size_type max_sym_shndx_count;
11342   Elf_Internal_Sym elfsym;
11343   unsigned int i;
11344   Elf_Internal_Shdr *symtab_hdr;
11345   Elf_Internal_Shdr *symtab_shndx_hdr;
11346   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
11347   struct elf_outext_info eoinfo;
11348   bfd_boolean merged;
11349   size_t relativecount = 0;
11350   asection *reldyn = 0;
11351   bfd_size_type amt;
11352   asection *attr_section = NULL;
11353   bfd_vma attr_size = 0;
11354   const char *std_attrs_section;
11355   struct elf_link_hash_table *htab = elf_hash_table (info);
11356
11357   if (!is_elf_hash_table (htab))
11358     return FALSE;
11359
11360   if (bfd_link_pic (info))
11361     abfd->flags |= DYNAMIC;
11362
11363   dynamic = htab->dynamic_sections_created;
11364   dynobj = htab->dynobj;
11365
11366   emit_relocs = (bfd_link_relocatable (info)
11367                  || info->emitrelocations);
11368
11369   flinfo.info = info;
11370   flinfo.output_bfd = abfd;
11371   flinfo.symstrtab = _bfd_elf_strtab_init ();
11372   if (flinfo.symstrtab == NULL)
11373     return FALSE;
11374
11375   if (! dynamic)
11376     {
11377       flinfo.hash_sec = NULL;
11378       flinfo.symver_sec = NULL;
11379     }
11380   else
11381     {
11382       flinfo.hash_sec = bfd_get_linker_section (dynobj, ".hash");
11383       /* Note that dynsym_sec can be NULL (on VMS).  */
11384       flinfo.symver_sec = bfd_get_linker_section (dynobj, ".gnu.version");
11385       /* Note that it is OK if symver_sec is NULL.  */
11386     }
11387
11388   flinfo.contents = NULL;
11389   flinfo.external_relocs = NULL;
11390   flinfo.internal_relocs = NULL;
11391   flinfo.external_syms = NULL;
11392   flinfo.locsym_shndx = NULL;
11393   flinfo.internal_syms = NULL;
11394   flinfo.indices = NULL;
11395   flinfo.sections = NULL;
11396   flinfo.symshndxbuf = NULL;
11397   flinfo.filesym_count = 0;
11398
11399   /* The object attributes have been merged.  Remove the input
11400      sections from the link, and set the contents of the output
11401      secton.  */
11402   std_attrs_section = get_elf_backend_data (abfd)->obj_attrs_section;
11403   for (o = abfd->sections; o != NULL; o = o->next)
11404     {
11405       if ((std_attrs_section && strcmp (o->name, std_attrs_section) == 0)
11406           || strcmp (o->name, ".gnu.attributes") == 0)
11407         {
11408           for (p = o->map_head.link_order; p != NULL; p = p->next)
11409             {
11410               asection *input_section;
11411
11412               if (p->type != bfd_indirect_link_order)
11413                 continue;
11414               input_section = p->u.indirect.section;
11415               /* Hack: reset the SEC_HAS_CONTENTS flag so that
11416                  elf_link_input_bfd ignores this section.  */
11417               input_section->flags &= ~SEC_HAS_CONTENTS;
11418             }
11419
11420           attr_size = bfd_elf_obj_attr_size (abfd);
11421           if (attr_size)
11422             {
11423               bfd_set_section_size (abfd, o, attr_size);
11424               attr_section = o;
11425               /* Skip this section later on.  */
11426               o->map_head.link_order = NULL;
11427             }
11428           else
11429             o->flags |= SEC_EXCLUDE;
11430         }
11431     }
11432
11433   /* Count up the number of relocations we will output for each output
11434      section, so that we know the sizes of the reloc sections.  We
11435      also figure out some maximum sizes.  */
11436   max_contents_size = 0;
11437   max_external_reloc_size = 0;
11438   max_internal_reloc_count = 0;
11439   max_sym_count = 0;
11440   max_sym_shndx_count = 0;
11441   merged = FALSE;
11442   for (o = abfd->sections; o != NULL; o = o->next)
11443     {
11444       struct bfd_elf_section_data *esdo = elf_section_data (o);
11445       o->reloc_count = 0;
11446
11447       for (p = o->map_head.link_order; p != NULL; p = p->next)
11448         {
11449           unsigned int reloc_count = 0;
11450           unsigned int additional_reloc_count = 0;
11451           struct bfd_elf_section_data *esdi = NULL;
11452
11453           if (p->type == bfd_section_reloc_link_order
11454               || p->type == bfd_symbol_reloc_link_order)
11455             reloc_count = 1;
11456           else if (p->type == bfd_indirect_link_order)
11457             {
11458               asection *sec;
11459
11460               sec = p->u.indirect.section;
11461
11462               /* Mark all sections which are to be included in the
11463                  link.  This will normally be every section.  We need
11464                  to do this so that we can identify any sections which
11465                  the linker has decided to not include.  */
11466               sec->linker_mark = TRUE;
11467
11468               if (sec->flags & SEC_MERGE)
11469                 merged = TRUE;
11470
11471               if (sec->rawsize > max_contents_size)
11472                 max_contents_size = sec->rawsize;
11473               if (sec->size > max_contents_size)
11474                 max_contents_size = sec->size;
11475
11476               if (bfd_get_flavour (sec->owner) == bfd_target_elf_flavour
11477                   && (sec->owner->flags & DYNAMIC) == 0)
11478                 {
11479                   size_t sym_count;
11480
11481                   /* We are interested in just local symbols, not all
11482                      symbols.  */
11483                   if (elf_bad_symtab (sec->owner))
11484                     sym_count = (elf_tdata (sec->owner)->symtab_hdr.sh_size
11485                                  / bed->s->sizeof_sym);
11486                   else
11487                     sym_count = elf_tdata (sec->owner)->symtab_hdr.sh_info;
11488
11489                   if (sym_count > max_sym_count)
11490                     max_sym_count = sym_count;
11491
11492                   if (sym_count > max_sym_shndx_count
11493                       && elf_symtab_shndx_list (sec->owner) != NULL)
11494                     max_sym_shndx_count = sym_count;
11495
11496                   if (esdo->this_hdr.sh_type == SHT_REL
11497                       || esdo->this_hdr.sh_type == SHT_RELA)
11498                     /* Some backends use reloc_count in relocation sections
11499                        to count particular types of relocs.  Of course,
11500                        reloc sections themselves can't have relocations.  */
11501                     ;
11502                   else if (emit_relocs)
11503                     {
11504                       reloc_count = sec->reloc_count;
11505                       if (bed->elf_backend_count_additional_relocs)
11506                         {
11507                           int c;
11508                           c = (*bed->elf_backend_count_additional_relocs) (sec);
11509                           additional_reloc_count += c;
11510                         }
11511                     }
11512                   else if (bed->elf_backend_count_relocs)
11513                     reloc_count = (*bed->elf_backend_count_relocs) (info, sec);
11514
11515                   esdi = elf_section_data (sec);
11516
11517                   if ((sec->flags & SEC_RELOC) != 0)
11518                     {
11519                       size_t ext_size = 0;
11520
11521                       if (esdi->rel.hdr != NULL)
11522                         ext_size = esdi->rel.hdr->sh_size;
11523                       if (esdi->rela.hdr != NULL)
11524                         ext_size += esdi->rela.hdr->sh_size;
11525
11526                       if (ext_size > max_external_reloc_size)
11527                         max_external_reloc_size = ext_size;
11528                       if (sec->reloc_count > max_internal_reloc_count)
11529                         max_internal_reloc_count = sec->reloc_count;
11530                     }
11531                 }
11532             }
11533
11534           if (reloc_count == 0)
11535             continue;
11536
11537           reloc_count += additional_reloc_count;
11538           o->reloc_count += reloc_count;
11539
11540           if (p->type == bfd_indirect_link_order && emit_relocs)
11541             {
11542               if (esdi->rel.hdr)
11543                 {
11544                   esdo->rel.count += NUM_SHDR_ENTRIES (esdi->rel.hdr);
11545                   esdo->rel.count += additional_reloc_count;
11546                 }
11547               if (esdi->rela.hdr)
11548                 {
11549                   esdo->rela.count += NUM_SHDR_ENTRIES (esdi->rela.hdr);
11550                   esdo->rela.count += additional_reloc_count;
11551                 }
11552             }
11553           else
11554             {
11555               if (o->use_rela_p)
11556                 esdo->rela.count += reloc_count;
11557               else
11558                 esdo->rel.count += reloc_count;
11559             }
11560         }
11561
11562       if (o->reloc_count > 0)
11563         o->flags |= SEC_RELOC;
11564       else
11565         {
11566           /* Explicitly clear the SEC_RELOC flag.  The linker tends to
11567              set it (this is probably a bug) and if it is set
11568              assign_section_numbers will create a reloc section.  */
11569           o->flags &=~ SEC_RELOC;
11570         }
11571
11572       /* If the SEC_ALLOC flag is not set, force the section VMA to
11573          zero.  This is done in elf_fake_sections as well, but forcing
11574          the VMA to 0 here will ensure that relocs against these
11575          sections are handled correctly.  */
11576       if ((o->flags & SEC_ALLOC) == 0
11577           && ! o->user_set_vma)
11578         o->vma = 0;
11579     }
11580
11581   if (! bfd_link_relocatable (info) && merged)
11582     elf_link_hash_traverse (htab, _bfd_elf_link_sec_merge_syms, abfd);
11583
11584   /* Figure out the file positions for everything but the symbol table
11585      and the relocs.  We set symcount to force assign_section_numbers
11586      to create a symbol table.  */
11587   bfd_get_symcount (abfd) = info->strip != strip_all || emit_relocs;
11588   BFD_ASSERT (! abfd->output_has_begun);
11589   if (! _bfd_elf_compute_section_file_positions (abfd, info))
11590     goto error_return;
11591
11592   /* Set sizes, and assign file positions for reloc sections.  */
11593   for (o = abfd->sections; o != NULL; o = o->next)
11594     {
11595       struct bfd_elf_section_data *esdo = elf_section_data (o);
11596       if ((o->flags & SEC_RELOC) != 0)
11597         {
11598           if (esdo->rel.hdr
11599               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rel)))
11600             goto error_return;
11601
11602           if (esdo->rela.hdr
11603               && !(_bfd_elf_link_size_reloc_section (abfd, &esdo->rela)))
11604             goto error_return;
11605         }
11606
11607       /* Now, reset REL_COUNT and REL_COUNT2 so that we can use them
11608          to count upwards while actually outputting the relocations.  */
11609       esdo->rel.count = 0;
11610       esdo->rela.count = 0;
11611
11612       if (esdo->this_hdr.sh_offset == (file_ptr) -1)
11613         {
11614           /* Cache the section contents so that they can be compressed
11615              later.  Use bfd_malloc since it will be freed by
11616              bfd_compress_section_contents.  */
11617           unsigned char *contents = esdo->this_hdr.contents;
11618           if ((o->flags & SEC_ELF_COMPRESS) == 0 || contents != NULL)
11619             abort ();
11620           contents
11621             = (unsigned char *) bfd_malloc (esdo->this_hdr.sh_size);
11622           if (contents == NULL)
11623             goto error_return;
11624           esdo->this_hdr.contents = contents;
11625         }
11626     }
11627
11628   /* We have now assigned file positions for all the sections except
11629      .symtab, .strtab, and non-loaded reloc sections.  We start the
11630      .symtab section at the current file position, and write directly
11631      to it.  We build the .strtab section in memory.  */
11632   bfd_get_symcount (abfd) = 0;
11633   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
11634   /* sh_name is set in prep_headers.  */
11635   symtab_hdr->sh_type = SHT_SYMTAB;
11636   /* sh_flags, sh_addr and sh_size all start off zero.  */
11637   symtab_hdr->sh_entsize = bed->s->sizeof_sym;
11638   /* sh_link is set in assign_section_numbers.  */
11639   /* sh_info is set below.  */
11640   /* sh_offset is set just below.  */
11641   symtab_hdr->sh_addralign = (bfd_vma) 1 << bed->s->log_file_align;
11642
11643   if (max_sym_count < 20)
11644     max_sym_count = 20;
11645   htab->strtabsize = max_sym_count;
11646   amt = max_sym_count * sizeof (struct elf_sym_strtab);
11647   htab->strtab = (struct elf_sym_strtab *) bfd_malloc (amt);
11648   if (htab->strtab == NULL)
11649     goto error_return;
11650   /* The real buffer will be allocated in elf_link_swap_symbols_out.  */
11651   flinfo.symshndxbuf
11652     = (elf_numsections (abfd) > (SHN_LORESERVE & 0xFFFF)
11653        ? (Elf_External_Sym_Shndx *) -1 : NULL);
11654
11655   if (info->strip != strip_all || emit_relocs)
11656     {
11657       file_ptr off = elf_next_file_pos (abfd);
11658
11659       _bfd_elf_assign_file_position_for_section (symtab_hdr, off, TRUE);
11660
11661       /* Note that at this point elf_next_file_pos (abfd) is
11662          incorrect.  We do not yet know the size of the .symtab section.
11663          We correct next_file_pos below, after we do know the size.  */
11664
11665       /* Start writing out the symbol table.  The first symbol is always a
11666          dummy symbol.  */
11667       elfsym.st_value = 0;
11668       elfsym.st_size = 0;
11669       elfsym.st_info = 0;
11670       elfsym.st_other = 0;
11671       elfsym.st_shndx = SHN_UNDEF;
11672       elfsym.st_target_internal = 0;
11673       if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym,
11674                                      bfd_und_section_ptr, NULL) != 1)
11675         goto error_return;
11676
11677       /* Output a symbol for each section.  We output these even if we are
11678          discarding local symbols, since they are used for relocs.  These
11679          symbols have no names.  We store the index of each one in the
11680          index field of the section, so that we can find it again when
11681          outputting relocs.  */
11682
11683       elfsym.st_size = 0;
11684       elfsym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11685       elfsym.st_other = 0;
11686       elfsym.st_value = 0;
11687       elfsym.st_target_internal = 0;
11688       for (i = 1; i < elf_numsections (abfd); i++)
11689         {
11690           o = bfd_section_from_elf_index (abfd, i);
11691           if (o != NULL)
11692             {
11693               o->target_index = bfd_get_symcount (abfd);
11694               elfsym.st_shndx = i;
11695               if (!bfd_link_relocatable (info))
11696                 elfsym.st_value = o->vma;
11697               if (elf_link_output_symstrtab (&flinfo, NULL, &elfsym, o,
11698                                              NULL) != 1)
11699                 goto error_return;
11700             }
11701         }
11702     }
11703
11704   /* Allocate some memory to hold information read in from the input
11705      files.  */
11706   if (max_contents_size != 0)
11707     {
11708       flinfo.contents = (bfd_byte *) bfd_malloc (max_contents_size);
11709       if (flinfo.contents == NULL)
11710         goto error_return;
11711     }
11712
11713   if (max_external_reloc_size != 0)
11714     {
11715       flinfo.external_relocs = bfd_malloc (max_external_reloc_size);
11716       if (flinfo.external_relocs == NULL)
11717         goto error_return;
11718     }
11719
11720   if (max_internal_reloc_count != 0)
11721     {
11722       amt = max_internal_reloc_count * bed->s->int_rels_per_ext_rel;
11723       amt *= sizeof (Elf_Internal_Rela);
11724       flinfo.internal_relocs = (Elf_Internal_Rela *) bfd_malloc (amt);
11725       if (flinfo.internal_relocs == NULL)
11726         goto error_return;
11727     }
11728
11729   if (max_sym_count != 0)
11730     {
11731       amt = max_sym_count * bed->s->sizeof_sym;
11732       flinfo.external_syms = (bfd_byte *) bfd_malloc (amt);
11733       if (flinfo.external_syms == NULL)
11734         goto error_return;
11735
11736       amt = max_sym_count * sizeof (Elf_Internal_Sym);
11737       flinfo.internal_syms = (Elf_Internal_Sym *) bfd_malloc (amt);
11738       if (flinfo.internal_syms == NULL)
11739         goto error_return;
11740
11741       amt = max_sym_count * sizeof (long);
11742       flinfo.indices = (long int *) bfd_malloc (amt);
11743       if (flinfo.indices == NULL)
11744         goto error_return;
11745
11746       amt = max_sym_count * sizeof (asection *);
11747       flinfo.sections = (asection **) bfd_malloc (amt);
11748       if (flinfo.sections == NULL)
11749         goto error_return;
11750     }
11751
11752   if (max_sym_shndx_count != 0)
11753     {
11754       amt = max_sym_shndx_count * sizeof (Elf_External_Sym_Shndx);
11755       flinfo.locsym_shndx = (Elf_External_Sym_Shndx *) bfd_malloc (amt);
11756       if (flinfo.locsym_shndx == NULL)
11757         goto error_return;
11758     }
11759
11760   if (htab->tls_sec)
11761     {
11762       bfd_vma base, end = 0;
11763       asection *sec;
11764
11765       for (sec = htab->tls_sec;
11766            sec && (sec->flags & SEC_THREAD_LOCAL);
11767            sec = sec->next)
11768         {
11769           bfd_size_type size = sec->size;
11770
11771           if (size == 0
11772               && (sec->flags & SEC_HAS_CONTENTS) == 0)
11773             {
11774               struct bfd_link_order *ord = sec->map_tail.link_order;
11775
11776               if (ord != NULL)
11777                 size = ord->offset + ord->size;
11778             }
11779           end = sec->vma + size;
11780         }
11781       base = htab->tls_sec->vma;
11782       /* Only align end of TLS section if static TLS doesn't have special
11783          alignment requirements.  */
11784       if (bed->static_tls_alignment == 1)
11785         end = align_power (end, htab->tls_sec->alignment_power);
11786       htab->tls_size = end - base;
11787     }
11788
11789   /* Reorder SHF_LINK_ORDER sections.  */
11790   for (o = abfd->sections; o != NULL; o = o->next)
11791     {
11792       if (!elf_fixup_link_order (abfd, o))
11793         return FALSE;
11794     }
11795
11796   if (!_bfd_elf_fixup_eh_frame_hdr (info))
11797     return FALSE;
11798
11799   /* Since ELF permits relocations to be against local symbols, we
11800      must have the local symbols available when we do the relocations.
11801      Since we would rather only read the local symbols once, and we
11802      would rather not keep them in memory, we handle all the
11803      relocations for a single input file at the same time.
11804
11805      Unfortunately, there is no way to know the total number of local
11806      symbols until we have seen all of them, and the local symbol
11807      indices precede the global symbol indices.  This means that when
11808      we are generating relocatable output, and we see a reloc against
11809      a global symbol, we can not know the symbol index until we have
11810      finished examining all the local symbols to see which ones we are
11811      going to output.  To deal with this, we keep the relocations in
11812      memory, and don't output them until the end of the link.  This is
11813      an unfortunate waste of memory, but I don't see a good way around
11814      it.  Fortunately, it only happens when performing a relocatable
11815      link, which is not the common case.  FIXME: If keep_memory is set
11816      we could write the relocs out and then read them again; I don't
11817      know how bad the memory loss will be.  */
11818
11819   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11820     sub->output_has_begun = FALSE;
11821   for (o = abfd->sections; o != NULL; o = o->next)
11822     {
11823       for (p = o->map_head.link_order; p != NULL; p = p->next)
11824         {
11825           if (p->type == bfd_indirect_link_order
11826               && (bfd_get_flavour ((sub = p->u.indirect.section->owner))
11827                   == bfd_target_elf_flavour)
11828               && elf_elfheader (sub)->e_ident[EI_CLASS] == bed->s->elfclass)
11829             {
11830               if (! sub->output_has_begun)
11831                 {
11832                   if (! elf_link_input_bfd (&flinfo, sub))
11833                     goto error_return;
11834                   sub->output_has_begun = TRUE;
11835                 }
11836             }
11837           else if (p->type == bfd_section_reloc_link_order
11838                    || p->type == bfd_symbol_reloc_link_order)
11839             {
11840               if (! elf_reloc_link_order (abfd, info, o, p))
11841                 goto error_return;
11842             }
11843           else
11844             {
11845               if (! _bfd_default_link_order (abfd, info, o, p))
11846                 {
11847                   if (p->type == bfd_indirect_link_order
11848                       && (bfd_get_flavour (sub)
11849                           == bfd_target_elf_flavour)
11850                       && (elf_elfheader (sub)->e_ident[EI_CLASS]
11851                           != bed->s->elfclass))
11852                     {
11853                       const char *iclass, *oclass;
11854
11855                       switch (bed->s->elfclass)
11856                         {
11857                         case ELFCLASS64: oclass = "ELFCLASS64"; break;
11858                         case ELFCLASS32: oclass = "ELFCLASS32"; break;
11859                         case ELFCLASSNONE: oclass = "ELFCLASSNONE"; break;
11860                         default: abort ();
11861                         }
11862
11863                       switch (elf_elfheader (sub)->e_ident[EI_CLASS])
11864                         {
11865                         case ELFCLASS64: iclass = "ELFCLASS64"; break;
11866                         case ELFCLASS32: iclass = "ELFCLASS32"; break;
11867                         case ELFCLASSNONE: iclass = "ELFCLASSNONE"; break;
11868                         default: abort ();
11869                         }
11870
11871                       bfd_set_error (bfd_error_wrong_format);
11872                       _bfd_error_handler
11873                         /* xgettext:c-format */
11874                         (_("%B: file class %s incompatible with %s"),
11875                          sub, iclass, oclass);
11876                     }
11877
11878                   goto error_return;
11879                 }
11880             }
11881         }
11882     }
11883
11884   /* Free symbol buffer if needed.  */
11885   if (!info->reduce_memory_overheads)
11886     {
11887       for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
11888         if (bfd_get_flavour (sub) == bfd_target_elf_flavour
11889             && elf_tdata (sub)->symbuf)
11890           {
11891             free (elf_tdata (sub)->symbuf);
11892             elf_tdata (sub)->symbuf = NULL;
11893           }
11894     }
11895
11896   /* Output any global symbols that got converted to local in a
11897      version script or due to symbol visibility.  We do this in a
11898      separate step since ELF requires all local symbols to appear
11899      prior to any global symbols.  FIXME: We should only do this if
11900      some global symbols were, in fact, converted to become local.
11901      FIXME: Will this work correctly with the Irix 5 linker?  */
11902   eoinfo.failed = FALSE;
11903   eoinfo.flinfo = &flinfo;
11904   eoinfo.localsyms = TRUE;
11905   eoinfo.file_sym_done = FALSE;
11906   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
11907   if (eoinfo.failed)
11908     return FALSE;
11909
11910   /* If backend needs to output some local symbols not present in the hash
11911      table, do it now.  */
11912   if (bed->elf_backend_output_arch_local_syms
11913       && (info->strip != strip_all || emit_relocs))
11914     {
11915       typedef int (*out_sym_func)
11916         (void *, const char *, Elf_Internal_Sym *, asection *,
11917          struct elf_link_hash_entry *);
11918
11919       if (! ((*bed->elf_backend_output_arch_local_syms)
11920              (abfd, info, &flinfo,
11921               (out_sym_func) elf_link_output_symstrtab)))
11922         return FALSE;
11923     }
11924
11925   /* That wrote out all the local symbols.  Finish up the symbol table
11926      with the global symbols. Even if we want to strip everything we
11927      can, we still need to deal with those global symbols that got
11928      converted to local in a version script.  */
11929
11930   /* The sh_info field records the index of the first non local symbol.  */
11931   symtab_hdr->sh_info = bfd_get_symcount (abfd);
11932
11933   if (dynamic
11934       && htab->dynsym != NULL
11935       && htab->dynsym->output_section != bfd_abs_section_ptr)
11936     {
11937       Elf_Internal_Sym sym;
11938       bfd_byte *dynsym = htab->dynsym->contents;
11939
11940       o = htab->dynsym->output_section;
11941       elf_section_data (o)->this_hdr.sh_info = htab->local_dynsymcount + 1;
11942
11943       /* Write out the section symbols for the output sections.  */
11944       if (bfd_link_pic (info)
11945           || htab->is_relocatable_executable)
11946         {
11947           asection *s;
11948
11949           sym.st_size = 0;
11950           sym.st_name = 0;
11951           sym.st_info = ELF_ST_INFO (STB_LOCAL, STT_SECTION);
11952           sym.st_other = 0;
11953           sym.st_target_internal = 0;
11954
11955           for (s = abfd->sections; s != NULL; s = s->next)
11956             {
11957               int indx;
11958               bfd_byte *dest;
11959               long dynindx;
11960
11961               dynindx = elf_section_data (s)->dynindx;
11962               if (dynindx <= 0)
11963                 continue;
11964               indx = elf_section_data (s)->this_idx;
11965               BFD_ASSERT (indx > 0);
11966               sym.st_shndx = indx;
11967               if (! check_dynsym (abfd, &sym))
11968                 return FALSE;
11969               sym.st_value = s->vma;
11970               dest = dynsym + dynindx * bed->s->sizeof_sym;
11971               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
11972             }
11973         }
11974
11975       /* Write out the local dynsyms.  */
11976       if (htab->dynlocal)
11977         {
11978           struct elf_link_local_dynamic_entry *e;
11979           for (e = htab->dynlocal; e ; e = e->next)
11980             {
11981               asection *s;
11982               bfd_byte *dest;
11983
11984               /* Copy the internal symbol and turn off visibility.
11985                  Note that we saved a word of storage and overwrote
11986                  the original st_name with the dynstr_index.  */
11987               sym = e->isym;
11988               sym.st_other &= ~ELF_ST_VISIBILITY (-1);
11989
11990               s = bfd_section_from_elf_index (e->input_bfd,
11991                                               e->isym.st_shndx);
11992               if (s != NULL)
11993                 {
11994                   sym.st_shndx =
11995                     elf_section_data (s->output_section)->this_idx;
11996                   if (! check_dynsym (abfd, &sym))
11997                     return FALSE;
11998                   sym.st_value = (s->output_section->vma
11999                                   + s->output_offset
12000                                   + e->isym.st_value);
12001                 }
12002
12003               dest = dynsym + e->dynindx * bed->s->sizeof_sym;
12004               bed->s->swap_symbol_out (abfd, &sym, dest, 0);
12005             }
12006         }
12007     }
12008
12009   /* We get the global symbols from the hash table.  */
12010   eoinfo.failed = FALSE;
12011   eoinfo.localsyms = FALSE;
12012   eoinfo.flinfo = &flinfo;
12013   bfd_hash_traverse (&info->hash->table, elf_link_output_extsym, &eoinfo);
12014   if (eoinfo.failed)
12015     return FALSE;
12016
12017   /* If backend needs to output some symbols not present in the hash
12018      table, do it now.  */
12019   if (bed->elf_backend_output_arch_syms
12020       && (info->strip != strip_all || emit_relocs))
12021     {
12022       typedef int (*out_sym_func)
12023         (void *, const char *, Elf_Internal_Sym *, asection *,
12024          struct elf_link_hash_entry *);
12025
12026       if (! ((*bed->elf_backend_output_arch_syms)
12027              (abfd, info, &flinfo,
12028               (out_sym_func) elf_link_output_symstrtab)))
12029         return FALSE;
12030     }
12031
12032   /* Finalize the .strtab section.  */
12033   _bfd_elf_strtab_finalize (flinfo.symstrtab);
12034
12035   /* Swap out the .strtab section. */
12036   if (!elf_link_swap_symbols_out (&flinfo))
12037     return FALSE;
12038
12039   /* Now we know the size of the symtab section.  */
12040   if (bfd_get_symcount (abfd) > 0)
12041     {
12042       /* Finish up and write out the symbol string table (.strtab)
12043          section.  */
12044       Elf_Internal_Shdr *symstrtab_hdr = NULL;
12045       file_ptr off = symtab_hdr->sh_offset + symtab_hdr->sh_size;
12046
12047       if (elf_symtab_shndx_list (abfd))
12048         {
12049           symtab_shndx_hdr = & elf_symtab_shndx_list (abfd)->hdr;
12050
12051           if (symtab_shndx_hdr != NULL && symtab_shndx_hdr->sh_name != 0)
12052             {
12053               symtab_shndx_hdr->sh_type = SHT_SYMTAB_SHNDX;
12054               symtab_shndx_hdr->sh_entsize = sizeof (Elf_External_Sym_Shndx);
12055               symtab_shndx_hdr->sh_addralign = sizeof (Elf_External_Sym_Shndx);
12056               amt = bfd_get_symcount (abfd) * sizeof (Elf_External_Sym_Shndx);
12057               symtab_shndx_hdr->sh_size = amt;
12058
12059               off = _bfd_elf_assign_file_position_for_section (symtab_shndx_hdr,
12060                                                                off, TRUE);
12061
12062               if (bfd_seek (abfd, symtab_shndx_hdr->sh_offset, SEEK_SET) != 0
12063                   || (bfd_bwrite (flinfo.symshndxbuf, amt, abfd) != amt))
12064                 return FALSE;
12065             }
12066         }
12067
12068       symstrtab_hdr = &elf_tdata (abfd)->strtab_hdr;
12069       /* sh_name was set in prep_headers.  */
12070       symstrtab_hdr->sh_type = SHT_STRTAB;
12071       symstrtab_hdr->sh_flags = bed->elf_strtab_flags;
12072       symstrtab_hdr->sh_addr = 0;
12073       symstrtab_hdr->sh_size = _bfd_elf_strtab_size (flinfo.symstrtab);
12074       symstrtab_hdr->sh_entsize = 0;
12075       symstrtab_hdr->sh_link = 0;
12076       symstrtab_hdr->sh_info = 0;
12077       /* sh_offset is set just below.  */
12078       symstrtab_hdr->sh_addralign = 1;
12079
12080       off = _bfd_elf_assign_file_position_for_section (symstrtab_hdr,
12081                                                        off, TRUE);
12082       elf_next_file_pos (abfd) = off;
12083
12084       if (bfd_seek (abfd, symstrtab_hdr->sh_offset, SEEK_SET) != 0
12085           || ! _bfd_elf_strtab_emit (abfd, flinfo.symstrtab))
12086         return FALSE;
12087     }
12088
12089   if (info->out_implib_bfd && !elf_output_implib (abfd, info))
12090     {
12091       _bfd_error_handler (_("%B: failed to generate import library"),
12092                           info->out_implib_bfd);
12093       return FALSE;
12094     }
12095
12096   /* Adjust the relocs to have the correct symbol indices.  */
12097   for (o = abfd->sections; o != NULL; o = o->next)
12098     {
12099       struct bfd_elf_section_data *esdo = elf_section_data (o);
12100       bfd_boolean sort;
12101       if ((o->flags & SEC_RELOC) == 0)
12102         continue;
12103
12104       sort = bed->sort_relocs_p == NULL || (*bed->sort_relocs_p) (o);
12105       if (esdo->rel.hdr != NULL
12106           && !elf_link_adjust_relocs (abfd, o, &esdo->rel, sort))
12107         return FALSE;
12108       if (esdo->rela.hdr != NULL
12109           && !elf_link_adjust_relocs (abfd, o, &esdo->rela, sort))
12110         return FALSE;
12111
12112       /* Set the reloc_count field to 0 to prevent write_relocs from
12113          trying to swap the relocs out itself.  */
12114       o->reloc_count = 0;
12115     }
12116
12117   if (dynamic && info->combreloc && dynobj != NULL)
12118     relativecount = elf_link_sort_relocs (abfd, info, &reldyn);
12119
12120   /* If we are linking against a dynamic object, or generating a
12121      shared library, finish up the dynamic linking information.  */
12122   if (dynamic)
12123     {
12124       bfd_byte *dyncon, *dynconend;
12125
12126       /* Fix up .dynamic entries.  */
12127       o = bfd_get_linker_section (dynobj, ".dynamic");
12128       BFD_ASSERT (o != NULL);
12129
12130       dyncon = o->contents;
12131       dynconend = o->contents + o->size;
12132       for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12133         {
12134           Elf_Internal_Dyn dyn;
12135           const char *name;
12136           unsigned int type;
12137           bfd_size_type sh_size;
12138           bfd_vma sh_addr;
12139
12140           bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12141
12142           switch (dyn.d_tag)
12143             {
12144             default:
12145               continue;
12146             case DT_NULL:
12147               if (relativecount > 0 && dyncon + bed->s->sizeof_dyn < dynconend)
12148                 {
12149                   switch (elf_section_data (reldyn)->this_hdr.sh_type)
12150                     {
12151                     case SHT_REL: dyn.d_tag = DT_RELCOUNT; break;
12152                     case SHT_RELA: dyn.d_tag = DT_RELACOUNT; break;
12153                     default: continue;
12154                     }
12155                   dyn.d_un.d_val = relativecount;
12156                   relativecount = 0;
12157                   break;
12158                 }
12159               continue;
12160
12161             case DT_INIT:
12162               name = info->init_function;
12163               goto get_sym;
12164             case DT_FINI:
12165               name = info->fini_function;
12166             get_sym:
12167               {
12168                 struct elf_link_hash_entry *h;
12169
12170                 h = elf_link_hash_lookup (htab, name, FALSE, FALSE, TRUE);
12171                 if (h != NULL
12172                     && (h->root.type == bfd_link_hash_defined
12173                         || h->root.type == bfd_link_hash_defweak))
12174                   {
12175                     dyn.d_un.d_ptr = h->root.u.def.value;
12176                     o = h->root.u.def.section;
12177                     if (o->output_section != NULL)
12178                       dyn.d_un.d_ptr += (o->output_section->vma
12179                                          + o->output_offset);
12180                     else
12181                       {
12182                         /* The symbol is imported from another shared
12183                            library and does not apply to this one.  */
12184                         dyn.d_un.d_ptr = 0;
12185                       }
12186                     break;
12187                   }
12188               }
12189               continue;
12190
12191             case DT_PREINIT_ARRAYSZ:
12192               name = ".preinit_array";
12193               goto get_out_size;
12194             case DT_INIT_ARRAYSZ:
12195               name = ".init_array";
12196               goto get_out_size;
12197             case DT_FINI_ARRAYSZ:
12198               name = ".fini_array";
12199             get_out_size:
12200               o = bfd_get_section_by_name (abfd, name);
12201               if (o == NULL)
12202                 {
12203                   _bfd_error_handler
12204                     (_("could not find section %s"), name);
12205                   goto error_return;
12206                 }
12207               if (o->size == 0)
12208                 _bfd_error_handler
12209                   (_("warning: %s section has zero size"), name);
12210               dyn.d_un.d_val = o->size;
12211               break;
12212
12213             case DT_PREINIT_ARRAY:
12214               name = ".preinit_array";
12215               goto get_out_vma;
12216             case DT_INIT_ARRAY:
12217               name = ".init_array";
12218               goto get_out_vma;
12219             case DT_FINI_ARRAY:
12220               name = ".fini_array";
12221             get_out_vma:
12222               o = bfd_get_section_by_name (abfd, name);
12223               goto do_vma;
12224
12225             case DT_HASH:
12226               name = ".hash";
12227               goto get_vma;
12228             case DT_GNU_HASH:
12229               name = ".gnu.hash";
12230               goto get_vma;
12231             case DT_STRTAB:
12232               name = ".dynstr";
12233               goto get_vma;
12234             case DT_SYMTAB:
12235               name = ".dynsym";
12236               goto get_vma;
12237             case DT_VERDEF:
12238               name = ".gnu.version_d";
12239               goto get_vma;
12240             case DT_VERNEED:
12241               name = ".gnu.version_r";
12242               goto get_vma;
12243             case DT_VERSYM:
12244               name = ".gnu.version";
12245             get_vma:
12246               o = bfd_get_linker_section (dynobj, name);
12247             do_vma:
12248               if (o == NULL)
12249                 {
12250                   _bfd_error_handler
12251                     (_("could not find section %s"), name);
12252                   goto error_return;
12253                 }
12254               if (elf_section_data (o->output_section)->this_hdr.sh_type == SHT_NOTE)
12255                 {
12256                   _bfd_error_handler
12257                     (_("warning: section '%s' is being made into a note"), name);
12258                   bfd_set_error (bfd_error_nonrepresentable_section);
12259                   goto error_return;
12260                 }
12261               dyn.d_un.d_ptr = o->output_section->vma + o->output_offset;
12262               break;
12263
12264             case DT_REL:
12265             case DT_RELA:
12266             case DT_RELSZ:
12267             case DT_RELASZ:
12268               if (dyn.d_tag == DT_REL || dyn.d_tag == DT_RELSZ)
12269                 type = SHT_REL;
12270               else
12271                 type = SHT_RELA;
12272               sh_size = 0;
12273               sh_addr = 0;
12274               for (i = 1; i < elf_numsections (abfd); i++)
12275                 {
12276                   Elf_Internal_Shdr *hdr;
12277
12278                   hdr = elf_elfsections (abfd)[i];
12279                   if (hdr->sh_type == type
12280                       && (hdr->sh_flags & SHF_ALLOC) != 0)
12281                     {
12282                       sh_size += hdr->sh_size;
12283                       if (sh_addr == 0
12284                           || sh_addr > hdr->sh_addr)
12285                         sh_addr = hdr->sh_addr;
12286                     }
12287                 }
12288
12289               if (bed->dtrel_excludes_plt && htab->srelplt != NULL)
12290                 {
12291                   /* Don't count procedure linkage table relocs in the
12292                      overall reloc count.  */
12293                   sh_size -= htab->srelplt->size;
12294                   if (sh_size == 0)
12295                     /* If the size is zero, make the address zero too.
12296                        This is to avoid a glibc bug.  If the backend
12297                        emits DT_RELA/DT_RELASZ even when DT_RELASZ is
12298                        zero, then we'll put DT_RELA at the end of
12299                        DT_JMPREL.  glibc will interpret the end of
12300                        DT_RELA matching the end of DT_JMPREL as the
12301                        case where DT_RELA includes DT_JMPREL, and for
12302                        LD_BIND_NOW will decide that processing DT_RELA
12303                        will process the PLT relocs too.  Net result:
12304                        No PLT relocs applied.  */
12305                     sh_addr = 0;
12306
12307                   /* If .rela.plt is the first .rela section, exclude
12308                      it from DT_RELA.  */
12309                   else if (sh_addr == (htab->srelplt->output_section->vma
12310                                        + htab->srelplt->output_offset))
12311                     sh_addr += htab->srelplt->size;
12312                 }
12313
12314               if (dyn.d_tag == DT_RELSZ || dyn.d_tag == DT_RELASZ)
12315                 dyn.d_un.d_val = sh_size;
12316               else
12317                 dyn.d_un.d_ptr = sh_addr;
12318               break;
12319             }
12320           bed->s->swap_dyn_out (dynobj, &dyn, dyncon);
12321         }
12322     }
12323
12324   /* If we have created any dynamic sections, then output them.  */
12325   if (dynobj != NULL)
12326     {
12327       if (! (*bed->elf_backend_finish_dynamic_sections) (abfd, info))
12328         goto error_return;
12329
12330       /* Check for DT_TEXTREL (late, in case the backend removes it).  */
12331       if (((info->warn_shared_textrel && bfd_link_pic (info))
12332            || info->error_textrel)
12333           && (o = bfd_get_linker_section (dynobj, ".dynamic")) != NULL)
12334         {
12335           bfd_byte *dyncon, *dynconend;
12336
12337           dyncon = o->contents;
12338           dynconend = o->contents + o->size;
12339           for (; dyncon < dynconend; dyncon += bed->s->sizeof_dyn)
12340             {
12341               Elf_Internal_Dyn dyn;
12342
12343               bed->s->swap_dyn_in (dynobj, dyncon, &dyn);
12344
12345               if (dyn.d_tag == DT_TEXTREL)
12346                 {
12347                   if (info->error_textrel)
12348                     info->callbacks->einfo
12349                       (_("%P%X: read-only segment has dynamic relocations.\n"));
12350                   else
12351                     info->callbacks->einfo
12352                       (_("%P: warning: creating a DT_TEXTREL in a shared object.\n"));
12353                   break;
12354                 }
12355             }
12356         }
12357
12358       for (o = dynobj->sections; o != NULL; o = o->next)
12359         {
12360           if ((o->flags & SEC_HAS_CONTENTS) == 0
12361               || o->size == 0
12362               || o->output_section == bfd_abs_section_ptr)
12363             continue;
12364           if ((o->flags & SEC_LINKER_CREATED) == 0)
12365             {
12366               /* At this point, we are only interested in sections
12367                  created by _bfd_elf_link_create_dynamic_sections.  */
12368               continue;
12369             }
12370           if (htab->stab_info.stabstr == o)
12371             continue;
12372           if (htab->eh_info.hdr_sec == o)
12373             continue;
12374           if (strcmp (o->name, ".dynstr") != 0)
12375             {
12376               if (! bfd_set_section_contents (abfd, o->output_section,
12377                                               o->contents,
12378                                               (file_ptr) o->output_offset
12379                                               * bfd_octets_per_byte (abfd),
12380                                               o->size))
12381                 goto error_return;
12382             }
12383           else
12384             {
12385               /* The contents of the .dynstr section are actually in a
12386                  stringtab.  */
12387               file_ptr off;
12388
12389               off = elf_section_data (o->output_section)->this_hdr.sh_offset;
12390               if (bfd_seek (abfd, off, SEEK_SET) != 0
12391                   || !_bfd_elf_strtab_emit (abfd, htab->dynstr))
12392                 goto error_return;
12393             }
12394         }
12395     }
12396
12397   if (bfd_link_relocatable (info))
12398     {
12399       bfd_boolean failed = FALSE;
12400
12401       bfd_map_over_sections (abfd, bfd_elf_set_group_contents, &failed);
12402       if (failed)
12403         goto error_return;
12404     }
12405
12406   /* If we have optimized stabs strings, output them.  */
12407   if (htab->stab_info.stabstr != NULL)
12408     {
12409       if (!_bfd_write_stab_strings (abfd, &htab->stab_info))
12410         goto error_return;
12411     }
12412
12413   if (! _bfd_elf_write_section_eh_frame_hdr (abfd, info))
12414     goto error_return;
12415
12416   elf_final_link_free (abfd, &flinfo);
12417
12418   elf_linker (abfd) = TRUE;
12419
12420   if (attr_section)
12421     {
12422       bfd_byte *contents = (bfd_byte *) bfd_malloc (attr_size);
12423       if (contents == NULL)
12424         return FALSE;   /* Bail out and fail.  */
12425       bfd_elf_set_obj_attr_contents (abfd, contents, attr_size);
12426       bfd_set_section_contents (abfd, attr_section, contents, 0, attr_size);
12427       free (contents);
12428     }
12429
12430   return TRUE;
12431
12432  error_return:
12433   elf_final_link_free (abfd, &flinfo);
12434   return FALSE;
12435 }
12436 \f
12437 /* Initialize COOKIE for input bfd ABFD.  */
12438
12439 static bfd_boolean
12440 init_reloc_cookie (struct elf_reloc_cookie *cookie,
12441                    struct bfd_link_info *info, bfd *abfd)
12442 {
12443   Elf_Internal_Shdr *symtab_hdr;
12444   const struct elf_backend_data *bed;
12445
12446   bed = get_elf_backend_data (abfd);
12447   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12448
12449   cookie->abfd = abfd;
12450   cookie->sym_hashes = elf_sym_hashes (abfd);
12451   cookie->bad_symtab = elf_bad_symtab (abfd);
12452   if (cookie->bad_symtab)
12453     {
12454       cookie->locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
12455       cookie->extsymoff = 0;
12456     }
12457   else
12458     {
12459       cookie->locsymcount = symtab_hdr->sh_info;
12460       cookie->extsymoff = symtab_hdr->sh_info;
12461     }
12462
12463   if (bed->s->arch_size == 32)
12464     cookie->r_sym_shift = 8;
12465   else
12466     cookie->r_sym_shift = 32;
12467
12468   cookie->locsyms = (Elf_Internal_Sym *) symtab_hdr->contents;
12469   if (cookie->locsyms == NULL && cookie->locsymcount != 0)
12470     {
12471       cookie->locsyms = bfd_elf_get_elf_syms (abfd, symtab_hdr,
12472                                               cookie->locsymcount, 0,
12473                                               NULL, NULL, NULL);
12474       if (cookie->locsyms == NULL)
12475         {
12476           info->callbacks->einfo (_("%P%X: can not read symbols: %E\n"));
12477           return FALSE;
12478         }
12479       if (info->keep_memory)
12480         symtab_hdr->contents = (bfd_byte *) cookie->locsyms;
12481     }
12482   return TRUE;
12483 }
12484
12485 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
12486
12487 static void
12488 fini_reloc_cookie (struct elf_reloc_cookie *cookie, bfd *abfd)
12489 {
12490   Elf_Internal_Shdr *symtab_hdr;
12491
12492   symtab_hdr = &elf_tdata (abfd)->symtab_hdr;
12493   if (cookie->locsyms != NULL
12494       && symtab_hdr->contents != (unsigned char *) cookie->locsyms)
12495     free (cookie->locsyms);
12496 }
12497
12498 /* Initialize the relocation information in COOKIE for input section SEC
12499    of input bfd ABFD.  */
12500
12501 static bfd_boolean
12502 init_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12503                         struct bfd_link_info *info, bfd *abfd,
12504                         asection *sec)
12505 {
12506   const struct elf_backend_data *bed;
12507
12508   if (sec->reloc_count == 0)
12509     {
12510       cookie->rels = NULL;
12511       cookie->relend = NULL;
12512     }
12513   else
12514     {
12515       bed = get_elf_backend_data (abfd);
12516
12517       cookie->rels = _bfd_elf_link_read_relocs (abfd, sec, NULL, NULL,
12518                                                 info->keep_memory);
12519       if (cookie->rels == NULL)
12520         return FALSE;
12521       cookie->rel = cookie->rels;
12522       cookie->relend = (cookie->rels
12523                         + sec->reloc_count * bed->s->int_rels_per_ext_rel);
12524     }
12525   cookie->rel = cookie->rels;
12526   return TRUE;
12527 }
12528
12529 /* Free the memory allocated by init_reloc_cookie_rels,
12530    if appropriate.  */
12531
12532 static void
12533 fini_reloc_cookie_rels (struct elf_reloc_cookie *cookie,
12534                         asection *sec)
12535 {
12536   if (cookie->rels && elf_section_data (sec)->relocs != cookie->rels)
12537     free (cookie->rels);
12538 }
12539
12540 /* Initialize the whole of COOKIE for input section SEC.  */
12541
12542 static bfd_boolean
12543 init_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12544                                struct bfd_link_info *info,
12545                                asection *sec)
12546 {
12547   if (!init_reloc_cookie (cookie, info, sec->owner))
12548     goto error1;
12549   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
12550     goto error2;
12551   return TRUE;
12552
12553  error2:
12554   fini_reloc_cookie (cookie, sec->owner);
12555  error1:
12556   return FALSE;
12557 }
12558
12559 /* Free the memory allocated by init_reloc_cookie_for_section,
12560    if appropriate.  */
12561
12562 static void
12563 fini_reloc_cookie_for_section (struct elf_reloc_cookie *cookie,
12564                                asection *sec)
12565 {
12566   fini_reloc_cookie_rels (cookie, sec);
12567   fini_reloc_cookie (cookie, sec->owner);
12568 }
12569 \f
12570 /* Garbage collect unused sections.  */
12571
12572 /* Default gc_mark_hook.  */
12573
12574 asection *
12575 _bfd_elf_gc_mark_hook (asection *sec,
12576                        struct bfd_link_info *info ATTRIBUTE_UNUSED,
12577                        Elf_Internal_Rela *rel ATTRIBUTE_UNUSED,
12578                        struct elf_link_hash_entry *h,
12579                        Elf_Internal_Sym *sym)
12580 {
12581   if (h != NULL)
12582     {
12583       switch (h->root.type)
12584         {
12585         case bfd_link_hash_defined:
12586         case bfd_link_hash_defweak:
12587           return h->root.u.def.section;
12588
12589         case bfd_link_hash_common:
12590           return h->root.u.c.p->section;
12591
12592         default:
12593           break;
12594         }
12595     }
12596   else
12597     return bfd_section_from_elf_index (sec->owner, sym->st_shndx);
12598
12599   return NULL;
12600 }
12601
12602 /* For undefined __start_<name> and __stop_<name> symbols, return the
12603    first input section matching <name>.  Return NULL otherwise.  */
12604
12605 asection *
12606 _bfd_elf_is_start_stop (const struct bfd_link_info *info,
12607                         struct elf_link_hash_entry *h)
12608 {
12609   asection *s;
12610   const char *sec_name;
12611
12612   if (h->root.type != bfd_link_hash_undefined
12613       && h->root.type != bfd_link_hash_undefweak)
12614     return NULL;
12615
12616   s = h->root.u.undef.section;
12617   if (s != NULL)
12618     {
12619       if (s == (asection *) 0 - 1)
12620         return NULL;
12621       return s;
12622     }
12623
12624   sec_name = NULL;
12625   if (strncmp (h->root.root.string, "__start_", 8) == 0)
12626     sec_name = h->root.root.string + 8;
12627   else if (strncmp (h->root.root.string, "__stop_", 7) == 0)
12628     sec_name = h->root.root.string + 7;
12629
12630   if (sec_name != NULL && *sec_name != '\0')
12631     {
12632       bfd *i;
12633
12634       for (i = info->input_bfds; i != NULL; i = i->link.next)
12635         {
12636           s = bfd_get_section_by_name (i, sec_name);
12637           if (s != NULL)
12638             {
12639               h->root.u.undef.section = s;
12640               break;
12641             }
12642         }
12643     }
12644
12645   if (s == NULL)
12646     h->root.u.undef.section = (asection *) 0 - 1;
12647
12648   return s;
12649 }
12650
12651 /* COOKIE->rel describes a relocation against section SEC, which is
12652    a section we've decided to keep.  Return the section that contains
12653    the relocation symbol, or NULL if no section contains it.  */
12654
12655 asection *
12656 _bfd_elf_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
12657                        elf_gc_mark_hook_fn gc_mark_hook,
12658                        struct elf_reloc_cookie *cookie,
12659                        bfd_boolean *start_stop)
12660 {
12661   unsigned long r_symndx;
12662   struct elf_link_hash_entry *h;
12663
12664   r_symndx = cookie->rel->r_info >> cookie->r_sym_shift;
12665   if (r_symndx == STN_UNDEF)
12666     return NULL;
12667
12668   if (r_symndx >= cookie->locsymcount
12669       || ELF_ST_BIND (cookie->locsyms[r_symndx].st_info) != STB_LOCAL)
12670     {
12671       h = cookie->sym_hashes[r_symndx - cookie->extsymoff];
12672       if (h == NULL)
12673         {
12674           info->callbacks->einfo (_("%F%P: corrupt input: %B\n"),
12675                                   sec->owner);
12676           return NULL;
12677         }
12678       while (h->root.type == bfd_link_hash_indirect
12679              || h->root.type == bfd_link_hash_warning)
12680         h = (struct elf_link_hash_entry *) h->root.u.i.link;
12681       h->mark = 1;
12682       /* If this symbol is weak and there is a non-weak definition, we
12683          keep the non-weak definition because many backends put
12684          dynamic reloc info on the non-weak definition for code
12685          handling copy relocs.  */
12686       if (h->u.weakdef != NULL)
12687         h->u.weakdef->mark = 1;
12688
12689       if (start_stop != NULL)
12690         {
12691           /* To work around a glibc bug, mark all XXX input sections
12692              when there is an as yet undefined reference to __start_XXX
12693              or __stop_XXX symbols.  The linker will later define such
12694              symbols for orphan input sections that have a name
12695              representable as a C identifier.  */
12696           asection *s = _bfd_elf_is_start_stop (info, h);
12697
12698           if (s != NULL)
12699             {
12700               *start_stop = !s->gc_mark;
12701               return s;
12702             }
12703         }
12704
12705       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
12706     }
12707
12708   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
12709                           &cookie->locsyms[r_symndx]);
12710 }
12711
12712 /* COOKIE->rel describes a relocation against section SEC, which is
12713    a section we've decided to keep.  Mark the section that contains
12714    the relocation symbol.  */
12715
12716 bfd_boolean
12717 _bfd_elf_gc_mark_reloc (struct bfd_link_info *info,
12718                         asection *sec,
12719                         elf_gc_mark_hook_fn gc_mark_hook,
12720                         struct elf_reloc_cookie *cookie)
12721 {
12722   asection *rsec;
12723   bfd_boolean start_stop = FALSE;
12724
12725   rsec = _bfd_elf_gc_mark_rsec (info, sec, gc_mark_hook, cookie, &start_stop);
12726   while (rsec != NULL)
12727     {
12728       if (!rsec->gc_mark)
12729         {
12730           if (bfd_get_flavour (rsec->owner) != bfd_target_elf_flavour
12731               || (rsec->owner->flags & DYNAMIC) != 0)
12732             rsec->gc_mark = 1;
12733           else if (!_bfd_elf_gc_mark (info, rsec, gc_mark_hook))
12734             return FALSE;
12735         }
12736       if (!start_stop)
12737         break;
12738       rsec = bfd_get_next_section_by_name (rsec->owner, rsec);
12739     }
12740   return TRUE;
12741 }
12742
12743 /* The mark phase of garbage collection.  For a given section, mark
12744    it and any sections in this section's group, and all the sections
12745    which define symbols to which it refers.  */
12746
12747 bfd_boolean
12748 _bfd_elf_gc_mark (struct bfd_link_info *info,
12749                   asection *sec,
12750                   elf_gc_mark_hook_fn gc_mark_hook)
12751 {
12752   bfd_boolean ret;
12753   asection *group_sec, *eh_frame;
12754
12755   sec->gc_mark = 1;
12756
12757   /* Mark all the sections in the group.  */
12758   group_sec = elf_section_data (sec)->next_in_group;
12759   if (group_sec && !group_sec->gc_mark)
12760     if (!_bfd_elf_gc_mark (info, group_sec, gc_mark_hook))
12761       return FALSE;
12762
12763   /* Look through the section relocs.  */
12764   ret = TRUE;
12765   eh_frame = elf_eh_frame_section (sec->owner);
12766   if ((sec->flags & SEC_RELOC) != 0
12767       && sec->reloc_count > 0
12768       && sec != eh_frame)
12769     {
12770       struct elf_reloc_cookie cookie;
12771
12772       if (!init_reloc_cookie_for_section (&cookie, info, sec))
12773         ret = FALSE;
12774       else
12775         {
12776           for (; cookie.rel < cookie.relend; cookie.rel++)
12777             if (!_bfd_elf_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
12778               {
12779                 ret = FALSE;
12780                 break;
12781               }
12782           fini_reloc_cookie_for_section (&cookie, sec);
12783         }
12784     }
12785
12786   if (ret && eh_frame && elf_fde_list (sec))
12787     {
12788       struct elf_reloc_cookie cookie;
12789
12790       if (!init_reloc_cookie_for_section (&cookie, info, eh_frame))
12791         ret = FALSE;
12792       else
12793         {
12794           if (!_bfd_elf_gc_mark_fdes (info, sec, eh_frame,
12795                                       gc_mark_hook, &cookie))
12796             ret = FALSE;
12797           fini_reloc_cookie_for_section (&cookie, eh_frame);
12798         }
12799     }
12800
12801   eh_frame = elf_section_eh_frame_entry (sec);
12802   if (ret && eh_frame && !eh_frame->gc_mark)
12803     if (!_bfd_elf_gc_mark (info, eh_frame, gc_mark_hook))
12804       ret = FALSE;
12805
12806   return ret;
12807 }
12808
12809 /* Scan and mark sections in a special or debug section group.  */
12810
12811 static void
12812 _bfd_elf_gc_mark_debug_special_section_group (asection *grp)
12813 {
12814   /* Point to first section of section group.  */
12815   asection *ssec;
12816   /* Used to iterate the section group.  */
12817   asection *msec;
12818
12819   bfd_boolean is_special_grp = TRUE;
12820   bfd_boolean is_debug_grp = TRUE;
12821
12822   /* First scan to see if group contains any section other than debug
12823      and special section.  */
12824   ssec = msec = elf_next_in_group (grp);
12825   do
12826     {
12827       if ((msec->flags & SEC_DEBUGGING) == 0)
12828         is_debug_grp = FALSE;
12829
12830       if ((msec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) != 0)
12831         is_special_grp = FALSE;
12832
12833       msec = elf_next_in_group (msec);
12834     }
12835   while (msec != ssec);
12836
12837   /* If this is a pure debug section group or pure special section group,
12838      keep all sections in this group.  */
12839   if (is_debug_grp || is_special_grp)
12840     {
12841       do
12842         {
12843           msec->gc_mark = 1;
12844           msec = elf_next_in_group (msec);
12845         }
12846       while (msec != ssec);
12847     }
12848 }
12849
12850 /* Keep debug and special sections.  */
12851
12852 bfd_boolean
12853 _bfd_elf_gc_mark_extra_sections (struct bfd_link_info *info,
12854                                  elf_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
12855 {
12856   bfd *ibfd;
12857
12858   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
12859     {
12860       asection *isec;
12861       bfd_boolean some_kept;
12862       bfd_boolean debug_frag_seen;
12863
12864       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
12865         continue;
12866
12867       /* Ensure all linker created sections are kept,
12868          see if any other section is already marked,
12869          and note if we have any fragmented debug sections.  */
12870       debug_frag_seen = some_kept = FALSE;
12871       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12872         {
12873           if ((isec->flags & SEC_LINKER_CREATED) != 0)
12874             isec->gc_mark = 1;
12875           else if (isec->gc_mark)
12876             some_kept = TRUE;
12877
12878           if (debug_frag_seen == FALSE
12879               && (isec->flags & SEC_DEBUGGING)
12880               && CONST_STRNEQ (isec->name, ".debug_line."))
12881             debug_frag_seen = TRUE;
12882         }
12883
12884       /* If no section in this file will be kept, then we can
12885          toss out the debug and special sections.  */
12886       if (!some_kept)
12887         continue;
12888
12889       /* Keep debug and special sections like .comment when they are
12890          not part of a group.  Also keep section groups that contain
12891          just debug sections or special sections.  */
12892       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12893         {
12894           if ((isec->flags & SEC_GROUP) != 0)
12895             _bfd_elf_gc_mark_debug_special_section_group (isec);
12896           else if (((isec->flags & SEC_DEBUGGING) != 0
12897                     || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
12898                    && elf_next_in_group (isec) == NULL)
12899             isec->gc_mark = 1;
12900         }
12901
12902       if (! debug_frag_seen)
12903         continue;
12904
12905       /* Look for CODE sections which are going to be discarded,
12906          and find and discard any fragmented debug sections which
12907          are associated with that code section.  */
12908       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
12909         if ((isec->flags & SEC_CODE) != 0
12910             && isec->gc_mark == 0)
12911           {
12912             unsigned int ilen;
12913             asection *dsec;
12914
12915             ilen = strlen (isec->name);
12916
12917             /* Association is determined by the name of the debug section
12918                containing the name of the code section as a suffix.  For
12919                example .debug_line.text.foo is a debug section associated
12920                with .text.foo.  */
12921             for (dsec = ibfd->sections; dsec != NULL; dsec = dsec->next)
12922               {
12923                 unsigned int dlen;
12924
12925                 if (dsec->gc_mark == 0
12926                     || (dsec->flags & SEC_DEBUGGING) == 0)
12927                   continue;
12928
12929                 dlen = strlen (dsec->name);
12930
12931                 if (dlen > ilen
12932                     && strncmp (dsec->name + (dlen - ilen),
12933                                 isec->name, ilen) == 0)
12934                   {
12935                     dsec->gc_mark = 0;
12936                   }
12937               }
12938           }
12939     }
12940   return TRUE;
12941 }
12942
12943 /* The sweep phase of garbage collection.  Remove all garbage sections.  */
12944
12945 typedef bfd_boolean (*gc_sweep_hook_fn)
12946   (bfd *, struct bfd_link_info *, asection *, const Elf_Internal_Rela *);
12947
12948 static bfd_boolean
12949 elf_gc_sweep (bfd *abfd, struct bfd_link_info *info)
12950 {
12951   bfd *sub;
12952   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
12953   gc_sweep_hook_fn gc_sweep_hook = bed->gc_sweep_hook;
12954
12955   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
12956     {
12957       asection *o;
12958
12959       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
12960           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
12961         continue;
12962
12963       for (o = sub->sections; o != NULL; o = o->next)
12964         {
12965           /* When any section in a section group is kept, we keep all
12966              sections in the section group.  If the first member of
12967              the section group is excluded, we will also exclude the
12968              group section.  */
12969           if (o->flags & SEC_GROUP)
12970             {
12971               asection *first = elf_next_in_group (o);
12972               o->gc_mark = first->gc_mark;
12973             }
12974
12975           if (o->gc_mark)
12976             continue;
12977
12978           /* Skip sweeping sections already excluded.  */
12979           if (o->flags & SEC_EXCLUDE)
12980             continue;
12981
12982           /* Since this is early in the link process, it is simple
12983              to remove a section from the output.  */
12984           o->flags |= SEC_EXCLUDE;
12985
12986           if (info->print_gc_sections && o->size != 0)
12987             /* xgettext:c-format */
12988             _bfd_error_handler (_("Removing unused section '%s' in file '%B'"),
12989                                 sub, o->name);
12990
12991           /* But we also have to update some of the relocation
12992              info we collected before.  */
12993           if (gc_sweep_hook
12994               && (o->flags & SEC_RELOC) != 0
12995               && o->reloc_count != 0
12996               && !((info->strip == strip_all || info->strip == strip_debugger)
12997                    && (o->flags & SEC_DEBUGGING) != 0)
12998               && !bfd_is_abs_section (o->output_section))
12999             {
13000               Elf_Internal_Rela *internal_relocs;
13001               bfd_boolean r;
13002
13003               internal_relocs
13004                 = _bfd_elf_link_read_relocs (o->owner, o, NULL, NULL,
13005                                              info->keep_memory);
13006               if (internal_relocs == NULL)
13007                 return FALSE;
13008
13009               r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
13010
13011               if (elf_section_data (o)->relocs != internal_relocs)
13012                 free (internal_relocs);
13013
13014               if (!r)
13015                 return FALSE;
13016             }
13017         }
13018     }
13019
13020   return TRUE;
13021 }
13022
13023 /* Propagate collected vtable information.  This is called through
13024    elf_link_hash_traverse.  */
13025
13026 static bfd_boolean
13027 elf_gc_propagate_vtable_entries_used (struct elf_link_hash_entry *h, void *okp)
13028 {
13029   /* Those that are not vtables.  */
13030   if (h->vtable == NULL || h->vtable->parent == NULL)
13031     return TRUE;
13032
13033   /* Those vtables that do not have parents, we cannot merge.  */
13034   if (h->vtable->parent == (struct elf_link_hash_entry *) -1)
13035     return TRUE;
13036
13037   /* If we've already been done, exit.  */
13038   if (h->vtable->used && h->vtable->used[-1])
13039     return TRUE;
13040
13041   /* Make sure the parent's table is up to date.  */
13042   elf_gc_propagate_vtable_entries_used (h->vtable->parent, okp);
13043
13044   if (h->vtable->used == NULL)
13045     {
13046       /* None of this table's entries were referenced.  Re-use the
13047          parent's table.  */
13048       h->vtable->used = h->vtable->parent->vtable->used;
13049       h->vtable->size = h->vtable->parent->vtable->size;
13050     }
13051   else
13052     {
13053       size_t n;
13054       bfd_boolean *cu, *pu;
13055
13056       /* Or the parent's entries into ours.  */
13057       cu = h->vtable->used;
13058       cu[-1] = TRUE;
13059       pu = h->vtable->parent->vtable->used;
13060       if (pu != NULL)
13061         {
13062           const struct elf_backend_data *bed;
13063           unsigned int log_file_align;
13064
13065           bed = get_elf_backend_data (h->root.u.def.section->owner);
13066           log_file_align = bed->s->log_file_align;
13067           n = h->vtable->parent->vtable->size >> log_file_align;
13068           while (n--)
13069             {
13070               if (*pu)
13071                 *cu = TRUE;
13072               pu++;
13073               cu++;
13074             }
13075         }
13076     }
13077
13078   return TRUE;
13079 }
13080
13081 static bfd_boolean
13082 elf_gc_smash_unused_vtentry_relocs (struct elf_link_hash_entry *h, void *okp)
13083 {
13084   asection *sec;
13085   bfd_vma hstart, hend;
13086   Elf_Internal_Rela *relstart, *relend, *rel;
13087   const struct elf_backend_data *bed;
13088   unsigned int log_file_align;
13089
13090   /* Take care of both those symbols that do not describe vtables as
13091      well as those that are not loaded.  */
13092   if (h->vtable == NULL || h->vtable->parent == NULL)
13093     return TRUE;
13094
13095   BFD_ASSERT (h->root.type == bfd_link_hash_defined
13096               || h->root.type == bfd_link_hash_defweak);
13097
13098   sec = h->root.u.def.section;
13099   hstart = h->root.u.def.value;
13100   hend = hstart + h->size;
13101
13102   relstart = _bfd_elf_link_read_relocs (sec->owner, sec, NULL, NULL, TRUE);
13103   if (!relstart)
13104     return *(bfd_boolean *) okp = FALSE;
13105   bed = get_elf_backend_data (sec->owner);
13106   log_file_align = bed->s->log_file_align;
13107
13108   relend = relstart + sec->reloc_count * bed->s->int_rels_per_ext_rel;
13109
13110   for (rel = relstart; rel < relend; ++rel)
13111     if (rel->r_offset >= hstart && rel->r_offset < hend)
13112       {
13113         /* If the entry is in use, do nothing.  */
13114         if (h->vtable->used
13115             && (rel->r_offset - hstart) < h->vtable->size)
13116           {
13117             bfd_vma entry = (rel->r_offset - hstart) >> log_file_align;
13118             if (h->vtable->used[entry])
13119               continue;
13120           }
13121         /* Otherwise, kill it.  */
13122         rel->r_offset = rel->r_info = rel->r_addend = 0;
13123       }
13124
13125   return TRUE;
13126 }
13127
13128 /* Mark sections containing dynamically referenced symbols.  When
13129    building shared libraries, we must assume that any visible symbol is
13130    referenced.  */
13131
13132 bfd_boolean
13133 bfd_elf_gc_mark_dynamic_ref_symbol (struct elf_link_hash_entry *h, void *inf)
13134 {
13135   struct bfd_link_info *info = (struct bfd_link_info *) inf;
13136   struct bfd_elf_dynamic_list *d = info->dynamic_list;
13137
13138   if ((h->root.type == bfd_link_hash_defined
13139        || h->root.type == bfd_link_hash_defweak)
13140       && (h->ref_dynamic
13141           || ((h->def_regular || ELF_COMMON_DEF_P (h))
13142               && ELF_ST_VISIBILITY (h->other) != STV_INTERNAL
13143               && ELF_ST_VISIBILITY (h->other) != STV_HIDDEN
13144               && (!bfd_link_executable (info)
13145                   || info->gc_keep_exported
13146                   || info->export_dynamic
13147                   || (h->dynamic
13148                       && d != NULL
13149                       && (*d->match) (&d->head, NULL, h->root.root.string)))
13150               && (h->versioned >= versioned
13151                   || !bfd_hide_sym_by_version (info->version_info,
13152                                                h->root.root.string)))))
13153     h->root.u.def.section->flags |= SEC_KEEP;
13154
13155   return TRUE;
13156 }
13157
13158 /* Keep all sections containing symbols undefined on the command-line,
13159    and the section containing the entry symbol.  */
13160
13161 void
13162 _bfd_elf_gc_keep (struct bfd_link_info *info)
13163 {
13164   struct bfd_sym_chain *sym;
13165
13166   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
13167     {
13168       struct elf_link_hash_entry *h;
13169
13170       h = elf_link_hash_lookup (elf_hash_table (info), sym->name,
13171                                 FALSE, FALSE, FALSE);
13172
13173       if (h != NULL
13174           && (h->root.type == bfd_link_hash_defined
13175               || h->root.type == bfd_link_hash_defweak)
13176           && !bfd_is_abs_section (h->root.u.def.section)
13177           && !bfd_is_und_section (h->root.u.def.section))
13178         h->root.u.def.section->flags |= SEC_KEEP;
13179     }
13180 }
13181
13182 bfd_boolean
13183 bfd_elf_parse_eh_frame_entries (bfd *abfd ATTRIBUTE_UNUSED,
13184                                 struct bfd_link_info *info)
13185 {
13186   bfd *ibfd = info->input_bfds;
13187
13188   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
13189     {
13190       asection *sec;
13191       struct elf_reloc_cookie cookie;
13192
13193       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
13194         continue;
13195
13196       if (!init_reloc_cookie (&cookie, info, ibfd))
13197         return FALSE;
13198
13199       for (sec = ibfd->sections; sec; sec = sec->next)
13200         {
13201           if (CONST_STRNEQ (bfd_section_name (ibfd, sec), ".eh_frame_entry")
13202               && init_reloc_cookie_rels (&cookie, info, ibfd, sec))
13203             {
13204               _bfd_elf_parse_eh_frame_entry (info, sec, &cookie);
13205               fini_reloc_cookie_rels (&cookie, sec);
13206             }
13207         }
13208     }
13209   return TRUE;
13210 }
13211
13212 /* Do mark and sweep of unused sections.  */
13213
13214 bfd_boolean
13215 bfd_elf_gc_sections (bfd *abfd, struct bfd_link_info *info)
13216 {
13217   bfd_boolean ok = TRUE;
13218   bfd *sub;
13219   elf_gc_mark_hook_fn gc_mark_hook;
13220   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13221   struct elf_link_hash_table *htab;
13222
13223   if (!bed->can_gc_sections
13224       || !is_elf_hash_table (info->hash))
13225     {
13226       _bfd_error_handler(_("Warning: gc-sections option ignored"));
13227       return TRUE;
13228     }
13229
13230   bed->gc_keep (info);
13231   htab = elf_hash_table (info);
13232
13233   /* Try to parse each bfd's .eh_frame section.  Point elf_eh_frame_section
13234      at the .eh_frame section if we can mark the FDEs individually.  */
13235   for (sub = info->input_bfds;
13236        info->eh_frame_hdr_type != COMPACT_EH_HDR && sub != NULL;
13237        sub = sub->link.next)
13238     {
13239       asection *sec;
13240       struct elf_reloc_cookie cookie;
13241
13242       sec = bfd_get_section_by_name (sub, ".eh_frame");
13243       while (sec && init_reloc_cookie_for_section (&cookie, info, sec))
13244         {
13245           _bfd_elf_parse_eh_frame (sub, info, sec, &cookie);
13246           if (elf_section_data (sec)->sec_info
13247               && (sec->flags & SEC_LINKER_CREATED) == 0)
13248             elf_eh_frame_section (sub) = sec;
13249           fini_reloc_cookie_for_section (&cookie, sec);
13250           sec = bfd_get_next_section_by_name (NULL, sec);
13251         }
13252     }
13253
13254   /* Apply transitive closure to the vtable entry usage info.  */
13255   elf_link_hash_traverse (htab, elf_gc_propagate_vtable_entries_used, &ok);
13256   if (!ok)
13257     return FALSE;
13258
13259   /* Kill the vtable relocations that were not used.  */
13260   elf_link_hash_traverse (htab, elf_gc_smash_unused_vtentry_relocs, &ok);
13261   if (!ok)
13262     return FALSE;
13263
13264   /* Mark dynamically referenced symbols.  */
13265   if (htab->dynamic_sections_created || info->gc_keep_exported)
13266     elf_link_hash_traverse (htab, bed->gc_mark_dynamic_ref, info);
13267
13268   /* Grovel through relocs to find out who stays ...  */
13269   gc_mark_hook = bed->gc_mark_hook;
13270   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
13271     {
13272       asection *o;
13273
13274       if (bfd_get_flavour (sub) != bfd_target_elf_flavour
13275           || !(*bed->relocs_compatible) (sub->xvec, abfd->xvec))
13276         continue;
13277
13278       /* Start at sections marked with SEC_KEEP (ref _bfd_elf_gc_keep).
13279          Also treat note sections as a root, if the section is not part
13280          of a group.  */
13281       for (o = sub->sections; o != NULL; o = o->next)
13282         if (!o->gc_mark
13283             && (o->flags & SEC_EXCLUDE) == 0
13284             && ((o->flags & SEC_KEEP) != 0
13285                 || (elf_section_data (o)->this_hdr.sh_type == SHT_NOTE
13286                     && elf_next_in_group (o) == NULL )))
13287           {
13288             if (!_bfd_elf_gc_mark (info, o, gc_mark_hook))
13289               return FALSE;
13290           }
13291     }
13292
13293   /* Allow the backend to mark additional target specific sections.  */
13294   bed->gc_mark_extra_sections (info, gc_mark_hook);
13295
13296   /* ... and mark SEC_EXCLUDE for those that go.  */
13297   return elf_gc_sweep (abfd, info);
13298 }
13299 \f
13300 /* Called from check_relocs to record the existence of a VTINHERIT reloc.  */
13301
13302 bfd_boolean
13303 bfd_elf_gc_record_vtinherit (bfd *abfd,
13304                              asection *sec,
13305                              struct elf_link_hash_entry *h,
13306                              bfd_vma offset)
13307 {
13308   struct elf_link_hash_entry **sym_hashes, **sym_hashes_end;
13309   struct elf_link_hash_entry **search, *child;
13310   size_t extsymcount;
13311   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13312
13313   /* The sh_info field of the symtab header tells us where the
13314      external symbols start.  We don't care about the local symbols at
13315      this point.  */
13316   extsymcount = elf_tdata (abfd)->symtab_hdr.sh_size / bed->s->sizeof_sym;
13317   if (!elf_bad_symtab (abfd))
13318     extsymcount -= elf_tdata (abfd)->symtab_hdr.sh_info;
13319
13320   sym_hashes = elf_sym_hashes (abfd);
13321   sym_hashes_end = sym_hashes + extsymcount;
13322
13323   /* Hunt down the child symbol, which is in this section at the same
13324      offset as the relocation.  */
13325   for (search = sym_hashes; search != sym_hashes_end; ++search)
13326     {
13327       if ((child = *search) != NULL
13328           && (child->root.type == bfd_link_hash_defined
13329               || child->root.type == bfd_link_hash_defweak)
13330           && child->root.u.def.section == sec
13331           && child->root.u.def.value == offset)
13332         goto win;
13333     }
13334
13335   /* xgettext:c-format */
13336   _bfd_error_handler (_("%B: %A+%lu: No symbol found for INHERIT"),
13337                       abfd, sec, (unsigned long) offset);
13338   bfd_set_error (bfd_error_invalid_operation);
13339   return FALSE;
13340
13341  win:
13342   if (!child->vtable)
13343     {
13344       child->vtable = ((struct elf_link_virtual_table_entry *)
13345                        bfd_zalloc (abfd, sizeof (*child->vtable)));
13346       if (!child->vtable)
13347         return FALSE;
13348     }
13349   if (!h)
13350     {
13351       /* This *should* only be the absolute section.  It could potentially
13352          be that someone has defined a non-global vtable though, which
13353          would be bad.  It isn't worth paging in the local symbols to be
13354          sure though; that case should simply be handled by the assembler.  */
13355
13356       child->vtable->parent = (struct elf_link_hash_entry *) -1;
13357     }
13358   else
13359     child->vtable->parent = h;
13360
13361   return TRUE;
13362 }
13363
13364 /* Called from check_relocs to record the existence of a VTENTRY reloc.  */
13365
13366 bfd_boolean
13367 bfd_elf_gc_record_vtentry (bfd *abfd ATTRIBUTE_UNUSED,
13368                            asection *sec ATTRIBUTE_UNUSED,
13369                            struct elf_link_hash_entry *h,
13370                            bfd_vma addend)
13371 {
13372   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13373   unsigned int log_file_align = bed->s->log_file_align;
13374
13375   if (!h->vtable)
13376     {
13377       h->vtable = ((struct elf_link_virtual_table_entry *)
13378                    bfd_zalloc (abfd, sizeof (*h->vtable)));
13379       if (!h->vtable)
13380         return FALSE;
13381     }
13382
13383   if (addend >= h->vtable->size)
13384     {
13385       size_t size, bytes, file_align;
13386       bfd_boolean *ptr = h->vtable->used;
13387
13388       /* While the symbol is undefined, we have to be prepared to handle
13389          a zero size.  */
13390       file_align = 1 << log_file_align;
13391       if (h->root.type == bfd_link_hash_undefined)
13392         size = addend + file_align;
13393       else
13394         {
13395           size = h->size;
13396           if (addend >= size)
13397             {
13398               /* Oops!  We've got a reference past the defined end of
13399                  the table.  This is probably a bug -- shall we warn?  */
13400               size = addend + file_align;
13401             }
13402         }
13403       size = (size + file_align - 1) & -file_align;
13404
13405       /* Allocate one extra entry for use as a "done" flag for the
13406          consolidation pass.  */
13407       bytes = ((size >> log_file_align) + 1) * sizeof (bfd_boolean);
13408
13409       if (ptr)
13410         {
13411           ptr = (bfd_boolean *) bfd_realloc (ptr - 1, bytes);
13412
13413           if (ptr != NULL)
13414             {
13415               size_t oldbytes;
13416
13417               oldbytes = (((h->vtable->size >> log_file_align) + 1)
13418                           * sizeof (bfd_boolean));
13419               memset (((char *) ptr) + oldbytes, 0, bytes - oldbytes);
13420             }
13421         }
13422       else
13423         ptr = (bfd_boolean *) bfd_zmalloc (bytes);
13424
13425       if (ptr == NULL)
13426         return FALSE;
13427
13428       /* And arrange for that done flag to be at index -1.  */
13429       h->vtable->used = ptr + 1;
13430       h->vtable->size = size;
13431     }
13432
13433   h->vtable->used[addend >> log_file_align] = TRUE;
13434
13435   return TRUE;
13436 }
13437
13438 /* Map an ELF section header flag to its corresponding string.  */
13439 typedef struct
13440 {
13441   char *flag_name;
13442   flagword flag_value;
13443 } elf_flags_to_name_table;
13444
13445 static elf_flags_to_name_table elf_flags_to_names [] =
13446 {
13447   { "SHF_WRITE", SHF_WRITE },
13448   { "SHF_ALLOC", SHF_ALLOC },
13449   { "SHF_EXECINSTR", SHF_EXECINSTR },
13450   { "SHF_MERGE", SHF_MERGE },
13451   { "SHF_STRINGS", SHF_STRINGS },
13452   { "SHF_INFO_LINK", SHF_INFO_LINK},
13453   { "SHF_LINK_ORDER", SHF_LINK_ORDER},
13454   { "SHF_OS_NONCONFORMING", SHF_OS_NONCONFORMING},
13455   { "SHF_GROUP", SHF_GROUP },
13456   { "SHF_TLS", SHF_TLS },
13457   { "SHF_MASKOS", SHF_MASKOS },
13458   { "SHF_EXCLUDE", SHF_EXCLUDE },
13459 };
13460
13461 /* Returns TRUE if the section is to be included, otherwise FALSE.  */
13462 bfd_boolean
13463 bfd_elf_lookup_section_flags (struct bfd_link_info *info,
13464                               struct flag_info *flaginfo,
13465                               asection *section)
13466 {
13467   const bfd_vma sh_flags = elf_section_flags (section);
13468
13469   if (!flaginfo->flags_initialized)
13470     {
13471       bfd *obfd = info->output_bfd;
13472       const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13473       struct flag_info_list *tf = flaginfo->flag_list;
13474       int with_hex = 0;
13475       int without_hex = 0;
13476
13477       for (tf = flaginfo->flag_list; tf != NULL; tf = tf->next)
13478         {
13479           unsigned i;
13480           flagword (*lookup) (char *);
13481
13482           lookup = bed->elf_backend_lookup_section_flags_hook;
13483           if (lookup != NULL)
13484             {
13485               flagword hexval = (*lookup) ((char *) tf->name);
13486
13487               if (hexval != 0)
13488                 {
13489                   if (tf->with == with_flags)
13490                     with_hex |= hexval;
13491                   else if (tf->with == without_flags)
13492                     without_hex |= hexval;
13493                   tf->valid = TRUE;
13494                   continue;
13495                 }
13496             }
13497           for (i = 0; i < ARRAY_SIZE (elf_flags_to_names); ++i)
13498             {
13499               if (strcmp (tf->name, elf_flags_to_names[i].flag_name) == 0)
13500                 {
13501                   if (tf->with == with_flags)
13502                     with_hex |= elf_flags_to_names[i].flag_value;
13503                   else if (tf->with == without_flags)
13504                     without_hex |= elf_flags_to_names[i].flag_value;
13505                   tf->valid = TRUE;
13506                   break;
13507                 }
13508             }
13509           if (!tf->valid)
13510             {
13511               info->callbacks->einfo
13512                 (_("Unrecognized INPUT_SECTION_FLAG %s\n"), tf->name);
13513               return FALSE;
13514             }
13515         }
13516       flaginfo->flags_initialized = TRUE;
13517       flaginfo->only_with_flags |= with_hex;
13518       flaginfo->not_with_flags |= without_hex;
13519     }
13520
13521   if ((flaginfo->only_with_flags & sh_flags) != flaginfo->only_with_flags)
13522     return FALSE;
13523
13524   if ((flaginfo->not_with_flags & sh_flags) != 0)
13525     return FALSE;
13526
13527   return TRUE;
13528 }
13529
13530 struct alloc_got_off_arg {
13531   bfd_vma gotoff;
13532   struct bfd_link_info *info;
13533 };
13534
13535 /* We need a special top-level link routine to convert got reference counts
13536    to real got offsets.  */
13537
13538 static bfd_boolean
13539 elf_gc_allocate_got_offsets (struct elf_link_hash_entry *h, void *arg)
13540 {
13541   struct alloc_got_off_arg *gofarg = (struct alloc_got_off_arg *) arg;
13542   bfd *obfd = gofarg->info->output_bfd;
13543   const struct elf_backend_data *bed = get_elf_backend_data (obfd);
13544
13545   if (h->got.refcount > 0)
13546     {
13547       h->got.offset = gofarg->gotoff;
13548       gofarg->gotoff += bed->got_elt_size (obfd, gofarg->info, h, NULL, 0);
13549     }
13550   else
13551     h->got.offset = (bfd_vma) -1;
13552
13553   return TRUE;
13554 }
13555
13556 /* And an accompanying bit to work out final got entry offsets once
13557    we're done.  Should be called from final_link.  */
13558
13559 bfd_boolean
13560 bfd_elf_gc_common_finalize_got_offsets (bfd *abfd,
13561                                         struct bfd_link_info *info)
13562 {
13563   bfd *i;
13564   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13565   bfd_vma gotoff;
13566   struct alloc_got_off_arg gofarg;
13567
13568   BFD_ASSERT (abfd == info->output_bfd);
13569
13570   if (! is_elf_hash_table (info->hash))
13571     return FALSE;
13572
13573   /* The GOT offset is relative to the .got section, but the GOT header is
13574      put into the .got.plt section, if the backend uses it.  */
13575   if (bed->want_got_plt)
13576     gotoff = 0;
13577   else
13578     gotoff = bed->got_header_size;
13579
13580   /* Do the local .got entries first.  */
13581   for (i = info->input_bfds; i; i = i->link.next)
13582     {
13583       bfd_signed_vma *local_got;
13584       size_t j, locsymcount;
13585       Elf_Internal_Shdr *symtab_hdr;
13586
13587       if (bfd_get_flavour (i) != bfd_target_elf_flavour)
13588         continue;
13589
13590       local_got = elf_local_got_refcounts (i);
13591       if (!local_got)
13592         continue;
13593
13594       symtab_hdr = &elf_tdata (i)->symtab_hdr;
13595       if (elf_bad_symtab (i))
13596         locsymcount = symtab_hdr->sh_size / bed->s->sizeof_sym;
13597       else
13598         locsymcount = symtab_hdr->sh_info;
13599
13600       for (j = 0; j < locsymcount; ++j)
13601         {
13602           if (local_got[j] > 0)
13603             {
13604               local_got[j] = gotoff;
13605               gotoff += bed->got_elt_size (abfd, info, NULL, i, j);
13606             }
13607           else
13608             local_got[j] = (bfd_vma) -1;
13609         }
13610     }
13611
13612   /* Then the global .got entries.  .plt refcounts are handled by
13613      adjust_dynamic_symbol  */
13614   gofarg.gotoff = gotoff;
13615   gofarg.info = info;
13616   elf_link_hash_traverse (elf_hash_table (info),
13617                           elf_gc_allocate_got_offsets,
13618                           &gofarg);
13619   return TRUE;
13620 }
13621
13622 /* Many folk need no more in the way of final link than this, once
13623    got entry reference counting is enabled.  */
13624
13625 bfd_boolean
13626 bfd_elf_gc_common_final_link (bfd *abfd, struct bfd_link_info *info)
13627 {
13628   if (!bfd_elf_gc_common_finalize_got_offsets (abfd, info))
13629     return FALSE;
13630
13631   /* Invoke the regular ELF backend linker to do all the work.  */
13632   return bfd_elf_final_link (abfd, info);
13633 }
13634
13635 bfd_boolean
13636 bfd_elf_reloc_symbol_deleted_p (bfd_vma offset, void *cookie)
13637 {
13638   struct elf_reloc_cookie *rcookie = (struct elf_reloc_cookie *) cookie;
13639
13640   if (rcookie->bad_symtab)
13641     rcookie->rel = rcookie->rels;
13642
13643   for (; rcookie->rel < rcookie->relend; rcookie->rel++)
13644     {
13645       unsigned long r_symndx;
13646
13647       if (! rcookie->bad_symtab)
13648         if (rcookie->rel->r_offset > offset)
13649           return FALSE;
13650       if (rcookie->rel->r_offset != offset)
13651         continue;
13652
13653       r_symndx = rcookie->rel->r_info >> rcookie->r_sym_shift;
13654       if (r_symndx == STN_UNDEF)
13655         return TRUE;
13656
13657       if (r_symndx >= rcookie->locsymcount
13658           || ELF_ST_BIND (rcookie->locsyms[r_symndx].st_info) != STB_LOCAL)
13659         {
13660           struct elf_link_hash_entry *h;
13661
13662           h = rcookie->sym_hashes[r_symndx - rcookie->extsymoff];
13663
13664           while (h->root.type == bfd_link_hash_indirect
13665                  || h->root.type == bfd_link_hash_warning)
13666             h = (struct elf_link_hash_entry *) h->root.u.i.link;
13667
13668           if ((h->root.type == bfd_link_hash_defined
13669                || h->root.type == bfd_link_hash_defweak)
13670               && (h->root.u.def.section->owner != rcookie->abfd
13671                   || h->root.u.def.section->kept_section != NULL
13672                   || discarded_section (h->root.u.def.section)))
13673             return TRUE;
13674         }
13675       else
13676         {
13677           /* It's not a relocation against a global symbol,
13678              but it could be a relocation against a local
13679              symbol for a discarded section.  */
13680           asection *isec;
13681           Elf_Internal_Sym *isym;
13682
13683           /* Need to: get the symbol; get the section.  */
13684           isym = &rcookie->locsyms[r_symndx];
13685           isec = bfd_section_from_elf_index (rcookie->abfd, isym->st_shndx);
13686           if (isec != NULL
13687               && (isec->kept_section != NULL
13688                   || discarded_section (isec)))
13689             return TRUE;
13690         }
13691       return FALSE;
13692     }
13693   return FALSE;
13694 }
13695
13696 /* Discard unneeded references to discarded sections.
13697    Returns -1 on error, 1 if any section's size was changed, 0 if
13698    nothing changed.  This function assumes that the relocations are in
13699    sorted order, which is true for all known assemblers.  */
13700
13701 int
13702 bfd_elf_discard_info (bfd *output_bfd, struct bfd_link_info *info)
13703 {
13704   struct elf_reloc_cookie cookie;
13705   asection *o;
13706   bfd *abfd;
13707   int changed = 0;
13708
13709   if (info->traditional_format
13710       || !is_elf_hash_table (info->hash))
13711     return 0;
13712
13713   o = bfd_get_section_by_name (output_bfd, ".stab");
13714   if (o != NULL)
13715     {
13716       asection *i;
13717
13718       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13719         {
13720           if (i->size == 0
13721               || i->reloc_count == 0
13722               || i->sec_info_type != SEC_INFO_TYPE_STABS)
13723             continue;
13724
13725           abfd = i->owner;
13726           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13727             continue;
13728
13729           if (!init_reloc_cookie_for_section (&cookie, info, i))
13730             return -1;
13731
13732           if (_bfd_discard_section_stabs (abfd, i,
13733                                           elf_section_data (i)->sec_info,
13734                                           bfd_elf_reloc_symbol_deleted_p,
13735                                           &cookie))
13736             changed = 1;
13737
13738           fini_reloc_cookie_for_section (&cookie, i);
13739         }
13740     }
13741
13742   o = NULL;
13743   if (info->eh_frame_hdr_type != COMPACT_EH_HDR)
13744     o = bfd_get_section_by_name (output_bfd, ".eh_frame");
13745   if (o != NULL)
13746     {
13747       asection *i;
13748
13749       for (i = o->map_head.s; i != NULL; i = i->map_head.s)
13750         {
13751           if (i->size == 0)
13752             continue;
13753
13754           abfd = i->owner;
13755           if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13756             continue;
13757
13758           if (!init_reloc_cookie_for_section (&cookie, info, i))
13759             return -1;
13760
13761           _bfd_elf_parse_eh_frame (abfd, info, i, &cookie);
13762           if (_bfd_elf_discard_section_eh_frame (abfd, info, i,
13763                                                  bfd_elf_reloc_symbol_deleted_p,
13764                                                  &cookie))
13765             changed = 1;
13766
13767           fini_reloc_cookie_for_section (&cookie, i);
13768         }
13769     }
13770
13771   for (abfd = info->input_bfds; abfd != NULL; abfd = abfd->link.next)
13772     {
13773       const struct elf_backend_data *bed;
13774
13775       if (bfd_get_flavour (abfd) != bfd_target_elf_flavour)
13776         continue;
13777
13778       bed = get_elf_backend_data (abfd);
13779
13780       if (bed->elf_backend_discard_info != NULL)
13781         {
13782           if (!init_reloc_cookie (&cookie, info, abfd))
13783             return -1;
13784
13785           if ((*bed->elf_backend_discard_info) (abfd, &cookie, info))
13786             changed = 1;
13787
13788           fini_reloc_cookie (&cookie, abfd);
13789         }
13790     }
13791
13792   if (info->eh_frame_hdr_type == COMPACT_EH_HDR)
13793     _bfd_elf_end_eh_frame_parsing (info);
13794
13795   if (info->eh_frame_hdr_type
13796       && !bfd_link_relocatable (info)
13797       && _bfd_elf_discard_section_eh_frame_hdr (output_bfd, info))
13798     changed = 1;
13799
13800   return changed;
13801 }
13802
13803 bfd_boolean
13804 _bfd_elf_section_already_linked (bfd *abfd,
13805                                  asection *sec,
13806                                  struct bfd_link_info *info)
13807 {
13808   flagword flags;
13809   const char *name, *key;
13810   struct bfd_section_already_linked *l;
13811   struct bfd_section_already_linked_hash_entry *already_linked_list;
13812
13813   if (sec->output_section == bfd_abs_section_ptr)
13814     return FALSE;
13815
13816   flags = sec->flags;
13817
13818   /* Return if it isn't a linkonce section.  A comdat group section
13819      also has SEC_LINK_ONCE set.  */
13820   if ((flags & SEC_LINK_ONCE) == 0)
13821     return FALSE;
13822
13823   /* Don't put group member sections on our list of already linked
13824      sections.  They are handled as a group via their group section.  */
13825   if (elf_sec_group (sec) != NULL)
13826     return FALSE;
13827
13828   /* For a SHT_GROUP section, use the group signature as the key.  */
13829   name = sec->name;
13830   if ((flags & SEC_GROUP) != 0
13831       && elf_next_in_group (sec) != NULL
13832       && elf_group_name (elf_next_in_group (sec)) != NULL)
13833     key = elf_group_name (elf_next_in_group (sec));
13834   else
13835     {
13836       /* Otherwise we should have a .gnu.linkonce.<type>.<key> section.  */
13837       if (CONST_STRNEQ (name, ".gnu.linkonce.")
13838           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
13839         key++;
13840       else
13841         /* Must be a user linkonce section that doesn't follow gcc's
13842            naming convention.  In this case we won't be matching
13843            single member groups.  */
13844         key = name;
13845     }
13846
13847   already_linked_list = bfd_section_already_linked_table_lookup (key);
13848
13849   for (l = already_linked_list->entry; l != NULL; l = l->next)
13850     {
13851       /* We may have 2 different types of sections on the list: group
13852          sections with a signature of <key> (<key> is some string),
13853          and linkonce sections named .gnu.linkonce.<type>.<key>.
13854          Match like sections.  LTO plugin sections are an exception.
13855          They are always named .gnu.linkonce.t.<key> and match either
13856          type of section.  */
13857       if (((flags & SEC_GROUP) == (l->sec->flags & SEC_GROUP)
13858            && ((flags & SEC_GROUP) != 0
13859                || strcmp (name, l->sec->name) == 0))
13860           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
13861         {
13862           /* The section has already been linked.  See if we should
13863              issue a warning.  */
13864           if (!_bfd_handle_already_linked (sec, l, info))
13865             return FALSE;
13866
13867           if (flags & SEC_GROUP)
13868             {
13869               asection *first = elf_next_in_group (sec);
13870               asection *s = first;
13871
13872               while (s != NULL)
13873                 {
13874                   s->output_section = bfd_abs_section_ptr;
13875                   /* Record which group discards it.  */
13876                   s->kept_section = l->sec;
13877                   s = elf_next_in_group (s);
13878                   /* These lists are circular.  */
13879                   if (s == first)
13880                     break;
13881                 }
13882             }
13883
13884           return TRUE;
13885         }
13886     }
13887
13888   /* A single member comdat group section may be discarded by a
13889      linkonce section and vice versa.  */
13890   if ((flags & SEC_GROUP) != 0)
13891     {
13892       asection *first = elf_next_in_group (sec);
13893
13894       if (first != NULL && elf_next_in_group (first) == first)
13895         /* Check this single member group against linkonce sections.  */
13896         for (l = already_linked_list->entry; l != NULL; l = l->next)
13897           if ((l->sec->flags & SEC_GROUP) == 0
13898               && bfd_elf_match_symbols_in_sections (l->sec, first, info))
13899             {
13900               first->output_section = bfd_abs_section_ptr;
13901               first->kept_section = l->sec;
13902               sec->output_section = bfd_abs_section_ptr;
13903               break;
13904             }
13905     }
13906   else
13907     /* Check this linkonce section against single member groups.  */
13908     for (l = already_linked_list->entry; l != NULL; l = l->next)
13909       if (l->sec->flags & SEC_GROUP)
13910         {
13911           asection *first = elf_next_in_group (l->sec);
13912
13913           if (first != NULL
13914               && elf_next_in_group (first) == first
13915               && bfd_elf_match_symbols_in_sections (first, sec, info))
13916             {
13917               sec->output_section = bfd_abs_section_ptr;
13918               sec->kept_section = first;
13919               break;
13920             }
13921         }
13922
13923   /* Do not complain on unresolved relocations in `.gnu.linkonce.r.F'
13924      referencing its discarded `.gnu.linkonce.t.F' counterpart - g++-3.4
13925      specific as g++-4.x is using COMDAT groups (without the `.gnu.linkonce'
13926      prefix) instead.  `.gnu.linkonce.r.*' were the `.rodata' part of its
13927      matching `.gnu.linkonce.t.*'.  If `.gnu.linkonce.r.F' is not discarded
13928      but its `.gnu.linkonce.t.F' is discarded means we chose one-only
13929      `.gnu.linkonce.t.F' section from a different bfd not requiring any
13930      `.gnu.linkonce.r.F'.  Thus `.gnu.linkonce.r.F' should be discarded.
13931      The reverse order cannot happen as there is never a bfd with only the
13932      `.gnu.linkonce.r.F' section.  The order of sections in a bfd does not
13933      matter as here were are looking only for cross-bfd sections.  */
13934
13935   if ((flags & SEC_GROUP) == 0 && CONST_STRNEQ (name, ".gnu.linkonce.r."))
13936     for (l = already_linked_list->entry; l != NULL; l = l->next)
13937       if ((l->sec->flags & SEC_GROUP) == 0
13938           && CONST_STRNEQ (l->sec->name, ".gnu.linkonce.t."))
13939         {
13940           if (abfd != l->sec->owner)
13941             sec->output_section = bfd_abs_section_ptr;
13942           break;
13943         }
13944
13945   /* This is the first section with this name.  Record it.  */
13946   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
13947     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
13948   return sec->output_section == bfd_abs_section_ptr;
13949 }
13950
13951 bfd_boolean
13952 _bfd_elf_common_definition (Elf_Internal_Sym *sym)
13953 {
13954   return sym->st_shndx == SHN_COMMON;
13955 }
13956
13957 unsigned int
13958 _bfd_elf_common_section_index (asection *sec ATTRIBUTE_UNUSED)
13959 {
13960   return SHN_COMMON;
13961 }
13962
13963 asection *
13964 _bfd_elf_common_section (asection *sec ATTRIBUTE_UNUSED)
13965 {
13966   return bfd_com_section_ptr;
13967 }
13968
13969 bfd_vma
13970 _bfd_elf_default_got_elt_size (bfd *abfd,
13971                                struct bfd_link_info *info ATTRIBUTE_UNUSED,
13972                                struct elf_link_hash_entry *h ATTRIBUTE_UNUSED,
13973                                bfd *ibfd ATTRIBUTE_UNUSED,
13974                                unsigned long symndx ATTRIBUTE_UNUSED)
13975 {
13976   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
13977   return bed->s->arch_size / 8;
13978 }
13979
13980 /* Routines to support the creation of dynamic relocs.  */
13981
13982 /* Returns the name of the dynamic reloc section associated with SEC.  */
13983
13984 static const char *
13985 get_dynamic_reloc_section_name (bfd *       abfd,
13986                                 asection *  sec,
13987                                 bfd_boolean is_rela)
13988 {
13989   char *name;
13990   const char *old_name = bfd_get_section_name (NULL, sec);
13991   const char *prefix = is_rela ? ".rela" : ".rel";
13992
13993   if (old_name == NULL)
13994     return NULL;
13995
13996   name = bfd_alloc (abfd, strlen (prefix) + strlen (old_name) + 1);
13997   sprintf (name, "%s%s", prefix, old_name);
13998
13999   return name;
14000 }
14001
14002 /* Returns the dynamic reloc section associated with SEC.
14003    If necessary compute the name of the dynamic reloc section based
14004    on SEC's name (looked up in ABFD's string table) and the setting
14005    of IS_RELA.  */
14006
14007 asection *
14008 _bfd_elf_get_dynamic_reloc_section (bfd *       abfd,
14009                                     asection *  sec,
14010                                     bfd_boolean is_rela)
14011 {
14012   asection * reloc_sec = elf_section_data (sec)->sreloc;
14013
14014   if (reloc_sec == NULL)
14015     {
14016       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14017
14018       if (name != NULL)
14019         {
14020           reloc_sec = bfd_get_linker_section (abfd, name);
14021
14022           if (reloc_sec != NULL)
14023             elf_section_data (sec)->sreloc = reloc_sec;
14024         }
14025     }
14026
14027   return reloc_sec;
14028 }
14029
14030 /* Returns the dynamic reloc section associated with SEC.  If the
14031    section does not exist it is created and attached to the DYNOBJ
14032    bfd and stored in the SRELOC field of SEC's elf_section_data
14033    structure.
14034
14035    ALIGNMENT is the alignment for the newly created section and
14036    IS_RELA defines whether the name should be .rela.<SEC's name>
14037    or .rel.<SEC's name>.  The section name is looked up in the
14038    string table associated with ABFD.  */
14039
14040 asection *
14041 _bfd_elf_make_dynamic_reloc_section (asection *sec,
14042                                      bfd *dynobj,
14043                                      unsigned int alignment,
14044                                      bfd *abfd,
14045                                      bfd_boolean is_rela)
14046 {
14047   asection * reloc_sec = elf_section_data (sec)->sreloc;
14048
14049   if (reloc_sec == NULL)
14050     {
14051       const char * name = get_dynamic_reloc_section_name (abfd, sec, is_rela);
14052
14053       if (name == NULL)
14054         return NULL;
14055
14056       reloc_sec = bfd_get_linker_section (dynobj, name);
14057
14058       if (reloc_sec == NULL)
14059         {
14060           flagword flags = (SEC_HAS_CONTENTS | SEC_READONLY
14061                             | SEC_IN_MEMORY | SEC_LINKER_CREATED);
14062           if ((sec->flags & SEC_ALLOC) != 0)
14063             flags |= SEC_ALLOC | SEC_LOAD;
14064
14065           reloc_sec = bfd_make_section_anyway_with_flags (dynobj, name, flags);
14066           if (reloc_sec != NULL)
14067             {
14068               /* _bfd_elf_get_sec_type_attr chooses a section type by
14069                  name.  Override as it may be wrong, eg. for a user
14070                  section named "auto" we'll get ".relauto" which is
14071                  seen to be a .rela section.  */
14072               elf_section_type (reloc_sec) = is_rela ? SHT_RELA : SHT_REL;
14073               if (! bfd_set_section_alignment (dynobj, reloc_sec, alignment))
14074                 reloc_sec = NULL;
14075             }
14076         }
14077
14078       elf_section_data (sec)->sreloc = reloc_sec;
14079     }
14080
14081   return reloc_sec;
14082 }
14083
14084 /* Copy the ELF symbol type and other attributes for a linker script
14085    assignment from HSRC to HDEST.  Generally this should be treated as
14086    if we found a strong non-dynamic definition for HDEST (except that
14087    ld ignores multiple definition errors).  */
14088 void
14089 _bfd_elf_copy_link_hash_symbol_type (bfd *abfd,
14090                                      struct bfd_link_hash_entry *hdest,
14091                                      struct bfd_link_hash_entry *hsrc)
14092 {
14093   struct elf_link_hash_entry *ehdest = (struct elf_link_hash_entry *) hdest;
14094   struct elf_link_hash_entry *ehsrc = (struct elf_link_hash_entry *) hsrc;
14095   Elf_Internal_Sym isym;
14096
14097   ehdest->type = ehsrc->type;
14098   ehdest->target_internal = ehsrc->target_internal;
14099
14100   isym.st_other = ehsrc->other;
14101   elf_merge_st_other (abfd, ehdest, &isym, NULL, TRUE, FALSE);
14102 }
14103
14104 /* Append a RELA relocation REL to section S in BFD.  */
14105
14106 void
14107 elf_append_rela (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14108 {
14109   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14110   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rela);
14111   BFD_ASSERT (loc + bed->s->sizeof_rela <= s->contents + s->size);
14112   bed->s->swap_reloca_out (abfd, rel, loc);
14113 }
14114
14115 /* Append a REL relocation REL to section S in BFD.  */
14116
14117 void
14118 elf_append_rel (bfd *abfd, asection *s, Elf_Internal_Rela *rel)
14119 {
14120   const struct elf_backend_data *bed = get_elf_backend_data (abfd);
14121   bfd_byte *loc = s->contents + (s->reloc_count++ * bed->s->sizeof_rel);
14122   BFD_ASSERT (loc + bed->s->sizeof_rel <= s->contents + s->size);
14123   bed->s->swap_reloc_out (abfd, rel, loc);
14124 }