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